texlite 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-rBWMBTI-.js","assets/react-CsO_xvbl.js","assets/spellCheck-R6fUM9oA.js","assets/PdfPreview-CHTibR8X.js","assets/pdf-DPnwNQHb.js","assets/plus-C_J43WcA.js","assets/LatexEditor-CEUW9LNB.js","assets/editor-DMLs-XWi.js","assets/GitDialog-_AsbwoMa.js","assets/HistoryDialog-Bc8OBByX.js","assets/ProjectNavigationDialogs-DVUI8Thi.js","assets/SystemMetricsDialog-CRq25lNt.js"])))=>i.map(i=>d[i]);
2
- import{i as Oh,r as h,j as o,R as nr,a as pl,b as _h,u as Pe,P as Ph,c as jr,d as Ri,e as Rh}from"./react-CsO_xvbl.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();const Lh="modulepreload",Ah=function(t){return"/"+t},Ja={},Jt=function(e,n,s){let r=Promise.resolve();if(n&&n.length>0){let l=function(d){return Promise.all(d.map(f=>Promise.resolve(f).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),c=a?.nonce||a?.getAttribute("nonce");r=l(n.map(d=>{if(d=Ah(d),d in Ja)return;Ja[d]=!0;const f=d.endsWith(".css"),u=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const m=document.createElement("link");if(m.rel=f?"stylesheet":Lh,f||(m.as="script"),m.crossOrigin="",m.href=d,c&&m.setAttribute("nonce",c),document.head.appendChild(m),f)return new Promise((p,g)=>{m.addEventListener("load",p),m.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return r.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return e().catch(i)})},Fh="0.4.0";var Li={};const K=t=>typeof t=="string",Rs=()=>{let t,e;const n=new Promise((s,r)=>{t=s,e=r});return n.resolve=t,n.reject=e,n},Ya=t=>t==null?"":""+t,Ih=(t,e,n)=>{t.forEach(s=>{e[s]&&(n[s]=e[s])})},Mh=/###/g,Xa=t=>t&&t.indexOf("###")>-1?t.replace(Mh,"."):t,Za=t=>!t||K(t),Is=(t,e,n)=>{const s=K(e)?e.split("."):e;let r=0;for(;r<s.length-1;){if(Za(t))return{};const i=Xa(s[r]);!t[i]&&n&&(t[i]=new n),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++r}return Za(t)?{}:{obj:t,k:Xa(s[r])}},Qa=(t,e,n)=>{const{obj:s,k:r}=Is(t,e,Object);if(s!==void 0||e.length===1){s[r]=n;return}let i=e[e.length-1],a=e.slice(0,e.length-1),c=Is(t,a,Object);for(;c.obj===void 0&&a.length;)i=`${a[a.length-1]}.${i}`,a=a.slice(0,a.length-1),c=Is(t,a,Object),c?.obj&&typeof c.obj[`${c.k}.${i}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${i}`]=n},$h=(t,e,n,s)=>{const{obj:r,k:i}=Is(t,e,Object);r[i]=r[i]||[],r[i].push(n)},$r=(t,e)=>{const{obj:n,k:s}=Is(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,s))return n[s]},Uh=(t,e,n)=>{const s=$r(t,n);return s!==void 0?s:$r(e,n)},ml=(t,e,n)=>{for(const s in e)s!=="__proto__"&&s!=="constructor"&&(s in t?K(t[s])||t[s]instanceof String||K(e[s])||e[s]instanceof String?n&&(t[s]=e[s]):ml(t[s],e[s],n):t[s]=e[s]);return t},gn=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var zh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Vh=t=>K(t)?t.replace(/[&<>"'\/]/g,e=>zh[e]):t;class Bh{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const s=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,s),this.regExpQueue.push(e),s}}const Hh=[" ",",","?","!",";"],qh=new Bh(20),Wh=(t,e,n)=>{e=e||"",n=n||"";const s=Hh.filter(a=>e.indexOf(a)<0&&n.indexOf(a)<0);if(s.length===0)return!0;const r=qh.getRegExp(`(${s.map(a=>a==="?"?"\\?":a).join("|")})`);let i=!r.test(t);if(!i){const a=t.indexOf(n);a>0&&!r.test(t.substring(0,a))&&(i=!0)}return i},oo=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const s=e.split(n);let r=t;for(let i=0;i<s.length;){if(!r||typeof r!="object")return;let a,c="";for(let l=i;l<s.length;++l)if(l!==i&&(c+=n),c+=s[l],a=r[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&l<s.length-1)continue;i+=l-i+1;break}r=a}return r},Us=t=>t?.replace(/_/g,"-"),Kh={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Ur{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||Kh,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,s,r){return r&&!this.debug?null:(K(e[0])&&(e[0]=`${s}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Ur(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ur(this.logger,e)}}var Nt=new Ur;class oi{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(s=>{this.observers[s]||(this.observers[s]=new Map);const r=this.observers[s].get(n)||0;this.observers[s].set(n,r+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([r,i])=>{for(let a=0;a<i;a++)r(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([r,i])=>{for(let a=0;a<i;a++)r.apply(r,[e,...n])})}}class ec extends oi{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,s,r={}){const i=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,a=r.ignoreJSONStructure!==void 0?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let c;e.indexOf(".")>-1?c=e.split("."):(c=[e,n],s&&(Array.isArray(s)?c.push(...s):K(s)&&i?c.push(...s.split(i)):c.push(s)));const l=$r(this.data,c);return!l&&!n&&!s&&e.indexOf(".")>-1&&(e=c[0],n=c[1],s=c.slice(2).join(".")),l||!a||!K(s)?l:oo(this.data?.[e]?.[n],s,i)}addResource(e,n,s,r,i={silent:!1}){const a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let c=[e,n];s&&(c=c.concat(a?s.split(a):s)),e.indexOf(".")>-1&&(c=e.split("."),r=n,n=c[1]),this.addNamespaces(n),Qa(this.data,c,r),i.silent||this.emit("added",e,n,s,r)}addResources(e,n,s,r={silent:!1}){for(const i in s)(K(s[i])||Array.isArray(s[i]))&&this.addResource(e,n,i,s[i],{silent:!0});r.silent||this.emit("added",e,n,s)}addResourceBundle(e,n,s,r,i,a={silent:!1,skipCopy:!1}){let c=[e,n];e.indexOf(".")>-1&&(c=e.split("."),r=s,s=n,n=c[1]),this.addNamespaces(n);let l=$r(this.data,c)||{};a.skipCopy||(s=JSON.parse(JSON.stringify(s))),r?ml(l,s,i):l={...l,...s},Qa(this.data,c,l),a.silent||this.emit("added",e,n,s)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(r=>n[r]&&Object.keys(n[r]).length>0)}toJSON(){return this.data}}var gl={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,s,r){return t.forEach(i=>{e=this.processors[i]?.process(e,n,s,r)??e}),e}};const yl=Symbol("i18next/PATH_KEY");function Gh(){const t=[],e=Object.create(null);let n;return e.get=(s,r)=>(n?.revoke?.(),r===yl?t:(t.push(r),n=Proxy.revocable(s,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Gn(t,e){const{[yl]:n}=t(Gh()),s=e?.keySeparator??".",r=e?.nsSeparator??":";if(n.length>1&&r){const i=e?.ns,a=Array.isArray(i)?i:null;if(a&&a.length>1&&a.slice(1).includes(n[0]))return`${n[0]}${r}${n.slice(1).join(s)}`}return n.join(s)}const tc={},Ai=t=>!K(t)&&typeof t!="boolean"&&typeof t!="number";class zr extends oi{constructor(e,n={}){super(),Ih(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Nt.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const s={...n};if(e==null)return!1;const r=this.resolve(e,s);if(r?.res===void 0)return!1;const i=Ai(r.res);return!(s.returnObjects===!1&&i)}extractFromKey(e,n){let s=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;s===void 0&&(s=":");const r=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let i=n.ns||this.options.defaultNS||[];const a=s&&e.indexOf(s)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Wh(e,s,r);if(a&&!c){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:K(i)?[i]:i};const d=e.split(s);(s!==r||s===r&&this.options.ns.indexOf(d[0])>-1)&&(i=d.shift()),e=d.join(r)}return{key:e,namespaces:K(i)?[i]:i}}translate(e,n,s){let r=typeof n=="object"?{...n}:n;if(typeof r!="object"&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),typeof r=="object"&&(r={...r}),r||(r={}),e==null)return"";typeof e=="function"&&(e=Gn(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(P=>typeof P=="function"?Gn(P,{...this.options,...r}):String(P));const i=r.returnDetails!==void 0?r.returnDetails:this.options.returnDetails,a=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,{key:c,namespaces:l}=this.extractFromKey(e[e.length-1],r),d=l[l.length-1];let f=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;f===void 0&&(f=":");const u=r.lng||this.language,m=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(u?.toLowerCase()==="cimode")return m?i?{res:`${d}${f}${c}`,usedKey:c,exactUsedKey:c,usedLng:u,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:`${d}${f}${c}`:i?{res:c,usedKey:c,exactUsedKey:c,usedLng:u,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:c;const p=this.resolve(e,r);let g=p?.res;const x=p?.usedKey||c,b=p?.exactUsedKey||c,j=["[object Number]","[object Function]","[object RegExp]"],C=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,N=!this.i18nFormat||this.i18nFormat.handleAsObject,T=r.count!==void 0&&!K(r.count),_=zr.hasDefaultValue(r),L=T?this.pluralResolver.getSuffix(u,r.count,r):"",E=r.ordinal&&T?this.pluralResolver.getSuffix(u,r.count,{ordinal:!1}):"",q=T&&!r.ordinal&&r.count===0,v=q&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${L}`]||r[`defaultValue${E}`]||r.defaultValue;let O=g;N&&!g&&_&&(O=v);const Z=Ai(O),W=Object.prototype.toString.apply(O);if(N&&O&&Z&&j.indexOf(W)<0&&!(K(C)&&Array.isArray(O))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const P=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,O,{...r,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return i?(p.res=P,p.usedParams=this.getUsedParamsDetails(r),p):P}if(a){const P=Array.isArray(O),R=P?[]:{},S=P?b:x;for(const F in O)if(Object.prototype.hasOwnProperty.call(O,F)){const le=`${S}${a}${F}`;_&&!g?R[F]=this.translate(le,{...r,defaultValue:Ai(v)?v[F]:void 0,joinArrays:!1,ns:l}):R[F]=this.translate(le,{...r,joinArrays:!1,ns:l}),R[F]===le&&(R[F]=O[F])}g=R}}else if(N&&K(C)&&Array.isArray(g))g=g.join(C),g&&(g=this.extendTranslation(g,e,r,s));else{let P=!1,R=!1;!this.isValidLookup(g)&&_&&(P=!0,g=v),this.isValidLookup(g)||(R=!0,g=c);const F=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&R?void 0:g,le=_&&v!==g&&this.options.updateMissing;if(R||P||le){if(this.logger.log(le?"updateKey":"missingKey",u,d,c,le?v:g),a){const ae=this.resolve(c,{...r,keySeparator:!1});ae&&ae.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Q=[];const ge=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ge&&ge[0])for(let ae=0;ae<ge.length;ae++)Q.push(ge[ae]);else this.options.saveMissingTo==="all"?Q=this.languageUtils.toResolveHierarchy(r.lng||this.language):Q.push(r.lng||this.language);const oe=(ae,he,Ce)=>{const B=_&&Ce!==g?Ce:F;this.options.missingKeyHandler?this.options.missingKeyHandler(ae,d,he,B,le,r):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(ae,d,he,B,le,r),this.emit("missingKey",ae,d,he,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&T?Q.forEach(ae=>{const he=this.pluralResolver.getSuffixes(ae,r);q&&r[`defaultValue${this.options.pluralSeparator}zero`]&&he.indexOf(`${this.options.pluralSeparator}zero`)<0&&he.push(`${this.options.pluralSeparator}zero`),he.forEach(Ce=>{oe([ae],c+Ce,r[`defaultValue${Ce}`]||v)})}):oe(Q,c,v))}g=this.extendTranslation(g,e,r,p,s),R&&g===c&&this.options.appendNamespaceToMissingKey&&(g=`${d}${f}${c}`),(R||P)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${f}${c}`:c,P?g:void 0,r))}return i?(p.res=g,p.usedParams=this.getUsedParamsDetails(r),p):g}extendTranslation(e,n,s,r,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});const l=K(e)&&(s?.interpolation?.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(l){const u=e.match(this.interpolator.nestingRegexp);d=u&&u.length}let f=s.replace&&!K(s.replace)?s.replace:s;if(this.options.interpolation.defaultVariables&&(f={...this.options.interpolation.defaultVariables,...f}),e=this.interpolator.interpolate(e,f,s.lng||this.language||r.usedLng,s),l){const u=e.match(this.interpolator.nestingRegexp),m=u&&u.length;d<m&&(s.nest=!1)}!s.lng&&r&&r.res&&(s.lng=this.language||r.usedLng),s.nest!==!1&&(e=this.interpolator.nest(e,(...u)=>i?.[0]===u[0]&&!s.context?(this.logger.warn(`It seems you are nesting recursively key: ${u[0]} in key: ${n[0]}`),null):this.translate(...u,n),s)),s.interpolation&&this.interpolator.reset()}const a=s.postProcess||this.options.postProcess,c=K(a)?[a]:a;return e!=null&&c?.length&&s.applyPostProcessor!==!1&&(e=gl.handle(c,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),e}resolve(e,n={}){let s,r,i,a,c;return K(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?Gn(l,{...this.options,...n}):l)),e.forEach(l=>{if(this.isValidLookup(s))return;const d=this.extractFromKey(l,n),f=d.key;r=f;let u=d.namespaces;this.options.fallbackNS&&(u=u.concat(this.options.fallbackNS));const m=n.count!==void 0&&!K(n.count),p=m&&!n.ordinal&&n.count===0,g=n.context!==void 0&&(K(n.context)||typeof n.context=="number")&&n.context!=="",x=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);u.forEach(b=>{this.isValidLookup(s)||(c=b,!tc[`${x[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(tc[`${x[0]}-${b}`]=!0,this.logger.warn(`key "${r}" for languages "${x.join(", ")}" won't get resolved as namespace "${c}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),x.forEach(j=>{if(this.isValidLookup(s))return;a=j;const C=[f];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(C,f,j,b,n);else{let T;m&&(T=this.pluralResolver.getSuffix(j,n.count,n));const _=`${this.options.pluralSeparator}zero`,L=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(n.ordinal&&T.indexOf(L)===0&&C.push(f+T.replace(L,this.options.pluralSeparator)),C.push(f+T),p&&C.push(f+_)),g){const E=`${f}${this.options.contextSeparator||"_"}${n.context}`;C.push(E),m&&(n.ordinal&&T.indexOf(L)===0&&C.push(E+T.replace(L,this.options.pluralSeparator)),C.push(E+T),p&&C.push(E+_))}}let N;for(;N=C.pop();)this.isValidLookup(s)||(i=N,s=this.getResource(j,b,N,n))}))})}),{res:s,usedKey:r,exactUsedKey:i,usedLng:a,usedNS:c}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,s,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,s,r):this.resourceStore.getResource(e,n,s,r)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=e.replace&&!K(e.replace);let r=s?e.replace:e;if(s&&typeof e.count<"u"&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!s){r={...r};for(const i of n)delete r[i]}return r}static hasDefaultValue(e){const n="defaultValue";for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&n===s.substring(0,n.length)&&e[s]!==void 0)return!0;return!1}}class nc{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Nt.create("languageUtils")}getScriptPartFromCode(e){if(e=Us(e),!e||e.indexOf("-")<0)return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=Us(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(K(e)&&e.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(s=>{if(n)return;const r=this.formatLanguageCode(s);(!this.options.supportedLngs||this.isSupportedCode(r))&&(n=r)}),!n&&this.options.supportedLngs&&e.forEach(s=>{if(n)return;const r=this.getScriptPartFromCode(s);if(this.isSupportedCode(r))return n=r;const i=this.getLanguagePartFromCode(s);if(this.isSupportedCode(i))return n=i;n=this.options.supportedLngs.find(a=>{if(a===i)return a;if(!(a.indexOf("-")<0&&i.indexOf("-")<0)&&(a.indexOf("-")>0&&i.indexOf("-")<0&&a.substring(0,a.indexOf("-"))===i||a.indexOf(i)===0&&i.length>1))return a})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),K(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let s=e[n];return s||(s=e[this.getScriptPartFromCode(n)]),s||(s=e[this.formatLanguageCode(n)]),s||(s=e[this.getLanguagePartFromCode(n)]),s||(s=e.default),s||[]}toResolveHierarchy(e,n){const s=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),r=[],i=a=>{a&&(this.isSupportedCode(a)?r.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return K(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):K(e)&&i(this.formatLanguageCode(e)),s.forEach(a=>{r.indexOf(a)<0&&i(this.formatLanguageCode(a))}),r}}const sc={zero:0,one:1,two:2,few:3,many:4,other:5},rc={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Jh{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Nt.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const s=Us(e==="dev"?"en":e),r=n.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:s,type:r});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(s,{type:r})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),rc;if(!e.match(/-|_/))return rc;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,n)}return this.pluralRulesCache[i]=a,a}needsPlural(e,n={}){let s=this.getRule(e,n);return s||(s=this.getRule("dev",n)),s?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,s={}){return this.getSuffixes(e,s).map(r=>`${n}${r}`)}getSuffixes(e,n={}){let s=this.getRule(e,n);return s||(s=this.getRule("dev",n)),s?s.resolvedOptions().pluralCategories.sort((r,i)=>sc[r]-sc[i]).map(r=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${r}`):[]}getSuffix(e,n,s={}){const r=this.getRule(e,s);return r?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${r.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,s))}}const ic=(t,e,n,s=".",r=!0)=>{let i=Uh(t,e,n);return!i&&r&&K(n)&&(i=oo(t,n,s),i===void 0&&(i=oo(e,n,s))),i},Fi=t=>t.replace(/\$/g,"$$$$");class oc{constructor(e={}){this.logger=Nt.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:s,useRawValueToEscape:r,prefix:i,prefixEscaped:a,suffix:c,suffixEscaped:l,formatSeparator:d,unescapeSuffix:f,unescapePrefix:u,nestingPrefix:m,nestingPrefixEscaped:p,nestingSuffix:g,nestingSuffixEscaped:x,nestingOptionsSeparator:b,maxReplaces:j,alwaysFormat:C}=e.interpolation;this.escape=n!==void 0?n:Vh,this.escapeValue=s!==void 0?s:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=i?gn(i):a||"{{",this.suffix=c?gn(c):l||"}}",this.formatSeparator=d||",",this.unescapePrefix=f?"":u||"-",this.unescapeSuffix=this.unescapePrefix?"":f||"",this.nestingPrefix=m?gn(m):p||gn("$t("),this.nestingSuffix=g?gn(g):x||gn(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=j||1e3,this.alwaysFormat=C!==void 0?C:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,s)=>n?.source===s?(n.lastIndex=0,n):new RegExp(s,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,s,r){let i,a,c;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=p=>{if(p.indexOf(this.formatSeparator)<0){const j=ic(n,l,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(j,void 0,s,{...r,...n,interpolationkey:p}):j}const g=p.split(this.formatSeparator),x=g.shift().trim(),b=g.join(this.formatSeparator).trim();return this.format(ic(n,l,x,this.options.keySeparator,this.options.ignoreJSONStructure),b,s,{...r,...n,interpolationkey:x})};this.resetRegExp();const f=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,u=r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:p=>Fi(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?Fi(this.escape(p)):Fi(p)}].forEach(p=>{for(c=0;i=p.regex.exec(e);){const g=i[1].trim();if(a=d(g),a===void 0)if(typeof f=="function"){const b=f(e,i,r);a=K(b)?b:""}else if(r&&Object.prototype.hasOwnProperty.call(r,g))a="";else if(u){a=i[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${e}`),a="";else!K(a)&&!this.useRawValueToEscape&&(a=Ya(a));const x=p.safeValue(a);if(e=e.replace(i[0],x),u?(p.regex.lastIndex+=a.length,p.regex.lastIndex-=i[0].length):p.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),e}nest(e,n,s={}){let r,i,a;const c=(l,d)=>{const f=this.nestingOptionsSeparator;if(l.indexOf(f)<0)return l;const u=l.split(new RegExp(`${gn(f)}[ ]*{`));let m=`{${u[1]}`;l=u[0],m=this.interpolate(m,a);const p=m.match(/'/g),g=m.match(/"/g);((p?.length??0)%2===0&&!g||(g?.length??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{a=JSON.parse(m),d&&(a={...d,...a})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,x),`${l}${f}${m}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;r=this.nestingRegexp.exec(e);){let l=[];a={...s},a=a.replace&&!K(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const d=/{.*}/.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(d!==-1&&(l=r[1].slice(d).split(this.formatSeparator).map(f=>f.trim()).filter(Boolean),r[1]=r[1].slice(0,d)),i=n(c.call(this,r[1].trim(),a),a),i&&r[0]===e&&!K(i))return i;K(i)||(i=Ya(i)),i||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),i=""),l.length&&(i=l.reduce((f,u)=>this.format(f,u,s.lng,{...s,interpolationkey:r[1].trim()}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}}const Yh=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const s=t.split("(");e=s[0].toLowerCase().trim();const r=s[1].substring(0,s[1].length-1);e==="currency"&&r.indexOf(":")<0?n.currency||(n.currency=r.trim()):e==="relativetime"&&r.indexOf(":")<0?n.range||(n.range=r.trim()):r.split(";").forEach(a=>{if(a){const[c,...l]=a.split(":"),d=l.join(":").trim().replace(/^'+|'+$/g,""),f=c.trim();n[f]||(n[f]=d),d==="false"&&(n[f]=!1),d==="true"&&(n[f]=!0),isNaN(d)||(n[f]=parseInt(d,10))}})}return{formatName:e,formatOptions:n}},ac=t=>{const e={};return(n,s,r)=>{let i=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(i={...i,[r.interpolationkey]:void 0});const a=s+JSON.stringify(i);let c=e[a];return c||(c=t(Us(s),r),e[a]=c),c(n)}},Xh=t=>(e,n,s)=>t(Us(n),s)(e);class Zh{constructor(e={}){this.logger=Nt.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const s=n.cacheInBuiltFormats?ac:Xh;this.formats={number:s((r,i)=>{const a=new Intl.NumberFormat(r,{...i});return c=>a.format(c)}),currency:s((r,i)=>{const a=new Intl.NumberFormat(r,{...i,style:"currency"});return c=>a.format(c)}),datetime:s((r,i)=>{const a=new Intl.DateTimeFormat(r,{...i});return c=>a.format(c)}),relativetime:s((r,i)=>{const a=new Intl.RelativeTimeFormat(r,{...i});return c=>a.format(c,i.range||"day")}),list:s((r,i)=>{const a=new Intl.ListFormat(r,{...i});return c=>a.format(c)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=ac(n)}format(e,n,s,r={}){const i=n.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(c=>c.indexOf(")")>-1)){const c=i.findIndex(l=>l.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,c)].join(this.formatSeparator)}return i.reduce((c,l)=>{const{formatName:d,formatOptions:f}=Yh(l);if(this.formats[d]){let u=c;try{const m=r?.formatParams?.[r.interpolationkey]||{},p=m.locale||m.lng||r.locale||r.lng||s;u=this.formats[d](c,p,{...f,...r,...m})}catch(m){this.logger.warn(m)}return u}else this.logger.warn(`there was no format function for ${d}`);return c},e)}}const Qh=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class ef extends oi{constructor(e,n,s,r={}){super(),this.backend=e,this.store=n,this.services=s,this.languageUtils=s.languageUtils,this.options=r,this.logger=Nt.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(s,r.backend,r)}queueLoad(e,n,s,r){const i={},a={},c={},l={};return e.forEach(d=>{let f=!0;n.forEach(u=>{const m=`${d}|${u}`;!s.reload&&this.store.hasResourceBundle(d,u)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?a[m]===void 0&&(a[m]=!0):(this.state[m]=1,f=!1,a[m]===void 0&&(a[m]=!0),i[m]===void 0&&(i[m]=!0),l[u]===void 0&&(l[u]=!0)))}),f||(c[d]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(c),toLoadNamespaces:Object.keys(l)}}loaded(e,n,s){const r=e.split("|"),i=r[0],a=r[1];n&&this.emit("failedLoading",i,a,n),!n&&s&&this.store.addResourceBundle(i,a,s,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&s&&(this.state[e]=0);const c={};this.queue.forEach(l=>{$h(l.loaded,[i],a),Qh(l,e),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(d=>{c[d]||(c[d]={});const f=l.loaded[d];f.length&&f.forEach(u=>{c[d][u]===void 0&&(c[d][u]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(l=>!l.done)}read(e,n,s,r=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:s,tried:r,wait:i,callback:a});return}this.readingCalls++;const c=(d,f)=>{if(this.readingCalls--,this.waitingReads.length>0){const u=this.waitingReads.shift();this.read(u.lng,u.ns,u.fcName,u.tried,u.wait,u.callback)}if(d&&f&&r<this.maxRetries){setTimeout(()=>{this.read.call(this,e,n,s,r+1,i*2,a)},i);return}a(d,f)},l=this.backend[s].bind(this.backend);if(l.length===2){try{const d=l(e,n);d&&typeof d.then=="function"?d.then(f=>c(null,f)).catch(c):c(null,d)}catch(d){c(d)}return}return l(e,n,c)}prepareLoading(e,n,s={},r){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();K(e)&&(e=this.languageUtils.toResolveHierarchy(e)),K(n)&&(n=[n]);const i=this.queueLoad(e,n,s,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach(a=>{this.loadOne(a)})}load(e,n,s){this.prepareLoading(e,n,{},s)}reload(e,n,s){this.prepareLoading(e,n,{reload:!0},s)}loadOne(e,n=""){const s=e.split("|"),r=s[0],i=s[1];this.read(r,i,"read",void 0,void 0,(a,c)=>{a&&this.logger.warn(`${n}loading namespace ${i} for language ${r} failed`,a),!a&&c&&this.logger.log(`${n}loaded namespace ${i} for language ${r}`,c),this.loaded(e,a,c)})}saveMissing(e,n,s,r,i,a={},c=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${s}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(s==null||s==="")){if(this.backend?.create){const l={...a,isUpdate:i},d=this.backend.create.bind(this.backend);if(d.length<6)try{let f;d.length===5?f=d(e,n,s,r,l):f=d(e,n,s,r),f&&typeof f.then=="function"?f.then(u=>c(null,u)).catch(c):c(null,f)}catch(f){c(f)}else d(e,n,s,r,c,l)}!e||!e[0]||this.store.addResource(e[0],n,s,r)}}}const Ii=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),K(t[1])&&(e.defaultValue=t[1]),K(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(s=>{e[s]=n[s]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),cc=t=>(K(t.ns)&&(t.ns=[t.ns]),K(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),K(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),Cr=()=>{},tf=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})},wl="__i18next_supportNoticeShown",nf=()=>!!(typeof globalThis<"u"&&globalThis[wl]||typeof process<"u"&&Li&&Li.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&Li),sf=()=>{typeof globalThis<"u"&&(globalThis[wl]=!0)},rf=t=>!!(t?.modules?.backend?.name?.indexOf("Locize")>0||t?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||t?.options?.backend?.backends&&t.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||t?.options?.backend?.projectId||t?.options?.backend?.backendOptions&&t.options.backend.backendOptions.some(e=>e?.projectId));class Ms extends oi{constructor(e={},n){if(super(),this.options=cc(e),this.services={},this.logger=Nt,this.modules={external:[]},tf(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(K(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const s=Ii();this.options={...s,...this.options,...cc(e)},this.options.interpolation={...s.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=s.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!rf(this)&&!nf()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),sf());const r=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Nt.init(r(this.modules.logger),this.options):Nt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=Zh;const f=new nc(this.options);this.store=new ec(this.options.resources,this.options);const u=this.services;u.logger=Nt,u.resourceStore=this.store,u.languageUtils=f,u.pluralResolver=new Jh(f,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==s.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(u.formatter=r(d),u.formatter.init&&u.formatter.init(u,this.options),this.options.interpolation.format=u.formatter.format.bind(u.formatter)),u.interpolator=new oc(this.options),u.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},u.backendConnector=new ef(r(this.modules.backend),u.resourceStore,u,this.options),u.backendConnector.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.languageDetector&&(u.languageDetector=r(this.modules.languageDetector),u.languageDetector.init&&u.languageDetector.init(u,this.options.detection,this.options)),this.modules.i18nFormat&&(u.i18nFormat=r(this.modules.i18nFormat),u.i18nFormat.init&&u.i18nFormat.init(this)),this.translator=new zr(this.services,this.options),this.translator.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,n||(n=Cr),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=(...f)=>this.store[d](...f)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...f)=>(this.store[d](...f),this)});const c=Rs(),l=()=>{const d=(f,u)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(u),n(f,u)};if(this.languages&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(e,n=Cr){let s=n;const r=K(e)?e:this.language;if(typeof e=="function"&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if(r?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return s();const i=[],a=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(d=>{d!=="cimode"&&i.indexOf(d)<0&&i.push(d)})};r?a(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>a(l)),this.options.preload?.forEach?.(c=>a(c)),this.services.backendConnector.load(i,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),s(c)})}else s(null)}reloadResources(e,n,s){const r=Rs();return typeof e=="function"&&(s=e,e=void 0),typeof n=="function"&&(s=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),s||(s=Cr),this.services.backendConnector.reload(e,n,i=>{r.resolve(),s(i)}),r}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&gl.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let n=0;n<this.languages.length;n++){const s=this.languages[n];if(!(["cimode","dev"].indexOf(s)>-1)&&this.store.hasLanguageSomeTranslations(s)){this.resolvedLanguage=s;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const s=Rs();this.emit("languageChanging",e);const r=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},i=(c,l)=>{l?this.isLanguageChangingTo===e&&(r(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,s.resolve((...d)=>this.t(...d)),n&&n(c,(...d)=>this.t(...d))},a=c=>{!e&&!c&&this.services.languageDetector&&(c=[]);const l=K(c)?c:c&&c[0],d=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(K(c)?[c]:c);d&&(this.language||r(d),this.translator.language||this.translator.changeLanguage(d),this.services.languageDetector?.cacheUserLanguage?.(d)),this.loadResources(d,f=>{i(f,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),s}getFixedT(e,n,s){const r=(i,a,...c)=>{let l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([i,a].concat(c)):l={...a},l.lng=l.lng||r.lng,l.lngs=l.lngs||r.lngs,l.ns=l.ns||r.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||s||r.keyPrefix);const d={...this.options,...l};typeof l.keyPrefix=="function"&&(l.keyPrefix=Gn(l.keyPrefix,d));const f=this.options.keySeparator||".";let u;return l.keyPrefix&&Array.isArray(i)?u=i.map(m=>(typeof m=="function"&&(m=Gn(m,d)),`${l.keyPrefix}${f}${m}`)):(typeof i=="function"&&(i=Gn(i,d)),u=l.keyPrefix?`${l.keyPrefix}${f}${i}`:i),this.t(u,l)};return K(e)?r.lng=e:r.lngs=e,r.ns=n,r.keyPrefix=s,r}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const s=n.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(s.toLowerCase()==="cimode")return!0;const a=(c,l)=>{const d=this.services.backendConnector.state[`${c}|${l}`];return d===-1||d===0||d===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(s,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(s,e)&&(!r||a(i,e)))}loadNamespaces(e,n){const s=Rs();return this.options.ns?(K(e)&&(e=[e]),e.forEach(r=>{this.options.ns.indexOf(r)<0&&this.options.ns.push(r)}),this.loadResources(r=>{s.resolve(),n&&n(r)}),s):(n&&n(),Promise.resolve())}loadLanguages(e,n){const s=Rs();K(e)&&(e=[e]);const r=this.options.preload||[],i=e.filter(a=>r.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return i.length?(this.options.preload=r.concat(i),this.loadResources(a=>{s.resolve(),n&&n(a)}),s):(n&&n(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const r=new Intl.Locale(e);if(r&&r.getTextInfo){const i=r.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],s=this.services?.languageUtils||new nc(Ii());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(s.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const s=new Ms(e,n);return s.createInstance=Ms.createInstance,s}cloneInstance(e={},n=Cr){const s=e.forkResourceStore;s&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},i=new Ms(r);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(c=>{i[c]=this[c]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},s){const c=Object.keys(this.store.data).reduce((l,d)=>(l[d]={...this.store.data[d]},l[d]=Object.keys(l[d]).reduce((f,u)=>(f[u]={...l[d][u]},f),l[d]),l),{});i.store=new ec(c,r),i.services.resourceStore=i.store}if(e.interpolation){const l={...Ii().interpolation,...this.options.interpolation,...e.interpolation},d={...r,interpolation:l};i.services.interpolator=new oc(d)}return i.translator=new zr(i.services,r),i.translator.on("*",(c,...l)=>{i.emit(c,...l)}),i.init(r,n),i.translator.options=r,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const we=Ms.createInstance();we.createInstance;we.dir;we.init;we.loadResources;we.reloadResources;we.use;we.changeLanguage;we.getFixedT;we.t;we.exists;we.setDefaultNamespace;we.hasLoadedNamespace;we.loadNamespaces;we.loadLanguages;const{slice:of,forEach:af}=[];function cf(t){return af.call(of.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function lf(t){return typeof t!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(t))}const lc=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,df=function(t,e){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},r=encodeURIComponent(e);let i=`${t}=${r}`;if(s.maxAge>0){const a=s.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(a)}`}if(s.domain){if(!lc.test(s.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${s.domain}`}if(s.path){if(!lc.test(s.path))throw new TypeError("option path is invalid");i+=`; Path=${s.path}`}if(s.expires){if(typeof s.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+=`; Expires=${s.expires.toUTCString()}`}if(s.httpOnly&&(i+="; HttpOnly"),s.secure&&(i+="; Secure"),s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s.partitioned&&(i+="; Partitioned"),i},dc={create(t,e,n,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(r.expires=new Date,r.expires.setTime(r.expires.getTime()+n*60*1e3)),s&&(r.domain=s),document.cookie=df(t,e,r)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let s=0;s<n.length;s++){let r=n[s];for(;r.charAt(0)===" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return r.substring(e.length,r.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var uf={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return dc.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:r,cookieOptions:i}=e;n&&typeof document<"u"&&dc.create(n,t,s,r,i)}},hf={name:"querystring",lookup(t){let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:s}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(s=window.location.hash.substring(window.location.hash.indexOf("?")));const i=s.substring(1).split("&");for(let a=0;a<i.length;a++){const c=i[a].indexOf("=");c>0&&i[a].substring(0,c)===e&&(n=i[a].substring(c+1))}}return n}},ff={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,s;if(typeof window<"u"){const{hash:r}=window.location;if(r&&r.length>2){const i=r.substring(1);if(e){const a=i.split("&");for(let c=0;c<a.length;c++){const l=a[c].indexOf("=");l>0&&a[c].substring(0,l)===e&&(s=a[c].substring(l+1))}}if(s)return s;if(!s&&n>-1){const a=r.match(/\/([a-zA-Z-]*)/g);return Array.isArray(a)?a[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return s}};let Fn=null;const uc=()=>{if(Fn!==null)return Fn;try{if(Fn=typeof window<"u"&&window.localStorage!==null,!Fn)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Fn=!1}return Fn};var pf={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&uc())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&uc()&&window.localStorage.setItem(n,t)}};let In=null;const hc=()=>{if(In!==null)return In;try{if(In=typeof window<"u"&&window.sessionStorage!==null,!In)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{In=!1}return In};var mf={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&hc())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&hc()&&window.sessionStorage.setItem(n,t)}},gf={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:s,language:r}=navigator;if(n)for(let i=0;i<n.length;i++)e.push(n[i]);s&&e.push(s),r&&e.push(r)}return e.length>0?e:void 0}},yf={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const s=e||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(n=s.getAttribute("lang")),n}},wf={name:"path",lookup(t){let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?n[typeof e=="number"?e:0]?.replace("/",""):void 0}},xf={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,s=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(s)return s[n]}};let xl=!1;try{document.cookie,xl=!0}catch{}const bl=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];xl||bl.splice(1,1);const bf=()=>({order:bl,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class vl{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=cf(n,this.options||{},bf()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=r=>r.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=s,this.addDetector(uf),this.addDetector(hf),this.addDetector(pf),this.addDetector(mf),this.addDetector(gf),this.addDetector(yf),this.addDetector(wf),this.addDetector(xf),this.addDetector(ff)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(s=>{if(this.detectors[s]){let r=this.detectors[s].lookup(this.options);r&&typeof r=="string"&&(r=[r]),r&&(n=n.concat(r))}}),n=n.filter(s=>s!=null&&!lf(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(e,this.options)}))}}vl.type="languageDetector";const vf={cancel:"Cancel",create:"Create",add:"Add",remove:"Remove",delete:"Delete",close:"Close",user:"User",permission:"Permission",readOnly:"Read only",readWrite:"Read & write",settings:"Settings",comments:"Comments",files:"Files",outline:"Outline",loading:"Loading…",enabled:"Enabled",disabled:"Disabled",normal:"Active",admin:"Administrator",language:"Language",languageEnglish:"English",languageChinese:"中文"},Sf={tagline:"A lightweight LaTeX writing environment",username:"Username",password:"Password",login:"Sign in",contact:"Need an account? Contact {{email}}",firstLogin:"Change your temporary password to continue",currentPassword:"Current password",newPassword:"New password",confirmPassword:"Confirm new password",updatePassword:"Update password",mismatch:"The new passwords do not match",passwordMinimum:"At least {{count}} characters",sessionExpired:"Your session has expired. Please sign in again.",logout:"Sign out"},jf={title:"Projects",subtitle:"Create, edit and share LaTeX documents",restricted:"You can access projects shared with you. Project creation requires administrator permission.",new:"New project",newDescription:"The project will use the configured default LaTeX engine.",name:"Project name",emptyTitle:"Let’s build something great",emptyDescription:"Create a project or upload an existing LaTeX archive to get started.",emptyRestricted:"Projects shared with you will appear here.",noMatches:"No projects match the current search or tag filter.",upload:"Upload project",uploadDescription:"Upload a ZIP archive. A single top-level folder is removed automatically. Maximum file size: {{size}} MB.",zipFile:"ZIP archive",import:"Import project",importing:"Importing…",search:"Search projects…",grid:"Grid",list:"List",scope:"Project status",active:"Active",archived:"Archived",archive:"Archive",unarchive:"Restore",noArchived:"No archived projects.",allTags:"All tags",sortBy:"Sort",sortModified:"Last modified",sortCreated:"Created",pagination:"Project pages",pageOf:"Page {{page}} of {{totalPages}} · {{count}} projects",previousPage:"Previous",nextPage:"Next",owner:"Owner",created:"Created",modified:"Last modified",modifiedBy:"Modified by",byUser:"By {{user}}",modifiedByUser:"{{time}} · By {{user}}",deletedUser:"Deleted user",filterTags:"Filter by tag",rename:"Rename",renameTitle:"Rename project",duplicate:"Duplicate",duplicating:"Duplicating…",duplicateTitle:"Duplicate project",duplicateDescription:"Create an independent copy of {{project}}. Files and project settings are copied; members, comments, Git history and compile output are not.",transfer:"Transfer",transferOwnership:"Transfer ownership",transferDescription:"Choose a new owner for {{project}}.",newOwner:"New owner",chooseNewOwner:"Choose a user",noTransferUsers:"No other active users",transferWarning:"You will keep read/write access. Source files, history, comments and members remain; the saved GitHub token is removed so the new owner can add their own credential.",transferForbidden:"Only the current project owner can transfer ownership.",transferTargetInvalid:"Choose a new project owner.",transferSelf:"You already own this project.",download:"Download",deleteTitle:"Delete project",deleteDescription:"Permanently delete {{project}} and all of its files? This cannot be undone.",chooseZip:"Choose a ZIP project",dropZip:"Drag and drop a ZIP archive here",browse:"Browse files",selectedFileSize:"Selected · {{size}}",clearFile:"Clear selected file"},Cf={manage:"User management",back:"Back to projects",onlyAdmin:"Only administrators can create users",add:"Add user",role:"Role",createProjects:"Create projects",ownedProjects:"Owned projects",status:"Status",actions:"Actions",adminRequired:"Administrator permission is required.",allow:"Allow",deny:"Deny",enable:"Enable",disable:"Disable",promote:"Make administrator",demote:"Make user",allowCreate:"Allow creation",denyCreate:"Deny creation",resetPassword:"Reset password",initialPassword:"Login password",displayName:"Display name",addDescription:"Set a login password or generate a secure random one.",createUser:"Create user",randomPassword:"Random password",generatePassword:"Generate a random password",resetDescription:"Set a temporary password for {{username}}. Existing sessions will be signed out.",reset:"Reset",deleteTitle:"Delete user",deleteDescription:"Delete {{username}}? This cannot be undone.",ownedChoice:"{{count}} owned projects",transferProjects:"Transfer them to the current administrator",deleteProjects:"Permanently delete projects and files"},kf={saved:"Saved",savedAt:"Saved to server at {{time}}",loading:"Loading",pending:"Waiting to save",saving:"Saving to server",saveFailed:"Save failed",offlineDraft:"Offline · local draft retained",compile:"Compile · {{engine}}",compiling:"Compiling…",compileQueued:"Compile queued…",compileFailedRetained:"Compilation failed; showing the last successful PDF from {{time}}.",compileFailedNoPdf:"Compilation failed and no successful PDF is available.",upToDate:"Files are up to date; no compilation was needed.",addComment:"Add comment",sourceComments:"Source comments",projectSettings:"Project settings",uploadAttachment:"Upload attachment",newFile:"New text file",binary:"The binary attachment is stored but cannot be opened in the text editor.",noOutline:"No sections in this file",preview:"PDF preview",previewHint:"Compile to generate the document",pdfCompiledAt:"Compiled successfully at {{time}}",pdfCompiledAtFor:"{{file}} compiled successfully at {{time}}",currentMainDocument:"Current document compiled as the root: {{path}}",mainDocumentCandidate:"LaTeX root document candidate: {{path}}",currentMainShort:"root",deletedUser:"Deleted User",orphaned:"Anchor lost",line:"Line {{line}}",reopen:"Reopen",resolve:"Mark resolved",noComments:"No comments in this file",newFileDescription:"Directories are allowed, for example chapters/introduction.tex.",filePath:"File path",commentDescription:"Selected {{count}} characters",pointComment:"No text selected; the comment will be anchored at the cursor.",commentContent:"Comment",backToProjects:"Back to projects",outputTabs:"Compile output",log:"Log",warnings:"Warnings",errors:"Errors",artifacts:"Artifacts",noLog:"Compile to see the log.",noWarnings:"No warnings in the latest compile.",noErrors:"No errors in the latest compile.",projectRoot:"Project root",uploadTo:"Upload to {{folder}}",dropFiles:"Drop files to upload",newFolder:"New folder",folderName:"Folder name",noArtifacts:"Compile to see generated artifacts.",selectArtifact:"Select a text artifact to preview it.",viewArtifact:"View artifact",downloadArtifact:"Download artifact",downloadToView:"Download this artifact to view it",folderDestination:"The folder will be created in {{folder}}.",uploadOverwriteTitle:"File already exists",uploadOverwriteDescription:"These files already exist: {{files}}. Replace them?",uploadOverwrite:"Replace files",collapseFiles:"Collapse file panel",move:"Move",moveTitle:"Move {{name}}",moveDescription:"Choose a destination folder. Files, comments and project paths stay linked.",deletePath:"Delete file or folder",deletePathTitle:"Delete {{name}}",deletePathDescription:"Delete {{path}}? This cannot be undone.",deletePathActiveDescription:"Delete {{path}}? It is currently open for {{users}} and will close in those sessions.",deletePathWillClose:"Any late edits to this path will be rejected to prevent silent data loss.",fileDeletedByCollaborator:"{{path}} was deleted in another session. A safe fallback file has been opened.",destinationFolder:"Destination folder",compileShortcut:"Save and compile (Ctrl+S / Cmd+S)",compilingBy:"{{name}} is compiling",formatSelection:"Format selection",formatting:"Formatting…",formatSelectionHint:"Select LaTeX source to format",formatSelectionRequired:"Select LaTeX source before formatting.",formatSelectionComplete:"Selected LaTeX source formatted.",formatFailedContinue:"Formatting failed; compilation will continue: {{message}}",formatFailed:"Unable to format the selection: {{message}}",formatSourceChanged:"The source changed during formatting, so formatting was skipped.",formatSelectionChanged:"The selected source changed during formatting. Select it again and retry.",vimOn:"Vim ON",vimOnHint:"Vim keybindings are enabled for this editor.",reply:"Reply",replyPlaceholder:"Write a reply…",sendReply:"Send reply",editComment:"Edit comment",deleteComment:"Delete comment",saveChanges:"Save changes",deleteCommentTitle:"Delete comment",deleteCommentDescription:"Delete this comment and its {{count}} replies? This cannot be undone.",editReply:"Edit reply",deleteReply:"Delete reply",deleteReplyTitle:"Delete reply",deleteReplyDescription:"Delete this reply? This cannot be undone.",editedAt:"Edited {{time}}",outlineJump:"Go to source line {{line}} and locate it in the PDF",lineNumber:"line {{line}}",showInSource:"Show the visible PDF location in source",showInPdf:"Show the source cursor location in PDF",pdfLoadFailed:"The PDF preview could not be loaded",pdfZoomControls:"PDF zoom controls",downloadPdf:"Download PDF",downloadResource:"Download file",resourceTooLarge:"This file is {{size}} and exceeds the direct preview limit of {{limit}}.",resourceTooLargeTitle:"File is too large to preview",resourceTooLargeDescription:"Download the file to open it locally.",resourceUnsupportedTitle:"Preview unavailable",resourceUnsupportedDescription:"This file type cannot be rendered in the browser. Download it to open it locally.",resourcePreview:{image:"Image preview",pdf:"PDF preview",text:"Text preview",unsupported:"File preview"},pdfZoomOut:"Zoom out",pdfZoomIn:"Zoom in",pdfFitWidth:"Fit width",layout:{label:"Layout",choose:"Choose layout",current:"Current layout: {{layout}}","editor-pdf":{name:"Editor & PDF",description:"Show the source editor and PDF preview side by side"},"editor-only":{name:"Editor only",description:"Use the workspace for source editing"},"pdf-only":{name:"PDF only",description:"Use the workspace for the PDF and compile output"}},collaboration:{connecting:"Connecting collaboration…",connected:"Live collaboration connected",disconnected:"Collaboration disconnected",editing:"Editing",viewing:"Viewing",joining:"Joining project",reconnect:"Reconnect",activeSessions:"{{count}} active sessions",showMoreSessions:"Show {{count}} more sessions",showFewerSessions:"Collapse session list",sessionTooltip:"{{name}} (@{{username}}) · {{file}} · {{activity}} · {{permission}}"},search:{button:"Find",title:"Find and replace (Ctrl+F / Cmd+F)",find:"Find",replace:"Replace",next:"Next",previous:"Previous",all:"Select all",matchCase:"Match case",regexp:"Regular expression",wholeWord:"Whole word",replaceNext:"Replace",replaceAll:"Replace all",currentMatch:"Current match",onLine:"on line",replacedMatchOnLine:"replaced match on line $",replacedMatches:"replaced $ matches",goToLine:"Go to line",go:"Go",matchCount:"{{count}} matches",noMatches:"No matches",invalidQuery:"Invalid regular expression"}},Ef={quickOpen:"Quick open",quickOpenDescription:"Open a project file by name (Ctrl/Cmd+P).",filePlaceholder:"Type a file name…",noFiles:"No matching files.",projectSearch:"Project search",projectSearchDescription:"Search and replace across project source files (Ctrl/Cmd+Shift+F).",searchPlaceholder:"Search all source files…",replacePlaceholder:"Replace with…",matchSummary:"{{count}} matches",truncated:"Showing the first {{count}} matches.",replaceAll:"Replace all {{count}}",replaceConfirmTitle:"Replace across the project",replaceConfirmDescription:"Replace all {{count}} matches? Automatic history records every changed file first.",replaced:"Replaced {{count}} matches in {{files}} files."},Df={title:"History",description:"Browse automatic project versions, compare files and safely restore earlier work.",empty:"No history versions yet.",changedCount:"{{count}} changed files",fileCount:"{{count}} files",changed:"changed",labelPlaceholder:"Name this version",saveLabel:"Save label",compareCurrent:"Compare with current",comparingCurrent:"Earlier version compared with the current file",chooseFile:"Choose a file, then compare it with the current source.",restore:"Restore",restoreFile:"Restore file",restoreProject:"Restore project",restoreFileTitle:"Restore this file",restoreProjectTitle:"Restore this project version",restoreFileDescription:"Restore {{path}} from this version? The current project is checkpointed first.",restoreProjectDescription:"Restore all source files and compiler settings from this version? The current project is checkpointed first.",storage:"History storage",storageUsage:"{{used}} of {{limit}}",versionUsage:"{{count}} of {{limit}} ordinary versions",protectedVersions:"{{count}} labeled",storageExceeded:"Protected or current data exceeds the soft storage limit.",deleteVersion:"Delete version",deleteVersionTitle:"Delete this history version",deleteVersionDescription:"Permanently delete {{name}}? Current project files are not changed.",clearAll:"Clear history",clearAllTitle:"Clear all project history",clearAllDescription:"Permanently delete every history version and its unreferenced stored data? Current project files are not changed.",reasons:{initial:"Project created",autosave:"Automatic save",file:"File operation",settings:"Compiler settings",git:"Git operation",restore:"Restored version",checkpoint:"Safety checkpoint"}},Nf={mainFile:"Main document",engine:"Compiler",latexmkrc:"Project latexmkrc",save:"Save project settings",members:"Shared members",recentLog:"Latest compile log",share:"Share project",shareDescription:"Projects can only be shared with users created by an administrator.",chooseUser:"Choose a user",latexmkrcPlaceholder:`# Empty disables the project rc file
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-rBWMBTI-.js","assets/react-CsO_xvbl.js","assets/spellCheck-ClNG2x_t.js","assets/PdfPreview-YbXIaedo.js","assets/pdf-DPnwNQHb.js","assets/plus-CvyFTTaw.js","assets/LatexEditor-ytqaJMkb.js","assets/editor-DMLs-XWi.js","assets/GitDialog-Cf5wW5Wn.js","assets/HistoryDialog-CXb-MzXH.js","assets/ProjectNavigationDialogs-BMz-OL3a.js","assets/SystemMetricsDialog-BLfDSaDc.js"])))=>i.map(i=>d[i]);
2
+ import{i as Oh,r as h,j as o,R as nr,a as pl,b as _h,u as Pe,P as Ph,c as jr,d as Ri,e as Rh}from"./react-CsO_xvbl.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();const Lh="modulepreload",Ah=function(t){return"/"+t},Ja={},Jt=function(e,n,s){let r=Promise.resolve();if(n&&n.length>0){let l=function(d){return Promise.all(d.map(f=>Promise.resolve(f).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),c=a?.nonce||a?.getAttribute("nonce");r=l(n.map(d=>{if(d=Ah(d),d in Ja)return;Ja[d]=!0;const f=d.endsWith(".css"),u=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const m=document.createElement("link");if(m.rel=f?"stylesheet":Lh,f||(m.as="script"),m.crossOrigin="",m.href=d,c&&m.setAttribute("nonce",c),document.head.appendChild(m),f)return new Promise((p,g)=>{m.addEventListener("load",p),m.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return r.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return e().catch(i)})},Fh="0.4.1";var Li={};const K=t=>typeof t=="string",Rs=()=>{let t,e;const n=new Promise((s,r)=>{t=s,e=r});return n.resolve=t,n.reject=e,n},Ya=t=>t==null?"":""+t,Ih=(t,e,n)=>{t.forEach(s=>{e[s]&&(n[s]=e[s])})},Mh=/###/g,Xa=t=>t&&t.indexOf("###")>-1?t.replace(Mh,"."):t,Za=t=>!t||K(t),Is=(t,e,n)=>{const s=K(e)?e.split("."):e;let r=0;for(;r<s.length-1;){if(Za(t))return{};const i=Xa(s[r]);!t[i]&&n&&(t[i]=new n),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++r}return Za(t)?{}:{obj:t,k:Xa(s[r])}},Qa=(t,e,n)=>{const{obj:s,k:r}=Is(t,e,Object);if(s!==void 0||e.length===1){s[r]=n;return}let i=e[e.length-1],a=e.slice(0,e.length-1),c=Is(t,a,Object);for(;c.obj===void 0&&a.length;)i=`${a[a.length-1]}.${i}`,a=a.slice(0,a.length-1),c=Is(t,a,Object),c?.obj&&typeof c.obj[`${c.k}.${i}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${i}`]=n},$h=(t,e,n,s)=>{const{obj:r,k:i}=Is(t,e,Object);r[i]=r[i]||[],r[i].push(n)},$r=(t,e)=>{const{obj:n,k:s}=Is(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,s))return n[s]},Uh=(t,e,n)=>{const s=$r(t,n);return s!==void 0?s:$r(e,n)},ml=(t,e,n)=>{for(const s in e)s!=="__proto__"&&s!=="constructor"&&(s in t?K(t[s])||t[s]instanceof String||K(e[s])||e[s]instanceof String?n&&(t[s]=e[s]):ml(t[s],e[s],n):t[s]=e[s]);return t},gn=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var zh={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Vh=t=>K(t)?t.replace(/[&<>"'\/]/g,e=>zh[e]):t;class Bh{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const s=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,s),this.regExpQueue.push(e),s}}const Hh=[" ",",","?","!",";"],qh=new Bh(20),Wh=(t,e,n)=>{e=e||"",n=n||"";const s=Hh.filter(a=>e.indexOf(a)<0&&n.indexOf(a)<0);if(s.length===0)return!0;const r=qh.getRegExp(`(${s.map(a=>a==="?"?"\\?":a).join("|")})`);let i=!r.test(t);if(!i){const a=t.indexOf(n);a>0&&!r.test(t.substring(0,a))&&(i=!0)}return i},oo=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const s=e.split(n);let r=t;for(let i=0;i<s.length;){if(!r||typeof r!="object")return;let a,c="";for(let l=i;l<s.length;++l)if(l!==i&&(c+=n),c+=s[l],a=r[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&l<s.length-1)continue;i+=l-i+1;break}r=a}return r},Us=t=>t?.replace(/_/g,"-"),Kh={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Ur{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||Kh,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,s,r){return r&&!this.debug?null:(K(e[0])&&(e[0]=`${s}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Ur(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ur(this.logger,e)}}var Nt=new Ur;class oi{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(s=>{this.observers[s]||(this.observers[s]=new Map);const r=this.observers[s].get(n)||0;this.observers[s].set(n,r+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([r,i])=>{for(let a=0;a<i;a++)r(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([r,i])=>{for(let a=0;a<i;a++)r.apply(r,[e,...n])})}}class ec extends oi{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,s,r={}){const i=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,a=r.ignoreJSONStructure!==void 0?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let c;e.indexOf(".")>-1?c=e.split("."):(c=[e,n],s&&(Array.isArray(s)?c.push(...s):K(s)&&i?c.push(...s.split(i)):c.push(s)));const l=$r(this.data,c);return!l&&!n&&!s&&e.indexOf(".")>-1&&(e=c[0],n=c[1],s=c.slice(2).join(".")),l||!a||!K(s)?l:oo(this.data?.[e]?.[n],s,i)}addResource(e,n,s,r,i={silent:!1}){const a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let c=[e,n];s&&(c=c.concat(a?s.split(a):s)),e.indexOf(".")>-1&&(c=e.split("."),r=n,n=c[1]),this.addNamespaces(n),Qa(this.data,c,r),i.silent||this.emit("added",e,n,s,r)}addResources(e,n,s,r={silent:!1}){for(const i in s)(K(s[i])||Array.isArray(s[i]))&&this.addResource(e,n,i,s[i],{silent:!0});r.silent||this.emit("added",e,n,s)}addResourceBundle(e,n,s,r,i,a={silent:!1,skipCopy:!1}){let c=[e,n];e.indexOf(".")>-1&&(c=e.split("."),r=s,s=n,n=c[1]),this.addNamespaces(n);let l=$r(this.data,c)||{};a.skipCopy||(s=JSON.parse(JSON.stringify(s))),r?ml(l,s,i):l={...l,...s},Qa(this.data,c,l),a.silent||this.emit("added",e,n,s)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(r=>n[r]&&Object.keys(n[r]).length>0)}toJSON(){return this.data}}var gl={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,s,r){return t.forEach(i=>{e=this.processors[i]?.process(e,n,s,r)??e}),e}};const yl=Symbol("i18next/PATH_KEY");function Gh(){const t=[],e=Object.create(null);let n;return e.get=(s,r)=>(n?.revoke?.(),r===yl?t:(t.push(r),n=Proxy.revocable(s,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Gn(t,e){const{[yl]:n}=t(Gh()),s=e?.keySeparator??".",r=e?.nsSeparator??":";if(n.length>1&&r){const i=e?.ns,a=Array.isArray(i)?i:null;if(a&&a.length>1&&a.slice(1).includes(n[0]))return`${n[0]}${r}${n.slice(1).join(s)}`}return n.join(s)}const tc={},Ai=t=>!K(t)&&typeof t!="boolean"&&typeof t!="number";class zr extends oi{constructor(e,n={}){super(),Ih(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Nt.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const s={...n};if(e==null)return!1;const r=this.resolve(e,s);if(r?.res===void 0)return!1;const i=Ai(r.res);return!(s.returnObjects===!1&&i)}extractFromKey(e,n){let s=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;s===void 0&&(s=":");const r=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let i=n.ns||this.options.defaultNS||[];const a=s&&e.indexOf(s)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Wh(e,s,r);if(a&&!c){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:K(i)?[i]:i};const d=e.split(s);(s!==r||s===r&&this.options.ns.indexOf(d[0])>-1)&&(i=d.shift()),e=d.join(r)}return{key:e,namespaces:K(i)?[i]:i}}translate(e,n,s){let r=typeof n=="object"?{...n}:n;if(typeof r!="object"&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),typeof r=="object"&&(r={...r}),r||(r={}),e==null)return"";typeof e=="function"&&(e=Gn(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(P=>typeof P=="function"?Gn(P,{...this.options,...r}):String(P));const i=r.returnDetails!==void 0?r.returnDetails:this.options.returnDetails,a=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,{key:c,namespaces:l}=this.extractFromKey(e[e.length-1],r),d=l[l.length-1];let f=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;f===void 0&&(f=":");const u=r.lng||this.language,m=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(u?.toLowerCase()==="cimode")return m?i?{res:`${d}${f}${c}`,usedKey:c,exactUsedKey:c,usedLng:u,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:`${d}${f}${c}`:i?{res:c,usedKey:c,exactUsedKey:c,usedLng:u,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:c;const p=this.resolve(e,r);let g=p?.res;const x=p?.usedKey||c,b=p?.exactUsedKey||c,j=["[object Number]","[object Function]","[object RegExp]"],C=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,N=!this.i18nFormat||this.i18nFormat.handleAsObject,T=r.count!==void 0&&!K(r.count),_=zr.hasDefaultValue(r),L=T?this.pluralResolver.getSuffix(u,r.count,r):"",E=r.ordinal&&T?this.pluralResolver.getSuffix(u,r.count,{ordinal:!1}):"",q=T&&!r.ordinal&&r.count===0,v=q&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${L}`]||r[`defaultValue${E}`]||r.defaultValue;let O=g;N&&!g&&_&&(O=v);const Z=Ai(O),W=Object.prototype.toString.apply(O);if(N&&O&&Z&&j.indexOf(W)<0&&!(K(C)&&Array.isArray(O))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const P=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,O,{...r,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return i?(p.res=P,p.usedParams=this.getUsedParamsDetails(r),p):P}if(a){const P=Array.isArray(O),R=P?[]:{},S=P?b:x;for(const F in O)if(Object.prototype.hasOwnProperty.call(O,F)){const le=`${S}${a}${F}`;_&&!g?R[F]=this.translate(le,{...r,defaultValue:Ai(v)?v[F]:void 0,joinArrays:!1,ns:l}):R[F]=this.translate(le,{...r,joinArrays:!1,ns:l}),R[F]===le&&(R[F]=O[F])}g=R}}else if(N&&K(C)&&Array.isArray(g))g=g.join(C),g&&(g=this.extendTranslation(g,e,r,s));else{let P=!1,R=!1;!this.isValidLookup(g)&&_&&(P=!0,g=v),this.isValidLookup(g)||(R=!0,g=c);const F=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&R?void 0:g,le=_&&v!==g&&this.options.updateMissing;if(R||P||le){if(this.logger.log(le?"updateKey":"missingKey",u,d,c,le?v:g),a){const ae=this.resolve(c,{...r,keySeparator:!1});ae&&ae.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Q=[];const ge=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ge&&ge[0])for(let ae=0;ae<ge.length;ae++)Q.push(ge[ae]);else this.options.saveMissingTo==="all"?Q=this.languageUtils.toResolveHierarchy(r.lng||this.language):Q.push(r.lng||this.language);const oe=(ae,he,Ce)=>{const B=_&&Ce!==g?Ce:F;this.options.missingKeyHandler?this.options.missingKeyHandler(ae,d,he,B,le,r):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(ae,d,he,B,le,r),this.emit("missingKey",ae,d,he,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&T?Q.forEach(ae=>{const he=this.pluralResolver.getSuffixes(ae,r);q&&r[`defaultValue${this.options.pluralSeparator}zero`]&&he.indexOf(`${this.options.pluralSeparator}zero`)<0&&he.push(`${this.options.pluralSeparator}zero`),he.forEach(Ce=>{oe([ae],c+Ce,r[`defaultValue${Ce}`]||v)})}):oe(Q,c,v))}g=this.extendTranslation(g,e,r,p,s),R&&g===c&&this.options.appendNamespaceToMissingKey&&(g=`${d}${f}${c}`),(R||P)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${f}${c}`:c,P?g:void 0,r))}return i?(p.res=g,p.usedParams=this.getUsedParamsDetails(r),p):g}extendTranslation(e,n,s,r,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});const l=K(e)&&(s?.interpolation?.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(l){const u=e.match(this.interpolator.nestingRegexp);d=u&&u.length}let f=s.replace&&!K(s.replace)?s.replace:s;if(this.options.interpolation.defaultVariables&&(f={...this.options.interpolation.defaultVariables,...f}),e=this.interpolator.interpolate(e,f,s.lng||this.language||r.usedLng,s),l){const u=e.match(this.interpolator.nestingRegexp),m=u&&u.length;d<m&&(s.nest=!1)}!s.lng&&r&&r.res&&(s.lng=this.language||r.usedLng),s.nest!==!1&&(e=this.interpolator.nest(e,(...u)=>i?.[0]===u[0]&&!s.context?(this.logger.warn(`It seems you are nesting recursively key: ${u[0]} in key: ${n[0]}`),null):this.translate(...u,n),s)),s.interpolation&&this.interpolator.reset()}const a=s.postProcess||this.options.postProcess,c=K(a)?[a]:a;return e!=null&&c?.length&&s.applyPostProcessor!==!1&&(e=gl.handle(c,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),e}resolve(e,n={}){let s,r,i,a,c;return K(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?Gn(l,{...this.options,...n}):l)),e.forEach(l=>{if(this.isValidLookup(s))return;const d=this.extractFromKey(l,n),f=d.key;r=f;let u=d.namespaces;this.options.fallbackNS&&(u=u.concat(this.options.fallbackNS));const m=n.count!==void 0&&!K(n.count),p=m&&!n.ordinal&&n.count===0,g=n.context!==void 0&&(K(n.context)||typeof n.context=="number")&&n.context!=="",x=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);u.forEach(b=>{this.isValidLookup(s)||(c=b,!tc[`${x[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(tc[`${x[0]}-${b}`]=!0,this.logger.warn(`key "${r}" for languages "${x.join(", ")}" won't get resolved as namespace "${c}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),x.forEach(j=>{if(this.isValidLookup(s))return;a=j;const C=[f];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(C,f,j,b,n);else{let T;m&&(T=this.pluralResolver.getSuffix(j,n.count,n));const _=`${this.options.pluralSeparator}zero`,L=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(n.ordinal&&T.indexOf(L)===0&&C.push(f+T.replace(L,this.options.pluralSeparator)),C.push(f+T),p&&C.push(f+_)),g){const E=`${f}${this.options.contextSeparator||"_"}${n.context}`;C.push(E),m&&(n.ordinal&&T.indexOf(L)===0&&C.push(E+T.replace(L,this.options.pluralSeparator)),C.push(E+T),p&&C.push(E+_))}}let N;for(;N=C.pop();)this.isValidLookup(s)||(i=N,s=this.getResource(j,b,N,n))}))})}),{res:s,usedKey:r,exactUsedKey:i,usedLng:a,usedNS:c}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,s,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,s,r):this.resourceStore.getResource(e,n,s,r)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=e.replace&&!K(e.replace);let r=s?e.replace:e;if(s&&typeof e.count<"u"&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!s){r={...r};for(const i of n)delete r[i]}return r}static hasDefaultValue(e){const n="defaultValue";for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&n===s.substring(0,n.length)&&e[s]!==void 0)return!0;return!1}}class nc{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Nt.create("languageUtils")}getScriptPartFromCode(e){if(e=Us(e),!e||e.indexOf("-")<0)return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=Us(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(K(e)&&e.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(s=>{if(n)return;const r=this.formatLanguageCode(s);(!this.options.supportedLngs||this.isSupportedCode(r))&&(n=r)}),!n&&this.options.supportedLngs&&e.forEach(s=>{if(n)return;const r=this.getScriptPartFromCode(s);if(this.isSupportedCode(r))return n=r;const i=this.getLanguagePartFromCode(s);if(this.isSupportedCode(i))return n=i;n=this.options.supportedLngs.find(a=>{if(a===i)return a;if(!(a.indexOf("-")<0&&i.indexOf("-")<0)&&(a.indexOf("-")>0&&i.indexOf("-")<0&&a.substring(0,a.indexOf("-"))===i||a.indexOf(i)===0&&i.length>1))return a})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),K(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let s=e[n];return s||(s=e[this.getScriptPartFromCode(n)]),s||(s=e[this.formatLanguageCode(n)]),s||(s=e[this.getLanguagePartFromCode(n)]),s||(s=e.default),s||[]}toResolveHierarchy(e,n){const s=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),r=[],i=a=>{a&&(this.isSupportedCode(a)?r.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return K(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):K(e)&&i(this.formatLanguageCode(e)),s.forEach(a=>{r.indexOf(a)<0&&i(this.formatLanguageCode(a))}),r}}const sc={zero:0,one:1,two:2,few:3,many:4,other:5},rc={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Jh{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Nt.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const s=Us(e==="dev"?"en":e),r=n.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:s,type:r});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(s,{type:r})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),rc;if(!e.match(/-|_/))return rc;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,n)}return this.pluralRulesCache[i]=a,a}needsPlural(e,n={}){let s=this.getRule(e,n);return s||(s=this.getRule("dev",n)),s?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,s={}){return this.getSuffixes(e,s).map(r=>`${n}${r}`)}getSuffixes(e,n={}){let s=this.getRule(e,n);return s||(s=this.getRule("dev",n)),s?s.resolvedOptions().pluralCategories.sort((r,i)=>sc[r]-sc[i]).map(r=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${r}`):[]}getSuffix(e,n,s={}){const r=this.getRule(e,s);return r?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${r.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,s))}}const ic=(t,e,n,s=".",r=!0)=>{let i=Uh(t,e,n);return!i&&r&&K(n)&&(i=oo(t,n,s),i===void 0&&(i=oo(e,n,s))),i},Fi=t=>t.replace(/\$/g,"$$$$");class oc{constructor(e={}){this.logger=Nt.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:s,useRawValueToEscape:r,prefix:i,prefixEscaped:a,suffix:c,suffixEscaped:l,formatSeparator:d,unescapeSuffix:f,unescapePrefix:u,nestingPrefix:m,nestingPrefixEscaped:p,nestingSuffix:g,nestingSuffixEscaped:x,nestingOptionsSeparator:b,maxReplaces:j,alwaysFormat:C}=e.interpolation;this.escape=n!==void 0?n:Vh,this.escapeValue=s!==void 0?s:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=i?gn(i):a||"{{",this.suffix=c?gn(c):l||"}}",this.formatSeparator=d||",",this.unescapePrefix=f?"":u||"-",this.unescapeSuffix=this.unescapePrefix?"":f||"",this.nestingPrefix=m?gn(m):p||gn("$t("),this.nestingSuffix=g?gn(g):x||gn(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=j||1e3,this.alwaysFormat=C!==void 0?C:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,s)=>n?.source===s?(n.lastIndex=0,n):new RegExp(s,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,s,r){let i,a,c;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=p=>{if(p.indexOf(this.formatSeparator)<0){const j=ic(n,l,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(j,void 0,s,{...r,...n,interpolationkey:p}):j}const g=p.split(this.formatSeparator),x=g.shift().trim(),b=g.join(this.formatSeparator).trim();return this.format(ic(n,l,x,this.options.keySeparator,this.options.ignoreJSONStructure),b,s,{...r,...n,interpolationkey:x})};this.resetRegExp();const f=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,u=r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:p=>Fi(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?Fi(this.escape(p)):Fi(p)}].forEach(p=>{for(c=0;i=p.regex.exec(e);){const g=i[1].trim();if(a=d(g),a===void 0)if(typeof f=="function"){const b=f(e,i,r);a=K(b)?b:""}else if(r&&Object.prototype.hasOwnProperty.call(r,g))a="";else if(u){a=i[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${e}`),a="";else!K(a)&&!this.useRawValueToEscape&&(a=Ya(a));const x=p.safeValue(a);if(e=e.replace(i[0],x),u?(p.regex.lastIndex+=a.length,p.regex.lastIndex-=i[0].length):p.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),e}nest(e,n,s={}){let r,i,a;const c=(l,d)=>{const f=this.nestingOptionsSeparator;if(l.indexOf(f)<0)return l;const u=l.split(new RegExp(`${gn(f)}[ ]*{`));let m=`{${u[1]}`;l=u[0],m=this.interpolate(m,a);const p=m.match(/'/g),g=m.match(/"/g);((p?.length??0)%2===0&&!g||(g?.length??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{a=JSON.parse(m),d&&(a={...d,...a})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,x),`${l}${f}${m}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;r=this.nestingRegexp.exec(e);){let l=[];a={...s},a=a.replace&&!K(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const d=/{.*}/.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(d!==-1&&(l=r[1].slice(d).split(this.formatSeparator).map(f=>f.trim()).filter(Boolean),r[1]=r[1].slice(0,d)),i=n(c.call(this,r[1].trim(),a),a),i&&r[0]===e&&!K(i))return i;K(i)||(i=Ya(i)),i||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),i=""),l.length&&(i=l.reduce((f,u)=>this.format(f,u,s.lng,{...s,interpolationkey:r[1].trim()}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}}const Yh=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const s=t.split("(");e=s[0].toLowerCase().trim();const r=s[1].substring(0,s[1].length-1);e==="currency"&&r.indexOf(":")<0?n.currency||(n.currency=r.trim()):e==="relativetime"&&r.indexOf(":")<0?n.range||(n.range=r.trim()):r.split(";").forEach(a=>{if(a){const[c,...l]=a.split(":"),d=l.join(":").trim().replace(/^'+|'+$/g,""),f=c.trim();n[f]||(n[f]=d),d==="false"&&(n[f]=!1),d==="true"&&(n[f]=!0),isNaN(d)||(n[f]=parseInt(d,10))}})}return{formatName:e,formatOptions:n}},ac=t=>{const e={};return(n,s,r)=>{let i=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(i={...i,[r.interpolationkey]:void 0});const a=s+JSON.stringify(i);let c=e[a];return c||(c=t(Us(s),r),e[a]=c),c(n)}},Xh=t=>(e,n,s)=>t(Us(n),s)(e);class Zh{constructor(e={}){this.logger=Nt.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const s=n.cacheInBuiltFormats?ac:Xh;this.formats={number:s((r,i)=>{const a=new Intl.NumberFormat(r,{...i});return c=>a.format(c)}),currency:s((r,i)=>{const a=new Intl.NumberFormat(r,{...i,style:"currency"});return c=>a.format(c)}),datetime:s((r,i)=>{const a=new Intl.DateTimeFormat(r,{...i});return c=>a.format(c)}),relativetime:s((r,i)=>{const a=new Intl.RelativeTimeFormat(r,{...i});return c=>a.format(c,i.range||"day")}),list:s((r,i)=>{const a=new Intl.ListFormat(r,{...i});return c=>a.format(c)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=ac(n)}format(e,n,s,r={}){const i=n.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(c=>c.indexOf(")")>-1)){const c=i.findIndex(l=>l.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,c)].join(this.formatSeparator)}return i.reduce((c,l)=>{const{formatName:d,formatOptions:f}=Yh(l);if(this.formats[d]){let u=c;try{const m=r?.formatParams?.[r.interpolationkey]||{},p=m.locale||m.lng||r.locale||r.lng||s;u=this.formats[d](c,p,{...f,...r,...m})}catch(m){this.logger.warn(m)}return u}else this.logger.warn(`there was no format function for ${d}`);return c},e)}}const Qh=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class ef extends oi{constructor(e,n,s,r={}){super(),this.backend=e,this.store=n,this.services=s,this.languageUtils=s.languageUtils,this.options=r,this.logger=Nt.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(s,r.backend,r)}queueLoad(e,n,s,r){const i={},a={},c={},l={};return e.forEach(d=>{let f=!0;n.forEach(u=>{const m=`${d}|${u}`;!s.reload&&this.store.hasResourceBundle(d,u)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?a[m]===void 0&&(a[m]=!0):(this.state[m]=1,f=!1,a[m]===void 0&&(a[m]=!0),i[m]===void 0&&(i[m]=!0),l[u]===void 0&&(l[u]=!0)))}),f||(c[d]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(c),toLoadNamespaces:Object.keys(l)}}loaded(e,n,s){const r=e.split("|"),i=r[0],a=r[1];n&&this.emit("failedLoading",i,a,n),!n&&s&&this.store.addResourceBundle(i,a,s,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&s&&(this.state[e]=0);const c={};this.queue.forEach(l=>{$h(l.loaded,[i],a),Qh(l,e),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(d=>{c[d]||(c[d]={});const f=l.loaded[d];f.length&&f.forEach(u=>{c[d][u]===void 0&&(c[d][u]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(l=>!l.done)}read(e,n,s,r=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:s,tried:r,wait:i,callback:a});return}this.readingCalls++;const c=(d,f)=>{if(this.readingCalls--,this.waitingReads.length>0){const u=this.waitingReads.shift();this.read(u.lng,u.ns,u.fcName,u.tried,u.wait,u.callback)}if(d&&f&&r<this.maxRetries){setTimeout(()=>{this.read.call(this,e,n,s,r+1,i*2,a)},i);return}a(d,f)},l=this.backend[s].bind(this.backend);if(l.length===2){try{const d=l(e,n);d&&typeof d.then=="function"?d.then(f=>c(null,f)).catch(c):c(null,d)}catch(d){c(d)}return}return l(e,n,c)}prepareLoading(e,n,s={},r){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();K(e)&&(e=this.languageUtils.toResolveHierarchy(e)),K(n)&&(n=[n]);const i=this.queueLoad(e,n,s,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach(a=>{this.loadOne(a)})}load(e,n,s){this.prepareLoading(e,n,{},s)}reload(e,n,s){this.prepareLoading(e,n,{reload:!0},s)}loadOne(e,n=""){const s=e.split("|"),r=s[0],i=s[1];this.read(r,i,"read",void 0,void 0,(a,c)=>{a&&this.logger.warn(`${n}loading namespace ${i} for language ${r} failed`,a),!a&&c&&this.logger.log(`${n}loaded namespace ${i} for language ${r}`,c),this.loaded(e,a,c)})}saveMissing(e,n,s,r,i,a={},c=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${s}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(s==null||s==="")){if(this.backend?.create){const l={...a,isUpdate:i},d=this.backend.create.bind(this.backend);if(d.length<6)try{let f;d.length===5?f=d(e,n,s,r,l):f=d(e,n,s,r),f&&typeof f.then=="function"?f.then(u=>c(null,u)).catch(c):c(null,f)}catch(f){c(f)}else d(e,n,s,r,c,l)}!e||!e[0]||this.store.addResource(e[0],n,s,r)}}}const Ii=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),K(t[1])&&(e.defaultValue=t[1]),K(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(s=>{e[s]=n[s]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),cc=t=>(K(t.ns)&&(t.ns=[t.ns]),K(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),K(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),Cr=()=>{},tf=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})},wl="__i18next_supportNoticeShown",nf=()=>!!(typeof globalThis<"u"&&globalThis[wl]||typeof process<"u"&&Li&&Li.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&Li),sf=()=>{typeof globalThis<"u"&&(globalThis[wl]=!0)},rf=t=>!!(t?.modules?.backend?.name?.indexOf("Locize")>0||t?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||t?.options?.backend?.backends&&t.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||t?.options?.backend?.projectId||t?.options?.backend?.backendOptions&&t.options.backend.backendOptions.some(e=>e?.projectId));class Ms extends oi{constructor(e={},n){if(super(),this.options=cc(e),this.services={},this.logger=Nt,this.modules={external:[]},tf(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(K(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const s=Ii();this.options={...s,...this.options,...cc(e)},this.options.interpolation={...s.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=s.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!rf(this)&&!nf()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),sf());const r=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Nt.init(r(this.modules.logger),this.options):Nt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=Zh;const f=new nc(this.options);this.store=new ec(this.options.resources,this.options);const u=this.services;u.logger=Nt,u.resourceStore=this.store,u.languageUtils=f,u.pluralResolver=new Jh(f,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==s.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(u.formatter=r(d),u.formatter.init&&u.formatter.init(u,this.options),this.options.interpolation.format=u.formatter.format.bind(u.formatter)),u.interpolator=new oc(this.options),u.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},u.backendConnector=new ef(r(this.modules.backend),u.resourceStore,u,this.options),u.backendConnector.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.languageDetector&&(u.languageDetector=r(this.modules.languageDetector),u.languageDetector.init&&u.languageDetector.init(u,this.options.detection,this.options)),this.modules.i18nFormat&&(u.i18nFormat=r(this.modules.i18nFormat),u.i18nFormat.init&&u.i18nFormat.init(this)),this.translator=new zr(this.services,this.options),this.translator.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,n||(n=Cr),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=(...f)=>this.store[d](...f)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...f)=>(this.store[d](...f),this)});const c=Rs(),l=()=>{const d=(f,u)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(u),n(f,u)};if(this.languages&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(e,n=Cr){let s=n;const r=K(e)?e:this.language;if(typeof e=="function"&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if(r?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return s();const i=[],a=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(d=>{d!=="cimode"&&i.indexOf(d)<0&&i.push(d)})};r?a(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>a(l)),this.options.preload?.forEach?.(c=>a(c)),this.services.backendConnector.load(i,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),s(c)})}else s(null)}reloadResources(e,n,s){const r=Rs();return typeof e=="function"&&(s=e,e=void 0),typeof n=="function"&&(s=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),s||(s=Cr),this.services.backendConnector.reload(e,n,i=>{r.resolve(),s(i)}),r}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&gl.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let n=0;n<this.languages.length;n++){const s=this.languages[n];if(!(["cimode","dev"].indexOf(s)>-1)&&this.store.hasLanguageSomeTranslations(s)){this.resolvedLanguage=s;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const s=Rs();this.emit("languageChanging",e);const r=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},i=(c,l)=>{l?this.isLanguageChangingTo===e&&(r(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,s.resolve((...d)=>this.t(...d)),n&&n(c,(...d)=>this.t(...d))},a=c=>{!e&&!c&&this.services.languageDetector&&(c=[]);const l=K(c)?c:c&&c[0],d=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(K(c)?[c]:c);d&&(this.language||r(d),this.translator.language||this.translator.changeLanguage(d),this.services.languageDetector?.cacheUserLanguage?.(d)),this.loadResources(d,f=>{i(f,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),s}getFixedT(e,n,s){const r=(i,a,...c)=>{let l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([i,a].concat(c)):l={...a},l.lng=l.lng||r.lng,l.lngs=l.lngs||r.lngs,l.ns=l.ns||r.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||s||r.keyPrefix);const d={...this.options,...l};typeof l.keyPrefix=="function"&&(l.keyPrefix=Gn(l.keyPrefix,d));const f=this.options.keySeparator||".";let u;return l.keyPrefix&&Array.isArray(i)?u=i.map(m=>(typeof m=="function"&&(m=Gn(m,d)),`${l.keyPrefix}${f}${m}`)):(typeof i=="function"&&(i=Gn(i,d)),u=l.keyPrefix?`${l.keyPrefix}${f}${i}`:i),this.t(u,l)};return K(e)?r.lng=e:r.lngs=e,r.ns=n,r.keyPrefix=s,r}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const s=n.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(s.toLowerCase()==="cimode")return!0;const a=(c,l)=>{const d=this.services.backendConnector.state[`${c}|${l}`];return d===-1||d===0||d===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(s,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(s,e)&&(!r||a(i,e)))}loadNamespaces(e,n){const s=Rs();return this.options.ns?(K(e)&&(e=[e]),e.forEach(r=>{this.options.ns.indexOf(r)<0&&this.options.ns.push(r)}),this.loadResources(r=>{s.resolve(),n&&n(r)}),s):(n&&n(),Promise.resolve())}loadLanguages(e,n){const s=Rs();K(e)&&(e=[e]);const r=this.options.preload||[],i=e.filter(a=>r.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return i.length?(this.options.preload=r.concat(i),this.loadResources(a=>{s.resolve(),n&&n(a)}),s):(n&&n(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const r=new Intl.Locale(e);if(r&&r.getTextInfo){const i=r.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],s=this.services?.languageUtils||new nc(Ii());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(s.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const s=new Ms(e,n);return s.createInstance=Ms.createInstance,s}cloneInstance(e={},n=Cr){const s=e.forkResourceStore;s&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},i=new Ms(r);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(c=>{i[c]=this[c]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},s){const c=Object.keys(this.store.data).reduce((l,d)=>(l[d]={...this.store.data[d]},l[d]=Object.keys(l[d]).reduce((f,u)=>(f[u]={...l[d][u]},f),l[d]),l),{});i.store=new ec(c,r),i.services.resourceStore=i.store}if(e.interpolation){const l={...Ii().interpolation,...this.options.interpolation,...e.interpolation},d={...r,interpolation:l};i.services.interpolator=new oc(d)}return i.translator=new zr(i.services,r),i.translator.on("*",(c,...l)=>{i.emit(c,...l)}),i.init(r,n),i.translator.options=r,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const we=Ms.createInstance();we.createInstance;we.dir;we.init;we.loadResources;we.reloadResources;we.use;we.changeLanguage;we.getFixedT;we.t;we.exists;we.setDefaultNamespace;we.hasLoadedNamespace;we.loadNamespaces;we.loadLanguages;const{slice:of,forEach:af}=[];function cf(t){return af.call(of.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function lf(t){return typeof t!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(t))}const lc=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,df=function(t,e){const s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},r=encodeURIComponent(e);let i=`${t}=${r}`;if(s.maxAge>0){const a=s.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(a)}`}if(s.domain){if(!lc.test(s.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${s.domain}`}if(s.path){if(!lc.test(s.path))throw new TypeError("option path is invalid");i+=`; Path=${s.path}`}if(s.expires){if(typeof s.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+=`; Expires=${s.expires.toUTCString()}`}if(s.httpOnly&&(i+="; HttpOnly"),s.secure&&(i+="; Secure"),s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s.partitioned&&(i+="; Partitioned"),i},dc={create(t,e,n,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(r.expires=new Date,r.expires.setTime(r.expires.getTime()+n*60*1e3)),s&&(r.domain=s),document.cookie=df(t,e,r)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let s=0;s<n.length;s++){let r=n[s];for(;r.charAt(0)===" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return r.substring(e.length,r.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var uf={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return dc.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:r,cookieOptions:i}=e;n&&typeof document<"u"&&dc.create(n,t,s,r,i)}},hf={name:"querystring",lookup(t){let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:s}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(s=window.location.hash.substring(window.location.hash.indexOf("?")));const i=s.substring(1).split("&");for(let a=0;a<i.length;a++){const c=i[a].indexOf("=");c>0&&i[a].substring(0,c)===e&&(n=i[a].substring(c+1))}}return n}},ff={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,s;if(typeof window<"u"){const{hash:r}=window.location;if(r&&r.length>2){const i=r.substring(1);if(e){const a=i.split("&");for(let c=0;c<a.length;c++){const l=a[c].indexOf("=");l>0&&a[c].substring(0,l)===e&&(s=a[c].substring(l+1))}}if(s)return s;if(!s&&n>-1){const a=r.match(/\/([a-zA-Z-]*)/g);return Array.isArray(a)?a[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return s}};let Fn=null;const uc=()=>{if(Fn!==null)return Fn;try{if(Fn=typeof window<"u"&&window.localStorage!==null,!Fn)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Fn=!1}return Fn};var pf={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&uc())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&uc()&&window.localStorage.setItem(n,t)}};let In=null;const hc=()=>{if(In!==null)return In;try{if(In=typeof window<"u"&&window.sessionStorage!==null,!In)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{In=!1}return In};var mf={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&hc())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&hc()&&window.sessionStorage.setItem(n,t)}},gf={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:s,language:r}=navigator;if(n)for(let i=0;i<n.length;i++)e.push(n[i]);s&&e.push(s),r&&e.push(r)}return e.length>0?e:void 0}},yf={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const s=e||(typeof document<"u"?document.documentElement:null);return s&&typeof s.getAttribute=="function"&&(n=s.getAttribute("lang")),n}},wf={name:"path",lookup(t){let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?n[typeof e=="number"?e:0]?.replace("/",""):void 0}},xf={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,s=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(s)return s[n]}};let xl=!1;try{document.cookie,xl=!0}catch{}const bl=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];xl||bl.splice(1,1);const bf=()=>({order:bl,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class vl{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=cf(n,this.options||{},bf()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=r=>r.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=s,this.addDetector(uf),this.addDetector(hf),this.addDetector(pf),this.addDetector(mf),this.addDetector(gf),this.addDetector(yf),this.addDetector(wf),this.addDetector(xf),this.addDetector(ff)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(s=>{if(this.detectors[s]){let r=this.detectors[s].lookup(this.options);r&&typeof r=="string"&&(r=[r]),r&&(n=n.concat(r))}}),n=n.filter(s=>s!=null&&!lf(s)).map(s=>this.options.convertDetectedLanguage(s)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(s=>{this.detectors[s]&&this.detectors[s].cacheUserLanguage(e,this.options)}))}}vl.type="languageDetector";const vf={cancel:"Cancel",create:"Create",add:"Add",remove:"Remove",delete:"Delete",close:"Close",user:"User",permission:"Permission",readOnly:"Read only",readWrite:"Read & write",settings:"Settings",comments:"Comments",files:"Files",outline:"Outline",loading:"Loading…",enabled:"Enabled",disabled:"Disabled",normal:"Active",admin:"Administrator",language:"Language",languageEnglish:"English",languageChinese:"中文"},Sf={tagline:"A lightweight LaTeX writing environment",username:"Username",password:"Password",login:"Sign in",contact:"Need an account? Contact {{email}}",firstLogin:"Change your temporary password to continue",currentPassword:"Current password",newPassword:"New password",confirmPassword:"Confirm new password",updatePassword:"Update password",mismatch:"The new passwords do not match",passwordMinimum:"At least {{count}} characters",sessionExpired:"Your session has expired. Please sign in again.",logout:"Sign out"},jf={title:"Projects",subtitle:"Create, edit and share LaTeX documents",restricted:"You can access projects shared with you. Project creation requires administrator permission.",new:"New project",newDescription:"The project will use the configured default LaTeX engine.",name:"Project name",emptyTitle:"Let’s build something great",emptyDescription:"Create a project or upload an existing LaTeX archive to get started.",emptyRestricted:"Projects shared with you will appear here.",noMatches:"No projects match the current search or tag filter.",upload:"Upload project",uploadDescription:"Upload a ZIP archive. A single top-level folder is removed automatically. Maximum file size: {{size}} MB.",zipFile:"ZIP archive",import:"Import project",importing:"Importing…",search:"Search projects…",grid:"Grid",list:"List",scope:"Project status",active:"Active",archived:"Archived",archive:"Archive",unarchive:"Restore",noArchived:"No archived projects.",allTags:"All tags",sortBy:"Sort",sortModified:"Last modified",sortCreated:"Created",pagination:"Project pages",pageOf:"Page {{page}} of {{totalPages}} · {{count}} projects",previousPage:"Previous",nextPage:"Next",owner:"Owner",created:"Created",modified:"Last modified",modifiedBy:"Modified by",byUser:"By {{user}}",modifiedByUser:"{{time}} · By {{user}}",deletedUser:"Deleted user",filterTags:"Filter by tag",rename:"Rename",renameTitle:"Rename project",duplicate:"Duplicate",duplicating:"Duplicating…",duplicateTitle:"Duplicate project",duplicateDescription:"Create an independent copy of {{project}}. Files and project settings are copied; members, comments, Git history and compile output are not.",transfer:"Transfer",transferOwnership:"Transfer ownership",transferDescription:"Choose a new owner for {{project}}.",newOwner:"New owner",chooseNewOwner:"Choose a user",noTransferUsers:"No other active users",transferWarning:"You will keep read/write access. Source files, history, comments and members remain; the saved GitHub token is removed so the new owner can add their own credential.",transferForbidden:"Only the current project owner can transfer ownership.",transferTargetInvalid:"Choose a new project owner.",transferSelf:"You already own this project.",download:"Download",deleteTitle:"Delete project",deleteDescription:"Permanently delete {{project}} and all of its files? This cannot be undone.",chooseZip:"Choose a ZIP project",dropZip:"Drag and drop a ZIP archive here",browse:"Browse files",selectedFileSize:"Selected · {{size}}",clearFile:"Clear selected file"},Cf={manage:"User management",back:"Back to projects",onlyAdmin:"Only administrators can create users",add:"Add user",role:"Role",createProjects:"Create projects",ownedProjects:"Owned projects",status:"Status",actions:"Actions",adminRequired:"Administrator permission is required.",allow:"Allow",deny:"Deny",enable:"Enable",disable:"Disable",promote:"Make administrator",demote:"Make user",allowCreate:"Allow creation",denyCreate:"Deny creation",resetPassword:"Reset password",initialPassword:"Login password",displayName:"Display name",addDescription:"Set a login password or generate a secure random one.",createUser:"Create user",randomPassword:"Random password",generatePassword:"Generate a random password",resetDescription:"Set a temporary password for {{username}}. Existing sessions will be signed out.",reset:"Reset",deleteTitle:"Delete user",deleteDescription:"Delete {{username}}? This cannot be undone.",ownedChoice:"{{count}} owned projects",transferProjects:"Transfer them to the current administrator",deleteProjects:"Permanently delete projects and files"},kf={saved:"Saved",savedAt:"Saved to server at {{time}}",loading:"Loading",pending:"Waiting to save",saving:"Saving to server",saveFailed:"Save failed",offlineDraft:"Offline · local draft retained",compile:"Compile · {{engine}}",compiling:"Compiling…",compileQueued:"Compile queued…",compileFailedRetained:"Compilation failed; showing the last successful PDF from {{time}}.",compileFailedNoPdf:"Compilation failed and no successful PDF is available.",upToDate:"Files are up to date; no compilation was needed.",addComment:"Add comment",sourceComments:"Source comments",projectSettings:"Project settings",uploadAttachment:"Upload attachment",newFile:"New text file",binary:"The binary attachment is stored but cannot be opened in the text editor.",noOutline:"No sections in this file",preview:"PDF preview",previewHint:"Compile to generate the document",pdfCompiledAt:"Compiled successfully at {{time}}",pdfCompiledAtFor:"{{file}} compiled successfully at {{time}}",currentMainDocument:"Current document compiled as the root: {{path}}",mainDocumentCandidate:"LaTeX root document candidate: {{path}}",currentMainShort:"root",deletedUser:"Deleted User",orphaned:"Anchor lost",line:"Line {{line}}",reopen:"Reopen",resolve:"Mark resolved",noComments:"No comments in this file",newFileDescription:"Directories are allowed, for example chapters/introduction.tex.",filePath:"File path",commentDescription:"Selected {{count}} characters",pointComment:"No text selected; the comment will be anchored at the cursor.",commentContent:"Comment",backToProjects:"Back to projects",outputTabs:"Compile output",log:"Log",warnings:"Warnings",errors:"Errors",artifacts:"Artifacts",noLog:"Compile to see the log.",noWarnings:"No warnings in the latest compile.",noErrors:"No errors in the latest compile.",projectRoot:"Project root",uploadTo:"Upload to {{folder}}",dropFiles:"Drop files to upload",newFolder:"New folder",folderName:"Folder name",noArtifacts:"Compile to see generated artifacts.",selectArtifact:"Select a text artifact to preview it.",viewArtifact:"View artifact",downloadArtifact:"Download artifact",downloadToView:"Download this artifact to view it",folderDestination:"The folder will be created in {{folder}}.",uploadOverwriteTitle:"File already exists",uploadOverwriteDescription:"These files already exist: {{files}}. Replace them?",uploadOverwrite:"Replace files",collapseFiles:"Collapse file panel",move:"Move",moveTitle:"Move {{name}}",moveDescription:"Choose a destination folder. Files, comments and project paths stay linked.",deletePath:"Delete file or folder",deletePathTitle:"Delete {{name}}",deletePathDescription:"Delete {{path}}? This cannot be undone.",deletePathActiveDescription:"Delete {{path}}? It is currently open for {{users}} and will close in those sessions.",deletePathWillClose:"Any late edits to this path will be rejected to prevent silent data loss.",fileDeletedByCollaborator:"{{path}} was deleted in another session. A safe fallback file has been opened.",destinationFolder:"Destination folder",compileShortcut:"Save and compile (Ctrl+S / Cmd+S)",compilingBy:"{{name}} is compiling",formatSelection:"Format selection",formatting:"Formatting…",formatSelectionHint:"Select LaTeX source to format",formatSelectionRequired:"Select LaTeX source before formatting.",formatSelectionComplete:"Selected LaTeX source formatted.",formatFailedContinue:"Formatting failed; compilation will continue: {{message}}",formatFailed:"Unable to format the selection: {{message}}",formatSourceChanged:"The source changed during formatting, so formatting was skipped.",formatSelectionChanged:"The selected source changed during formatting. Select it again and retry.",vimOn:"Vim ON",vimOnHint:"Vim keybindings are enabled for this editor.",reply:"Reply",replyPlaceholder:"Write a reply…",sendReply:"Send reply",editComment:"Edit comment",deleteComment:"Delete comment",saveChanges:"Save changes",deleteCommentTitle:"Delete comment",deleteCommentDescription:"Delete this comment and its {{count}} replies? This cannot be undone.",editReply:"Edit reply",deleteReply:"Delete reply",deleteReplyTitle:"Delete reply",deleteReplyDescription:"Delete this reply? This cannot be undone.",editedAt:"Edited {{time}}",outlineJump:"Go to source line {{line}} and locate it in the PDF",lineNumber:"line {{line}}",showInSource:"Show the visible PDF location in source",showInPdf:"Show the source cursor location in PDF",pdfLoadFailed:"The PDF preview could not be loaded",pdfZoomControls:"PDF zoom controls",downloadPdf:"Download PDF",downloadResource:"Download file",resourceTooLarge:"This file is {{size}} and exceeds the direct preview limit of {{limit}}.",resourceTooLargeTitle:"File is too large to preview",resourceTooLargeDescription:"Download the file to open it locally.",resourceUnsupportedTitle:"Preview unavailable",resourceUnsupportedDescription:"This file type cannot be rendered in the browser. Download it to open it locally.",resourcePreview:{image:"Image preview",pdf:"PDF preview",text:"Text preview",unsupported:"File preview"},pdfZoomOut:"Zoom out",pdfZoomIn:"Zoom in",pdfFitWidth:"Fit width",layout:{label:"Layout",choose:"Choose layout",current:"Current layout: {{layout}}","editor-pdf":{name:"Editor & PDF",description:"Show the source editor and PDF preview side by side"},"editor-only":{name:"Editor only",description:"Use the workspace for source editing"},"pdf-only":{name:"PDF only",description:"Use the workspace for the PDF and compile output"}},collaboration:{connecting:"Connecting collaboration…",connected:"Live collaboration connected",disconnected:"Collaboration disconnected",editing:"Editing",viewing:"Viewing",joining:"Joining project",reconnect:"Reconnect",activeSessions:"{{count}} active sessions",showMoreSessions:"Show {{count}} more sessions",showFewerSessions:"Collapse session list",sessionTooltip:"{{name}} (@{{username}}) · {{file}} · {{activity}} · {{permission}}"},search:{button:"Find",title:"Find and replace (Ctrl+F / Cmd+F)",find:"Find",replace:"Replace",next:"Next",previous:"Previous",all:"Select all",matchCase:"Match case",regexp:"Regular expression",wholeWord:"Whole word",replaceNext:"Replace",replaceAll:"Replace all",currentMatch:"Current match",onLine:"on line",replacedMatchOnLine:"replaced match on line $",replacedMatches:"replaced $ matches",goToLine:"Go to line",go:"Go",matchCount:"{{count}} matches",noMatches:"No matches",invalidQuery:"Invalid regular expression"}},Ef={quickOpen:"Quick open",quickOpenDescription:"Open a project file by name (Ctrl/Cmd+P).",filePlaceholder:"Type a file name…",noFiles:"No matching files.",projectSearch:"Project search",projectSearchDescription:"Search and replace across project source files (Ctrl/Cmd+Shift+F).",searchPlaceholder:"Search all source files…",replacePlaceholder:"Replace with…",matchSummary:"{{count}} matches",truncated:"Showing the first {{count}} matches.",replaceAll:"Replace all {{count}}",replaceConfirmTitle:"Replace across the project",replaceConfirmDescription:"Replace all {{count}} matches? Automatic history records every changed file first.",replaced:"Replaced {{count}} matches in {{files}} files."},Df={title:"History",description:"Browse automatic project versions, compare files and safely restore earlier work.",empty:"No history versions yet.",changedCount:"{{count}} changed files",fileCount:"{{count}} files",changed:"changed",labelPlaceholder:"Name this version",saveLabel:"Save label",compareCurrent:"Compare with current",comparingCurrent:"Earlier version compared with the current file",chooseFile:"Choose a file, then compare it with the current source.",restore:"Restore",restoreFile:"Restore file",restoreProject:"Restore project",restoreFileTitle:"Restore this file",restoreProjectTitle:"Restore this project version",restoreFileDescription:"Restore {{path}} from this version? The current project is checkpointed first.",restoreProjectDescription:"Restore all source files and compiler settings from this version? The current project is checkpointed first.",storage:"History storage",storageUsage:"{{used}} of {{limit}}",versionUsage:"{{count}} of {{limit}} ordinary versions",protectedVersions:"{{count}} labeled",storageExceeded:"Protected or current data exceeds the soft storage limit.",deleteVersion:"Delete version",deleteVersionTitle:"Delete this history version",deleteVersionDescription:"Permanently delete {{name}}? Current project files are not changed.",clearAll:"Clear history",clearAllTitle:"Clear all project history",clearAllDescription:"Permanently delete every history version and its unreferenced stored data? Current project files are not changed.",reasons:{initial:"Project created",autosave:"Automatic save",file:"File operation",settings:"Compiler settings",git:"Git operation",restore:"Restored version",checkpoint:"Safety checkpoint"}},Nf={mainFile:"Main document",engine:"Compiler",latexmkrc:"Project latexmkrc",save:"Save project settings",members:"Shared members",recentLog:"Latest compile log",share:"Share project",shareDescription:"Projects can only be shared with users created by an administrator.",chooseUser:"Choose a user",latexmkrcPlaceholder:`# Empty disables the project rc file
3
3
  $pdf_mode = 1;`,addMember:"Add member",noMembers:"This project has not been shared with anyone.",removeTitle:"Remove shared member",removeDescription:"Remove {{username}}? Their account and other projects are unaffected.",editorTab:"Editor appearance",compilerTab:"LaTeX compiler",compilerDescription:"Choose the main document and compiler options shared by everyone in this project.",editorAppearance:"Editor appearance",editorAppearanceDescription:"These preferences are private to this user and project on this browser. The project dictionary is shared.",saveAppearance:"Save appearance",saveCompiler:"Save compiler settings",projectConfiguration:"Project configuration",fontFamily:"English font",fontSize:"Font size",lineHeight:"Line spacing",dictionary:"Project dictionary",dictionaryDescription:"Words added here are ignored by spell checking for this project. Editors can maintain this list.",dictionaryPlaceholder:"Add a custom word",addWord:"Add word",dictionaryEmpty:"No custom words yet.",lineWrapping:"Wrap long lines",spellCheck:"Spell checking",vimMode:"Vim keybindings",vimModeDescription:"Use Vim normal/insert/visual modes in this editor.",vimHelp:"View help",formatOnCompile:"Format LaTeX before compiling",formatOnCompileDescription:"Off by default. Formatting runs on the server immediately before compilation.",formatRequiresWrite:"Formatting requires permission to edit this project.",formatterDescription:"Formatting uses the optional host-side tex-fmt command.",formatterInstall:"Install or view tex-fmt documentation",spellingIssues:"{{count}} spelling issues ({{uniqueCount}} unique words)",noSpellingIssues:"No spelling issues found.",spellCheckFirst:"First spelling issue",spellCheckPrevious:"Previous spelling issue",spellCheckNext:"Next spelling issue",spellCheckLast:"Last spelling issue",spellCheckPosition:"{{current}}/{{total}}",fontJetBrains:"JetBrains Mono",fontSourceCode:"Source Code Pro",fontIbmPlex:"IBM Plex Mono",fontFiraCode:"Fira Code",fontIosevka:"Iosevka",lineHeightCompact:"Compact",lineHeightNormal:"Normal",lineHeightRelaxed:"Relaxed"},Tf={title:"Git backup",description:"Manage the local Git history and its GitHub backup. Only the project owner can use these actions.",authentication:"GitHub authentication",authenticationHint:"Use a token with repository Administration and Contents write access. It is encrypted at rest and never written to the repository or remote URL.",recommendedAccessTitle:"Recommended repository access: All repositories",recommendedAccess:"texLite is intended for trusted users. Select All repositories so this token can create a repository and access repositories created later. Grant Administration and Contents read and write permissions.",token:"Personal access token",tokenPlaceholder:"Paste your GitHub token",replaceToken:"Replace personal access token",saveToken:"Save and verify token",createToken:"Create a fine-grained token",connectedAs:"Connected as @{{login}}",removeToken:"Remove token",tokenSaved:"GitHub token saved; the local repository is ready.",tokenRemoved:"GitHub token removed.",repository:"Repository",localReady:"The project source is managed by a local Git repository.",localPending:"Saving a valid token initializes the local Git repository.",repositoryName:"GitHub repository name",privateRepository:"Create as a private repository",createRepository:"Create GitHub repository",repositoryCreated:"GitHub repository created.",origin:"origin",openGitHub:"Open GitHub",clean:"Working tree clean",changedFiles:"{{count}} changed files",commitAndPush:"Commit and push",identity:"Commits use {{username}} <{{username}}@texlite.com> for this command only.",detachedHead:"Detached HEAD: return to the default branch before committing or pushing.",detachedAt:"detached at {{revision}}",commitMessage:"Commit message",commitPlaceholder:"Describe this backup…",commit:"Commit",committed:"Changes committed.",noChangesToCommit:"There are no new changes to commit.",push:"Push",pushed:"Push succeeded. The backup is up to date on GitHub.",pushFailed:"Push failed",workingDiff:"Working diff",refresh:"Refresh",diffTitle:"Diff",diffTruncated:"output truncated",diffFontSize:"Diff font size",diffFontDecrease:"Decrease diff font size",diffFontIncrease:"Increase diff font size",fullscreenDiff:"View diff full screen",exitFullscreenDiff:"Exit full screen",noChanges:"No differences to display.",history:"History",historyHint:"Up to 100 recent commits",noCommits:"No commits yet.",viewCommitDiff:"View this commit's diff",checkoutVersion:"Checkout this version",checkoutTitle:"Checkout version",checkout:"Checkout",checkoutDescription:"Checkout {{revision}} — {{message}}. By default Git preserves compatible uncommitted changes and refuses conflicts.",forceCheckout:"Force overwrite",forceCheckoutDescription:"Explicitly discard tracked and untracked working changes before checkout. This cannot be undone.",returnToBranch:"Return to {{branch}}",returnTitle:"Return to default branch",returnDescription:"Checkout {{branch}}. By default Git preserves compatible uncommitted changes and refuses conflicts.",discardChanges:"Discard changes",noChangesToDiscard:"There are no changes to discard.",discardTitle:"Discard uncommitted changes",discardDescription:"Restore all tracked files to the current HEAD commit. Untracked files are unaffected.",discardConfirm:"Discard changes"},Of={title:"System status",description:"Live server health and recent operation latency. Values refresh every five seconds.",refresh:"Refresh",uptime:"Uptime",memory:"Memory",heap:"heap",compileQueue:"Compile jobs",pending:"{{count}} pending",collaboration:"Collaboration",sessions:"{{count}} sessions",roomsAndDirty:"{{rooms}} rooms · {{dirty}} dirty files",eventLoop:"Event-loop latency",latencySummary:"P50 {{p50Ms}} ms · P95 {{p95Ms}} ms · max {{maxMs}} ms",operationDurations:"Recent operation durations",noSamples:"No operation samples have been collected yet.",operation:"Operation",samples:"Samples",last:"Last",max:"Max",operations:{collaboration:{connect:"Open collaboration room",persist:"Save collaboration changes"},workspace:{project:"Load project metadata",files:"Load project files",compileState:"Load retained PDF state"},compile:{snapshot:"Prepare compile snapshot",request:"Compile request total",cacheSync:"Update compiler cache",latexmk:"Run latexmk",artifactCopy:"Publish compile artifacts"},outline:{build:"Build project outline"},search:{project:"Search project"},completions:{build:"Build completion index"}}},_f={title:"Tags",add:"Add tag",create:"Create tag",createDescription:"Create a private reusable colored tag for organizing your projects.",assign:"Tags",assignTitle:"Tags for {{project}}",assignDescription:"Select your private tags for this project. Other users have their own tags.",empty:"Create a tag first.",allAssigned:"All available tags are already assigned.",name:"Tag name",color:"Color",filter:"Filter",red:"Red",orange:"Orange",yellow:"Yellow",green:"Green",blue:"Blue",purple:"Purple",gray:"Gray"},Pf={generic:"Operation failed",request:"Request failed ({{status}})",upload:"Upload failed",fileExists:"A file or folder with this name already exists.",pathConflict:"The destination path is already used by a folder or file.",duplicateUploadNames:"The selected files contain duplicate names: {{files}}.",fileTooLarge:"The file exceeds the {{size}} MB limit.",zipOnly:"Please choose a ZIP archive.",collaborationUnavailable:"Live collaboration is not connected. Reconnect before saving or compiling.",codes:{AUTH_INVALID:"The username or password is incorrect.",CURRENT_PASSWORD_INVALID:"The current password is incorrect.",USER_NOT_FOUND:"The user no longer exists.",LAST_ADMIN:"At least one administrator must remain active.",SELF_DELETE_FORBIDDEN:"You cannot delete the currently signed-in administrator.",PROJECT_CREATE_FORBIDDEN:"You do not have permission to create projects.",PROJECT_NOT_FOUND:"The project does not exist or is no longer accessible.",PROJECT_OWNER_ONLY:"Only the project owner can change this setting.",PROJECT_EDIT_FORBIDDEN:"You do not have edit permission for this project.",DICTIONARY_EDIT_FORBIDDEN:"You do not have permission to maintain this project's dictionary.",TAG_NOT_FOUND:"The selected tag does not exist.",GIT_TOKEN_INVALID:"Enter a GitHub token.",GIT_REPOSITORY_NAME_INVALID:"Enter a GitHub repository name.",GIT_REVISION_INVALID:"Choose a Git revision to check out.",PROJECT_DELETE_FORBIDDEN:"Only the project owner can delete this project.",MEMBERS_MANAGE_FORBIDDEN:"Only the project owner can manage project members.",OWNER_MEMBER_FORBIDDEN:"The project owner cannot be added as a member.",INVALID_PATH:"The file path is invalid.",RESERVED_PATH:"This path is reserved by TexLite.",PATH_EXISTS:"The destination path is already used by a file or folder.",FILE_EXISTS:"A file with this name already exists.",PATH_NOT_FOUND:"The file or folder does not exist.",FILE_NOT_FOUND:"The file does not exist.",DIRECTORY_NOT_FOUND:"The destination folder does not exist.",MOVE_INTO_SELF:"A folder cannot be moved into itself.",MAIN_FILE_DELETE_FORBIDDEN:"The main document cannot be deleted.",FILE_TOO_LARGE:"This file is too large to open or upload.",UPLOAD_EMPTY:"No file was selected for upload.",COMMENT_FILE_NOT_FOUND:"The file for this comment does not exist.",COMMENT_RANGE_INVALID:"The comment source range is invalid.",COMMENT_NOT_FOUND:"The comment does not exist.",COMMENT_EDIT_FORBIDDEN:"You can only edit your own comments.",COMMENT_DELETE_FORBIDDEN:"You can only delete your own comments.",REPLY_NOT_FOUND:"The reply does not exist.",REPLY_EDIT_FORBIDDEN:"You can only edit your own replies.",REPLY_DELETE_FORBIDDEN:"You can only delete your own replies.",COMMENT_UPDATE_EMPTY:"There is no comment content to update.",MAIN_FILE_NOT_FOUND:"The selected main document does not exist.",LATEXMKRC_DISABLED:"Project latexmkrc files are disabled by the administrator.",LATEXMKRC_NOT_FOUND:"The selected latexmkrc file does not exist.",COMPILE_ARTIFACTS_NOT_FOUND:"No compiled artifacts are available yet.",COMPILE_ARTIFACT_NOT_FOUND:"The compiled artifact does not exist.",ARTIFACT_PREVIEW_UNSUPPORTED:"This artifact cannot be previewed as text; download it instead.",SYNC_SOURCE_INVALID:"The source location is invalid.",SOURCE_FILE_NOT_FOUND:"The source file does not exist.",SYNCTEX_NOT_AVAILABLE:"No SyncTeX data is available. Compile the project again.",SYNC_PDF_INVALID:"The PDF location is invalid.",SYNCTEX_EXTERNAL_PATH:"SyncTeX returned a source path outside the project.",COMPILE_FORBIDDEN:"You do not have permission to compile this project.",PDF_NOT_FOUND:"No PDF has been generated yet.",API_NOT_FOUND:"The API endpoint does not exist.",SERVER_ERROR:"The server could not complete the request.",REQUEST_INVALID:"The request is invalid."}},Rf={historyVersionNotFound:"The selected history version no longer exists.",historyFileNotFound:"This file does not exist in the selected history version.",historyPreviewUnsupported:"This historical file cannot be compared as text.",searchInvalid:"Enter valid text to search for.",gitUnavailable:"Git integration is unavailable. Install Git on the host or correct git.binary in the configuration, then try again.",formatterUnavailable:"tex-fmt is not installed on the host. Install it from https://github.com/wgunderwood/tex-fmt and restart TexLite.",formatFailed:"tex-fmt could not format this source.",mainDocumentInvalid:"The selected file is not a valid LaTeX root document."},Lf={copyright:"© {{year}}",credit:"Designed and developed by CHEN Zhongpu"},Af={section:"Section",subsection:"Subsection",bold:"Bold",emphasis:"Emphasis",citation:"Citation",reference:"Cross-reference",label:"Label",image:"Image",unordered:"Unordered list",ordered:"Ordered list",equation:"Equation",figure:"Figure",projectCommand:"Project command",projectCommandArgs:"Project command ({{count}} arguments)",projectMacro:"Project macro",expl3Command:"Expl3 project command",mathOperator:"Project math operator",mathDelimiter:"Project math delimiter",projectEnvironment:"Project environment",projectFile:"Project file",package:"Package",documentClass:"Document class",currentFile:"Current file",project:"Project",latex:"LaTeX",standard:"LaTeX command"},Ff={common:vf,auth:Sf,projects:jf,users:Cf,editor:kf,navigation:Ef,history:Df,projectSettings:Nf,git:Tf,metrics:Of,tags:_f,errors:Pf,apiErrors:Rf,footer:Lf,completions:Af},If={cancel:"取消",create:"创建",add:"添加",remove:"移除",delete:"删除",close:"关闭",user:"用户",permission:"权限",readOnly:"只读",readWrite:"读写",settings:"设置",comments:"批注",files:"文件",outline:"大纲",loading:"正在载入…",enabled:"允许",disabled:"禁止",normal:"正常",admin:"管理员",language:"语言",languageEnglish:"English",languageChinese:"中文"},Mf={tagline:"轻量 LaTeX 写作环境",username:"用户名",password:"密码",login:"登录",contact:"需要账号?请联系 {{email}}",firstLogin:"首次登录,请修改初始密码",currentPassword:"当前密码",newPassword:"新密码",confirmPassword:"确认新密码",updatePassword:"更新密码",mismatch:"两次输入的新密码不一致",passwordMinimum:"至少 {{count}} 位",sessionExpired:"登录状态已过期,请重新登录。",logout:"退出"},$f={title:"项目",subtitle:"创建、编辑和分享 LaTeX 文档",restricted:"你可以访问别人共享给你的项目;创建权限由管理员授予",new:"新建项目",newDescription:"项目会使用配置文件中的默认 LaTeX 引擎。",name:"项目名称",emptyTitle:"一起创造出色的作品",emptyDescription:"创建新项目,或上传已有的 LaTeX 压缩包开始写作。",emptyRestricted:"共享给你的项目会显示在这里。",noMatches:"没有符合当前搜索或标签筛选条件的项目。",upload:"上传项目",uploadDescription:"上传 ZIP 压缩包;若只有一个顶层目录会自动去除。单文件最大 {{size}} MB。",zipFile:"ZIP 压缩包",import:"导入项目",importing:"正在导入…",search:"搜索项目…",grid:"网格",list:"列表",allTags:"全部标签",sortBy:"排序",sortModified:"最后修改时间",sortCreated:"创建时间",scope:"项目状态",active:"活跃项目",archived:"已归档",archive:"归档",unarchive:"取消归档",noArchived:"还没有归档项目。",pagination:"项目分页",pageOf:"第 {{page}} / {{totalPages}} 页 · 共 {{count}} 个项目",previousPage:"上一页",nextPage:"下一页",owner:"所有者",created:"创建时间",modified:"最后修改",modifiedBy:"最后修改人",byUser:"由 {{user}} 修改",modifiedByUser:"{{time}} · 由 {{user}} 修改",deletedUser:"已删除用户",filterTags:"按标签过滤",rename:"重命名",renameTitle:"重命名项目",duplicate:"复制项目",duplicating:"正在复制…",duplicateTitle:"复制项目",duplicateDescription:"创建“{{project}}”的独立副本。会复制文件和项目设置,但不会复制成员、批注、Git 历史和编译产物。",download:"下载",transfer:"转让",transferOwnership:"转让项目",transferDescription:"为“{{project}}”选择新的所有者。",newOwner:"新所有者",chooseNewOwner:"请选择用户",noTransferUsers:"没有其他可用用户",transferWarning:"转让后你仍保留读写权限。源码、历史、批注和成员不会改变;已保存的 GitHub token 会被移除,由新所有者配置自己的凭据。",transferForbidden:"只有当前项目所有者可以转让项目。",transferTargetInvalid:"请选择新的项目所有者。",transferSelf:"你已经是该项目的所有者。",deleteTitle:"删除项目",deleteDescription:"确定永久删除“{{project}}”及其全部文件吗?此操作不可撤销。",chooseZip:"选择 ZIP 项目",dropZip:"将 ZIP 压缩包拖放到这里",browse:"浏览文件",selectedFileSize:"已选择 · {{size}}",clearFile:"清除已选文件"},Uf={manage:"用户管理",back:"返回项目",onlyAdmin:"仅管理员可以创建用户",add:"添加用户",role:"角色",createProjects:"创建项目",ownedProjects:"拥有项目",status:"状态",actions:"操作",adminRequired:"需要管理员权限。",allow:"允许",deny:"禁止",enable:"启用",disable:"禁用",promote:"设为管理员",demote:"降为用户",allowCreate:"允许创建",denyCreate:"禁止创建",resetPassword:"重置密码",initialPassword:"登录密码",displayName:"显示名称",addDescription:"设置登录密码,或生成一个安全的随机密码。",createUser:"创建用户",randomPassword:"随机密码",generatePassword:"生成随机密码",resetDescription:"为 {{username}} 设置初始密码;其现有会话会被注销。",reset:"重置",deleteTitle:"删除用户",deleteDescription:"确认删除 {{username}}?此操作不可撤销。",ownedChoice:"其拥有的 {{count}} 个项目",transferProjects:"转移给当前管理员",deleteProjects:"永久删除项目及全部文件"},zf={saved:"已保存",savedAt:"已于 {{time}} 保存到服务器",loading:"载入中",pending:"等待保存",saving:"正在保存到服务器",saveFailed:"保存失败",offlineDraft:"离线 · 本地草稿已保留",compile:"编译 · {{engine}}",compiling:"编译中…",compileQueued:"编译已排队…",compileFailedRetained:"编译失败,当前显示上一次成功生成的 PDF({{time}})。",compileFailedNoPdf:"编译失败,且没有可用的成功 PDF。",upToDate:"文件已是最新,无需重新编译。",addComment:"添加批注",sourceComments:"源码批注",projectSettings:"项目设置",uploadAttachment:"上传附件",newFile:"新建文本文件",binary:"二进制附件已保存,但不能在文本编辑器中打开。",noOutline:"当前文件没有章节",preview:"PDF 预览",previewHint:"点击“编译”生成文档",pdfCompiledAt:"成功编译于 {{time}}",pdfCompiledAtFor:"{{file}} 成功编译于 {{time}}",currentMainDocument:"当前作为主文档编译:{{path}}",mainDocumentCandidate:"LaTeX 主文档候选:{{path}}",currentMainShort:"主文档",deletedUser:"已删除用户",orphaned:"锚点已丢失",line:"第 {{line}} 行",reopen:"重新打开",resolve:"标记为已解决",noComments:"当前文件没有批注",newFileDescription:"可以包含目录,例如 chapters/introduction.tex。",filePath:"文件路径",commentDescription:"已选择 {{count}} 个字符",pointComment:"未选择文本,将在当前光标位置添加批注。",commentContent:"批注内容",backToProjects:"返回项目列表",outputTabs:"编译输出",log:"日志",warnings:"警告",errors:"错误",artifacts:"产物",noLog:"编译后将在此显示日志。",noWarnings:"最近一次编译没有警告。",noErrors:"最近一次编译没有错误。",projectRoot:"项目根目录",uploadTo:"上传到 {{folder}}",dropFiles:"拖放文件以上传",newFolder:"新建文件夹",folderName:"文件夹名称",folderDestination:"文件夹将创建在 {{folder}} 中。",uploadOverwriteTitle:"文件已存在",uploadOverwriteDescription:"以下文件已经存在:{{files}}。要覆盖它们吗?",uploadOverwrite:"覆盖文件",noArtifacts:"编译后将在此显示输出产物。",selectArtifact:"选择一个文本产物进行预览。",viewArtifact:"查看产物",downloadArtifact:"下载产物",downloadToView:"该产物需要下载后查看",collapseFiles:"折叠文件面板",move:"移动",moveTitle:"移动 {{name}}",moveDescription:"选择目标文件夹;源码、批注和项目路径会保持关联。",destinationFolder:"目标文件夹",deletePath:"删除文件或文件夹",deletePathTitle:"删除 {{name}}",deletePathDescription:"确定删除 {{path}}?此操作不可撤销。",deletePathActiveDescription:"确定删除 {{path}}?{{users}} 当前正在打开它,删除后这些会话将关闭该文件。",deletePathWillClose:"系统会拒绝该路径上迟到的修改,避免内容被静默丢失。",fileDeletedByCollaborator:"{{path}} 已在其他会话中删除,现已打开安全的备用文件。",compileShortcut:"保存并编译(Ctrl+S / Cmd+S)",compilingBy:"{{name}} 正在编译",formatSelection:"格式化选区",formatting:"正在格式化…",formatSelectionHint:"选择一段 LaTeX 源码后格式化",formatSelectionRequired:"请先选择 LaTeX 源码,再进行格式化。",formatSelectionComplete:"所选 LaTeX 源码已格式化。",formatFailedContinue:"格式化失败,仍将继续编译:{{message}}",formatFailed:"无法格式化选区:{{message}}",formatSourceChanged:"格式化期间源码已发生变化,已跳过本次格式化。",formatSelectionChanged:"格式化期间所选源码已发生变化,请重新选择后再试。",vimOn:"Vim 已开启",vimOnHint:"当前编辑器已启用 Vim 键位。",reply:"回复",replyPlaceholder:"输入回复内容…",sendReply:"发送回复",editComment:"编辑批注",deleteComment:"删除批注",saveChanges:"保存修改",deleteCommentTitle:"删除批注",deleteCommentDescription:"确定删除这条批注及其 {{count}} 条回复吗?此操作不可撤销。",editReply:"编辑回复",deleteReply:"删除回复",deleteReplyTitle:"删除回复",deleteReplyDescription:"确定删除这条回复吗?此操作不可撤销。",editedAt:"编辑于 {{time}}",outlineJump:"跳转到源码第 {{line}} 行并定位 PDF",lineNumber:"第 {{line}} 行",showInSource:"在源码中显示当前 PDF 位置",showInPdf:"在 PDF 中显示当前源码光标位置",pdfLoadFailed:"无法载入 PDF 预览",pdfZoomControls:"PDF 缩放控件",downloadPdf:"下载 PDF",downloadResource:"下载文件",resourceTooLarge:"该文件大小为 {{size}},超过 {{limit}} 的直接预览上限。",resourceTooLargeTitle:"文件过大,无法直接预览",resourceTooLargeDescription:"请下载文件后在本地打开。",resourceUnsupportedTitle:"无法预览",resourceUnsupportedDescription:"浏览器不能直接渲染此文件类型,请下载后在本地打开。",resourcePreview:{image:"图片预览",pdf:"PDF 预览",text:"文本预览",unsupported:"文件预览"},pdfZoomOut:"缩小",pdfZoomIn:"放大",pdfFitWidth:"适合宽度",layout:{label:"布局",choose:"选择布局",current:"当前布局:{{layout}}","editor-pdf":{name:"编辑器与 PDF",description:"并排显示源码编辑器和 PDF 预览"},"editor-only":{name:"仅编辑器",description:"将工作区用于源码编辑"},"pdf-only":{name:"仅 PDF",description:"将工作区用于 PDF 和编译输出"}},collaboration:{connecting:"正在连接协作服务…",connected:"实时协作已连接",disconnected:"实时协作连接已断开",editing:"正在编辑",viewing:"正在查看",joining:"正在进入项目",reconnect:"重新连接",activeSessions:"{{count}} 个活跃会话",showMoreSessions:"展开另外 {{count}} 个会话",showFewerSessions:"收起会话列表",sessionTooltip:"{{name}}(@{{username}})· {{file}} · {{activity}} · {{permission}}"},search:{button:"查找",title:"查找和替换(Ctrl+F / Cmd+F)",find:"查找",replace:"替换为",next:"下一个",previous:"上一个",all:"选择全部",matchCase:"区分大小写",regexp:"正则表达式",wholeWord:"全字匹配",replaceNext:"替换",replaceAll:"全部替换",currentMatch:"当前匹配",onLine:"位于行",replacedMatchOnLine:"已替换第 $ 行的匹配项",replacedMatches:"已替换 $ 个匹配项",goToLine:"跳转到行",go:"跳转",matchCount:"共 {{count}} 个匹配",noMatches:"没有匹配项",invalidQuery:"正则表达式无效"}},Vf={quickOpen:"快速打开",quickOpenDescription:"按名称打开项目文件(Ctrl/Cmd+P)。",filePlaceholder:"输入文件名…",noFiles:"没有匹配的文件。",projectSearch:"项目搜索",projectSearchDescription:"在项目源码文件中搜索和替换(Ctrl/Cmd+Shift+F)。",searchPlaceholder:"搜索全部源码文件…",replacePlaceholder:"替换为…",matchSummary:"共 {{count}} 个匹配",truncated:"仅显示前 {{count}} 个匹配。",replaceAll:"替换全部 {{count}} 项",replaceConfirmTitle:"在项目中批量替换",replaceConfirmDescription:"确定替换全部 {{count}} 个匹配?自动历史会记录所有修改文件。",replaced:"已在 {{files}} 个文件中替换 {{count}} 项。"},Bf={title:"历史",description:"浏览自动项目版本、比较文件,并安全恢复较早的工作。",empty:"尚无历史版本。",changedCount:"{{count}} 个文件有变化",fileCount:"{{count}} 个文件",changed:"有修改",labelPlaceholder:"为此版本命名",saveLabel:"保存标签",compareCurrent:"与当前版本比较",comparingCurrent:"历史版本与当前文件的比较",chooseFile:"选择文件后,可与当前源码进行比较。",restore:"恢复",restoreFile:"恢复文件",restoreProject:"恢复项目",restoreFileTitle:"恢复此文件",restoreProjectTitle:"恢复此项目版本",restoreFileDescription:"从此版本恢复 {{path}}?系统会先为当前项目创建安全检查点。",restoreProjectDescription:"恢复此版本的全部源码和编译器设置?系统会先为当前项目创建安全检查点。",storage:"历史存储",storageUsage:"已使用 {{used}},上限 {{limit}}",versionUsage:"普通版本 {{count}} / {{limit}}",protectedVersions:"{{count}} 个已标记版本",storageExceeded:"受保护版本或当前基线已超过存储软上限。",deleteVersion:"删除版本",deleteVersionTitle:"删除此历史版本",deleteVersionDescription:"永久删除“{{name}}”?当前项目文件不会改变。",clearAll:"清空历史",clearAllTitle:"清空全部项目历史",clearAllDescription:"永久删除全部历史版本及不再引用的存储数据?当前项目文件不会改变。",reasons:{initial:"项目创建",autosave:"自动保存",file:"文件操作",settings:"编译器设置",git:"Git 操作",restore:"恢复版本",checkpoint:"安全检查点"}},Hf={mainFile:"主文档",engine:"编译引擎",latexmkrc:"项目 latexmkrc",save:"保存项目设置",members:"共享成员",recentLog:"最近编译日志",share:"共享项目",shareDescription:"仅可共享给管理员已创建的用户。",chooseUser:"请选择用户",latexmkrcPlaceholder:`# 留空表示不使用项目 rc 文件
4
4
  $pdf_mode = 1;`,addMember:"添加成员",noMembers:"该项目尚未分享给其他成员。",removeTitle:"移除共享成员",removeDescription:"确认移除 {{username}}?其账号和其他项目不会受到影响。",editorTab:"编辑器外观",compilerTab:"LaTeX 编译器",compilerDescription:"选择本项目所有成员共享的主文档和 LaTeX 编译选项。",editorAppearance:"编辑器外观",editorAppearanceDescription:"这些偏好仅作用于当前浏览器中的当前用户和项目;项目词典是共享的。",saveAppearance:"保存外观设置",saveCompiler:"保存编译器设置",projectConfiguration:"项目配置",fontFamily:"英文字体",fontSize:"字体大小",lineHeight:"行间距",dictionary:"项目词典",dictionaryDescription:"添加到这里的词不会在本项目的拼写检查中标记;具有编辑权限的用户可以维护此列表。",dictionaryPlaceholder:"添加自定义词",addWord:"添加词",dictionaryEmpty:"暂未添加自定义词。",lineWrapping:"自动换行",spellCheck:"单词拼写检查",vimMode:"Vim 键位",vimModeDescription:"在当前编辑器中使用 Vim 的普通、插入和可视模式。",vimHelp:"查看帮助",formatOnCompile:"编译前自动格式化 LaTeX",formatOnCompileDescription:"默认关闭;格式化会在编译前由服务器执行。",formatRequiresWrite:"需要项目编辑权限才能使用格式化。",formatterDescription:"格式化使用宿主机上的可选 tex-fmt 命令。",formatterInstall:"安装或查看 tex-fmt 文档",spellingIssues:"发现 {{count}} 个拼写问题(去重后 {{uniqueCount}} 个)",noSpellingIssues:"未发现拼写问题。",spellCheckFirst:"第一个拼写问题",spellCheckPrevious:"上一个拼写问题",spellCheckNext:"下一个拼写问题",spellCheckLast:"最后一个拼写问题",spellCheckPosition:"第 {{current}}/{{total}} 个",fontJetBrains:"JetBrains Mono",fontSourceCode:"Source Code Pro",fontIbmPlex:"IBM Plex Mono",fontFiraCode:"Fira Code",fontIosevka:"Iosevka",lineHeightCompact:"紧凑",lineHeightNormal:"标准",lineHeightRelaxed:"宽松"},qf={title:"Git 备份",description:"管理本地 Git 历史及 GitHub 备份;只有项目创建者可以执行这些操作。",authentication:"GitHub 身份验证",authenticationHint:"token 需要仓库 Administration 与 Contents 写权限;它会加密保存,不会写入项目仓库或远程地址。",recommendedAccessTitle:"建议的仓库访问范围:All repositories(所有仓库)",recommendedAccess:"texLite 面向相互信任的用户。请选择 All repositories,使该 token 能创建仓库,并访问之后新建的仓库;同时授予 Administration 和 Contents 的 Read and write 权限。",token:"个人访问 token",tokenPlaceholder:"在此粘贴 GitHub token",replaceToken:"替换个人访问 token",saveToken:"保存并验证 token",createToken:"创建细粒度 token",connectedAs:"已连接为 @{{login}}",removeToken:"移除 token",tokenSaved:"GitHub token 已保存,本地仓库已就绪。",tokenRemoved:"GitHub token 已移除。",repository:"仓库",localReady:"项目源码已由本地 Git 仓库管理。",localPending:"保存有效 token 后将自动初始化本地 Git 仓库。",repositoryName:"GitHub 仓库名称",privateRepository:"创建为私有仓库",createRepository:"创建 GitHub 仓库",repositoryCreated:"GitHub 仓库创建成功。",origin:"远程仓库",openGitHub:"打开 GitHub",clean:"工作区干净",changedFiles:"{{count}} 个文件有修改",commitAndPush:"提交与推送",identity:"本次提交临时使用 {{username}} <{{username}}@texlite.com>,不会写入 Git 配置。",detachedHead:"当前处于 detached HEAD;请先返回默认分支再提交或推送。",detachedAt:"detached 于 {{revision}}",commitMessage:"提交说明",commitPlaceholder:"说明本次备份的内容…",commit:"提交",committed:"修改已提交。",noChangesToCommit:"当前没有新的修改可以提交。",push:"推送",pushed:"推送成功,GitHub 备份已是最新。",pushFailed:"推送失败",workingDiff:"当前差异",refresh:"刷新",diffTitle:"差异",diffTruncated:"输出已截断",diffFontSize:"差异字体大小",diffFontDecrease:"减小差异字体",diffFontIncrease:"增大差异字体",fullscreenDiff:"全屏查看差异",exitFullscreenDiff:"退出全屏",noChanges:"没有可显示的差异。",history:"提交历史",historyHint:"最多显示最近 100 次提交",noCommits:"尚无提交。",viewCommitDiff:"查看该提交的差异",checkoutVersion:"checkout 到该版本",checkoutTitle:"Checkout 版本",checkout:"Checkout",checkoutDescription:"将 checkout 到 {{revision}} — {{message}}。默认由 Git 保留兼容的未提交修改,发生冲突时拒绝操作。",forceCheckout:"强制覆盖",forceCheckoutDescription:"明确丢弃所有已跟踪及未跟踪的工作区修改后再 checkout;此操作不可撤销。",returnToBranch:"返回 {{branch}}",returnTitle:"返回默认分支",returnDescription:"将 checkout 到 {{branch}}。默认由 Git 保留兼容的未提交修改,发生冲突时拒绝操作。",discardChanges:"撤销修改",noChangesToDiscard:"当前没有可以撤销的修改。",discardTitle:"撤销未提交修改",discardDescription:"把所有已跟踪文件恢复到当前 HEAD(上次 commit)。未跟踪文件不受影响。",discardConfirm:"确认撤销"},Wf={title:"系统状态",description:"服务器实时健康状态和近期操作耗时,每五秒自动刷新。",refresh:"刷新",uptime:"运行时间",memory:"内存",heap:"堆内存",compileQueue:"编译任务",pending:"{{count}} 个等待中",collaboration:"协作",sessions:"{{count}} 个会话",roomsAndDirty:"{{rooms}} 个房间 · {{dirty}} 个待保存文件",eventLoop:"事件循环延迟",latencySummary:"P50 {{p50Ms}} ms · P95 {{p95Ms}} ms · 最大 {{maxMs}} ms",operationDurations:"近期操作耗时",noSamples:"尚未采集到操作样本。",operation:"操作",samples:"样本",last:"最近",max:"最大",operations:{collaboration:{connect:"打开协作房间",persist:"保存协作修改"},workspace:{project:"加载项目元数据",files:"加载项目文件",compileState:"加载保留的 PDF 状态"},compile:{snapshot:"准备编译快照",request:"编译请求总耗时",cacheSync:"更新编译缓存",latexmk:"运行 latexmk",artifactCopy:"发布编译产物"},outline:{build:"生成项目大纲"},search:{project:"项目内搜索"},completions:{build:"生成补全索引"}}},Kf={title:"标签",add:"添加标签",create:"新建标签",createDescription:"创建仅自己可见的可复用彩色标签,用于整理项目。",assign:"标签",assignTitle:"“{{project}}”的标签",assignDescription:"勾选你为此项目设置的私有标签;其他用户拥有各自的标签。",empty:"请先创建标签。",allAssigned:"所有可用标签均已添加。",name:"标签名称",color:"颜色",filter:"筛选",red:"红色",orange:"橙色",yellow:"黄色",green:"绿色",blue:"蓝色",purple:"紫色",gray:"灰色"},Gf={generic:"操作失败",request:"请求失败({{status}})",upload:"上传失败",fileExists:"同名文件或文件夹已经存在。",pathConflict:"目标路径已经被文件或文件夹占用。",duplicateUploadNames:"所选文件中存在重复名称:{{files}}。",fileTooLarge:"文件超过 {{size}} MB 限制。",zipOnly:"请选择 ZIP 压缩包。",collaborationUnavailable:"实时协作尚未连接,请在重新连接后保存或编译。",codes:{AUTH_INVALID:"用户名或密码错误。",CURRENT_PASSWORD_INVALID:"当前密码错误。",USER_NOT_FOUND:"用户不存在或已被删除。",LAST_ADMIN:"系统必须保留至少一名可用管理员。",SELF_DELETE_FORBIDDEN:"不能删除当前登录的管理员。",PROJECT_CREATE_FORBIDDEN:"管理员尚未授予你创建项目的权限。",PROJECT_NOT_FOUND:"项目不存在或你已无法访问。",PROJECT_OWNER_ONLY:"只有项目所有者可以修改此设置。",PROJECT_EDIT_FORBIDDEN:"你没有此项目的编辑权限。",DICTIONARY_EDIT_FORBIDDEN:"你没有维护本项目词典的权限。",TAG_NOT_FOUND:"所选标签不存在。",GIT_TOKEN_INVALID:"请输入 GitHub token。",GIT_REPOSITORY_NAME_INVALID:"请输入 GitHub 仓库名称。",GIT_REVISION_INVALID:"请选择要 checkout 的 Git 版本。",PROJECT_DELETE_FORBIDDEN:"只有项目所有者可以删除项目。",MEMBERS_MANAGE_FORBIDDEN:"只有项目所有者可以管理项目成员。",OWNER_MEMBER_FORBIDDEN:"项目所有者不能作为成员添加。",INVALID_PATH:"文件路径无效。",RESERVED_PATH:"此路径由 TexLite 保留。",PATH_EXISTS:"目标路径已被文件或文件夹占用。",FILE_EXISTS:"同名文件已经存在。",PATH_NOT_FOUND:"文件或文件夹不存在。",FILE_NOT_FOUND:"文件不存在。",DIRECTORY_NOT_FOUND:"目标文件夹不存在。",MOVE_INTO_SELF:"不能把文件夹移动到自身内部。",MAIN_FILE_DELETE_FORBIDDEN:"不能删除主文档。",FILE_TOO_LARGE:"文件过大,无法打开或上传。",UPLOAD_EMPTY:"没有选择要上传的文件。",COMMENT_FILE_NOT_FOUND:"批注对应的文件不存在。",COMMENT_RANGE_INVALID:"批注的源码区间无效。",COMMENT_NOT_FOUND:"批注不存在。",COMMENT_EDIT_FORBIDDEN:"只能编辑自己的批注。",COMMENT_DELETE_FORBIDDEN:"只能删除自己的批注。",REPLY_NOT_FOUND:"回复不存在。",REPLY_EDIT_FORBIDDEN:"只能编辑自己的回复。",REPLY_DELETE_FORBIDDEN:"只能删除自己的回复。",COMMENT_UPDATE_EMPTY:"没有可更新的批注内容。",MAIN_FILE_NOT_FOUND:"所选主文档不存在。",LATEXMKRC_DISABLED:"管理员已禁用项目级 latexmkrc。",LATEXMKRC_NOT_FOUND:"所选 latexmkrc 文件不存在。",COMPILE_ARTIFACTS_NOT_FOUND:"尚无可用的编译产物。",COMPILE_ARTIFACT_NOT_FOUND:"编译产物不存在。",ARTIFACT_PREVIEW_UNSUPPORTED:"该产物不能作为文本预览,请下载后查看。",SYNC_SOURCE_INVALID:"源码位置无效。",SOURCE_FILE_NOT_FOUND:"源码文件不存在。",SYNCTEX_NOT_AVAILABLE:"尚无可用的 SyncTeX 数据,请重新编译。",SYNC_PDF_INVALID:"PDF 位置无效。",SYNCTEX_EXTERNAL_PATH:"SyncTeX 返回了项目外部的源码路径。",COMPILE_FORBIDDEN:"你没有编译此项目的权限。",PDF_NOT_FOUND:"尚未生成 PDF。",API_NOT_FOUND:"接口不存在。",SERVER_ERROR:"服务器无法完成请求。",REQUEST_INVALID:"请求格式无效。"}},Jf={historyVersionNotFound:"所选历史版本已不存在。",historyFileNotFound:"所选历史版本中没有这个文件。",historyPreviewUnsupported:"这个历史文件不能作为文本比较。",searchInvalid:"请输入有效的搜索内容。",gitUnavailable:"Git 集成功能不可用。请在宿主机安装 Git,或修正配置中的 git.binary 后重试。",formatterUnavailable:"宿主机未安装 tex-fmt。请访问 https://github.com/wgunderwood/tex-fmt 安装后重启 TexLite。",formatFailed:"tex-fmt 无法格式化这段源码。",mainDocumentInvalid:"所选文件不是有效的 LaTeX 主文档。"},Yf={copyright:"© {{year}}",credit:"Designed and developed by CHEN Zhongpu"},Xf={section:"章节",subsection:"小节",bold:"粗体",emphasis:"强调",citation:"引用文献",reference:"交叉引用",label:"标签",image:"插入图片",unordered:"无序列表",ordered:"有序列表",equation:"公式",figure:"图片环境",projectCommand:"项目命令",projectCommandArgs:"项目命令({{count}} 个参数)",projectMacro:"项目宏",expl3Command:"Expl3 项目命令",mathOperator:"项目数学算子",mathDelimiter:"项目数学定界符",projectEnvironment:"项目环境",projectFile:"项目文件",package:"宏包",documentClass:"文档类",currentFile:"当前文件",project:"项目",latex:"LaTeX",standard:"LaTeX 命令"},Zf={common:If,auth:Mf,projects:$f,users:Uf,editor:zf,navigation:Vf,history:Bf,projectSettings:Hf,git:qf,metrics:Wf,tags:Kf,errors:Gf,apiErrors:Jf,footer:Yf,completions:Xf};we.use(vl).use(Oh).init({resources:{en:{translation:Ff},zh:{translation:Zf}},fallbackLng:"en",supportedLngs:["en","zh"],nonExplicitSupportedLngs:!0,interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator"],caches:["localStorage"]}});class Ao extends Error{constructor(e,n,s=null){super(e),this.status=n,this.code=s}status;code}async function A(t,e={}){const n=await fetch(t,{...e,headers:e.body?{"Content-Type":"application/json",...e.headers}:e.headers}),r=(n.headers.get("content-type")??"").includes("application/json")?await n.json():null;if(!n.ok)throw n.status===401&&typeof window<"u"&&window.dispatchEvent(new Event("texlite:session-expired")),new Ao(Fo(r,n.status),n.status,Sl(r));return r}function Fo(t,e,n="errors.request"){const s=typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:"",r=Sl(t);if(r){const i={AUTH_REQUIRED:"auth.sessionExpired",ADMIN_REQUIRED:"users.adminRequired",HISTORY_VERSION_NOT_FOUND:"apiErrors.historyVersionNotFound",HISTORY_FILE_NOT_FOUND:"apiErrors.historyFileNotFound",HISTORY_FILE_PREVIEW_UNSUPPORTED:"apiErrors.historyPreviewUnsupported",SEARCH_QUERY_INVALID:"apiErrors.searchInvalid",GIT_UNAVAILABLE:"apiErrors.gitUnavailable",FORMATTER_UNAVAILABLE:"apiErrors.formatterUnavailable",FORMAT_FAILED:"apiErrors.formatFailed",PROJECT_TRANSFER_FORBIDDEN:"projects.transferForbidden",PROJECT_TRANSFER_TARGET_INVALID:"projects.transferTargetInvalid",PROJECT_TRANSFER_SELF:"projects.transferSelf",MAIN_DOCUMENT_INVALID:"apiErrors.mainDocumentInvalid"}[r]??`errors.codes.${r}`;if(we.exists(i))return we.t(i,{status:e,...typeof t=="object"&&t!==null?t:{}})}return we.resolvedLanguage?.startsWith("zh")&&s?s:we.t(n,{status:e})}function Sl(t){return typeof t!="object"||t===null||!("code"in t)||typeof t.code!="string"?null:t.code}var Qf=Object.defineProperty,fs=(t,e)=>Qf(t,"name",{value:e,configurable:!0}),jl=!!(typeof window<"u"&&window.document&&window.document.createElement);function rn(t,e,{checkForDefaultPrevented:n=!0}={}){return fs(function(r){if(t?.(r),n===!1||!r||!r.defaultPrevented)return e?.(r)},"handleEvent")}fs(rn,"composeEventHandlers");function ep(t){if(!jl)throw new Error("Cannot access window outside of the DOM");return t?.ownerDocument?.defaultView??window}fs(ep,"getOwnerWindow");function ao(t){if(!jl)throw new Error("Cannot access document outside of the DOM");return t?.ownerDocument??document}fs(ao,"getOwnerDocument");function Cl(t,e=!1){const{activeElement:n}=ao(t);if(!n?.nodeName)return null;if(kl(n)&&n.contentDocument)return Cl(n.contentDocument.body,e);if(e){const s=n.getAttribute("aria-activedescendant");if(s){const r=ao(n).getElementById(s);if(r)return r}}return n}fs(Cl,"getActiveElement");function kl(t){return t.tagName==="IFRAME"}fs(kl,"isFrame");var tp=Object.defineProperty,Io=(t,e)=>tp(t,"name",{value:e,configurable:!0});function co(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}Io(co,"setRef");function El(...t){return e=>{let n=!1;const s=t.map(r=>{const i=co(r,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let r=0;r<s.length;r++){const i=s[r];typeof i=="function"?i():co(t[r],null)}}}}Io(El,"composeRefs");function ps(...t){return h.useCallback(El(...t),t)}Io(ps,"useComposedRefs");var np=Object.defineProperty,ut=(t,e)=>np(t,"name",{value:e,configurable:!0});function sp(t,e){const n=h.createContext(e);n.displayName=t+"Context";const s=ut(i=>{const{children:a,...c}=i,l=h.useMemo(()=>c,Object.values(c));return o.jsx(n.Provider,{value:l,children:a})},"Provider");s.displayName=t+"Provider";function r(i,a={}){const{optional:c=!1}=a,l=h.useContext(n);if(l)return l;if(e!==void 0)return e;if(!c)throw new Error(`\`${i}\` must be used within \`${t}\``)}return ut(r,"useContext"),[s,r]}ut(sp,"createContext");function Dl(t,e=[]){let n=[];function s(i,a){const c=h.createContext(a);c.displayName=i+"Context";const l=n.length;n=[...n,a];const d=ut(u=>{const{scope:m,children:p,...g}=u,x=m?.[t]?.[l]||c,b=h.useMemo(()=>g,Object.values(g));return o.jsx(x.Provider,{value:b,children:p})},"Provider");d.displayName=i+"Provider";function f(u,m,p={}){const{optional:g=!1}=p,x=m?.[t]?.[l]||c,b=h.useContext(x);if(b)return b;if(a!==void 0)return a;if(!g)throw new Error(`\`${u}\` must be used within \`${i}\``)}return ut(f,"useContext"),[d,f]}ut(s,"createContext");const r=ut(()=>{const i=n.map(a=>h.createContext(a));return ut(function(c){const l=c?.[t]||i;return h.useMemo(()=>({[`__scope${t}`]:{...c,[t]:l}}),[c,l])},"useScope")},"createScope");return r.scopeName=t,[s,Nl(r,...e)]}ut(Dl,"createContextScope");function Nl(...t){const e=t[0];if(t.length===1)return e;const n=ut(()=>{const s=t.map(r=>({useScope:r(),scopeName:r.scopeName}));return ut(function(i){const a=s.reduce((c,{useScope:l,scopeName:d})=>{const u=l(i)[`__scope${d}`];return{...c,...u}},{});return h.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])},"useComposedScopes")},"createScope");return n.scopeName=e.scopeName,n}ut(Nl,"composeContextScopes");var on=globalThis?.document?h.useLayoutEffect:()=>{},rp=Object.defineProperty,ip=(t,e)=>rp(t,"name",{value:e,configurable:!0}),op=nr[" useId ".trim().toString()]||(()=>{}),ap=0;function Rr(t){const[e,n]=h.useState(op());return on(()=>{t||n(s=>s??String(ap++))},[t]),t||(e?`radix-${e}`:"")}ip(Rr,"useId");var cp=Object.defineProperty,lp=(t,e)=>cp(t,"name",{value:e,configurable:!0}),fc=nr[" useEffectEvent ".trim().toString()],pc=nr[" useInsertionEffect ".trim().toString()];function Tl(t){if(typeof fc=="function")return fc(t);const e=h.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof pc=="function"?pc(()=>{e.current=t}):on(()=>{e.current=t}),h.useMemo(()=>((...n)=>e.current?.(...n)),[])}lp(Tl,"useEffectEvent");var dp=Object.defineProperty,sr=(t,e)=>dp(t,"name",{value:e,configurable:!0}),up=nr[" useInsertionEffect ".trim().toString()]||on;function Ol({prop:t,defaultProp:e,onChange:n=sr(()=>{},"onChange"),caller:s}){const[r,i,a]=_l({defaultProp:e,onChange:n}),c=t!==void 0,l=c?t:r,d=h.useCallback(f=>{if(c){const u=Pl(f)?f(t):f;u!==t&&a.current?.(u)}else i(f)},[c,t,i,a]);return[l,d]}sr(Ol,"useControllableState");function _l({defaultProp:t,onChange:e}){const[n,s]=h.useState(t),r=h.useRef(n),i=h.useRef(e);return up(()=>{i.current=e},[e]),h.useEffect(()=>{r.current!==n&&(i.current?.(n),r.current=n)},[n,r]),[n,s,i]}sr(_l,"useUncontrolledState");function Pl(t){return typeof t=="function"}sr(Pl,"isFunction");var mc=Symbol("RADIX:SYNC_STATE");function hp(t,e,n,s){const{prop:r,defaultProp:i,onChange:a,caller:c}=e,l=r!==void 0,d=Tl(a),f=[{...n,state:i}];s&&f.push(s);const[u,m]=h.useReducer((b,j)=>{if(j.type===mc)return{...b,state:j.state};const C=t(b,j);return l&&!Object.is(C.state,b.state)&&d(C.state),C},...f),p=u.state,g=h.useRef(p);h.useEffect(()=>{g.current!==p&&(g.current=p,l||d(p))},[p,g,l]);const x=h.useMemo(()=>r!==void 0?{...u,state:r}:u,[u,r]);return h.useEffect(()=>{l&&!Object.is(r,u.state)&&m({type:mc,state:r})},[r,u.state,l]),[x,m]}sr(hp,"useControllableStateReducer");var fp=Object.defineProperty,bt=(t,e)=>fp(t,"name",{value:e,configurable:!0});function Mo(t){const e=h.forwardRef((n,s)=>{let{children:r,...i}=n,a=null,c=!1;const l=[];lo(r)&&typeof kr=="function"&&(r=kr(r._payload)),h.Children.forEach(r,m=>{if(Fl(m)){c=!0;const p=m;let g="child"in p.props?p.props.child:p.props.children;lo(g)&&typeof kr=="function"&&(g=kr(g._payload)),a=mp(p,g),l.push(a?.props?.children)}else l.push(m)}),a?a=h.cloneElement(a,void 0,l):!c&&h.Children.count(r)===1&&h.isValidElement(r)&&(a=r);const d=a?Al(a):void 0,f=ps(s,d);if(!a){if(r||r===0)throw new Error(c?wp(t):yp(t));return r}const u=Ll(i,a.props??{});return a.type!==h.Fragment&&(u.ref=s?f:d),h.cloneElement(a,u)});return e.displayName=`${t}.Slot`,e}bt(Mo,"createSlot");var Rl=Symbol.for("radix.slottable");function pp(t){const e=bt(n=>"child"in n?n.children(n.child):n.children,"Slottable");return e.displayName=`${t}.Slottable`,e.__radixId=Rl,e}bt(pp,"createSlottable");var mp=bt((t,e)=>{if("child"in t.props){const n=t.props.child;return h.isValidElement(n)?h.cloneElement(n,void 0,t.props.children(n.props.children)):null}return h.isValidElement(e)?e:null},"getSlottableElementFromSlottable");function Ll(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]=(...c)=>{const l=i(...c);return r(...c),l}:r&&(n[s]=r):s==="style"?n[s]={...r,...i}:s==="className"&&(n[s]=[r,i].filter(Boolean).join(" "))}return{...t,...n}}bt(Ll,"mergeProps");function Al(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)}bt(Al,"getElementRef");function Fl(t){return h.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Rl}bt(Fl,"isSlottable");var gp=Symbol.for("react.lazy");function lo(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===gp&&"_payload"in t&&Il(t._payload)}bt(lo,"isLazyComponent");function Il(t){return typeof t=="object"&&t!==null&&"then"in t}bt(Il,"isPromiseLike");var yp=bt(t=>`${t} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),wp=bt(t=>`${t} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),kr=nr[" use ".trim().toString()],xp=Object.defineProperty,bp=(t,e)=>xp(t,"name",{value:e,configurable:!0}),vp=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],jn=vp.reduce((t,e)=>{const n=Mo(`Primitive.${e}`),s=h.forwardRef((r,i)=>{const{asChild:a,...c}=r,l=a?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(l,{...c,ref:i})});return s.displayName=`Primitive.${e}`,{...t,[e]:s}},{});function Ml(t,e){t&&pl.flushSync(()=>t.dispatchEvent(e))}bp(Ml,"dispatchDiscreteCustomEvent");var Sp=Object.defineProperty,jp=(t,e)=>Sp(t,"name",{value:e,configurable:!0});function ns(t){const e=h.useRef(t);return h.useEffect(()=>{e.current=t}),h.useMemo(()=>((...n)=>e.current?.(...n)),[])}jp(ns,"useCallbackRef");var Cp=Object.defineProperty,Fe=(t,e)=>Cp(t,"name",{value:e,configurable:!0}),uo="dismissableLayer.update",kp="dismissableLayer.pointerDownOutside",Ep="dismissableLayer.focusOutside",gc,$l=h.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Dp=h.forwardRef(Fe(function(e,n){const{disableOutsidePointerEvents:s=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:c,onInteractOutside:l,onDismiss:d,...f}=e,u=h.useContext($l),[m,p]=h.useState(null),g=m?.ownerDocument??globalThis?.document,[,x]=h.useState({}),b=ps(n,p),j=Array.from(u.layers),[C]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),N=C?j.indexOf(C):-1,T=m?j.indexOf(m):-1,_=u.layersWithOutsidePointerEventsDisabled.size>0,L=T>=N,E=h.useRef(!1),q=zl(W=>{a?.(W),l?.(W),W.defaultPrevented||d?.()},{ownerDocument:g,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:E,dismissableSurfaces:u.dismissableSurfaces,shouldHandlePointerDownOutside:h.useCallback(W=>{if(!(W instanceof Node))return!1;const P=[...u.branches].some(R=>R.contains(W));return L&&!P},[u.branches,L])}),v=Vl(W=>{if(r&&E.current)return;const P=W.target;[...u.branches].some(S=>S.contains(P))||(c?.(W),l?.(W),W.defaultPrevented||d?.())},g),O=m?T===j.length-1:!1,Z=ns(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&d&&(W.preventDefault(),d()))});return h.useEffect(()=>{if(O)return g.addEventListener("keydown",Z,{capture:!0}),()=>g.removeEventListener("keydown",Z,{capture:!0})},[g,O,Z]),h.useEffect(()=>{if(m)return s&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(gc=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(m)),u.layers.add(m),ho(),()=>{s&&(u.layersWithOutsidePointerEventsDisabled.delete(m),u.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=gc))}},[m,g,s,u]),h.useEffect(()=>()=>{m&&(u.layers.delete(m),u.layersWithOutsidePointerEventsDisabled.delete(m),ho())},[m,u]),h.useEffect(()=>{const W=Fe(()=>x({}),"handleUpdate");return document.addEventListener(uo,W),()=>document.removeEventListener(uo,W)},[]),o.jsx(jn.div,{...f,ref:b,style:{pointerEvents:_?L?"auto":"none":void 0,...e.style},onFocusCapture:rn(e.onFocusCapture,v.onFocusCapture),onBlurCapture:rn(e.onBlurCapture,v.onBlurCapture),onPointerDownCapture:rn(e.onPointerDownCapture,q.onPointerDownCapture)})},"DismissableLayer"));function Ul(){const t=h.useContext($l),[e,n]=h.useState(null);return h.useEffect(()=>{if(e)return t.dismissableSurfaces.add(e),()=>{t.dismissableSurfaces.delete(e)}},[e,t.dismissableSurfaces]),n}Fe(Ul,"useDismissableLayerSurface");var Np=Fe(()=>!0,"IS_TRUE");function zl(t,e){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:s=!1,isDeferredPointerDownOutsideRef:r,dismissableSurfaces:i,shouldHandlePointerDownOutside:a=Np}=e,c=ns(t),l=h.useRef(!1),d=h.useRef(!1),f=h.useRef(new Map),u=h.useRef(()=>{});return h.useEffect(()=>{function m(){d.current=!1,r.current=!1,f.current.clear()}Fe(m,"resetOutsideInteraction");function p(){return Array.from(f.current.values()).some(Boolean)}Fe(p,"isOutsideInteractionIntercepted");function g(N){if(!d.current)return;const T=N.target;T instanceof Node&&[...i].some(L=>L.contains(T))||f.current.set(N.type,!0),N.type==="click"&&window.setTimeout(()=>{d.current&&u.current()},0)}Fe(g,"handleInteractionCapture");function x(N){d.current&&f.current.set(N.type,!1)}Fe(x,"handleInteractionBubble");const b=Fe(N=>{if(N.target&&!l.current){let T=function(){n.removeEventListener("click",u.current);const L=p();m(),L||$o(kp,c,_,{discrete:!0})};if(Fe(T,"handleAndDispatchPointerDownOutsideEvent"),!a(N.target)){n.removeEventListener("click",u.current),m(),l.current=!1;return}const _={originalEvent:N};d.current=!0,r.current=s&&N.button===0,f.current.clear(),!s||N.button!==0?T():(n.removeEventListener("click",u.current),u.current=T,n.addEventListener("click",u.current,{once:!0}))}else n.removeEventListener("click",u.current),m();l.current=!1},"handlePointerDown"),j=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const N of j)n.addEventListener(N,g,!0),n.addEventListener(N,x);const C=window.setTimeout(()=>{n.addEventListener("pointerdown",b)},0);return()=>{window.clearTimeout(C),n.removeEventListener("pointerdown",b),n.removeEventListener("click",u.current);for(const N of j)n.removeEventListener(N,g,!0),n.removeEventListener(N,x)}},[n,c,s,r,i,a]),{onPointerDownCapture:Fe(()=>l.current=!0,"onPointerDownCapture")}}Fe(zl,"usePointerDownOutside");function Vl(t,e=globalThis?.document){const n=ns(t),s=h.useRef(!1);return h.useEffect(()=>{const r=Fe(i=>{i.target&&!s.current&&$o(Ep,n,{originalEvent:i},{discrete:!1})},"handleFocus");return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,n]),{onFocusCapture:Fe(()=>s.current=!0,"onFocusCapture"),onBlurCapture:Fe(()=>s.current=!1,"onBlurCapture")}}Fe(Vl,"useFocusOutside");function ho(){const t=new CustomEvent(uo);document.dispatchEvent(t)}Fe(ho,"dispatchUpdate");function $o(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?Ml(r,i):r.dispatchEvent(i)}Fe($o,"handleAndDispatchCustomEvent");var Tp=Object.defineProperty,Ze=(t,e)=>Tp(t,"name",{value:e,configurable:!0}),Mi="focusScope.autoFocusOnMount",$i="focusScope.autoFocusOnUnmount",yc={bubbles:!1,cancelable:!0},Op=h.forwardRef(Ze(function(e,n){const{loop:s=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...c}=e,[l,d]=h.useState(null),f=ns(i),u=ns(a),m=h.useRef(null),p=ps(n,d),g=h.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;h.useEffect(()=>{if(r){let b=function(T){if(g.paused||!l)return;const _=T.target;l.contains(_)?m.current=_:Ht(m.current,{select:!0})},j=function(T){if(g.paused||!l)return;const _=T.relatedTarget;_!==null&&(l.contains(_)||Ht(m.current,{select:!0}))},C=function(T){if(document.activeElement===document.body)for(const L of T)L.removedNodes.length>0&&Ht(l)};Ze(b,"handleFocusIn"),Ze(j,"handleFocusOut"),Ze(C,"handleMutations"),document.addEventListener("focusin",b),document.addEventListener("focusout",j);const N=new MutationObserver(C);return l&&N.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",j),N.disconnect()}}},[r,l,g.paused]),h.useEffect(()=>{if(l){wc.add(g);const b=document.activeElement;if(!l.contains(b)){const C=new CustomEvent(Mi,yc);l.addEventListener(Mi,f),l.dispatchEvent(C),C.defaultPrevented||(Bl(Gl(Uo(l)),{select:!0}),document.activeElement===b&&Ht(l))}return()=>{l.removeEventListener(Mi,f),setTimeout(()=>{const C=new CustomEvent($i,yc);l.addEventListener($i,u),l.dispatchEvent(C),C.defaultPrevented||Ht(b??document.body,{select:!0}),l.removeEventListener($i,u),wc.remove(g)},0)}}},[l,f,u,g]);const x=h.useCallback(b=>{if(!s&&!r||g.paused)return;const j=b.key==="Tab"&&!b.altKey&&!b.ctrlKey&&!b.metaKey,C=document.activeElement;if(j&&C){const N=b.currentTarget,[T,_]=Hl(N);T&&_?!b.shiftKey&&C===_?(b.preventDefault(),s&&Ht(T,{select:!0})):b.shiftKey&&C===T&&(b.preventDefault(),s&&Ht(_,{select:!0})):C===N&&b.preventDefault()}},[s,r,g.paused]);return o.jsx(jn.div,{tabIndex:-1,...c,ref:p,onKeyDown:x})},"FocusScope"));function Bl(t,{select:e=!1}={}){const n=document.activeElement;for(const s of t)if(Ht(s,{select:e}),document.activeElement!==n)return}Ze(Bl,"focusFirst");function Hl(t){const e=Uo(t),n=fo(e,t),s=fo(e.reverse(),t);return[n,s]}Ze(Hl,"getTabbableEdges");function Uo(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:Ze(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}Ze(Uo,"getTabbableCandidates");function fo(t,e){const n=typeof e.checkVisibility=="function"&&e.checkVisibility({checkVisibilityCSS:!0});for(const s of t)if(!(n?!s.checkVisibility({checkVisibilityCSS:!0}):ql(s,{upTo:e})))return s}Ze(fo,"findVisible");function ql(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}Ze(ql,"isHidden");function Wl(t){return t instanceof HTMLInputElement&&"select"in t}Ze(Wl,"isSelectableInput");function Ht(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&Wl(t)&&e&&t.select()}}Ze(Ht,"focus");var wc=Kl();function Kl(){let t=[];return{add(e){const n=t[0];e!==n&&n?.pause(),t=po(t,e),t.unshift(e)},remove(e){t=po(t,e),t[0]?.resume()}}}Ze(Kl,"createFocusScopesStack");function po(t,e){const n=[...t],s=n.indexOf(e);return s!==-1&&n.splice(s,1),n}Ze(po,"arrayRemove");function Gl(t){return t.filter(e=>e.tagName!=="A")}Ze(Gl,"removeLinks");var _p=Object.defineProperty,Pp=(t,e)=>_p(t,"name",{value:e,configurable:!0}),Rp=h.forwardRef(Pp(function(e,n){const{container:s,...r}=e,[i,a]=h.useState(!1);on(()=>a(!0),[]);const c=s||i&&globalThis?.document?.body;return c?pl.createPortal(o.jsx(jn.div,{...r,ref:n}),c):null},"Portal")),Lp=Object.defineProperty,Kt=(t,e)=>Lp(t,"name",{value:e,configurable:!0});function Jl(t,e){return h.useReducer((n,s)=>e[n][s]??n,t)}Kt(Jl,"useStateMachine");var zo=Kt(t=>{const{present:e,children:n}=t,s=Yl(e),r=typeof n=="function"?n({present:s.isPresent}):h.Children.only(n),i=Xl(s.ref,Zl(r));return typeof n=="function"||s.isPresent?h.cloneElement(r,{ref:i}):null},"Presence");function Yl(t){const[e,n]=h.useState(),s=h.useRef(null),r=h.useRef(t),i=h.useRef("none"),a=h.useRef(void 0),c=t?"mounted":"unmounted",[l,d]=Jl(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return h.useEffect(()=>{l==="mounted"?(i.current=a.current??Vn(s.current),a.current=void 0):i.current="none"},[l]),on(()=>{const f=s.current,u=r.current;if(u!==t){const p=i.current,g=Vn(f);t?(a.current=g,d("MOUNT")):g==="none"||f?.display==="none"?d("UNMOUNT"):d(u&&p!==g?"ANIMATION_OUT":"UNMOUNT"),r.current=t}},[t,d]),on(()=>{if(e){let f;const u=e.ownerDocument.defaultView??window,m=Kt(g=>{const b=Vn(s.current).includes(CSS.escape(g.animationName));if(g.target===e&&b&&(d("ANIMATION_END"),!r.current)){const j=e.style.animationFillMode;e.style.animationFillMode="forwards",f=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=j)})}},"handleAnimationEnd"),p=Kt(g=>{g.target===e&&(i.current=Vn(s.current))},"handleAnimationStart");return e.addEventListener("animationstart",p),e.addEventListener("animationcancel",m),e.addEventListener("animationend",m),()=>{u.clearTimeout(f),e.removeEventListener("animationstart",p),e.removeEventListener("animationcancel",m),e.removeEventListener("animationend",m)}}else d("ANIMATION_END")},[e,d]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:h.useCallback(f=>{if(f){const u=getComputedStyle(f);s.current=u,a.current=Vn(u)}else s.current=null;n(f)},[])}}Kt(Yl,"usePresence");function mo(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}Kt(mo,"setRef");function Xl(...t){const e=h.useRef(t);return e.current=t,h.useCallback(n=>{const s=e.current;let r=!1;const i=s.map(a=>{const c=mo(a,n);return!r&&typeof c=="function"&&(r=!0),c});if(r)return()=>{for(let a=0;a<i.length;a++){const c=i[a];typeof c=="function"?c():mo(s[a],null)}}},[])}Kt(Xl,"useStableComposedRefs");function Vn(t){return t?.animationName||"none"}Kt(Vn,"getAnimationName");function Zl(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)}Kt(Zl,"getElementRef");var Ap=Object.defineProperty,Vo=(t,e)=>Ap(t,"name",{value:e,configurable:!0}),Er=0,Mn=null;function Fp(t){return Bo(),t.children}Vo(Fp,"FocusGuards");function Bo(){h.useEffect(()=>{Mn||(Mn={start:go(),end:go()});const{start:t,end:e}=Mn;return document.body.firstElementChild!==t&&document.body.insertAdjacentElement("afterbegin",t),document.body.lastElementChild!==e&&document.body.insertAdjacentElement("beforeend",e),Er++,()=>{Er===1&&(Mn?.start.remove(),Mn?.end.remove(),Mn=null),Er=Math.max(0,Er-1)}},[])}Vo(Bo,"useFocusGuards");function go(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}Vo(go,"createFocusGuard");var Ip=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},$n=new WeakMap,Dr=new WeakMap,Nr={},Ui=0,Ql=function(t){return t&&(t.host||Ql(t.parentNode))},Mp=function(t,e){return e.map(function(n){if(t.contains(n))return n;var s=Ql(n);return s&&t.contains(s)?s:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},$p=function(t,e,n,s){var r=Mp(e,Array.isArray(t)?t:[t]);Nr[n]||(Nr[n]=new WeakMap);var i=Nr[n],a=[],c=new Set,l=new Set(r),d=function(u){!u||c.has(u)||(c.add(u),d(u.parentNode))};r.forEach(d);var f=function(u){!u||l.has(u)||Array.prototype.forEach.call(u.children,function(m){if(c.has(m))f(m);else try{var p=m.getAttribute(s),g=p!==null&&p!=="false",x=($n.get(m)||0)+1,b=(i.get(m)||0)+1;$n.set(m,x),i.set(m,b),a.push(m),x===1&&g&&Dr.set(m,!0),b===1&&m.setAttribute(n,"true"),g||m.setAttribute(s,"true")}catch(j){console.error("aria-hidden: cannot operate on ",m,j)}})};return f(e),c.clear(),Ui++,function(){a.forEach(function(u){var m=$n.get(u)-1,p=i.get(u)-1;$n.set(u,m),i.set(u,p),m||(Dr.has(u)||u.removeAttribute(s),Dr.delete(u)),p||u.removeAttribute(n)}),Ui--,Ui||($n=new WeakMap,$n=new WeakMap,Dr=new WeakMap,Nr={})}},Up=function(t,e,n){n===void 0&&(n="data-aria-hidden");var s=Array.from(Array.isArray(t)?t:[t]),r=Ip(t);return r?(s.push.apply(s,Array.from(r.querySelectorAll("[aria-live], script"))),$p(s,r,n,"aria-hidden")):function(){return null}},zp=Object.defineProperty,pt=(t,e)=>zp(t,"name",{value:e,configurable:!0}),Ho="Dialog",[ed,Fb]=Dl(Ho),[Vp,_t]=ed(Ho),Bp=pt(t=>{const{__scopeDialog:e,children:n,open:s,defaultOpen:r,onOpenChange:i,modal:a=!0}=t,c=h.useRef(null),l=h.useRef(null),[d,f]=Ol({prop:s,defaultProp:r??!1,onChange:i,caller:Ho}),[u,m]=h.useState(0),[p,g]=h.useState(0);return o.jsx(Vp,{scope:e,triggerRef:c,contentRef:l,contentId:Rr(),titleId:Rr(),descriptionId:Rr(),titlePresent:u>0,descriptionPresent:p>0,setTitleCount:m,setDescriptionCount:g,open:d,onOpenChange:f,onOpenToggle:h.useCallback(()=>f(x=>!x),[f]),modal:a,children:n})},"Dialog"),td="DialogPortal",[Hp,nd]=ed(td,{forceMount:void 0}),qp=pt(t=>{const{__scopeDialog:e,forceMount:n,children:s,container:r}=t,i=_t(td,e);return o.jsx(Hp,{scope:e,forceMount:n,children:h.Children.map(s,a=>o.jsx(zo,{present:n||i.open,children:o.jsx(Rp,{asChild:!0,container:r,children:a})}))})},"DialogPortal"),yo="DialogOverlay",Wp=h.forwardRef(pt(function(e,n){const s=nd(yo,e.__scopeDialog),{forceMount:r=s.forceMount,...i}=e,a=_t(yo,e.__scopeDialog);return a.modal?o.jsx(zo,{present:r||a.open,children:o.jsx(Gp,{...i,ref:n})}):null},"DialogOverlay")),Kp=Mo("DialogOverlay.RemoveScroll"),Gp=h.forwardRef(pt(function(e,n){const{__scopeDialog:s,...r}=e,i=_t(yo,s),a=Ul(),c=ps(n,a);return o.jsx(_h,{as:Kp,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(jn.div,{"data-state":qo(i.open),...r,ref:c,style:{pointerEvents:"auto",...r.style}})})},"DialogOverlayImpl")),zs="DialogContent",Jp=h.forwardRef(pt(function(e,n){const s=nd(zs,e.__scopeDialog),{forceMount:r=s.forceMount,...i}=e,a=_t(zs,e.__scopeDialog);return o.jsx(zo,{present:r||a.open,children:a.modal?o.jsx(Yp,{...i,ref:n}):o.jsx(Xp,{...i,ref:n})})},"DialogContent")),Yp=h.forwardRef(pt(function(e,n){const s=_t(zs,e.__scopeDialog),r=h.useRef(null),i=ps(n,s.contentRef,r);return h.useEffect(()=>{const a=r.current;if(a)return Up(a)},[]),o.jsx(sd,{...e,ref:i,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:rn(e.onCloseAutoFocus,a=>{a.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:rn(e.onPointerDownOutside,a=>{const c=a.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;(c.button===2||l)&&a.preventDefault()}),onFocusOutside:rn(e.onFocusOutside,a=>a.preventDefault())})},"DialogContentModal")),Xp=h.forwardRef(pt(function(e,n){const s=_t(zs,e.__scopeDialog),r=h.useRef(!1),i=h.useRef(!1);return o.jsx(sd,{...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 c=a.target;s.triggerRef.current?.contains(c)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})},"DialogContentNonModal")),sd=h.forwardRef(pt(function(e,n){const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...c}=e,l=_t(zs,s);return Bo(),o.jsx(o.Fragment,{children:o.jsx(Op,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o.jsx(Dp,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionPresent?l.descriptionId:void 0,"aria-labelledby":l.titlePresent?l.titleId:void 0,"data-state":qo(l.open),...c,ref:n,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})},"DialogContentImpl")),Zp="DialogTitle",Qp=h.forwardRef(pt(function(e,n){const{__scopeDialog:s,...r}=e,i=_t(Zp,s),{setTitleCount:a}=i;return on(()=>(a(c=>c+1),()=>a(c=>c-1)),[a]),o.jsx(jn.h2,{id:i.titleId,...r,ref:n})},"DialogTitle")),em="DialogDescription",tm=h.forwardRef(pt(function(e,n){const{__scopeDialog:s,...r}=e,i=_t(em,s),{setDescriptionCount:a}=i;return on(()=>(a(c=>c+1),()=>a(c=>c-1)),[a]),o.jsx(jn.p,{id:i.descriptionId,...r,ref:n})},"DialogDescription")),nm="DialogClose",sm=h.forwardRef(pt(function(e,n){const{__scopeDialog:s,...r}=e,i=_t(nm,s);return o.jsx(jn.button,{type:"button",...r,ref:n,onClick:rn(e.onClick,()=>i.onOpenChange(!1))})},"DialogClose"));function qo(t){return t?"open":"closed"}pt(qo,"getState");function Ie({open:t,title:e,description:n,onOpenChange:s,children:r,footer:i,wide:a,extraWide:c,className:l}){const{t:d}=Pe();return o.jsx(Bp,{open:t,onOpenChange:s,children:o.jsxs(qp,{children:[o.jsx(Wp,{className:"dialog-overlay"}),o.jsxs(Jp,{className:`dialog-content${a?" dialog-wide":""}${c?" dialog-extra-wide":""}${l?` ${l}`:""}`,children:[o.jsxs("div",{className:"dialog-header",children:[o.jsxs("div",{children:[o.jsx(Qp,{children:e}),n&&o.jsx(tm,{children:n})]}),o.jsx(sm,{className:"dialog-close","aria-label":d("common.close"),children:"×"})]}),o.jsx("div",{className:"dialog-body",children:r}),i&&o.jsx("div",{className:"dialog-footer",children:i})]})]})})}function Vs({open:t,title:e,description:n,confirmLabel:s,danger:r,onCancel:i,onConfirm:a}){const{t:c}=Pe();return o.jsx(Ie,{open:t,title:e,description:n,onOpenChange:l=>{l||i()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:i,children:c("common.cancel")}),o.jsx("button",{className:r?"danger":"primary",onClick:a,children:s??c("common.remove")})]}),children:o.jsx("div",{})})}function Wo({compact:t=!1}){const{i18n:e,t:n}=Pe(),s=e.resolvedLanguage?.startsWith("zh")?"zh":"en";return o.jsxs("label",{className:`language-switcher${t?" compact":""}`,title:n("common.language"),children:[o.jsx("span",{children:"文/A"}),o.jsxs("select",{value:s,"aria-label":n("common.language"),onChange:r=>{e.changeLanguage(r.target.value)},children:[o.jsx("option",{value:"en",children:n("common.languageEnglish")}),o.jsx("option",{value:"zh",children:n("common.languageChinese")})]})]})}const rm=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),rd=(...t)=>t.filter((e,n,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===n).join(" ").trim();var im={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const om=h.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:s,className:r="",children:i,iconNode:a,...c},l)=>h.createElement("svg",{ref:l,...im,width:e,height:e,stroke:t,strokeWidth:s?Number(n)*24/Number(e):n,className:rd("lucide",r),...c},[...a.map(([d,f])=>h.createElement(d,f)),...Array.isArray(i)?i:[i]]));const I=(t,e)=>{const n=h.forwardRef(({className:s,...r},i)=>h.createElement(om,{ref:i,iconNode:e,className:rd(`lucide-${rm(t)}`,s),...r}));return n.displayName=`${t}`,n};const am=I("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);const id=I("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const cm=I("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);const xc=I("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);const lm=I("ArrowDownUp",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"m21 8-4-4-4 4",key:"1c9v7m"}],["path",{d:"M17 4v16",key:"7dpous"}]]);const od=I("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);const zi=I("ArrowRightLeft",[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);const ad=I("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);const dm=I("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);const um=I("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const cd=I("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const ld=I("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);const Ko=I("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const hm=I("ChevronsLeft",[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]]);const fm=I("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);const pm=I("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Go=I("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 bc=I("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const mm=I("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);const gm=I("Dices",[["rect",{width:"12",height:"12",x:"2",y:"10",rx:"2",ry:"2",key:"6agr2n"}],["path",{d:"m17.92 14 3.5-3.5a2.24 2.24 0 0 0 0-3l-5-4.92a2.24 2.24 0 0 0-3 0L10 6",key:"1o487t"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 14h.01",key:"ssrbsk"}],["path",{d:"M15 6h.01",key:"cblpky"}],["path",{d:"M18 9h.01",key:"2061c0"}]]);const Bs=I("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);const wo=I("FileArchive",[["path",{d:"M10 12v-1",key:"v7bkov"}],["path",{d:"M10 18v-2",key:"1cjy8d"}],["path",{d:"M10 7V6",key:"dljcrl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01",key:"gkbcor"}],["circle",{cx:"10",cy:"20",r:"2",key:"1xzdoj"}]]);const ym=I("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=I("FileSearch",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]]);const Wn=I("FileText",[["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 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);const Vr=I("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);const dd=I("FolderPlus",[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);const xm=I("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);const bm=I("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);const Vi=I("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 ud=I("History",[["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"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);const vm=I("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=I("ListTree",[["path",{d:"M21 12h-8",key:"1bmf0i"}],["path",{d:"M21 6H8",key:"1pqkrb"}],["path",{d:"M21 18h-8",key:"1tm79t"}],["path",{d:"M3 6v4c0 1.1.9 2 2 2h3",key:"1ywdgy"}],["path",{d:"M3 10v6c0 1.1.9 2 2 2h3",key:"2wc746"}]]);const yn=I("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const jm=I("MessageSquarePlus",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);const Cm=I("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);const vc=I("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 hd=I("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 Sc=I("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=I("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 Em=I("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const Dm=I("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const xo=I("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);const Nm=I("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const Tm=I("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 Om=I("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 Br=I("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 bo=I("ScrollText",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);const _m=I("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);const Pm=I("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 Lr=I("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"}]]);const Rm=I("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);const Lm=I("SpellCheck2",[["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M4 21c1.1 0 1.1-1 2.3-1s1.1 1 2.3 1c1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1",key:"8mdmtu"}]]);const jc=I("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);const ss=I("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);const Hs=I("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const Cc=I("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);const Hr=I("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);const fd=I("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);const qs=I("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);const Am=I("WrapText",[["line",{x1:"3",x2:"21",y1:"6",y2:"6",key:"4m8b97"}],["path",{d:"M3 12h15a3 3 0 1 1 0 6h-4",key:"1cl7v7"}],["polyline",{points:"16 16 14 18 16 20",key:"1jznyi"}],["line",{x1:"3",x2:"10",y1:"18",y2:"18",key:"1h33wv"}]]);const Jo=I("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),qr=[{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'}],tn={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,spellCheck:!0,vimMode:!1,formatOnCompile:!1},Fm="texlite-editor-preferences";function pd(t,e){return`${Fm}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function Ib(t){return qr.find(e=>e.id===t)?.stack??qr[0].stack}function kc(t,e){try{const n=JSON.parse(localStorage.getItem(pd(t,e))??"{}");return{font:qr.some(s=>s.id===n.font)?n.font:tn.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):tn.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):tn.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:tn.lineWrapping,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:tn.spellCheck,vimMode:typeof n.vimMode=="boolean"?n.vimMode:tn.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:tn.formatOnCompile}}catch{return tn}}function Im(t,e,n){localStorage.setItem(pd(t,e),JSON.stringify(n))}const Mm=/\.(?:tex|bib|cls|sty)$/i;function Bi(t){return Mm.test(t)}function $m(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Um(t,e){const n=$m(t),a=(n?t.slice(0,-n.length):t).split(/\r?\n/).find(d=>d.trim())?.match(/^[\t ]*/)?.[0]??"",c=e.replace(/(?:\r?\n)+$/,"");return`${a?c.split(`
5
5
  `).map(d=>d&&`${a}${d}`).join(`
@@ -10,7 +10,7 @@ ${n.toString()}`)};class Oy{constructor(e){this.patterns=[],this.$state=e}if(e,n
10
10
  `;n.right=new me(Y(a,je(i.store,a)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Ot(l)),n.right.integrate(t,0),n.forward()}Du(t,e,n,c)},Ou=(t,e,n,s,r)=>{let i=e;const a=it();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===_e){const d=i.content;a.set(d.key,d)}i=i.right}let c=0,l=!1;for(;e!==i;){if(n===e&&(l=!0),!e.deleted){const d=e.content;if(d.constructor===_e){const{key:f,value:u}=d,m=s.get(f)??null;(a.get(f)!==d||m===u)&&(e.delete(t),c++,!l&&(r.get(f)??null)===u&&m!==u&&(m===null?r.delete(f):r.set(f,m))),!l&&!e.deleted&&ws(r,d)}}e=e.right}return c},zw=(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===_e){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},Vw=t=>{let e=0;return ue(t.doc,n=>{let s=t._start,r=t._start,i=it();const a=vo(i);for(;r;)r.deleted===!1&&(r.content.constructor===_e?ws(a,r.content):(e+=Ou(n,s,r,i,a),i=vo(a),s=r)),r=r.right}),e},Bw=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&&fu(t,n.store.clients.get(s),i,r,a=>{!a.deleted&&a.content.constructor===_e&&a.constructor!==ht&&e.add(a.parent)})}ue(n,s=>{cs(t,t.deleteSet,r=>{if(r instanceof ht||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===_e?e.add(i):zw(s,r)});for(const r of e)Vw(r)})},el=(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 Lt:case En:case Ot:n<e.right.length&&rt(t,Y(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&Ou(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 Hw extends yi{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=[];ue(e,s=>{const r=new Map,i=new Map;let a=this.target._start,c=null;const l={};let d="",f=0,u=0;const m=()=>{if(c!==null){let p=null;switch(c){case"delete":u>0&&(p={delete:u}),u=0;break;case"insert":(typeof d=="object"||d.length>0)&&(p={insert:d},r.size>0&&(p.attributes={},r.forEach((g,x)=>{g!==null&&(p.attributes[x]=g)}))),d="";break;case"retain":f>0&&(p={retain:f},Ig(l)||(p.attributes=Rg({},l))),f=0;break}p&&n.push(p),c=null}};for(;a!==null;){switch(a.content.constructor){case Lt:case En:this.adds(a)?this.deletes(a)||(m(),c="insert",d=a.content.getContent()[0],m()):this.deletes(a)?(c!=="delete"&&(m(),c="delete"),u+=1):a.deleted||(c!=="retain"&&(m(),c="retain"),f+=1);break;case Ot:this.adds(a)?this.deletes(a)||(c!=="insert"&&(m(),c="insert"),d+=a.content.str):this.deletes(a)?(c!=="delete"&&(m(),c="delete"),u+=a.length):a.deleted||(c!=="retain"&&(m(),c="retain"),f+=a.length);break;case _e:{const{key:p,value:g}=a.content;if(this.adds(a)){if(!this.deletes(a)){const x=r.get(p)??null;sn(x,g)?g!==null&&a.delete(s):(c==="retain"&&m(),sn(g,i.get(p)??null)?delete l[p]:l[p]=g)}}else if(this.deletes(a)){i.set(p,g);const x=r.get(p)??null;sn(x,g)||(c==="retain"&&m(),l[p]=x)}else if(!a.deleted){i.set(p,g);const x=l[p];x!==void 0&&(sn(x,g)?x!==null&&a.delete(s):(c==="retain"&&m(),g===null?delete l[p]:l[p]=g))}a.deleted||(c==="insert"&&m(),ws(r,a.content));break}}a=a.right}for(m();n.length>0;){const p=n[n.length-1];if(p.retain!==void 0&&p.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class us extends Me{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ge(),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 us}clone(){const e=new us;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new Hw(this,e,n);xi(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ge();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Ot&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?ue(this.doc,s=>{const r=new Oo(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const a=e[i];if(a.insert!==void 0){const c=!n&&typeof a.insert=="string"&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
11
11
  `?a.insert.slice(0,-1):a.insert;(typeof c!="string"||c.length>0)&&Qi(s,this,r,c,a.attributes||{})}else a.retain!==void 0?Qc(s,this,r,a.retain,a.attributes||{}):a.delete!==void 0&&el(s,r,a.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??Ge();const r=[],i=new Map,a=this.doc;let c="",l=this._start;function d(){if(c.length>0){const u={};let m=!1;i.forEach((g,x)=>{m=!0,u[x]=g});const p={insert:c};m&&(p.attributes=u),r.push(p),c=""}}const f=()=>{for(;l!==null;){if(Bn(l,e)||n!==void 0&&Bn(l,n))switch(l.content.constructor){case Ot:{const u=i.get("ychange");e!==void 0&&!Bn(l,e)?(u===void 0||u.user!==l.id.client||u.type!=="removed")&&(d(),i.set("ychange",s?s("removed",l.id):{type:"removed"})):n!==void 0&&!Bn(l,n)?(u===void 0||u.user!==l.id.client||u.type!=="added")&&(d(),i.set("ychange",s?s("added",l.id):{type:"added"})):u!==void 0&&(d(),i.delete("ychange")),c+=l.content.str;break}case Lt:case En:{d();const u={insert:l.content.getContent()[0]};if(i.size>0){const m={};u.attributes=m,i.forEach((p,g)=>{m[g]=p})}r.push(u);break}case _e:Bn(l,e)&&(d(),ws(i,l.content));break}l=l.right}d()};return e||n?ue(a,u=>{e&&No(u,e),n&&No(u,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?ue(r,i=>{const a=Pr(i,this,e,!s);s||(s={},a.currentAttributes.forEach((c,l)=>{s[l]=c})),Qi(i,this,a,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?ue(r,i=>{const a=Pr(i,this,e,!s);Qi(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?ue(s,r=>{el(r,Pr(r,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,s){if(n===0)return;const r=this.doc;r!==null?ue(r,i=>{const a=Pr(i,this,e,!1);a.right!==null&&Qc(i,this,a,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?ue(this.doc,n=>{ei(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?ue(this.doc,s=>{Sa(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return ja(this,e)}getAttributes(){return ku(this)}_write(e){e.writeTypeRef(dx)}}const qw=t=>new us;class eo{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ge()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===hs||n.constructor===vn)&&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 vn extends Me{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 vn}clone(){const e=new vn;return e.insert(0,this.toArray().map(n=>n instanceof Me?n.clone():n)),e}get length(){return this.doc??Ge(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new eo(this,e)}querySelector(e){e=e.toUpperCase();const s=new eo(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),Gt(new eo(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){xi(this,e,new Gw(this,n,e))}toString(){return bu(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?ue(this.doc,s=>{ju(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)ue(this.doc,s=>{const r=e&&e instanceof Me?e._item:e;Qr(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 xt("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?ue(this.doc,s=>{Cu(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return xu(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return vu(this,e)}slice(e=0,n=this.length){return wu(this,e,n)}forEach(e){er(this,e)}_write(e){e.writeTypeRef(hx)}}const Ww=t=>new vn;class hs extends vn{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new hs(this.nodeName)}clone(){const e=new hs(this.nodeName),n=this.getAttributes();return Ag(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof Me?s.clone():s)),e}toString(){const e=this.getAttributes(),n=[],s=[];for(const c in e)s.push(c);s.sort();const r=s.length;for(let c=0;c<r;c++){const l=s[c];n.push(l+'="'+e[l]+'"')}const i=this.nodeName.toLocaleLowerCase(),a=n.length>0?" "+n.join(" "):"";return`<${i}${a}>${super.toString()}</${i}>`}removeAttribute(e){this.doc!==null?ue(this.doc,n=>{ei(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?ue(this.doc,s=>{Sa(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return ja(this,e)}hasAttribute(e){return Eu(this,e)}getAttributes(e){return e?Fw(this,e):ku(this)}toDOM(e=document,n={},s){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const a in i){const c=i[a];typeof c=="string"&&r.setAttribute(a,c)}return er(this,a=>{r.appendChild(a.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(ux),e.writeKey(this.nodeName)}}const Kw=t=>new hs(t.readKey());class Gw extends yi{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 ti extends ds{constructor(e){super(),this.hookName=e}_copy(){return new ti(this.hookName)}clone(){const e=new ti(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(fx),e.writeKey(this.hookName)}}const Jw=t=>new ti(t.readKey());class ni extends us{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 ni}clone(){const e=new ni;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,c)=>a.key<c.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 c=i.attrs[a];s+=` ${c.key}="${c.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(px)}}const Yw=t=>new ni;class Ca{constructor(e,n){this.id=e,this.length=n}get deleted(){throw gt()}mergeWith(e){return!1}write(e,n,s){throw gt()}integrate(e,n){throw gt()}}const Xw=0;class ht 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),hu(e.doc.store,this)}write(e,n){e.writeInfo(Xw),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 gt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const Zw=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 Qw=t=>new tr(t.readLen()),_u=(t,e)=>new kn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class lr{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 lr(_u(this.doc.guid,this.opts))}splice(e){throw gt()}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 ex=t=>new lr(_u(t.readString(),t.readAny()));class En{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new En(this.embed)}splice(e){throw gt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const tx=t=>new En(t.readJSON());class _e{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new _e(this.key,this.value)}splice(e){throw gt()}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 nx=t=>new _e(t.readKey(),t.readJSON());class si{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new si(this.arr)}splice(e){const n=new si(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 sx=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 si(n)},rx=Gr("node_env")==="development";class Sn{constructor(e){this.arr=e,rx&&Cd(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Sn(this.arr)}splice(e){const n=new Sn(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 ix=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new Sn(n)};class Ot{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Ot(this.str)}splice(e){const n=new Ot(this.str.slice(e));this.str=this.str.slice(0,e);const s=this.str.charCodeAt(e-1);return s>=55296&&s<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const ox=t=>new Ot(t.readString()),ax=[Mw,Uw,qw,Kw,Ww,Jw,Yw],cx=0,lx=1,dx=2,ux=3,hx=4,fx=5,px=6;class Lt{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Lt(this.type._copy())}splice(e){throw gt()}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 mx=t=>new Lt(ax[t.readTypeRef()](t)),_o=(t,e)=>{let n=e,s=0,r;do s>0&&(n=Y(n.client,n.clock+s)),r=Zn(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof me);return{item:r,diff:s}},ka=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},ri=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new me(Y(s,r+n),e,Y(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=Y(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},tl=(t,e)=>Xo(t,n=>or(n.deletions,e)),Pu=(t,e,n,s,r,i)=>{const a=t.doc,c=a.store,l=a.clientID,d=e.redone;if(d!==null)return rt(t,d);let f=e.parent._item,u=null,m;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||Pu(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=rt(t,f.redone)}const p=f===null?e.parent:f.content.type;if(e.parentSub===null){for(u=e.left,m=e;u!==null;){let j=u;for(;j!==null&&j.parent._item!==f;)j=j.redone===null?null:rt(t,j.redone);if(j!==null&&j.parent._item===f){u=j;break}u=u.left}for(;m!==null;){let j=m;for(;j!==null&&j.parent._item!==f;)j=j.redone===null?null:rt(t,j.redone);if(j!==null&&j.parent._item===f){m=j;break}m=m.right}}else{if(m=null,e.right&&!r){for(u=e;u!==null&&u.right!==null&&(u.right.redone||or(s,u.right.id)||tl(i.undoStack,u.right.id)||tl(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=rt(t,u.redone);if(u&&u.right!==null)return null}else u=p._map.get(e.parentSub)||null;u!==null&&u.parent._item!==f&&(u=p._map.get(e.parentSub)||null)}const g=je(c,l),x=Y(l,g),b=new me(x,u,u&&u.lastId,m,m&&m.id,p,e.parentSub,e.content.copy());return e.redone=x,ka(b,!0),b.integrate(t,0),b};class me extends Ca{constructor(e,n,s,r,i,a,c,l){super(e,l.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=c,this.redone=null,this.content=l,this.info=this.content.isCountable()?_c:0}set marker(e){(this.info&Ki)>0!==e&&(this.info^=Ki)}get marker(){return(this.info&Ki)>0}get keep(){return(this.info&Oc)>0}set keep(e){this.keep!==e&&(this.info^=Oc)}get countable(){return(this.info&_c)>0}get deleted(){return(this.info&Wi)>0}set deleted(e){this.deleted!==e&&(this.info^=Wi)}markDeleted(){this.info|=Wi}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=je(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=je(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Xn&&this.id.client!==this.parent.client&&this.parent.clock>=je(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Wc(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ht||this.right&&this.right.constructor===ht)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===me?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===me&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Xn){const s=Zn(n,this.parent);s.constructor===ht?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=Wc(e,e.doc.store,Y(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),Kn(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Kn(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&a.has(Zn(e.doc.store,r.origin)))i.has(Zn(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),hu(e.doc.store,this),this.content.integrate(e,this),Gc(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ht(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:Y(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Kn(e.origin,this.lastId)&&this.right===e&&Kn(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),Gc(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw lt();this.content.gc(e),n?xw(e,this,new ht(this.id,this.length)):this.content=new tr(this.length)}write(e,n){const s=n>0?Y(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&ai|(s===null?0:ct)|(r===null?0:qt)|(i===null?0:Ws);if(e.writeInfo(a),s!==null&&e.writeLeftID(s),r!==null&&e.writeRightID(r),s===null&&r===null){const c=this.parent;if(c._item!==void 0){const l=c._item;if(l===null){const d=lu(c);e.writeParentInfo(!0),e.writeString(d)}else e.writeParentInfo(!1),e.writeLeftID(l.id)}else c.constructor===String?(e.writeParentInfo(!0),e.writeString(c)):c.constructor===Xn?(e.writeParentInfo(!1),e.writeLeftID(c)):lt();i!==null&&e.writeString(i)}this.content.write(e,n)}}const Ru=(t,e)=>gx[e&ai](t),gx=[()=>{lt()},Qw,sx,Zw,ox,tx,nx,mx,ix,ex,()=>{lt()}],yx=10;class ft extends Ca{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){lt()}write(e,n){e.writeInfo(yx),$(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Lu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Au="__ $YJS$ __";Lu[Au]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Lu[Au]=!0;const Fu=new Map;class wx{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:Qg(n.newValue||"")}),Og(this._onChange)}postMessage(e){Sd.setItem(this.room,Zg(Kg(e)))}close(){_g(this._onChange)}}const xx=typeof BroadcastChannel>"u"?wx:BroadcastChannel,Ea=t=>Pt(Fu,t,()=>{const e=an(),n=new xx(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),bx=(t,e)=>(Ea(t).subs.add(e),e),vx=(t,e)=>{const n=Ea(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),Fu.delete(t)),s},Hn=(t,e,n=null)=>{const s=Ea(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},Iu=0,Da=1,Mu=2,ii=(t,e)=>{$(t,Iu);const n=fw(e);be(t,n)},$u=(t,e,n)=>{$(t,Da),be(t,ya(e,n))},Sx=(t,e,n)=>$u(e,n,Ke(t)),Uu=(t,e,n,s)=>{try{iu(e,Ke(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},jx=(t,e)=>{$(t,Mu),be(t,e)},Cx=Uu,kx=(t,e,n,s,r)=>{const i=G(t);switch(i){case Iu:Sx(t,e,n);break;case Da:Uu(t,n,s,r);break;case Mu:Cx(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Ex=0,Dx=(t,e,n)=>{G(t)===Ex&&n(e,yt(t))},to=3e4;class Nx extends md{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=cn();this.getLocalState()!==null&&to/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&to<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Na(this,s,"timeout")},wt(to/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);e===null?this.states.delete(n):this.states.set(n,e),this.meta.set(n,{clock:r,lastUpdated:cn()});const a=[],c=[],l=[],d=[];e===null?d.push(n):i==null?e!=null&&a.push(n):(c.push(n),Jn(i,e)||l.push(n)),(a.length>0||l.length>0||d.length>0)&&this.emit("change",[{added:a,updated:l,removed:d},"local"]),this.emit("update",[{added:a,updated:c,removed:d},"local"])}setLocalStateField(e,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:n})}getStates(){return this.states}}const Na=(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:cn()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},es=(t,e,n=t.states)=>{const s=e.length,r=Ne();$(r,s);for(let i=0;i<s;i++){const a=e[i],c=n.get(a)||null,l=t.meta.get(a).clock;$(r,a),$(r,l),Wt(r,JSON.stringify(c))}return pe(r)},Tx=(t,e,n)=>{const s=dn(e),r=cn(),i=[],a=[],c=[],l=[],d=G(s);for(let f=0;f<d;f++){const u=G(s);let m=G(s);const p=JSON.parse(yt(s)),g=t.meta.get(u),x=t.states.get(u),b=g===void 0?0:g.clock;(b<m||b===m&&p===null&&t.states.has(u))&&(p===null?u===t.clientID&&t.getLocalState()!=null?m++:t.states.delete(u):t.states.set(u,p),t.meta.set(u,{clock:m,lastUpdated:r}),g===void 0&&p!==null?i.push(u):g!==void 0&&p===null?l.push(u):p!==null&&(Jn(p,x)||c.push(u),a.push(u)))}(i.length>0||c.length>0||l.length>0)&&t.emit("change",[{added:i,updated:c,removed:l},n]),(i.length>0||a.length>0||l.length>0)&&t.emit("update",[{added:i,updated:a,removed:l},n])},Ox=t=>Fg(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),wn=0,zu=3,ts=1,_x=2,dr=[];dr[wn]=(t,e,n,s,r)=>{$(t,wn);const i=kx(e,t,n.doc,n);s&&i===Da&&!n.synced&&(n.synced=!0)};dr[zu]=(t,e,n,s,r)=>{$(t,ts),be(t,es(n.awareness,Array.from(n.awareness.getStates().keys())))};dr[ts]=(t,e,n,s,r)=>{Tx(n.awareness,Ke(e),n)};dr[_x]=(t,e,n,s,r)=>{Dx(e,n.doc,(i,a)=>Px(n,a))};const nl=3e4,Px=(t,e)=>console.warn(`Permission denied to access ${t.url}.
12
12
  ${e}`),Vu=(t,e,n)=>{const s=dn(e),r=Ne(),i=G(s),a=t.messageHandlers[i];return a?a(r,s,t,n,i):console.error("Unable to compute message"),r},Po=(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,Na(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Bu,Qo(Xm(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Bu=t=>{if(t.shouldConnect&&t.ws===null){const e=new t._WS(t.url,t.protocols);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=n=>{t.wsLastMessageReceived=cn();const s=Vu(t,new Uint8Array(n.data),!0);ea(s)>1&&e.send(pe(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Po(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=cn(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Ne();if($(n,wn),ii(n,t.doc),e.send(pe(n)),t.awareness.getLocalState()!==null){const s=Ne();$(s,ts),be(s,es(t.awareness,[t.doc.clientID])),e.send(pe(s))}},t.emit("status",[{status:"connecting"}])}},no=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Hn(t.bcChannel,e,t)};class Rx extends Zo{constructor(e,n,s,{connect:r=!0,awareness:i=new Nx(s),params:a={},protocols:c=[],WebSocketPolyfill:l=WebSocket,resyncInterval:d=-1,maxBackoffTime:f=2500,disableBc:u=!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=c,this.roomname=n,this.doc=s,this._WS=l,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,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 m=Ne();$(m,wn),ii(m,s),this.ws.send(pe(m))}},d)),this._bcSubscriber=(m,p)=>{if(p!==this){const g=Vu(this,new Uint8Array(m),!1);ea(g)>1&&Hn(this.bcChannel,pe(g),this)}},this._updateHandler=(m,p)=>{if(p!==this){const g=Ne();$(g,wn),jx(g,m),no(this,pe(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:m,updated:p,removed:g},x)=>{const b=m.concat(p).concat(g),j=Ne();$(j,ts),be(j,es(i,b)),no(this,pe(j))},this._exitHandler=()=>{Na(this.awareness,[s.clientID],"app closed")},ln&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&nl<cn()-this.wsLastMessageReceived&&Po(this,this.ws,null)},nl/10),r&&this.connect()}get url(){const e=Ox(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(),ln&&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||(bx(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Ne();$(e,wn),ii(e,this.doc),Hn(this.bcChannel,pe(e),this);const n=Ne();$(n,wn),$u(n,this.doc),Hn(this.bcChannel,pe(n),this);const s=Ne();$(s,zu),Hn(this.bcChannel,pe(s),this);const r=Ne();$(r,ts),be(r,es(this.awareness,[this.doc.clientID])),Hn(this.bcChannel,pe(r),this)}disconnectBc(){const e=Ne();$(e,ts),be(e,es(this.awareness,[this.doc.clientID],new Map)),no(this,pe(e)),this.bcconnected&&(vx(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Po(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Bu(this),this.connectBc())}}const Dn=t=>os((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),Lx=(t,e)=>os((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(xt(i.target.error)),r.onsuccess=i=>{const a=i.target.result;a.onversionchange=()=>{a.close()},n(a)}}),Ax=t=>Dn(indexedDB.deleteDatabase(t)),Fx=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),As=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>Hx(s,r))},Hu=(t,e)=>Dn(t.count(e)),Ix=(t,e)=>Dn(t.get(e)),qu=(t,e)=>Dn(t.delete(e)),Mx=(t,e,n)=>Dn(t.put(e,n)),Ro=(t,e)=>Dn(t.add(e)),$x=(t,e,n)=>Dn(t.getAll(e,n)),Ux=(t,e,n)=>{let s=null;return Bx(t,e,r=>(s=r,!1),n).then(()=>s)},zx=(t,e=null)=>Ux(t,e,"prev"),Vx=(t,e)=>os((n,s)=>{t.onerror=s,t.onsuccess=async r=>{const i=r.target.result;if(i===null||await e(i)===!1)return n();i.continue()}}),Bx=(t,e,n,s="next")=>Vx(t.openKeyCursor(e,s),r=>n(r.key)),Hx=(t,e)=>t.objectStore(e),qx=(t,e)=>IDBKeyRange.upperBound(t,e),Wx=(t,e)=>IDBKeyRange.lowerBound(t,e),so="custom",Wu="updates",Ku=500,Gu=(t,e=()=>{},n=()=>{})=>{const[s]=As(t.db,[Wu]);return $x(s,Wx(t._dbref,!1)).then(r=>{t._destroyed||(e(s),ue(t.doc,()=>{r.forEach(i=>iu(t.doc,i))},t,!1),n(s))}).then(()=>zx(s).then(r=>{t._dbref=r+1})).then(()=>Hu(s).then(r=>{t._dbsize=r})).then(()=>s)},Kx=(t,e=!0)=>Gu(t).then(n=>{(e||t._dbsize>=Ku)&&Ro(n,ya(t.doc)).then(()=>qu(n,qx(t._dbref,!0))).then(()=>Hu(n).then(s=>{t._dbsize=s}))});class Gx extends md{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=Lx(e,s=>Fx(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=os(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Gu(this,a=>Ro(a,ya(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]=As(this.db,[Wu]);Ro(i,s),++this._dbsize>=Ku&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Kx(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]=As(n,[so],"readonly");return Ix(s,e)})}set(e,n){return this._db.then(s=>{const[r]=As(s,[so]);return Mx(r,n,e)})}del(e){return this._db.then(n=>{const[s]=As(n,[so]);return qu(s,e)})}}const sl=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],rl=4,il=5;function Jx(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!["queued","running","succeeded","failed"].includes(e.status??"")||typeof e.updatedAt!="string"||!n||typeof n.id!="string"||typeof n.username!="string"||typeof n.name!="string"?null:e}function ol(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=Jx(s);r&&r.mainFile===n&&(e[n]=r)}return e}class Yx{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.persistence=new Gx(`texlite:${n.id}:${e}`,this.doc),this.persistence.on("synced",()=>{this.localDraftReady=!0;for(const r of this.draftListeners)r()}),this.provider=new Rx(`${s}//${window.location.host}/api/collaboration`,e,this.doc,{disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness,this.provider.messageHandlers[rl]=(r,i)=>{const a=yt(i),c=this.flushRequests.get(a);if(!c)return;const l=G(i),d=yt(i);window.clearTimeout(c.timer),this.flushRequests.delete(a),c.resolve({revision:l,persistedAt:d})},this.provider.messageHandlers[il]=(r,i)=>{const a=yt(i),c=this.epochStorageKey(),l=Xx(c);if(this.epoch&&this.epoch!==a||l&&l!==a){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed")),this.persistence.clearData().then(()=>{al(c,a),window.location.reload()});return}this.epoch=a,al(c,a);const d=this.provider.ws;if(!d||d.readyState!==WebSocket.OPEN)return;const f=Ne();$(f,il),Wt(f,a),d.send(pe(f));const u=Ne();$(u,0),ii(u,this.doc),d.send(pe(u));const m=Ne();$(m,1),be(m,es(this.awareness,[this.doc.clientID])),d.send(pe(m))},this.provider.on("status",({status:r})=>{r==="disconnected"&&this.rejectFlushes(new Error("Collaboration connection closed"))}),this.updateLocalAwareness()}projectId;user;doc=new kn;provider;awareness;persistence;permission="read";activeFile="";epoch=null;destroyed=!1;localDraftReady=!1;draftListeners=new Set;flushRequests=new Map;getText(e){return this.doc.getText(`source:${e}`)}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")}get synced(){return this.provider.synced}get connected(){return this.provider.wsconnected}get draftReady(){return this.localDraftReady}onDraftReady(e){return this.draftListeners.add(e),this.localDraftReady&&e(),()=>this.draftListeners.delete(e)}setPermission(e){this.permission=e,this.updateLocalAwareness()}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=crypto.randomUUID(),s=Ne();return $(s,rl),Wt(s,n),new Promise((r,i)=>{const a=window.setTimeout(()=>{this.flushRequests.delete(n),i(new Error("Collaboration save timed out"))},5e3);this.flushRequests.set(n,{resolve:r,reject:i,timer:a}),e.send(pe(s))})}reconnect(){this.destroyed||(this.rejectFlushes(new Error("Collaboration connection reset")),this.provider.disconnect(),this.provider.connect(),this.updateLocalAwareness())}destroy(){this.destroyed=!0,this.rejectFlushes(new Error("Collaboration connection closed")),this.provider.destroy(),this.persistence.destroy(),this.draftListeners.clear(),this.doc.destroy()}rejectFlushes(e){for(const n of this.flushRequests.values())window.clearTimeout(n.timer),n.reject(e);this.flushRequests.clear()}updateLocalAwareness(){const[e,n]=sl[Math.abs(this.doc.clientID)%sl.length];this.awareness.setLocalStateField("user",{id:this.user.id,username:this.user.username,name:this.user.displayName,color:e,colorLight:n,permission:this.permission,sessionId:String(this.doc.clientID)}),this.awareness.setLocalStateField("filePath",this.activeFile)}epochStorageKey(){return`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`}}function Xx(t){try{return window.localStorage.getItem(t)}catch{return null}}function al(t,e){try{window.localStorage.setItem(t,e)}catch{}}function Zx(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function Qx({sessions:t,status:e}){const{t:n}=Pe(),[s,r]=h.useState(!1),i=Math.max(0,t.length-5),a=s&&i>0,c=a?t:t.slice(0,5);return h.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,title:n(`editor.collaboration.${e}`),children:[o.jsx("span",{className:"collaboration-status-dot","aria-label":n(`editor.collaboration.${e}`)}),o.jsxs("div",{className:"collaboration-avatars","aria-label":n("editor.collaboration.activeSessions",{count:t.length}),children:[c.map(l=>{const d=l.editing?n("editor.collaboration.editing"):n("editor.collaboration.viewing"),f=l.permission==="read"?n("common.readOnly"):n("common.readWrite"),u=n("editor.collaboration.sessionTooltip",{name:l.name,username:l.username,file:l.filePath||n("editor.collaboration.joining"),activity:d,permission:f});return o.jsxs("span",{className:`collaboration-avatar${l.editing?" editing":""}${l.local?" local":""}`,style:{"--session-color":l.color},title:u,"aria-label":u,tabIndex:0,children:[Zx(l.name,l.username),o.jsxs("span",{className:"collaboration-avatar-tooltip",role:"tooltip",children:[o.jsx("strong",{children:l.name}),o.jsxs("span",{children:["@",l.username]}),o.jsxs("small",{children:[l.filePath||n("editor.collaboration.joining")," · ",d," · ",f]})]})]},l.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(l=>!l),children:a?"−":`+${i}`})]})]})}function eb({value:t,onChange:e}){const{t:n}=Pe(),[s,r]=h.useState(!1),i=h.useRef(null),a=[{value:"editor-pdf",icon:bc},{value:"editor-only",icon:Em},{value:"pdf-only",icon:Dm}];return h.useEffect(()=>{if(!s)return;const c=d=>{i.current?.contains(d.target)||r(!1)},l=d=>{d.key==="Escape"&&r(!1)};return document.addEventListener("pointerdown",c),document.addEventListener("keydown",l),()=>{document.removeEventListener("pointerdown",c),document.removeEventListener("keydown",l)}},[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(c=>!c),children:[o.jsx(bc,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(cd,{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(c=>{const l=c.icon,d=c.value===t;return o.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":d,className:`layout-option${d?" selected":""}`,onClick:()=>{e(c.value),r(!1)},children:[o.jsx(l,{size:19}),o.jsxs("span",{children:[o.jsx("strong",{children:n(`editor.layout.${c.value}.name`)}),o.jsx("small",{children:n(`editor.layout.${c.value}.description`)})]}),d&&o.jsx(um,{size:16})]},c.value)})]})]})}function tb({comment:t,currentUserId:e,onFocus:n,onToggle:s,onReply:r,onEdit:i,onDelete:a,onEditReply:c,onDeleteReply:l}){const{t:d}=Pe(),[f,u]=h.useState(!1),[m,p]=h.useState(""),[g,x]=h.useState(!1),[b,j]=h.useState(t.content),[C,N]=h.useState(!1),[T,_]=h.useState(null),[L,E]=h.useState(""),[q,v]=h.useState(null),O=async S=>{S.preventDefault(),m.trim()&&await r(m)&&(p(""),u(!1))},Z=async S=>{S.preventDefault(),b.trim()&&await i(b)&&x(!1)},W=async S=>{S.preventDefault(),!(!T||!L.trim())&&await c(T,L)&&_(null)},P=t.authorUsername,R=S=>new Date(S).toLocaleString(we.resolvedLanguage);return o.jsxs(o.Fragment,{children:[o.jsxs("article",{className:`comment-thread${t.resolved?" resolved":""}${t.orphaned?" orphaned":""}`,onClick:n,children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:t.authorDisplayName??P??d("editor.deletedUser")}),P&&o.jsxs("small",{children:["@",P]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:t.createdAt,title:new Date(t.createdAt).toISOString(),children:R(t.createdAt)}),t.editedAt&&o.jsx("small",{children:d("editor.editedAt",{time:R(t.editedAt)})})]})]}),o.jsx("div",{className:"comment-location",children:t.orphaned?d("editor.orphaned"):d("editor.line",{line:t.startLine})}),t.selectedText&&o.jsx("blockquote",{children:t.selectedText}),g?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:S=>{Z(S)},onClick:S=>S.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:4,value:b,onChange:S=>j(S.target.value)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>x(!1),children:d("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!b.trim(),children:[o.jsx(Br,{size:13}),d("editor.saveChanges")]})]})]}):o.jsx("p",{children:t.content}),t.replies.length>0&&o.jsx("div",{className:"comment-replies",children:t.replies.map(S=>o.jsxs("div",{className:"comment-reply",children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:S.authorDisplayName??S.authorUsername??d("editor.deletedUser")}),S.authorUsername&&o.jsxs("small",{children:["@",S.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:S.createdAt,title:new Date(S.createdAt).toISOString(),children:R(S.createdAt)}),S.editedAt&&o.jsx("small",{children:d("editor.editedAt",{time:R(S.editedAt)})})]})]}),T===S.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:F=>{W(F)},onClick:F=>F.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:3,value:L,onChange:F=>E(F.target.value)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>_(null),children:d("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!L.trim(),children:[o.jsx(Br,{size:13}),d("editor.saveChanges")]})]})]}):o.jsx("p",{children:S.content}),S.authorId===e&&T!==S.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:d("editor.editReply"),"aria-label":d("editor.editReply"),onClick:F=>{F.stopPropagation(),_(S.id),E(S.content)},children:o.jsx(xo,{size:12})}),o.jsx("button",{className:"danger-text",title:d("editor.deleteReply"),"aria-label":d("editor.deleteReply"),onClick:F=>{F.stopPropagation(),v(S.id)},children:o.jsx(ss,{size:12})})]})]},S.id))}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:S=>{S.stopPropagation(),s()},children:[t.resolved?o.jsx(Om,{size:13}):o.jsx(pm,{size:13}),t.resolved?d("editor.reopen"):d("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:S=>{S.stopPropagation(),u(F=>!F)},children:[o.jsx(Tm,{size:13}),d("editor.reply")]}),t.authorId===e&&!g&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:d("editor.editComment"),"aria-label":d("editor.editComment"),onClick:S=>{S.stopPropagation(),j(t.content),x(!0)},children:o.jsx(xo,{size:13})}),o.jsx("button",{className:"danger-text",title:d("editor.deleteComment"),"aria-label":d("editor.deleteComment"),onClick:S=>{S.stopPropagation(),N(!0)},children:o.jsx(ss,{size:13})})]})]}),f&&o.jsxs("form",{className:"comment-reply-form",onSubmit:S=>{O(S)},onClick:S=>S.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:3,value:m,placeholder:d("editor.replyPlaceholder"),onChange:S=>p(S.target.value)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{u(!1),p("")},children:d("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!m.trim(),children:[o.jsx(Pm,{size:13}),d("editor.sendReply")]})]})]})]}),o.jsx(Vs,{open:C,title:d("editor.deleteCommentTitle"),description:d("editor.deleteCommentDescription",{count:t.replies.length}),confirmLabel:d("common.delete"),danger:!0,onCancel:()=>N(!1),onConfirm:()=>{a().then(S=>{S&&N(!1)})}}),o.jsx(Vs,{open:!!q,title:d("editor.deleteReplyTitle"),description:d("editor.deleteReplyDescription"),confirmLabel:d("common.delete"),danger:!0,onCancel:()=>v(null),onConfirm:()=>{q&&l(q).then(S=>{S&&v(null)})}})]})}function nb({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=Pe(),[i,a]=h.useState([]),[c,l]=h.useState([]),[d,f]=h.useState(""),[u,m]=h.useState("read"),[p,g]=h.useState(null),[x,b]=h.useState(""),j=n.permission==="owner",C=async()=>{try{const[E,q]=await Promise.all([A(`/api/projects/${s}/members`),A("/api/users")]);a(E.members),l(q.users.filter(v=>v.id!==n.ownerId))}catch(E){b(V(E))}};h.useEffect(()=>{t&&C()},[t,s]);const N=async()=>{if(d)try{await A(`/api/projects/${s}/members/${d}`,{method:"PUT",body:JSON.stringify({permission:u})}),f(""),m("read"),await C()}catch(E){b(V(E))}},T=async(E,q)=>{try{await A(`/api/projects/${s}/members/${E.id}`,{method:"PUT",body:JSON.stringify({permission:q})}),await C()}catch(v){b(V(v))}},_=async()=>{if(p)try{await A(`/api/projects/${s}/members/${p.id}`,{method:"DELETE"}),g(null),await C()}catch(E){b(V(E))}},L=c.filter(E=>!i.some(q=>q.id===E.id));return o.jsxs(o.Fragment,{children:[o.jsx(Ie,{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(qs,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),j&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:d,onChange:E=>f(E.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),L.map(E=>o.jsx("option",{value:E.id,children:E.displayName??E.username},E.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:u,onChange:E=>m(E.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:()=>{N()},children:[o.jsx(fd,{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(E=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(E.displayName??E.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:E.displayName??E.username}),o.jsxs("small",{children:["@",E.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!j,value:E.permission,onChange:q=>{T(E,q.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),j&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(E),children:o.jsx(ss,{size:15})})]})]},E.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(qs,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(Vs,{open:!!p,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:p?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{_()}})]})}function sb({project:t,projectId:e,site:n,files:s,dictionaryWords:r,onDictionaryChange:i,editorPreferences:a,onEditorPreferences:c,spellCheckCount:l,spellCheckUniqueCount:d,spellCheckIndex:f,onSpellCheckNavigate:u,onProject:m}){const{t:p}=Pe(),[g,x]=h.useState(t.engine),[b,j]=h.useState(""),[C,N]=h.useState(t.name),[T,_]=h.useState(t.mainFile),[L,E]=h.useState(""),[q,v]=h.useState(""),[O,Z]=h.useState(""),[W,P]=h.useState("appearance"),[R,S]=h.useState(a),F=t.permission==="owner",le=t.permission!=="read",Q=t.permission!=="read";h.useEffect(()=>S(a),[a]),h.useEffect(()=>{if(!t.latexmkrc)return j("");A(`/api/projects/${e}/file?path=${encodeURIComponent(t.latexmkrc)}`).then(({content:D})=>j(D)).catch(D=>E(V(D)))},[t.latexmkrc]);const ge=s.filter(D=>D.type==="file"&&/\.tex$/i.test(D.path)).map(D=>D.path),oe=[...new Set(t.mainFile.toLowerCase().endsWith(".tex")?[...ge,t.mainFile]:ge)].sort((D,ye)=>D.localeCompare(ye)),ae=async()=>{try{const D=b.trim()&&n.allowProjectLatexmkrc!==!1?".latexmkrc":null;D&&await A(`/api/projects/${e}/file`,{method:"PUT",body:JSON.stringify({path:D,content:b})});const ye=await A(`/api/projects/${e}`,{method:"PATCH",body:JSON.stringify({name:C,mainFile:T,engine:g,latexmkrc:D})});m(ye.project)}catch(D){E(V(D))}},he=()=>c(R),Ce=async()=>{const D=q.trim();if(D)try{const ye=await A(`/api/projects/${e}/dictionary`,{method:"POST",body:JSON.stringify({word:D})});i(ye.words),v(""),Z("")}catch(ye){Z(V(ye))}},B=async D=>{try{const ye=await A(`/api/projects/${e}/dictionary/${encodeURIComponent(D)}`,{method:"DELETE"});i(ye.words),Z("")}catch(ye){Z(V(ye))}};return o.jsxs("div",{className:"settings padded",children:[L&&o.jsx("p",{className:"error",children:L}),o.jsxs("div",{className:"settings-tabs",role:"tablist","aria-label":p("common.settings"),children:[o.jsxs("button",{id:"settings-tab-appearance",type:"button",role:"tab","aria-selected":W==="appearance","aria-controls":"settings-panel-appearance",className:`settings-tab${W==="appearance"?" active":""}`,onClick:()=>P("appearance"),children:[o.jsx(Cc,{size:15}),p("projectSettings.editorTab")]}),o.jsxs("button",{id:"settings-tab-compiler",type:"button",role:"tab","aria-selected":W==="compiler","aria-controls":"settings-panel-compiler",className:`settings-tab${W==="compiler"?" active":""}`,onClick:()=>P("compiler"),children:[o.jsx(Lr,{size:15}),p("projectSettings.compilerTab")]})]}),W==="appearance"?o.jsxs("section",{id:"settings-panel-appearance",role:"tabpanel","aria-labelledby":"settings-tab-appearance",children:[o.jsxs("div",{className:"settings-section-title",children:[o.jsx(Cc,{size:15}),o.jsx("strong",{children:p("projectSettings.editorAppearance")})]}),o.jsx("p",{className:"settings-description appearance-description",children:p("projectSettings.editorAppearanceDescription")}),o.jsxs("label",{children:[p("projectSettings.fontFamily"),o.jsx("select",{value:R.font,onChange:D=>S({...R,font:D.target.value}),children:qr.map(D=>o.jsx("option",{value:D.id,children:p(D.labelKey)},D.id))})]}),o.jsxs("label",{children:[p("projectSettings.fontSize"),o.jsx("select",{value:R.fontSize,onChange:D=>S({...R,fontSize:Number(D.target.value)}),children:[12,13,14,15,16,18,20].map(D=>o.jsxs("option",{value:D,children:[D," px"]},D))})]}),o.jsxs("label",{children:[p("projectSettings.lineHeight"),o.jsxs("select",{value:R.lineHeight,onChange:D=>S({...R,lineHeight:Number(D.target.value)}),children:[o.jsx("option",{value:1.45,children:p("projectSettings.lineHeightCompact")}),o.jsx("option",{value:1.65,children:p("projectSettings.lineHeightNormal")}),o.jsx("option",{value:1.85,children:p("projectSettings.lineHeightRelaxed")})]})]}),o.jsxs("label",{className:"editor-checkbox",children:[o.jsx("input",{type:"checkbox",checked:R.lineWrapping,onChange:D=>S({...R,lineWrapping:D.target.checked})}),o.jsx(Am,{size:15}),o.jsx("span",{children:p("projectSettings.lineWrapping")})]}),o.jsxs("label",{className:"editor-checkbox",children:[o.jsx("input",{type:"checkbox",checked:R.spellCheck,onChange:D=>S({...R,spellCheck:D.target.checked})}),o.jsx("span",{children:p("projectSettings.spellCheck")})]}),o.jsxs("label",{className:"editor-checkbox",children:[o.jsx("input",{type:"checkbox",checked:R.vimMode,onChange:D=>S({...R,vimMode:D.target.checked})}),o.jsx("span",{children:p("projectSettings.vimMode")})]}),o.jsxs("p",{className:"field-hint",children:[p("projectSettings.vimModeDescription")," ",o.jsx("a",{href:"https://replit-codemirror-vim.mintlify.app/",target:"_blank",rel:"noreferrer",children:p("projectSettings.vimHelp")})]}),o.jsxs("label",{className:"editor-checkbox",children:[o.jsx("input",{type:"checkbox",disabled:!le,checked:R.formatOnCompile,onChange:D=>S({...R,formatOnCompile:D.target.checked})}),o.jsx(id,{size:15}),o.jsx("span",{children:p("projectSettings.formatOnCompile")})]}),o.jsxs("p",{className:"field-hint",children:[p(le?"projectSettings.formatOnCompileDescription":"projectSettings.formatRequiresWrite")," ",p("projectSettings.formatterDescription")," ",o.jsx("a",{href:"https://github.com/wgunderwood/tex-fmt",target:"_blank",rel:"noreferrer",children:p("projectSettings.formatterInstall")})]}),l!==null&&o.jsxs("div",{className:`spell-check-result${l?" has-issues":""}`,role:"status","aria-live":"polite",children:[o.jsx(Lm,{size:14}),o.jsx("span",{children:l?p("projectSettings.spellingIssues",{count:l,uniqueCount:d??0}):p("projectSettings.noSpellingIssues")}),l>0&&o.jsxs("span",{className:"spell-check-controls",children:[o.jsx("button",{type:"button",title:p("projectSettings.spellCheckFirst"),"aria-label":p("projectSettings.spellCheckFirst"),disabled:f<=0,onClick:()=>u(0),children:o.jsx(hm,{size:14})}),o.jsx("button",{type:"button",title:p("projectSettings.spellCheckPrevious"),"aria-label":p("projectSettings.spellCheckPrevious"),disabled:f<=0,onClick:()=>u(f-1),children:o.jsx(ld,{size:14})}),o.jsx("span",{className:"spell-check-position",children:p("projectSettings.spellCheckPosition",{current:Math.min(f+1,l),total:l})}),o.jsx("button",{type:"button",title:p("projectSettings.spellCheckNext"),"aria-label":p("projectSettings.spellCheckNext"),disabled:f>=l-1,onClick:()=>u(f+1),children:o.jsx(Ko,{size:14})}),o.jsx("button",{type:"button",title:p("projectSettings.spellCheckLast"),"aria-label":p("projectSettings.spellCheckLast"),disabled:f>=l-1,onClick:()=>u(l-1),children:o.jsx(fm,{size:14})})]})]}),o.jsxs("div",{className:"settings-section-title",children:[o.jsx(ad,{size:15}),o.jsx("strong",{children:p("projectSettings.dictionary")})]}),o.jsx("p",{className:"settings-description",children:p("projectSettings.dictionaryDescription")}),O&&o.jsx("p",{className:"error dictionary-error",children:O}),Q&&o.jsxs("div",{className:"dictionary-add",children:[o.jsx("input",{value:q,placeholder:p("projectSettings.dictionaryPlaceholder"),onChange:D=>v(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),Ce())}}),o.jsx("button",{type:"button",disabled:!q.trim(),onClick:()=>{Ce()},children:p("projectSettings.addWord")})]}),o.jsxs("div",{className:"dictionary-words",children:[r.map(D=>o.jsxs("span",{className:"dictionary-word",children:[o.jsx("code",{children:D}),Q&&o.jsx("button",{type:"button",title:p("common.delete"),"aria-label":`${p("common.delete")} ${D}`,onClick:()=>{B(D)},children:o.jsx(Jo,{size:13})})]},D)),r.length===0&&o.jsx("span",{className:"dictionary-empty",children:p("projectSettings.dictionaryEmpty")})]}),o.jsx("div",{className:"settings-actions",children:o.jsxs("button",{className:"settings-save",onClick:he,children:[o.jsx(Br,{size:15}),p("projectSettings.saveAppearance")]})})]}):o.jsxs("section",{id:"settings-panel-compiler",role:"tabpanel","aria-labelledby":"settings-tab-compiler",children:[o.jsxs("div",{className:"settings-section-title",children:[o.jsx(Lr,{size:15}),o.jsx("strong",{children:p("projectSettings.compilerTab")})]}),o.jsx("p",{className:"settings-description compiler-description",children:p("projectSettings.compilerDescription")}),o.jsxs("div",{className:"settings-section-title project-configuration",children:[o.jsx(Lr,{size:15}),o.jsx("strong",{children:p("projectSettings.projectConfiguration")})]}),o.jsxs("label",{children:[p("projects.name"),o.jsx("input",{disabled:!F,value:C,onChange:D=>N(D.target.value)})]}),o.jsxs("label",{children:[p("projectSettings.mainFile"),o.jsx("select",{disabled:!F||oe.length===0,value:T,onChange:D=>_(D.target.value),children:oe.map(D=>o.jsx("option",{value:D,children:D},D))})]}),o.jsxs("label",{children:[p("projectSettings.engine"),o.jsx("select",{disabled:!F,value:g,onChange:D=>x(D.target.value),children:(n.allowedEngines??["pdflatex","xelatex","lualatex"]).map(D=>o.jsx("option",{children:D},D))})]}),o.jsxs("label",{children:[p("projectSettings.latexmkrc"),o.jsx("textarea",{className:"latexmkrc-editor",rows:10,spellCheck:!1,disabled:!F||n.allowProjectLatexmkrc===!1,value:b,placeholder:p("projectSettings.latexmkrcPlaceholder"),onChange:D=>j(D.target.value)})]}),o.jsx("div",{className:"settings-actions",children:F&&o.jsxs("button",{className:"settings-save",onClick:()=>{ae()},children:[o.jsx(Br,{size:15}),p("projectSettings.saveCompiler")]})})]})]})}function cl({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=Pe(),a=s==="error"?Go:Hs;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((c,l)=>{const d=ib(c.file,e),f=!!(d&&c.line);return o.jsxs("button",{type:"button",disabled:!f,className:"compile-diagnostic-row",onClick:()=>{d&&c.line&&r(d,c.line,c.column??1)},children:[o.jsx(a,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c.message}),o.jsxs("small",{children:[c.phase,d?` · ${d}${c.line?`:${c.line}`:""}`:c.line?` · ${i("editor.lineNumber",{line:c.line})}`:""]})]})]},`${c.phase}-${c.file??""}-${c.line??0}-${l}`)})}):o.jsxs("div",{className:`compile-empty compile-${s}`,children:[o.jsx(a,{size:26}),o.jsx("span",{children:n})]})}function ro({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Go:n==="warning"?Hs:bo;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
13
- `)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function rb({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:a}=Pe(),c=l=>`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(l)}&download=1`;return n.length?o.jsxs("div",{className:"artifact-browser",children:[o.jsx("div",{className:"artifact-list",children:n.map(l=>o.jsxs("div",{className:`artifact-row${s?.path===l.path?" active":""}`,children:[o.jsxs("button",{type:"button",disabled:!l.viewable,title:l.viewable?a("editor.viewArtifact"):a("editor.downloadToView"),onClick:()=>i(l),children:[o.jsx(Wn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:l.path}),o.jsx("small",{children:ob(l.size)})]})]}),o.jsx("a",{href:c(l.path),title:a("editor.downloadArtifact"),"aria-label":a("editor.downloadArtifact"),children:o.jsx(Bs,{size:14})})]},l.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(yn,{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:c(s.path),children:[o.jsx(Bs,{size:13}),a("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Wn,{size:24}),o.jsx("span",{children:a("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(hd,{size:26}),o.jsx("span",{children:a("editor.noArtifacts")})]})}function ib(t,e){if(!t)return null;const n=e.filter(c=>c.type==="file").map(c=>c.path),s=t.replaceAll("\\","/").replace(/^\.\//,"");if(n.includes(s))return s;const r=n.filter(c=>s.endsWith(`/${c}`));if(r.length===1)return r[0];const i=s.split("/").at(-1),a=n.filter(c=>c.split("/").at(-1)===i);return a.length===1?a[0]:null}function ob(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function ab(t){return t instanceof Error&&t.name==="AbortError"}function cb({projectId:t,activeFile:e,permission:n,revision:s,selection:r,save:i,onError:a,onAdded:c}){const[l,d]=h.useState([]),[f,u]=h.useState(null),[m,p]=h.useState(!1),[g,x]=h.useState(""),b=h.useRef(null),j=h.useRef(e),C=h.useRef(i),N=h.useRef(a),T=h.useRef(c);j.current=e,C.current=i,N.current=a,T.current=c;const _=async P=>{b.current?.abort();const R=new AbortController;b.current=R;try{const S=await A(`/api/projects/${t}/comments?path=${encodeURIComponent(P)}`,{signal:R.signal});j.current===P&&d(S.comments)}catch(S){!ab(S)&&j.current===P&&d([])}finally{b.current===R&&(b.current=null)}};return h.useEffect(()=>{u(null)},[t,e]),h.useEffect(()=>(e?_(e):d([]),()=>{b.current?.abort(),b.current=null}),[t,e,s]),{comments:l,focusComment:f,setFocusComment:u,commentOpen:m,setCommentOpen:p,commentText:g,setCommentText:x,addComment:async()=>{if(!(!g.trim()||!e))try{if(n!=="read"&&!await C.current())return;await A(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:e,content:g,...r})}),await _(e),p(!1),x(""),T.current()}catch(P){N.current(V(P))}},toggleComment:async P=>{try{await A(`/api/projects/${t}/comments/${P.id}`,{method:"PATCH",body:JSON.stringify({resolved:!P.resolved})}),await _(e)}catch(R){N.current(V(R))}},replyToComment:async(P,R)=>{try{return await A(`/api/projects/${t}/comments/${P.id}/replies`,{method:"POST",body:JSON.stringify({content:R})}),await _(e),!0}catch(S){return N.current(V(S)),!1}},editComment:async(P,R)=>{try{return await A(`/api/projects/${t}/comments/${P.id}`,{method:"PATCH",body:JSON.stringify({content:R})}),await _(e),!0}catch(S){return N.current(V(S)),!1}},deleteComment:async P=>{try{return await A(`/api/projects/${t}/comments/${P.id}`,{method:"DELETE"}),await _(e),u(R=>R?.id===P.id?null:R),!0}catch(R){return N.current(V(R)),!1}},editCommentReply:async(P,R,S)=>{try{return await A(`/api/projects/${t}/comments/${P.id}/replies/${R}`,{method:"PATCH",body:JSON.stringify({content:S})}),await _(e),!0}catch(F){return N.current(V(F)),!1}},deleteCommentReply:async(P,R)=>{try{return await A(`/api/projects/${t}/comments/${P.id}/replies/${R}`,{method:"DELETE"}),await _(e),!0}catch(S){return N.current(V(S)),!1}}}}function lb(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 db(t,e,n,s){const[r]=h.useState(()=>new Yx(t,e)),[i,a]=h.useState("connecting"),[c,l]=h.useState(!1),[d,f]=h.useState([]),[u,m]=h.useState(null),[p,g]=h.useState(null),[x,b]=h.useState(""),[j,C]=h.useState(""),[N,T]=h.useState(!1),_=h.useRef(n),L=h.useRef(s);return _.current=n,L.current=s,h.useEffect(()=>{const q=ol(r.meta.get("compileStates"));m(q[n]??null)},[n,r]),h.useEffect(()=>{const q=()=>f(r.sessions()),v=()=>{l(!1),f([]),m(null),g(null),b(""),C(""),L.current()},O=({status:S})=>{a(S),S!=="connected"&&v()},Z=S=>{l(S),S||v()},W=()=>{a("disconnected"),v()},P=()=>{const S=r.meta.get("filesEvent");lb(S)&&g(S);const F=r.meta.get("commentsRevision");typeof F=="string"&&b(F);const le=r.meta.get("dictionaryRevision");typeof le=="string"&&C(le);const Q=ol(r.meta.get("compileStates"));m(Q[_.current]??null)};r.awareness.on("change",q),r.provider.on("status",O),r.provider.on("sync",Z),r.provider.on("connection-close",W),r.provider.on("connection-error",W),r.meta.observe(P);const R=r.onDraftReady(()=>T(!0));return q(),P(),a(r.connected?"connected":"connecting"),l(r.synced),()=>{r.awareness.off("change",q),r.provider.off("status",O),r.provider.off("sync",Z),r.provider.off("connection-close",W),r.provider.off("connection-error",W),r.meta.unobserve(P),R(),r.destroy()}},[r]),{collaboration:r,status:i,synced:c,activeSessions:d,compileState:u,setCompileState:m,filesEvent:p,commentsRevision:x,dictionaryRevision:j,localDraftReady:N,reconnect:()=>{a("connecting"),l(!1),f([]),m(null),r.reconnect()}}}function Ls(t){return t instanceof Error&&t.name==="AbortError"}function ub({projectId:t,project:e,mainFile:n,collaborationSynced:s,sharedState:r,onSharedState:i,save:a,loadOutline:c,onPreviewTab:l,onError:d,onCompileStart:f,onCompileSuccess:u,onPdfChanged:m}){const{t:p}=Pe(),[g,x]=h.useState(""),[b,j]=h.useState(null),[C,N]=h.useState(""),[T,_]=h.useState(null),[L,E]=h.useState(null),[q,v]=h.useState([]),[O,Z]=h.useState(null),[W,P]=h.useState(!1),[R,S]=h.useState(()=>new Set),[F,le]=h.useState(""),Q=h.useRef(n),ge=h.useRef(null),oe=h.useRef(null),ae=h.useRef(new Map),he=h.useRef(null),Ce=h.useRef(()=>{}),B=h.useRef({onSharedState:i,save:a,loadOutline:c,onPreviewTab:l,onError:d,onCompileStart:f,onCompileSuccess:u,onPdfChanged:m});Q.current=n,B.current={onSharedState:i,save:a,loadOutline:c,onPreviewTab:l,onError:d,onCompileStart:f,onCompileSuccess:u,onPdfChanged:m};const D=H=>{he.current!==H&&(he.current=H,B.current.onCompileSuccess())},ye=async(H,X)=>{X||(oe.current?.abort(),oe.current=new AbortController,X=oe.current.signal);try{const z=H?`?mainFile=${encodeURIComponent(H)}`:"",ee=await A(`/api/projects/${t}/compile/artifacts${z}`,{signal:X});Q.current===H&&(v(ee.artifacts),Z(null))}catch(z){!Ls(z)&&Q.current===H&&(v([]),Z(null))}finally{oe.current?.signal===X&&(oe.current=null)}};h.useEffect(()=>{ge.current?.abort();const H=new AbortController;if(ge.current=H,N(""),_(null),E(null),x(""),j(null),v([]),Z(null),B.current.onPdfChanged(),!e||!n)return()=>H.abort();const X=`?mainFile=${encodeURIComponent(n)}`,z=A(`/api/projects/${t}/compile/artifacts${X}`,{signal:H.signal}).catch(ee=>{if(Ls(ee))throw ee;return{artifacts:[]}});return Promise.all([A(`/api/projects/${t}/compile/latest${X}`,{signal:H.signal}),z,B.current.loadOutline(H.signal,n)]).then(([ee,mt])=>{H.signal.aborted||ee.mainFile!==Q.current||(v(mt.artifacts),N(ee.latestRun?.log??""),_(ee.latestRun?.diagnostics??null),E(ee.latestRun?.status==="succeeded"||ee.latestRun?.status==="failed"?ee.latestRun.status:null),ee.latestRun?.requestedBy&&(ee.latestRun.status==="queued"||ee.latestRun.status==="running")&&B.current.onSharedState({mainFile:n,runId:ee.latestRun.id,status:ee.latestRun.status,requestedBy:ee.latestRun.requestedBy,updatedAt:new Date().toISOString()}),ee.pdfUrl&&(x(ee.pdfUrl),j(ee.pdfCompiledAt),B.current.onPreviewTab("pdf")))}).catch(ee=>{!Ls(ee)&&Q.current===n&&B.current.onError(V(ee))}).finally(()=>{ge.current===H&&(ge.current=null)}),()=>H.abort()},[e?.id,t,n]),h.useEffect(()=>{if(!r||r.mainFile!==n||r.status!=="succeeded"&&r.status!=="failed")return;let H=!1;ge.current?.abort();const X=new AbortController;return ge.current=X,A(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:X.signal}).then(z=>{H||z.mainFile!==Q.current||z.latestRun?.id!==r.runId||(N(z.latestRun.log),_(z.latestRun.diagnostics),E(r.status==="succeeded"?"succeeded":"failed"),r.status==="succeeded"&&z.pdfUrl?(B.current.onPdfChanged(),x(z.pdfUrl),j(z.pdfCompiledAt),B.current.onPreviewTab("pdf"),D(r.runId),ye(n)):r.status==="failed"&&B.current.onPreviewTab(z.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(z=>{!Ls(z)&&!H&&B.current.onError(V(z))}),()=>{H=!0,X.abort(),ge.current===X&&(ge.current=null)}},[r?.runId,r?.status,r?.mainFile,n,t]);const ke=async()=>{if(!e||!n||e.permission==="read"||!s||ae.current.has(n)||r?.mainFile===n&&(r.status==="queued"||r.status==="running"))return;const H=n;S(z=>new Set([...z,H])),B.current.onCompileStart(),le(""),N(""),_(null),E(null),B.current.onPreviewTab(g?"pdf":"log");const X=new AbortController;ae.current.set(H,X);try{if(!await B.current.save())return;const z=await A(`/api/projects/${t}/compile`,{method:"POST",signal:X.signal,body:JSON.stringify({mainFile:H})});if(z.mainFile!==Q.current)return;N(z.log),_(z.diagnostics),E(z.ok?"succeeded":"failed"),z.skipped&&le(p("editor.upToDate")),z.pdfUrl?(B.current.onPdfChanged(),x(z.pdfUrl),j(z.pdfCompiledAt),B.current.onPreviewTab("pdf"),z.ok&&(z.skipped?B.current.onCompileSuccess():D(z.runId))):B.current.onPreviewTab(z.diagnostics.errors.length?"errors":"log")}catch(z){!Ls(z)&&Q.current===H&&B.current.onError(V(z))}finally{ae.current.get(H)===X&&(ae.current.delete(H),S(z=>{const ee=new Set(z);return ee.delete(H),ee}))}};Ce.current=()=>{ke()},h.useEffect(()=>{if(!F)return;const H=window.setTimeout(()=>le(""),3e3);return()=>window.clearTimeout(H)},[F]),h.useEffect(()=>{const H=X=>{!(X.ctrlKey||X.metaKey)||X.key.toLocaleLowerCase()!=="s"||(X.preventDefault(),X.stopPropagation(),X.repeat||Ce.current())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[]),h.useEffect(()=>()=>{ge.current?.abort(),oe.current?.abort();for(const H of ae.current.values())H.abort();ae.current.clear()},[]);const Be=async H=>{if(H.viewable){P(!0);try{const X=await A(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(H.path)}`);Z(X)}catch(X){B.current.onError(V(X))}finally{P(!1)}}};return{pdfUrl:g,pdfCompiledAt:b,compileLog:C,compileDiagnostics:T,compileOutcome:L,artifacts:q,artifactPreview:O,artifactLoading:W,editorNotice:F,localCompiling:R.has(n),compile:ke,viewArtifact:Be}}const ll=10*1024*1024,hb=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 dl(t){return t instanceof Error&&t.name==="AbortError"}function Fs(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function zn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function fb(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!hb.has(e)}function Lo(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function ul(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":fb(t)?"text":"unsupported"}function pb(t,e){return`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`}function mb({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:a,onActiveFile:c,onActiveMainFile:l,onRootDocuments:d}){const{t:f}=Pe(),[u,m]=h.useState([]),[p,g]=h.useState(!1),[x,b]=h.useState(""),[j,C]=h.useState(null),[N,T]=h.useState(!1),[_,L]=h.useState(!1),[E,q]=h.useState(""),[v,O]=h.useState(""),[Z,W]=h.useState(""),[P,R]=h.useState(new Set),[S,F]=h.useState(null),[le,Q]=h.useState(""),[ge,oe]=h.useState(null),[ae,he]=h.useState(!1),[Ce,B]=h.useState(null),[D,ye]=h.useState(!1),ke=h.useRef(null),Be=h.useRef(null),H=async(U={})=>{ke.current?.abort(),ke.current=null;const re=U.signal?null:new AbortController;re&&(ke.current=re);try{const xe=await A(`/api/projects/${t}/files`,{signal:U.signal??re?.signal});return(!U.isCurrent||U.isCurrent())&&m(xe.files),xe.files}catch(xe){if(!dl(xe))throw xe;return}finally{re&&ke.current===re&&(ke.current=null)}},X=async()=>{if(!(!x.trim()||x.trim().endsWith("/"))){O("");try{await A(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:x,content:""})}),await H(),c(x),R(U=>new Set([...U,...Fs(x)])),g(!1),b("")}catch(U){O(V(U))}}},z=async()=>{if(!E.trim())return;O("");const U=Z?`${Z}/${E.trim()}`:E.trim();try{const re=await A(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:U})});await H(),R(xe=>new Set([...xe,...Fs(re.path),re.path])),W(re.path),L(!1),q("")}catch(re){O(V(re))}},ee=async(U,re=new Set,xe=Z)=>{if(!U.length)return;const et=e.maxUploadSizeMB??50;if(U.find(ie=>ie.size>et*1024*1024))return i(f("errors.fileTooLarge",{size:et}));const Oe=xe,He=U.map(ie=>Oe?`${Oe}/${ie.name}`:ie.name),ot=new Map;for(const ie of He)ot.set(ie,(ot.get(ie)??0)+1);const vt=[...ot.entries()].filter(([,ie])=>ie>1).map(([ie])=>ie);if(vt.length)return i(f("errors.duplicateUploadNames",{files:vt.join(", ")}));const St=new Set(u.map(ie=>ie.path)),tt=[...new Set(He.filter(ie=>St.has(ie)&&!re.has(ie)))];if(tt.length){B({files:U,directory:Oe,collisions:tt});return}B(null),ye(!0);try{const ie=new URLSearchParams;Oe&&ie.set("directory",Oe);let jt="";for(const[dt,Re]of U.entries()){const Ct=He[dt];ie.delete("overwrite"),re.has(Ct)&&ie.set("overwrite","1");const nt=ie.toString()?`?${ie.toString()}`:"",hn=new FormData;hn.append("file",Re);const ne=await fetch(`/api/projects/${t}/upload${nt}`,{method:"POST",body:hn}),Ue=await ne.json().catch(()=>({}));if(!ne.ok){if(ne.status===409&&!re.has(Ct)&&Ue.code==="FILE_EXISTS"){dt>0&&await H(),B({files:U.slice(dt),directory:Oe,collisions:[typeof Ue.path=="string"?Ue.path:Ct]});return}throw new Error(ne.status===409?f("errors.pathConflict"):Fo(Ue,ne.status,"errors.upload"))}typeof Ue.path=="string"&&Lo(Ue.path)&&(jt=Ue.path)}await H(),jt&&c(jt)}catch(ie){i(V(ie))}finally{ye(!1)}},mt=async U=>{await ee(Array.from(U.target.files??[])),U.target.value=""},Xt=async U=>{Be.current?.abort(),Be.current=null,T(!1);const re=pb(t,U.path);if((U.size??0)>ll){C({path:U.path,kind:"large",size:U.size??0,url:re});return}const xe=ul(U.path);if(xe!=="text"){C({path:U.path,kind:xe,size:U.size??0,url:re});return}C({path:U.path,kind:xe,size:U.size??0,url:re,content:""}),T(!0);const et=new AbortController;Be.current=et;try{const ce=await fetch(re,{signal:et.signal}),Oe=await ce.text();if(!ce.ok)throw new Error(Oe||f("errors.request",{status:ce.status}));C(He=>He?.path===U.path?{...He,content:Oe}:He)}catch(ce){dl(ce)||(C(null),i(V(ce)))}finally{Be.current===et&&(Be.current=null,T(!1))}},un=U=>{const re=ul(U.path);(U.size??0)>ll||re!=="text"||!Lo(U.path)?Xt(U):c(U.path)},At=async()=>{if(S){O("");try{if(!await r())return;const U=await A(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:S.path,destinationDirectory:le})}),re=ce=>ce===S.path?U.path:ce.startsWith(`${S.path}/`)?`${U.path}${ce.slice(S.path.length)}`:ce;c(ce=>re(ce)),l(ce=>re(ce)),d(ce=>new Set([...ce].map(re))),W(ce=>ce&&re(ce));const[xe,et]=await Promise.all([A(`/api/projects/${t}/files`),A(`/api/projects/${t}`)]);m(xe.files),a(et.project),R(ce=>new Set([...ce,...Fs(U.path),le].filter(Boolean))),F(null),Q("")}catch(U){O(V(U))}}},Zt=async()=>{if(ge){O("");try{if(s&&!await r())return;await A(`/api/projects/${t}/file?path=${encodeURIComponent(ge.path)}`,{method:"DELETE"}),oe(null)}catch(U){O(V(U))}}};h.useEffect(()=>()=>{ke.current?.abort(),Be.current?.abort()},[]),h.useEffect(()=>{Be.current?.abort(),Be.current=null,T(!1)},[n]);const Ft=u.filter(U=>U.type==="directory"),It=u.filter(U=>Fs(U.path).every(re=>P.has(re)));return{files:u,setFiles:m,loadFiles:H,newFileOpen:p,setNewFileOpen:g,newFilePath:x,setNewFilePath:b,resourcePreview:j,setResourcePreview:C,resourcePreviewLoading:N,setResourcePreviewLoading:T,newFolderOpen:_,setNewFolderOpen:L,newFolderName:E,setNewFolderName:q,fileDialogError:v,setFileDialogError:O,selectedFolder:Z,setSelectedFolder:W,expandedFolders:P,setExpandedFolders:R,moveEntry:S,setMoveEntry:F,moveDestination:le,setMoveDestination:Q,deleteEntry:ge,setDeleteEntry:oe,fileDragActive:ae,setFileDragActive:he,uploadConflict:Ce,setUploadConflict:B,uploadingFiles:D,directoryEntries:Ft,visibleEntries:It,createFile:X,createFolder:z,uploadFiles:ee,upload:mt,openFile:un,movePath:At,removePath:Zt}}function gb({active:t,activeFile:e,content:n,dictionaryWords:s}){const[r,i]=h.useState([]),[a,c]=h.useState(""),[l,d]=h.useState(""),[f,u]=h.useState(0),[m,p]=h.useState(null),g=h.useRef(0),x=h.useRef(n),b=h.useRef(e),j=h.useRef(0);x.current=n,b.current=e,h.useEffect(()=>{i([]),c(""),d(""),p(null)},[e,s]),h.useEffect(()=>{u(_=>r.length?Math.min(_,r.length-1):0)},[r]),h.useEffect(()=>{const _=++g.current;if(!t||!e){i([]),c(""),d(""),p(null);return}const L=n,E=e,q=window.setTimeout(()=>{Jt(async()=>{const{checkSpelling:v}=await import("./spellCheck-R6fUM9oA.js");return{checkSpelling:v}},__vite__mapDeps([2,1])).then(({checkSpelling:v})=>{if(_!==g.current||x.current!==L||b.current!==E)return;const O=v(L,s);_!==g.current||x.current!==L||b.current!==E||(i(O),c(L),d(E),u(0),p(null))}).catch(()=>{})},700);return()=>window.clearTimeout(q)},[t,e,n,s]);const C=l===e&&a===n,N=h.useMemo(()=>C?{total:r.length,unique:new Set(r.map(_=>_.word.toLocaleLowerCase("en-US"))).size}:null,[C,r]);return{issues:C?r:[],jump:C?m:null,index:f,summary:N,jumpToIssue:_=>{if(!r.length)return;const L=Math.max(0,Math.min(_,r.length-1)),E=r[L];u(L),p({from:E.from,to:E.to,nonce:++j.current})}}}function hl(t){return t instanceof Error&&t.name==="AbortError"}function yb({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[a,c]=h.useState(null),[l,d]=h.useState(null),[f,u]=h.useState(null),m=h.useRef(null),p=h.useRef(0),g=h.useRef(n),x=h.useRef(s),b=h.useRef(r),j=h.useRef(i);g.current=n,x.current=s,b.current=r,j.current=i,h.useEffect(()=>(m.current?.abort(),m.current=null,c(null),d(null),u(null),()=>m.current?.abort()),[t,e]);const C=(L,E,q)=>{u({path:L,line:E,column:q,nonce:++p.current}),g.current!==L&&x.current(L)},N=async(L,E,q,v={})=>{m.current?.abort();const O=new AbortController;m.current=O;try{const Z=await A(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(L)}&line=${E}&column=${q}`,{signal:O.signal});if(m.current!==O)return;c({...Z,nonce:++p.current}),j.current()}catch(Z){!hl(Z)&&!v.silent&&b.current(V(Z))}finally{m.current===O&&(m.current=null)}},T=async(L,E,q)=>{m.current?.abort();const v=new AbortController;m.current=v;try{const O=await A(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${L}&x=${E}&y=${q}`,{signal:v.signal});if(m.current!==v)return;C(O.path,O.line,O.column)}catch(O){hl(O)||b.current(V(O))}finally{m.current===v&&(m.current=null)}};return{pdfTarget:a,pdfViewport:l,sourceJump:f,setPdfViewport:d,clearPdfViewport:()=>d(null),jumpToSource:C,syncSourceToPdf:N,syncPdfToSource:T,syncVisiblePdfToSource:()=>{l&&T(l.page,l.x,l.y)}}}function Ju(t,e){return`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function fl(t,e){try{const n=window.localStorage.getItem(Ju(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function wb(t,e){const[n,s]=h.useState(()=>fl(t,e));return h.useEffect(()=>{s(fl(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Ju(t,e),i)}catch{}}}}const Yu=()=>Jt(()=>import("./PdfPreview-CHTibR8X.js"),__vite__mapDeps([3,1,4,5])),xb=h.lazy(()=>Yu().then(t=>({default:t.PdfPreview}))),bb=h.lazy(()=>Jt(()=>import("./LatexEditor-CEUW9LNB.js"),__vite__mapDeps([6,1,7])).then(t=>({default:t.LatexEditor}))),vb=h.lazy(()=>Jt(()=>import("./GitDialog-_AsbwoMa.js"),__vite__mapDeps([8,1,5])).then(t=>({default:t.GitDialog}))),Sb=h.lazy(()=>Jt(()=>import("./HistoryDialog-Bc8OBByX.js"),__vite__mapDeps([9,1,0])).then(t=>({default:t.HistoryDialog}))),jb=h.lazy(()=>Jt(()=>import("./ProjectNavigationDialogs-DVUI8Thi.js"),__vite__mapDeps([10,1])).then(t=>({default:t.ProjectSearchDialog}))),Cb=h.lazy(()=>Jt(()=>import("./ProjectNavigationDialogs-DVUI8Thi.js"),__vite__mapDeps([10,1])).then(t=>({default:t.QuickOpenDialog}))),kb=h.lazy(()=>Jt(()=>import("./SystemMetricsDialog-CRq25lNt.js"),__vite__mapDeps([11,1])).then(t=>({default:t.SystemMetricsDialog}))),Xe=8;function qn(t){return t instanceof Error&&t.name==="AbortError"}function Eb(){const{t}=Pe(),[e,n]=h.useState({siteName:"TexLite",adminEmail:""}),[s,r]=h.useState(),[i,a]=h.useState(()=>typeof window>"u"?null:Tr(window.location.pathname)),[c,l]=h.useState(null);h.useEffect(()=>{const m=Tr(window.location.pathname);if(m&&window.location.pathname!==Hi(m)){const x={texliteRoute:"project",projectId:m,fromDashboard:!1};window.history.replaceState(x,"",Hi(m))}const p=()=>a(Tr(window.location.pathname)),g=()=>{if(l(null),r(null),Tr(window.location.pathname)){const x={texliteRoute:"dashboard"};window.history.replaceState(x,"","/"),a(null)}};return window.addEventListener("popstate",p),window.addEventListener("texlite:session-expired",g),()=>{window.removeEventListener("popstate",p),window.removeEventListener("texlite:session-expired",g)}},[]);const d=m=>{const p=Hi(m);if(window.location.pathname!==p){const g={texliteRoute:"project",projectId:m,fromDashboard:!0};window.history.pushState(g,"",p)}a(m)},f=()=>{const m=window.history.state;if(Wm(m)&&m.fromDashboard){window.history.back();return}const p={texliteRoute:"dashboard"};window.history.replaceState(p,"","/"),a(null)};if(h.useEffect(()=>{A("/api/config").then(m=>{n(m),document.title=m.siteName}),A("/api/me").then(({user:m})=>r(m)).catch(m=>{m instanceof Ao&&m.status,r(null)})},[]),s===void 0)return o.jsx("div",{className:"center-card",children:t("common.loading")});if(!s)return o.jsx(Nb,{site:e,onLogin:r});if(s.mustChangePassword)return o.jsx(Db,{site:e,user:s,onChanged:m=>r(m)});if(i)return o.jsx(Pb,{site:e,user:s,projectId:i,onBack:f},i);const u=c?.userId===s.id?c:null;return o.jsx(Tb,{site:e,user:s,initialData:u?{projects:u.projects,tags:u.tags,pagination:u.pagination}:null,onDataChange:(m,p,g)=>l({userId:s.id,projects:m,tags:p,pagination:g}),onUser:m=>{(!m||m.id!==s.id)&&l(null),r(m),m||f()},onOpenProject:d})}function bi({siteName:t,compact:e=!1,auth:n=!1}){return o.jsx("span",{className:`site-logo${e?" compact":""}${n?" auth-logo":""}`,children:o.jsx("img",{src:"/logo.svg",alt:t})})}function Ta(){const{t}=Pe();return o.jsxs("footer",{className:"site-footer",children:[o.jsxs("span",{children:[t("footer.copyright",{year:new Date().getFullYear()})," ",o.jsxs("a",{href:"https://github.com/SWUFE-DB-Group/TexLite",target:"_blank",rel:"noreferrer",children:["TexLite v",Fh]})]}),o.jsx("span",{children:t("footer.credit")})]})}function Db({site:t,user:e,onChanged:n}){const{t:s}=Pe(),[r,i]=h.useState(""),[a,c]=h.useState(""),[l,d]=h.useState(""),[f,u]=h.useState(""),m=async p=>{if(p.preventDefault(),a!==l)return u(s("auth.mismatch"));if(a.length<Xe)return u(s("auth.passwordMinimum",{count:Xe}));try{await A("/api/me/password",{method:"PUT",body:JSON.stringify({currentPassword:r,newPassword:a})}),n({...e,mustChangePassword:!1})}catch(g){u(V(g))}};return o.jsxs("main",{className:"login-page",children:[o.jsx(Wo,{}),o.jsxs("form",{className:"login-card",onSubmit:m,children:[o.jsx(bi,{siteName:t.siteName,auth:!0}),o.jsx("h1",{className:"sr-only",children:t.siteName}),o.jsx("p",{className:"muted",children:s("auth.firstLogin")}),o.jsxs("label",{children:[s("auth.currentPassword"),o.jsx("input",{type:"password",value:r,onChange:p=>i(p.target.value)})]}),o.jsxs("label",{children:[s("auth.newPassword"),o.jsx("input",{type:"password",minLength:Xe,autoComplete:"new-password",value:a,onChange:p=>c(p.target.value)}),o.jsx("small",{className:"field-hint",children:s("auth.passwordMinimum",{count:Xe})})]}),o.jsxs("label",{children:[s("auth.confirmPassword"),o.jsx("input",{type:"password",minLength:Xe,autoComplete:"new-password",value:l,onChange:p=>d(p.target.value)})]}),f&&o.jsx("p",{className:"error",children:f}),o.jsx("button",{className:"primary",children:s("auth.updatePassword")})]}),o.jsx(Ta,{})]})}function Nb({site:t,onLogin:e}){const{t:n}=Pe(),[s,r]=h.useState(""),[i,a]=h.useState(""),[c,l]=h.useState(""),d=async f=>{f.preventDefault(),l("");try{const u=await A("/api/auth/login",{method:"POST",body:JSON.stringify({username:s,password:i})});e(u.user)}catch(u){l(V(u))}};return o.jsxs("main",{className:"login-page",children:[o.jsx(Wo,{}),o.jsxs("form",{className:"login-card",onSubmit:d,children:[o.jsx(bi,{siteName:t.siteName,auth:!0}),o.jsx("h1",{className:"sr-only",children:t.siteName}),o.jsx("p",{className:"muted",children:n("auth.tagline")}),o.jsxs("label",{children:[n("auth.username"),o.jsx("input",{autoFocus:!0,value:s,onChange:f=>r(f.target.value)})]}),o.jsxs("label",{children:[n("auth.password"),o.jsx("input",{type:"password",value:i,onChange:f=>a(f.target.value)})]}),c&&o.jsx("p",{className:"error",children:c}),o.jsx("button",{className:"primary",type:"submit",children:n("auth.login")}),t.adminEmail&&o.jsx("small",{className:"support",children:n("auth.contact",{email:t.adminEmail})})]}),o.jsx(Ta,{})]})}function Tb({site:t,user:e,initialData:n,onDataChange:s,onUser:r,onOpenProject:i}){const{t:a}=Pe(),[c,l]=h.useState(()=>n?.projects??[]),[d,f]=h.useState(()=>n?.tags??[]),[u,m]=h.useState(()=>n?.pagination??{page:1,pageSize:20,total:n?.projects.length??0,totalPages:n?.projects.length?1:0}),[p,g]=h.useState(!!n),[x,b]=h.useState(!1),[j,C]=h.useState(!1),[N,T]=h.useState(""),[_,L]=h.useState(!1),[E,q]=h.useState(""),[v,O]=h.useState(!1),[Z,W]=h.useState(""),[P,R]=h.useState(null),[S,F]=h.useState(""),le=h.useRef(null),[Q,ge]=h.useState(!1),[oe,ae]=h.useState(""),[he,Ce]=h.useState(""),[B,D]=h.useState(!1),[ye,ke]=h.useState(""),[Be,H]=h.useState("blue"),[X,z]=h.useState(null),[ee,mt]=h.useState(null),[Xt,un]=h.useState(""),[At,Zt]=h.useState(null),[Ft,It]=h.useState(""),[U,re]=h.useState(!1),[xe,et]=h.useState(null),[ce,Oe]=h.useState(null),[He,ot]=h.useState([]),[vt,St]=h.useState(""),[tt,ie]=h.useState(!1),[jt,dt]=h.useState(""),[Re,Ct]=h.useState(()=>localStorage.getItem("texlite-project-view")==="list"?"list":"grid"),[nt,hn]=h.useState(()=>localStorage.getItem("texlite-project-sort")==="created"?"created":"updated"),[ne,Ue]=h.useState(!1),[Mt,$t]=h.useState(""),[Ee,Je]=h.useState(1),[xs,vi]=h.useState(""),ze=h.useRef(0),kt=h.useRef(null),qe=(w,te,se,Se,Ve)=>`${w?"archived":"active"}|${te}|${se}|${Se}|${Ve}`,bs=qe(ne,Ee,oe,he,nt),st=(w,te,se,Se,Ve)=>{const Le=new URLSearchParams({page:String(te),pageSize:"20",sort:Ve});w&&Le.set("archived","1"),se.trim()&&Le.set("search",se.trim()),Se&&Le.set("tag",Se);const at=qe(w,te,se,Se,Ve),pn=++ze.current;kt.current?.abort();const On=new AbortController;return kt.current=On,Promise.all([A(`/api/projects?${Le.toString()}`,{signal:On.signal}),A("/api/tags",{signal:On.signal})]).then(([Qt,Ts])=>{pn===ze.current&&(l(Qt.projects),f(Ts.tags),m(Qt.pagination),Je(Qt.pagination.page),g(!0),vi(at))}).catch(Qt=>{!qn(Qt)&&pn===ze.current&&T(V(Qt))}).finally(()=>{kt.current===On&&(kt.current=null)})};h.useEffect(()=>(st(ne,Ee,oe,he,nt),()=>kt.current?.abort()),[ne,Ee,oe,he,nt]),h.useEffect(()=>{p&&!ne&&xs===bs&&s(c,d,u)},[c,d,u,p,xs,bs,ne]);const vs=w=>{Ct(w),localStorage.setItem("texlite-project-view",w)},ve=w=>{hn(w),Je(1),localStorage.setItem("texlite-project-sort",w)},ur=w=>{Ue(w),Je(1)},Ss=w=>{Ce(w),Je(1)},js=async()=>{if(E.trim())try{const{project:w}=await A("/api/projects",{method:"POST",body:JSON.stringify({name:E})});L(!1),q("");const te=ne||Ee!==1?c:[w,...c].slice(0,u.pageSize),se=ne?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(te),m(se),ne||s(te,d,se),i(w.id)}catch(w){T(V(w))}},Si=async()=>{if(!P)return;const w=t.maxUploadSizeMB??50;if(P.size>w*1024*1024)return F(a("errors.fileTooLarge",{size:w}));ge(!0),F("");const te=new FormData;te.append("file",P);try{const se=await fetch(`/api/projects/import?name=${encodeURIComponent(Z.trim())}`,{method:"POST",body:te}),Se=await se.json();if(!se.ok)throw new Error(Fo(Se,se.status,"errors.upload"));const Ve=Se.project,Le=ne||Ee!==1?c:[Ve,...c].slice(0,u.pageSize),at=ne?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(Le),m(at),ne||s(Le,d,at),O(!1),R(null),W(""),i(Ve.id)}catch(se){F(V(se))}finally{ge(!1)}},Cs=w=>{if(w&&!w.name.toLocaleLowerCase().endsWith(".zip")){F(a("errors.zipOnly"));return}F(""),R(w),w&&!Z&&W(w.name.replace(/\.zip$/i,""))},ji=async()=>{await A("/api/auth/logout",{method:"POST"}),r(null)},hr=async()=>{if(ye.trim())try{const w=await A("/api/tags",{method:"POST",body:JSON.stringify({name:ye,color:Be})});f(te=>[...te,w.tag].sort((se,Se)=>se.name.localeCompare(Se.name))),D(!1),ke(""),H("blue")}catch(w){T(V(w))}},Ci=async w=>{if(!X)return;const te=X.tags.some(se=>se.id===w.id);try{const Se=(await A(te?`/api/projects/${X.id}/tags/${w.id}`:`/api/projects/${X.id}/tags`,te?{method:"DELETE"}:{method:"POST",body:JSON.stringify({tagId:w.id})})).project;z(Se),l(Ve=>Ve.map(Le=>Le.id===Se.id?Se:Le))}catch(se){T(V(se))}},ks=async()=>{if(!(!ee||!Xt.trim()))try{const w=await A(`/api/projects/${ee.id}`,{method:"PATCH",body:JSON.stringify({name:Xt})});l(te=>te.map(se=>se.id===w.project.id?w.project:se)),mt(null),un("")}catch(w){T(V(w))}},fn=async()=>{if(!(!At||!Ft.trim())){re(!0),T("");try{await A(`/api/projects/${At.id}/duplicate`,{method:"POST",body:JSON.stringify({name:Ft})}),Zt(null),It(""),st(ne,Ee,oe,he,nt)}catch(w){T(V(w))}finally{re(!1)}}},Es=async()=>{if(xe)try{await A(`/api/projects/${xe.id}`,{method:"DELETE"}),l(Ve=>Ve.filter(Le=>Le.id!==xe.id));const w=Math.max(0,u.total-1),te=Math.ceil(w/u.pageSize),se=te===0?1:Math.min(Ee,te),Se={...u,page:se,total:w,totalPages:te};m(Se),et(null),se!==Ee?Je(se):st(ne,Ee,oe,he,nt)}catch(w){T(V(w))}},fr=async w=>{Oe(w),St(""),ot([]),dt(""),ie(!0);try{const te=await A("/api/users");ot(te.users.filter(se=>se.id!==w.ownerId))}catch(te){dt(V(te))}finally{ie(!1)}},Ut=async()=>{if(!(!ce||!vt)){ie(!0),dt("");try{await A(`/api/projects/${ce.id}/owner`,{method:"PUT",body:JSON.stringify({userId:vt})}),Oe(null),St(""),st(ne,Ee,oe,he,nt)}catch(w){dt(V(w))}finally{ie(!1)}}},Ds=async w=>{const te=!ne;$t(w.id),T("");try{await A(`/api/projects/${w.id}/archive`,{method:te?"PUT":"DELETE"});const se=c.filter(pn=>pn.id!==w.id);l(se);const Se=Math.max(0,u.total-1),Ve=Math.ceil(Se/u.pageSize),Le=Ve===0?1:Math.min(Ee,Ve),at={...u,page:Le,total:Se,totalPages:Ve};m(at),ne||s(se,d,at),Le!==Ee?Je(Le):st(ne,Ee,oe,he,nt)}catch(se){T(V(se))}finally{$t("")}},Nn=c,Ns=["red","orange","yellow","green","blue","purple","gray"],Tn=w=>new Date(w).toLocaleString(we.resolvedLanguage);return o.jsxs("div",{className:"page",children:[o.jsxs("header",{className:"topbar",children:[o.jsx("span",{className:"site-title",children:t.siteName}),o.jsx(bi,{siteName:t.siteName}),o.jsxs("div",{className:"top-actions",children:[e.role==="admin"&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{className:"ghost",onClick:()=>C(!0),children:[o.jsx(am,{"aria-hidden":!0,size:14}),a("metrics.title")]}),o.jsxs("button",{className:"ghost",onClick:()=>b(!x),children:[x?o.jsx(od,{"aria-hidden":!0,size:14}):o.jsx(qs,{"aria-hidden":!0,size:14}),a(x?"users.back":"users.manage")]})]}),o.jsx(Wo,{compact:!0}),o.jsxs("span",{className:"top-user-identity",children:[o.jsx("strong",{children:e.displayName}),o.jsxs("small",{children:["@",e.username]})]}),o.jsx("button",{className:"ghost",onClick:ji,children:a("auth.logout")})]})]}),x?o.jsx(_b,{currentUser:e}):o.jsxs("main",{className:"dashboard",children:[o.jsxs("div",{className:"section-title",children:[o.jsxs("div",{children:[o.jsxs("h1",{children:[o.jsx(Vr,{"aria-hidden":!0,size:25}),a("projects.title")]}),o.jsx("p",{className:"muted",children:e.canCreateProjects?a("projects.subtitle"):a("projects.restricted")})]}),o.jsxs("div",{className:"section-actions",children:[o.jsxs("button",{onClick:()=>D(!0),children:[o.jsx(jc,{"aria-hidden":!0,size:15}),a("tags.create")]}),e.canCreateProjects&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>{F(""),O(!0)},children:[o.jsx(Hr,{"aria-hidden":!0,size:15}),a("projects.upload")]}),o.jsxs("button",{className:"primary",onClick:()=>L(!0),children:[o.jsx(dd,{"aria-hidden":!0,size:15}),a("projects.new")]})]})]})]}),N&&o.jsx("p",{className:"error",children:N}),o.jsxs("div",{className:"project-toolbar",children:[o.jsx("input",{type:"search",placeholder:a("projects.search"),value:oe,onChange:w=>{ae(w.target.value),Je(1)}}),o.jsxs("div",{className:"project-scope",role:"tablist","aria-label":a("projects.scope"),children:[o.jsxs("button",{className:ne?"":"active",onClick:()=>ur(!1),role:"tab","aria-selected":!ne,children:[o.jsx(Vr,{size:14}),a("projects.active")]}),o.jsxs("button",{className:ne?"active":"",onClick:()=>ur(!0),role:"tab","aria-selected":ne,children:[o.jsx(xc,{size:14}),a("projects.archived")]})]}),o.jsxs("div",{className:"tag-filters",children:[o.jsx("button",{className:he?"":"active",onClick:()=>Ss(""),children:a("projects.allTags")}),d.map(w=>o.jsxs("button",{className:he===w.id?"active":"",onClick:()=>Ss(he===w.id?"":w.id),children:[o.jsx(io,{color:w.color}),w.name]},w.id))]}),o.jsxs("label",{className:"project-sort",children:[o.jsx(lm,{size:14}),o.jsx("span",{children:a("projects.sortBy")}),o.jsxs("select",{value:nt,onChange:w=>ve(w.target.value),children:[o.jsx("option",{value:"updated",children:a("projects.sortModified")}),o.jsx("option",{value:"created",children:a("projects.sortCreated")})]})]}),o.jsxs("div",{className:"view-toggle",children:[o.jsx("button",{className:Re==="grid"?"active":"",onClick:()=>vs("grid"),title:a("projects.grid"),children:"▦"}),o.jsx("button",{className:Re==="list"?"active":"",onClick:()=>vs("list"),title:a("projects.list"),children:"☷"})]})]}),o.jsxs("div",{className:`project-grid ${Re==="list"?"list-view":""}`,children:[Nn.map(w=>o.jsxs("article",{className:`project-card${w.ownerId===e.id?" owned-project":""}`,children:[Re==="grid"&&w.ownerId===e.id&&o.jsxs("button",{className:"project-transfer-action",title:a("projects.transferOwnership"),onClick:()=>{fr(w)},children:[o.jsx(zi,{"aria-hidden":!0,size:13}),a("projects.transfer")]}),o.jsxs("button",{className:"project-card-open",onClick:()=>i(w.id),children:[o.jsx("span",{className:"owner-badge",title:w.ownerDisplayName??w.ownerUsername,children:w.ownerDisplayName??w.ownerUsername}),o.jsxs("span",{className:"project-card-main",children:[o.jsx("strong",{children:w.name}),o.jsx("span",{className:"project-tags",children:w.tags?.map(te=>o.jsx("span",{className:`tag tag-${te.color}`,children:te.name},te.id))})]}),o.jsxs("dl",{className:"project-meta",children:[o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(dm,{"aria-hidden":!0,size:13}),a("projects.created")]}),o.jsx("dd",{children:o.jsx("time",{dateTime:w.createdAt,children:Tn(w.createdAt)})})]}),o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(ud,{"aria-hidden":!0,size:13}),a("projects.modified")]}),o.jsxs("dd",{title:a("projects.modifiedByUser",{time:Tn(w.updatedAt),user:w.lastModifiedDisplayName??w.lastModifiedUsername??a("projects.deletedUser")}),children:[o.jsx("time",{dateTime:w.updatedAt,children:Tn(w.updatedAt)}),o.jsxs("span",{className:"project-modified-by",children:[" · ",a("projects.byUser",{user:w.lastModifiedDisplayName??w.lastModifiedUsername??a("projects.deletedUser")})]})]})]})]})]}),o.jsxs("div",{className:"project-card-actions",children:[o.jsxs("button",{onClick:()=>z(w),children:[o.jsx(jc,{"aria-hidden":!0,size:14}),a("tags.assign")]}),w.permission==="owner"&&o.jsxs("button",{onClick:()=>{mt(w),un(w.name)},children:[o.jsx(xo,{"aria-hidden":!0,size:14}),a("projects.rename")]}),(e.role==="admin"||e.canCreateProjects)&&o.jsxs("button",{onClick:()=>{Zt(w),It(`${w.name} (1)`)},children:[o.jsx(mm,{"aria-hidden":!0,size:14}),a("projects.duplicate")]}),o.jsxs("a",{href:`/api/projects/${w.id}/download`,download:!0,children:[o.jsx(Bs,{"aria-hidden":!0,size:14}),a("projects.download")]}),o.jsxs("button",{disabled:Mt===w.id,onClick:()=>{Ds(w)},children:[ne?o.jsx(cm,{"aria-hidden":!0,size:14}):o.jsx(xc,{"aria-hidden":!0,size:14}),a(ne?"projects.unarchive":"projects.archive")]}),Re==="list"&&w.ownerId===e.id&&o.jsxs("button",{onClick:()=>{fr(w)},children:[o.jsx(zi,{"aria-hidden":!0,size:14}),a("projects.transfer")]}),w.permission==="owner"&&o.jsxs("button",{className:"danger-text",onClick:()=>et(w),children:[o.jsx(ss,{"aria-hidden":!0,size:14}),a("common.delete")]})]})]},w.id)),Nn.length===0&&(c.length===0?ne?o.jsx("div",{className:"empty",children:a("projects.noArchived")}):o.jsxs("div",{className:"project-empty",children:[o.jsx("span",{className:"project-empty-icon",children:o.jsx(Rm,{size:28})}),o.jsx("h2",{children:a("projects.emptyTitle")}),o.jsx("p",{children:e.canCreateProjects?a("projects.emptyDescription"):a("projects.emptyRestricted")})]}):o.jsx("div",{className:"empty",children:a("projects.noMatches")}))]}),u.totalPages>1&&o.jsxs("nav",{className:"project-pagination","aria-label":a("projects.pagination"),children:[o.jsxs("button",{disabled:u.page<=1,onClick:()=>Je(w=>Math.max(1,w-1)),title:a("projects.previousPage"),children:[o.jsx(ld,{size:15}),a("projects.previousPage")]}),o.jsx("span",{children:a("projects.pageOf",{page:u.page,totalPages:u.totalPages,count:u.total})}),o.jsxs("button",{disabled:u.page>=u.totalPages,onClick:()=>Je(w=>Math.min(u.totalPages,w+1)),title:a("projects.nextPage"),children:[o.jsx(Ko,{size:15}),a("projects.nextPage")]})]}),o.jsx(Ie,{open:_,title:a("projects.new"),description:a("projects.newDescription"),onOpenChange:L,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>L(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{js()},children:a("common.create")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:E,onChange:w=>q(w.target.value),onKeyDown:w=>{w.key==="Enter"&&js()}})]})}),o.jsx(Ie,{open:v,title:a("projects.upload"),description:a("projects.uploadDescription",{size:t.maxUploadSizeMB??50}),onOpenChange:w=>{O(w),w||F("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>{O(!1),F("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:!P||Q,onClick:()=>{Si()},children:a(Q?"projects.importing":"projects.import")})]}),children:o.jsxs("div",{className:"form-stack",children:[S&&o.jsx("p",{className:"error import-error",children:S}),o.jsxs("div",{className:`upload-picker${P?" has-file":""}`,onDragOver:w=>{w.preventDefault(),w.dataTransfer.dropEffect="copy"},onDrop:w=>{w.preventDefault(),Cs(w.dataTransfer.files[0]??null)},children:[o.jsx("input",{ref:le,className:"sr-only",type:"file",accept:".zip,application/zip",onChange:w=>Cs(w.target.files?.[0]??null)}),o.jsx(wo,{size:34}),o.jsxs("div",{className:"upload-picker-copy",children:[o.jsx("strong",{children:P?.name??a("projects.chooseZip")}),o.jsx("span",{children:P?a("projects.selectedFileSize",{size:Xu(P.size)}):a("projects.dropZip")})]}),o.jsxs("button",{type:"button",onClick:()=>le.current?.click(),children:[o.jsx(Hr,{size:15}),a("projects.browse")]}),P&&o.jsx("button",{className:"upload-clear",type:"button",title:a("projects.clearFile"),"aria-label":a("projects.clearFile"),onClick:()=>{Cs(null),le.current&&(le.current.value="")},children:o.jsx(Jo,{size:14})})]}),o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{value:Z,onChange:w=>W(w.target.value)})]})]})}),o.jsx(Ie,{open:B,title:a("tags.create"),description:a("tags.createDescription"),onOpenChange:D,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>D(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{hr()},children:a("common.create")})]}),children:o.jsxs("div",{className:"form-stack",children:[o.jsxs("label",{className:"form-field",children:[a("tags.name"),o.jsx("input",{autoFocus:!0,value:ye,onChange:w=>ke(w.target.value)})]}),o.jsxs("fieldset",{className:"color-picker",children:[o.jsx("legend",{children:a("tags.color")}),Ns.map(w=>o.jsxs("label",{className:Be===w?"active":"",children:[o.jsx("input",{type:"radio",name:"dashboard-tag-color",checked:Be===w,onChange:()=>H(w)}),o.jsx(io,{color:w}),a(`tags.${w}`)]},w))]})]})}),o.jsx(Ie,{open:!!X,title:a("tags.assignTitle",{project:X?.name??""}),description:a("tags.assignDescription"),onOpenChange:w=>{w||z(null)},footer:o.jsx("button",{onClick:()=>z(null),children:a("common.close")}),children:o.jsxs("div",{className:"tag-assignment-list",children:[d.map(w=>o.jsxs("label",{children:[o.jsx("input",{type:"checkbox",checked:!!X?.tags.some(te=>te.id===w.id),onChange:()=>{Ci(w)}}),o.jsx(io,{color:w.color}),o.jsx("span",{children:w.name})]},w.id)),d.length===0&&o.jsx("p",{className:"muted",children:a("tags.empty")})]})}),o.jsx(Ie,{open:!!ee,title:a("projects.renameTitle"),onOpenChange:w=>{w||mt(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>mt(null),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ks()},children:a("projects.rename")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:Xt,onChange:w=>un(w.target.value),onKeyDown:w=>{w.key==="Enter"&&ks()}})]})}),o.jsx(Ie,{open:!!At,title:a("projects.duplicateTitle"),description:a("projects.duplicateDescription",{project:At?.name??""}),onOpenChange:w=>{!w&&!U&&(Zt(null),It(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:U,onClick:()=>{Zt(null),It("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:U||!Ft.trim(),onClick:()=>{fn()},children:a(U?"projects.duplicating":"projects.duplicate")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:Ft,onChange:w=>It(w.target.value),onKeyDown:w=>{w.key==="Enter"&&fn()}})]})}),o.jsx(Ie,{open:!!ce,title:a("projects.transferOwnership"),description:a("projects.transferDescription",{project:ce?.name??""}),onOpenChange:w=>{!w&&!tt&&(Oe(null),St(""),dt(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:tt,onClick:()=>{Oe(null),St(""),dt("")},children:a("common.cancel")}),o.jsxs("button",{className:"primary",disabled:tt||!vt,onClick:()=>{Ut()},children:[tt?o.jsx(yn,{className:"spin",size:14}):o.jsx(zi,{size:14}),a("projects.transfer")]})]}),children:o.jsxs("div",{className:"form-stack",children:[jt&&o.jsx("p",{className:"error dialog-error",children:jt}),o.jsxs("label",{className:"form-field",children:[a("projects.newOwner"),o.jsxs("select",{disabled:tt||He.length===0,value:vt,onChange:w=>St(w.target.value),children:[o.jsx("option",{value:"",children:tt?a("common.loading"):He.length>0?a("projects.chooseNewOwner"):a("projects.noTransferUsers")}),He.map(w=>o.jsxs("option",{value:w.id,children:[w.displayName??w.username," (@",w.username,")"]},w.id))]})]}),o.jsxs("p",{className:"warning",children:[o.jsx(Hs,{size:15}),a("projects.transferWarning")]})]})}),o.jsx(Vs,{open:!!xe,title:a("projects.deleteTitle"),description:a("projects.deleteDescription",{project:xe?.name??""}),confirmLabel:a("common.delete"),danger:!0,onCancel:()=>et(null),onConfirm:()=>{Es()}})]}),j&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(kb,{open:!0,onOpenChange:C})}),o.jsx(Ta,{})]})}function io({color:t}){return o.jsx("span",{className:`tag-dot tag-${t}`})}function Ob(t=10){const e="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%",n=crypto.getRandomValues(new Uint8Array(t));return Array.from(n,s=>e[s%e.length]).join("")}function _b({currentUser:t}){const{t:e}=Pe(),[n,s]=h.useState([]),[r,i]=h.useState(""),[a,c]=h.useState(!1),[l,d]=h.useState({username:"",displayName:"",password:"",role:"user",canCreateProjects:!1}),[f,u]=h.useState(null),[m,p]=h.useState(""),[g,x]=h.useState(null),[b,j]=h.useState(!1),C=()=>A("/api/admin/users").then(({users:v})=>s(v)).catch(v=>i(V(v)));h.useEffect(()=>{C()},[]);const N=async()=>{if(l.password.length<Xe)return i(e("auth.passwordMinimum",{count:Xe}));try{await A("/api/admin/users",{method:"POST",body:JSON.stringify({username:l.username,displayName:l.displayName||l.username,password:l.password,role:l.role,canCreateProjects:l.canCreateProjects})}),c(!1),d({username:"",displayName:"",password:"",role:"user",canCreateProjects:!1}),await C()}catch(v){i(V(v))}},T=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({disabled:!v.disabled})}),await C()}catch(O){i(V(O))}},_=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({role:v.role==="admin"?"user":"admin"})}),await C()}catch(O){i(V(O))}},L=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({canCreateProjects:!v.canCreateProjects})}),await C()}catch(O){i(V(O))}},E=async()=>{if(!(!f||!m)){if(m.length<Xe)return i(e("auth.passwordMinimum",{count:Xe}));try{await A(`/api/admin/users/${f.id}`,{method:"PATCH",body:JSON.stringify({password:m})}),u(null),p("")}catch(v){i(V(v))}}},q=async()=>{if(g)try{await A(`/api/admin/users/${g.id}`,{method:"DELETE",body:JSON.stringify({deleteProjects:b})}),x(null),j(!1),await C()}catch(v){i(V(v))}};return o.jsxs("main",{className:"dashboard",children:[o.jsxs("div",{className:"section-title",children:[o.jsxs("div",{children:[o.jsxs("h1",{children:[o.jsx(qs,{"aria-hidden":!0,size:25}),e("users.manage")]}),o.jsx("p",{className:"muted",children:e("users.onlyAdmin")})]}),o.jsxs("button",{className:"primary icon-button",onClick:()=>c(!0),children:[o.jsx(fd,{"aria-hidden":!0,size:15}),e("users.add")]})]}),r&&o.jsx("p",{className:"error",children:r}),o.jsx("div",{className:"table-card",children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:e("common.user")}),o.jsx("th",{children:e("users.role")}),o.jsx("th",{children:e("users.createProjects")}),o.jsx("th",{children:e("users.ownedProjects")}),o.jsx("th",{children:e("users.status")}),o.jsx("th",{children:e("users.actions")})]})}),o.jsx("tbody",{children:n.map(v=>o.jsxs("tr",{children:[o.jsxs("td",{children:[o.jsx("strong",{children:v.displayName}),o.jsxs("small",{children:["@",v.username]})]}),o.jsx("td",{children:v.role==="admin"?e("common.admin"):e("common.user")}),o.jsx("td",{children:v.canCreateProjects?e("users.allow"):e("users.deny")}),o.jsx("td",{children:v.ownedProjects}),o.jsx("td",{children:v.disabled?e("common.disabled"):e("common.normal")}),o.jsxs("td",{children:[o.jsx("button",{disabled:v.id===t.id,onClick:()=>T(v),children:v.disabled?e("users.enable"):e("users.disable")}),o.jsx("button",{disabled:v.id===t.id,onClick:()=>_(v),children:v.role==="admin"?e("users.demote"):e("users.promote")}),o.jsx("button",{disabled:v.role==="admin",onClick:()=>L(v),children:v.canCreateProjects?e("users.denyCreate"):e("users.allowCreate")}),o.jsx("button",{onClick:()=>{u(v),p("")},children:e("users.resetPassword")}),o.jsx("button",{className:"danger-text",disabled:v.id===t.id,onClick:()=>{x(v),j(!1)},children:e("common.delete")})]})]},v.id))})]})}),o.jsx(Ie,{open:a,title:e("users.add"),description:e("users.addDescription"),onOpenChange:c,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>c(!1),children:e("common.cancel")}),o.jsx("button",{className:"primary",disabled:l.password.length<Xe,onClick:()=>{N()},children:e("users.createUser")})]}),children:o.jsxs("div",{className:"form-stack",children:[o.jsxs("label",{className:"form-field",children:[e("auth.username"),o.jsx("input",{value:l.username,onChange:v=>d({...l,username:v.target.value})})]}),o.jsxs("label",{className:"form-field",children:[e("users.displayName"),o.jsx("input",{value:l.displayName,onChange:v=>d({...l,displayName:v.target.value})})]}),o.jsxs("label",{className:"form-field",children:[e("users.initialPassword"),o.jsxs("span",{className:"password-generator",children:[o.jsx("input",{minLength:Xe,autoComplete:"new-password",value:l.password,onChange:v=>d({...l,password:v.target.value})}),o.jsxs("button",{type:"button",title:e("users.generatePassword"),onClick:()=>d({...l,password:Ob()}),children:[o.jsx(gm,{size:15}),e("users.randomPassword")]})]}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Xe})})]}),o.jsxs("label",{className:"form-field",children:[e("users.role"),o.jsxs("select",{value:l.role,onChange:v=>d({...l,role:v.target.value}),children:[o.jsx("option",{value:"user",children:e("common.user")}),o.jsx("option",{value:"admin",children:e("common.admin")})]})]}),o.jsxs("label",{className:"checkbox-field",children:[o.jsx("input",{type:"checkbox",checked:l.canCreateProjects||l.role==="admin",disabled:l.role==="admin",onChange:v=>d({...l,canCreateProjects:v.target.checked})})," ",e("users.allowCreate")]})]})}),o.jsx(Ie,{open:!!f,title:e("users.resetPassword"),description:e("users.resetDescription",{username:f?.username??""}),onOpenChange:v=>{v||u(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>u(null),children:e("common.cancel")}),o.jsx("button",{className:"primary",disabled:m.length<Xe,onClick:()=>{E()},children:e("users.reset")})]}),children:o.jsxs("label",{className:"form-field",children:[e("auth.newPassword"),o.jsx("input",{autoFocus:!0,type:"password",minLength:Xe,autoComplete:"new-password",value:m,onChange:v=>p(v.target.value)}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Xe})})]})}),o.jsx(Ie,{open:!!g,title:e("users.deleteTitle"),description:e("users.deleteDescription",{username:g?.username??""}),onOpenChange:v=>{v||x(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>x(null),children:e("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{q()},children:e("users.deleteTitle")})]}),children:o.jsxs("fieldset",{className:"choice-group",children:[o.jsx("legend",{children:e("users.ownedChoice",{count:g?.ownedProjects??0})}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",checked:!b,onChange:()=>j(!1)})," ",e("users.transferProjects")]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",checked:b,onChange:()=>j(!0)})," ",e("users.deleteProjects")]})]})})]})}function Pb({site:t,user:e,projectId:n,onBack:s}){const{t:r}=Pe(),[i,a]=h.useState(null),[c,l]=h.useState([]),[d,f]=h.useState(null),[u,m]=h.useState([]),[p,g]=h.useState(""),[x,b]=h.useState(""),[j,C]=h.useState(new Set),[N,T]=h.useState(""),[_,L]=h.useState(""),[E,q]=h.useState(!1),[v,O]=h.useState("editor.saved"),[Z,W]=h.useState(null),[P,R]=h.useState({line:1,column:1}),S=h.useRef(P),[F,le]=h.useState("pdf"),[Q,ge]=h.useState("log"),oe=y=>{if(y==="pdf"){le("pdf");return}ge(y),le("diagnostics")},{workspaceLayout:ae,setWorkspaceLayout:he}=wb(e.id,n),[Ce,B]=h.useState(""),[D,ye]=h.useState(""),[ke,Be]=h.useState({selectedText:"",startOffset:0,endOffset:0}),H=h.useRef({selectedText:"",startOffset:0,endOffset:0}),X=y=>{H.current=y,Be(y)},[z,ee]=h.useState(null),[mt,Xt]=h.useState(!1),[un,At]=h.useState(!1),[Zt,Ft]=h.useState(!1),[It,U]=h.useState(!1),[re,xe]=h.useState(!1),[et,ce]=h.useState(!1),[Oe,He]=h.useState(!1),[ot,vt]=h.useState(()=>kc(e.id,n)),St=h.useRef(null),tt=h.useRef(null),ie=h.useRef(0),jt=h.useRef(0),dt=h.useRef(""),Re=h.useRef(""),Ct=h.useRef(""),nt=h.useRef(""),hn=h.useRef(0),ne=h.useRef(null),Ue=h.useRef(null),Mt=h.useRef(null),$t=h.useRef(null),Ee=h.useRef(!1),Je=h.useRef(null),xs=h.useRef(s);xs.current=s,Ct.current=x;const vi=(y,k)=>{const M={line:y,column:k};S.current=M,R(M)},{collaboration:ze,status:kt,synced:qe,activeSessions:bs,compileState:st,setCompileState:vs,filesEvent:ve,commentsRevision:ur,dictionaryRevision:Ss,localDraftReady:js,reconnect:Si}=db(n,e,x,()=>O("editor.offlineDraft")),{pdfTarget:Cs,pdfViewport:ji,sourceJump:hr,setPdfViewport:Ci,clearPdfViewport:ks,jumpToSource:fn,syncSourceToPdf:Es,syncVisiblePdfToSource:fr}=yb({projectId:n,mainFile:x,activeFile:p,onActiveFile:g,onError:B,onShowPdf:()=>oe("pdf")}),Ut=gb({active:!!(i&&p&&qe&&ot.spellCheck),activeFile:p,content:N,dictionaryWords:c});h.useEffect(()=>{vt(kc(e.id,n))},[e.id,n]);const Ds=y=>{dt.current=y,T(y)};h.useEffect(()=>{Re.current=p,S.current={line:1,column:1},R({line:1,column:1}),X({selectedText:"",startOffset:0,endOffset:0})},[p]),h.useEffect(()=>{if(!E)return;const y=k=>{k.preventDefault(),k.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[E]),h.useEffect(()=>{if(kt!=="disconnected")return;const y=new AbortController;return A(`/api/projects/${n}`,{signal:y.signal}).then(({project:k})=>{y.signal.aborted||(a(k),B(""))}).catch(k=>{if(!qn(k)){if(k instanceof Ao&&[401,403,404].includes(k.status)){B(V(k)),xs.current();return}B(r("errors.collaborationUnavailable"))}}),()=>y.abort()},[kt,n,r]);const Nn=async(y={})=>{ne.current?.abort(),ne.current=null;const k=y.signal?null:new AbortController;k&&(ne.current=k);try{const M=await A(`/api/projects/${n}/completions`,{signal:y.signal??k?.signal});(!y.isCurrent||y.isCurrent())&&f(M.index)}catch(M){if(qn(M))return;(!y.isCurrent||y.isCurrent())&&f(null)}finally{k&&ne.current===k&&(ne.current=null)}},Ns=async(y={},k=Ct.current)=>{Ue.current?.abort(),Ue.current=null;const M=y.signal?null:new AbortController;M&&(Ue.current=M);try{const J=k?`?mainFile=${encodeURIComponent(k)}`:"",fe=await A(`/api/projects/${n}/outline${J}`,{signal:y.signal??M?.signal});(!y.isCurrent||y.isCurrent())&&m(fe.outline)}catch(J){!qn(J)&&(!y.isCurrent||y.isCurrent())&&m([])}finally{M&&Ue.current===M&&(Ue.current=null)}},Tn=async(y={})=>{Mt.current?.abort(),Mt.current=null;const k=y.signal?null:new AbortController;k&&(Mt.current=k);try{const M=await A(`/api/projects/${n}/dictionary`,{signal:y.signal??k?.signal});(!y.isCurrent||y.isCurrent())&&l(M.words)}catch(M){if(qn(M))return;(!y.isCurrent||y.isCurrent())&&l([])}finally{k&&Mt.current===k&&(Mt.current=null)}};h.useEffect(()=>{let y=!1;const k=++hn.current,M=new AbortController,J=()=>!y&&hn.current===k;let fe=!1;nt.current="",a(null),pn([]),m([]),g(""),b(""),C(new Set),T(""),L(""),vs(null),ks(),f(null),l([]),Yu();const Ye=A(`/api/projects/${n}`,{signal:M.signal}).then(We=>{J()&&(fe=!0,a(We.project),g(We.project.mainFile),b(We.project.mainFile),C(new Set([We.project.mainFile])),Ra(new Set(Fs(We.project.mainFile))))}).catch(We=>{J()&&B(V(We))}),de=A(`/api/projects/${n}/files`,{signal:M.signal}).then(We=>{J()&&pn(We.files)}).catch(We=>{J()&&B(V(We))});return Promise.allSettled([Ye,de]).then(()=>{!J()||!fe||window.setTimeout(()=>{J()&&Promise.all([Nn({signal:M.signal,isCurrent:J}),Tn({signal:M.signal,isCurrent:J})])},0)}),()=>{y=!0,M.abort(),ne.current?.abort(),ne.current=null,Ue.current?.abort(),Ue.current=null,Mt.current?.abort(),Mt.current=null,$t.current?.abort(),$t.current=null}},[n]),h.useEffect(()=>{Ss&&Tn()},[Ss,n]),h.useEffect(()=>{i&&ze.setPermission(i.permission)},[ze,i?.permission]),h.useEffect(()=>{if(!ve)return;const y=ve.kind==="delete"&&!!ve.path&&zn(ve.path,Re.current),k=ve.kind==="delete"&&!!ve.path&&zn(ve.path,Ct.current);if(ve.kind==="move"&&ve.source&&ve.destination){const J=ve.source,fe=ve.destination,Ye=de=>de===J?fe:de.startsWith(`${J}/`)?`${fe}${de.slice(J.length)}`:de;g(de=>Ye(de)),b(de=>Ye(de)),C(de=>new Set([...de].map(Ye))),pr(de=>de&&Ye(de))}y&&(g(""),L(""),Ds(""),ye(r("editor.fileDeletedByCollaborator",{path:ve.path}))),ve.kind==="delete"&&ve.path&&(C(J=>new Set([...J].filter(fe=>!zn(ve.path,fe)))),pr(J=>zn(ve.path,J)?"":J),_a(J=>J&&zn(ve.path,J.path)?null:J)),$t.current?.abort();const M=new AbortController;$t.current=M,Promise.all([On({signal:M.signal}),A(`/api/projects/${n}`,{signal:M.signal})]).then(([J,fe])=>{if(a(fe.project),k&&b(fe.project.mainFile),y&&J){const Ye=J.find(de=>de.type==="file"&&de.path===fe.project.mainFile)??J.find(de=>de.type==="file"&&Lo(de.path));g(Ye?.path??"")}Nn({signal:M.signal}),Ns({signal:M.signal},k?fe.project.mainFile:Ct.current)}).catch(J=>{qn(J)}).finally(()=>{$t.current===M&&($t.current=null)})},[ve?.revision]),h.useEffect(()=>{if(ze.setActiveFile(p),!p)return;L(""),O("editor.loading");const y=ze.getText(p),k=(M,J)=>{Ds(y.toString()),L(p),J?.local&&i?.permission!=="read"?(ie.current+=1,q(!0),O("editor.pending")):ie.current<=jt.current&&O(Z?"editor.savedAt":"editor.saved")};return y.observe(k),(qe||js)&&k(),()=>{y.unobserve(k)}},[p,ze,qe,js,i?.permission]),h.useEffect(()=>{!p||_!==p||nt.current===p||(nt.current=p,!(!p.toLocaleLowerCase().endsWith(".tex")||!Rb(N))&&(C(y=>new Set([...y,p])),b(p)))},[p,_,N]);const w=async()=>{if(!qe)throw new Error("Collaboration is not synchronized");const y=ie.current,k=await ze.flush();return jt.current=Math.max(jt.current,y),W(k.persistedAt),/\.tex$/i.test(Re.current)&&Ns(),ie.current===y?(q(!1),O("editor.savedAt")):O("editor.pending"),k};h.useEffect(()=>{if(!E||!p)return;if(!qe){O("editor.offlineDraft");return}O("editor.pending");const y=window.setTimeout(()=>{O("editor.saving"),w().catch(()=>{O(ze.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(y)},[N,E,p,qe]);const te=async()=>{if(!i||i.permission==="read"||!qe||!p)return!1;O("editor.saving");try{return await w(),Nn(),!0}catch{return O("editor.saveFailed"),B(r("errors.collaborationUnavailable")),!1}},se=async(y,k)=>(await A(`/api/projects/${n}/format`,{method:"POST",body:JSON.stringify({path:y,source:k})})).formatted,Se=async()=>{if(!ot.formatOnCompile||!i||i.permission==="read"||!qe||!Bi(Re.current)||Ee.current)return;const y=Re.current,k=ze.getText(y),M=k.toString();Ee.current=!0,He(!0);try{const J=await se(y,M),fe=await Ec(M,J);if(Re.current!==y||k.toString()!==M)throw new Error(r("editor.formatSourceChanged"));fe.length&&ze.applyTextEdits(y,fe)}catch(J){B(r("editor.formatFailedContinue",{message:V(J)}))}finally{Ee.current=!1,He(!1)}},Ve=async()=>(Je.current&&await Je.current,await Se(),te()),Le=async()=>{if(!i||i.permission==="read"||!qe||Ee.current||!Bi(Re.current))return;const y=H.current;if(!y.selectedText.trim()){ye(r("editor.formatSelectionRequired"));return}const k=Re.current,{startOffset:M,endOffset:J,selectedText:fe}=y,Ye=ze.getText(k);if(Ye.toString().slice(M,J)!==fe){B(r("editor.formatSelectionChanged"));return}Ee.current=!0,He(!0);let de=()=>{};const We=new Promise(Et=>{de=Et});Je.current=We;try{const Et=Um(fe,await se(k,fe)),Ga=await Ec(fe,Et,M);if(Re.current!==k||Ye.toString().slice(M,J)!==fe){B(r("editor.formatSelectionChanged"));return}Ga.length&&ze.applyTextEdits(k,Ga),B(""),ye(r("editor.formatSelectionComplete"))}catch(Et){B(r("editor.formatFailed",{message:V(Et)}))}finally{Ee.current=!1,He(!1),de(),Je.current===We&&(Je.current=null)}},{files:at,setFiles:pn,loadFiles:On,newFileOpen:Qt,setNewFileOpen:Ts,newFilePath:Zu,setNewFilePath:Oa,resourcePreview:De,setResourcePreview:_a,resourcePreviewLoading:Qu,setResourcePreviewLoading:eh,newFolderOpen:th,setNewFolderOpen:ki,newFolderName:nh,setNewFolderName:Pa,fileDialogError:en,setFileDialogError:_n,selectedFolder:zt,setSelectedFolder:pr,expandedFolders:sh,setExpandedFolders:Ra,moveEntry:Os,setMoveEntry:mr,moveDestination:rh,setMoveDestination:Ei,deleteEntry:Pn,setDeleteEntry:gr,fileDragActive:La,setFileDragActive:Di,uploadConflict:Ni,setUploadConflict:Aa,uploadingFiles:yr,directoryEntries:ih,visibleEntries:oh,createFile:ah,createFolder:Fa,uploadFiles:Ia,upload:ch,openFile:Ma,movePath:lh,removePath:dh}=mb({projectId:n,site:t,activeFile:p,dirty:E,save:te,onError:B,onProject:a,onActiveFile:g,onActiveMainFile:b,onRootDocuments:C}),{comments:_s,focusComment:uh,setFocusComment:$a,commentOpen:hh,setCommentOpen:Ti,commentText:fh,setCommentText:ph,addComment:mh,toggleComment:gh,replyToComment:yh,editComment:wh,deleteComment:xh,editCommentReply:bh,deleteCommentReply:vh}=cb({projectId:n,activeFile:p,permission:i?.permission,revision:ur,selection:ke,save:te,onError:B,onAdded:()=>ee("comments")}),{pdfUrl:mn,pdfCompiledAt:Rn,compileLog:wr,compileDiagnostics:xr,compileOutcome:br,artifacts:Oi,artifactPreview:Sh,artifactLoading:jh,editorNotice:Ua,localCompiling:_i,compile:Ch,viewArtifact:kh}=ub({projectId:n,project:i,mainFile:x,collaborationSynced:qe,sharedState:st,onSharedState:vs,save:Ve,loadOutline:(y,k)=>Ns({signal:y},k),onPreviewTab:oe,onError:B,onCompileStart:()=>{B(""),ye("")},onCompileSuccess:()=>{const y=Re.current;y&&Es(y,S.current.line,S.current.column,{silent:!0})},onPdfChanged:ks});h.useEffect(()=>{const y=k=>{(k.ctrlKey||k.metaKey)&&(!k.shiftKey&&k.key.toLocaleLowerCase()==="p"?(k.preventDefault(),xe(!0)):k.shiftKey&&k.key.toLocaleLowerCase()==="f"&&(k.preventDefault(),ce(!0)))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[]);const Eh=y=>{vt(y),Im(e.id,n,y)},za=()=>{tt.current?.isCollapsed()?tt.current.expand():tt.current?.collapse()},Va=h.useMemo(()=>u.length?u:Lb(N).map(y=>({...y,path:p})),[u,N,p]),Ln=h.useMemo(()=>zm(wr,br),[wr,br]),An=ae!=="pdf-only",Ba=ae!=="editor-only",vr=y=>{he(y),y==="pdf-only"&&oe("pdf")},Pi=Pn?bs.filter(y=>y.filePath&&zn(Pn.path,y.filePath)):[];if(!i)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:Ce||r("common.loading")}),Ce&&o.jsx("button",{className:"primary",onClick:s,children:r("editor.backToProjects")})]});const Vt=i.permission==="read"||!qe,Sr=st?.mainFile===x&&(st.status==="queued"||st.status==="running"),Ps=_i||Sr,Ha=p?ze.getText(p):null,qa=Rn?new Date(Rn).toLocaleString(we.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Dh=x.split("/").at(-1)??x,Nh=Ln.warnings.length+Ln.errors.length+Oi.length,Wa=mn?`${mn}${mn.includes("?")?"&":"?"}download=1`:"",Ka=Ps?Sr?st?.status==="queued"?r("editor.compileQueued"):r("editor.compilingBy",{name:st?.requestedBy.name??r("common.user")}):r("editor.compiling"):br==="failed"?mn&&Rn?r("editor.compileFailedRetained",{time:new Date(Rn).toLocaleString(we.resolvedLanguage)}):r("editor.compileFailedNoPdf"):"",Th=v==="editor.savedAt"&&Z?r("editor.savedAt",{time:new Date(Z).toLocaleTimeString(we.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):r(v);return o.jsxs("div",{className:"workspace",children:[o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:r("editor.backToProjects"),"aria-label":r("editor.backToProjects"),onClick:s,children:o.jsx(od,{size:18})}),o.jsx(bi,{siteName:t.siteName,compact:!0}),o.jsxs("div",{className:"project-heading",children:[o.jsx("strong",{children:i.name}),o.jsxs("small",{children:[p," · ",Th]})]}),ot.vimMode&&o.jsxs("span",{className:"vim-status-badge",title:r("editor.vimOnHint"),children:[o.jsx(vm,{size:14}),r("editor.vimOn")]}),o.jsx(Qx,{sessions:bs,status:kt}),kt==="disconnected"&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:r("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:Si,children:r("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[An&&o.jsxs("button",{className:mt?"":"active",onClick:za,children:[mt?o.jsx(km,{size:15}):o.jsx(Sc,{size:15}),r("common.files")]}),o.jsx(eb,{value:ae,onChange:vr}),o.jsxs("button",{onClick:()=>U(!0),children:[o.jsx(ud,{size:15}),r("history.title")]}),o.jsxs("button",{onClick:()=>At(!0),children:[o.jsx(qs,{size:15}),r("projectSettings.share")]}),i.ownerId===e.id&&o.jsxs("button",{onClick:()=>Ft(!0),children:[o.jsx(bm,{size:15}),"Git"]}),An&&i.permission!=="read"&&Bi(p)&&o.jsxs("button",{title:ke.selectedText.trim()?r("editor.formatSelection"):r("editor.formatSelectionHint"),onMouseDown:y=>y.preventDefault(),onClick:()=>{Le()},disabled:Vt||Oe||!qe,children:[Oe?o.jsx(yn,{className:"spin",size:15}):o.jsx(id,{size:15}),r(Oe?"editor.formatting":"editor.formatSelection")]}),o.jsxs("button",{onClick:()=>Ti(!0),disabled:!p,children:[o.jsx(jm,{size:15}),r("editor.addComment")]}),o.jsxs("button",{className:z==="comments"?"active":"",onClick:()=>ee(z==="comments"?null:"comments"),children:[o.jsx(Cm,{size:15}),r("common.comments")," ",_s.filter(y=>!y.resolved).length||""]}),o.jsxs("button",{className:z==="settings"?"active":"",onClick:()=>ee(z==="settings"?null:"settings"),children:[o.jsx(Lr,{size:15}),r("common.settings")]}),o.jsxs("button",{className:"compile",title:Sr?r("editor.compilingBy",{name:st?.requestedBy.name??""}):r("editor.compileShortcut"),onClick:Ch,disabled:Ps||Oe||Vt||!qe,children:[Ps?o.jsx(yn,{className:"spin",size:15}):o.jsx(Nm,{size:15}),Sr?r("editor.compilingBy",{name:st?.requestedBy.name??""}):_i?r("editor.compiling"):r("editor.compile",{engine:i.engine})]})]})]}),Ka&&o.jsxs("div",{className:`compile-status-strip${br==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(yn,{className:Ps?"spin":"",size:14}),o.jsx("span",{children:Ka})]}),Ce&&o.jsx("div",{className:"toast",onClick:()=>B(""),children:Ce}),D&&o.jsx("div",{className:"toast success",onClick:()=>ye(""),children:D}),o.jsxs(Ph,{autoSaveId:"texlite-workspace-layout",direction:"horizontal",className:"work-grid",children:[An&&o.jsx(jr,{id:"files",order:1,ref:tt,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>Xt(!0),onExpand:()=>Xt(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${La?" drop-active":""}`,onDragEnter:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),!Vt&&!yr&&Di(!0))},onDragOver:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),y.dataTransfer.dropEffect=Vt||yr?"none":"copy")},onDragLeave:y=>{y.currentTarget.contains(y.relatedTarget)||Di(!1)},onDrop:y=>{y.preventDefault(),Di(!1),!Vt&&!yr&&Ia(Array.from(y.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("span",{children:[o.jsx(Wn,{size:14}),r("common.files")]}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{"aria-label":r("navigation.quickOpen"),title:`${r("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>xe(!0),children:o.jsx(wm,{size:15})}),o.jsx("button",{"aria-label":r("navigation.projectSearch"),title:`${r("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>ce(!0),children:o.jsx(_m,{size:15})}),!Vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:yr,"aria-label":r("editor.uploadAttachment"),title:r("editor.uploadTo",{folder:zt||r("editor.projectRoot")}),onClick:()=>St.current?.click(),children:o.jsx(Hr,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFolder"),title:r("editor.newFolder"),onClick:()=>{Pa(""),ki(!0)},children:o.jsx(dd,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFile"),title:r("editor.newFile"),onClick:()=>{Oa(zt?`${zt}/`:""),Ts(!0)},children:o.jsx(ym,{size:15})}),o.jsx("input",{ref:St,type:"file",multiple:!0,hidden:!0,onChange:y=>{ch(y)}})]}),o.jsx("button",{"aria-label":r("editor.collapseFiles"),title:r("editor.collapseFiles"),onClick:za,children:o.jsx(Sc,{size:15})})]})]}),La&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(Hr,{size:24}),o.jsx("strong",{children:r("editor.dropFiles")}),o.jsx("span",{children:r("editor.uploadTo",{folder:zt||r("editor.projectRoot")})})]}),o.jsxs("div",{className:"folder-target",title:zt||r("editor.projectRoot"),children:[o.jsx(Vr,{size:13}),o.jsx("span",{children:zt||r("editor.projectRoot")})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${ot.fontSize}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${zt===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>pr(""),children:[o.jsx(Vr,{size:15}),o.jsx("span",{children:r("editor.projectRoot")})]})}),oh.map(y=>{const k=y.path.split("/").length-1,M=y.path.split("/").at(-1),J=sh.has(y.path),fe=j.has(y.path),Ye=x===y.path,de=y.path!==i.mainFile&&!i.mainFile.startsWith(`${y.path}/`);return y.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${zt===y.path?" selected":""}`,style:{paddingLeft:`${k*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",title:y.path,onClick:()=>{pr(y.path),Ra(We=>{const Et=new Set(We);return Et.has(y.path)?Et.delete(y.path):Et.add(y.path),Et})},children:[J?o.jsx(cd,{size:13}):o.jsx(Ko,{size:13}),o.jsx(xm,{size:14}),o.jsx("span",{children:M})]}),!Vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:r("editor.move"),"aria-label":r("editor.move"),onClick:()=>{mr(y),Ei("")},children:o.jsx(vc,{size:13})}),de&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),_n("")},children:o.jsx(ss,{size:13})})]})]},y.path):o.jsxs("div",{className:`file-entry${p===y.path?" active":""}${fe?" root-document":""}${Ye?" compile-target":""}`,style:{paddingLeft:`${k*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",title:Ye?r("editor.currentMainDocument",{path:y.path}):fe?r("editor.mainDocumentCandidate",{path:y.path}):y.path,onClick:()=>Ma(y),children:[fe?o.jsx(ad,{size:13}):o.jsx(Wn,{size:13}),o.jsx("span",{children:M}),Ye&&o.jsx("small",{children:r("editor.currentMainShort")})]}),!Vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:r("editor.move"),"aria-label":r("editor.move"),onClick:()=>{mr(y),Ei("")},children:o.jsx(vc,{size:13})}),de&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),_n("")},children:o.jsx(ss,{size:13})})]})]},y.path)})]})]}),o.jsxs("section",{className:"outline-panel",children:[o.jsx("div",{className:"panel-title",children:o.jsxs("span",{children:[o.jsx(Sm,{size:14}),r("common.outline")]})}),o.jsxs("div",{className:"outline",children:[Va.map((y,k)=>o.jsxs("button",{className:`outline-item${p===y.path&&P.line===y.line?" current":""}`,title:`${y.path}:${y.line}`,onClick:()=>{fn(y.path,y.line,1),Es(y.path,y.line,1)},children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${y.level*12}px`}}),o.jsx("small",{children:y.path===p?y.line:y.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:y.title})]},`${y.path}-${y.line}-${k}`)),Va.length===0&&o.jsx("p",{className:"muted padded",children:r("editor.noOutline")})]})]})]})}),An&&o.jsx(Ri,{className:"resize-handle",children:o.jsx(Vi,{size:12})}),An&&o.jsx(jr,{id:"source",order:2,defaultSize:42,minSize:22,children:o.jsxs("main",{className:"source-panel",children:[o.jsx(h.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(yn,{className:"spin",size:22}),o.jsx("span",{children:r("common.loading")})]}),children:o.jsx(bb,{value:N,readOnly:Vt,comments:_s,focusComment:uh,preferences:ot,completionIndex:d,spellCheckWords:c,spellCheckIssues:Ut.issues,spellCheckJump:Ut.jump,jumpTo:_===p&&hr?.path===p?hr:null,searchRequest:0,collaboration:Ha?{text:Ha,awareness:ze.awareness}:void 0,onChange:Ds,onSelection:(y,k,M)=>X({selectedText:y,startOffset:k,endOffset:M}),onCommentClick:y=>{const k=_s.find(M=>M.id===y);k&&($a({...k}),ee("comments"))},onCursor:vi},p)}),Ua&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:Ua})]})}),An&&Ba&&o.jsxs(Ri,{className:"resize-handle sync-resize-handle",children:[o.jsx(Vi,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:y=>y.stopPropagation(),children:[o.jsx("button",{disabled:!ji,title:r("editor.showInSource"),"aria-label":r("editor.showInSource"),onClick:fr,children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!p||!mn,title:r("editor.showInPdf"),"aria-label":r("editor.showInPdf"),onClick:()=>{Es(p,P.line,P.column)},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),Ba&&o.jsx(jr,{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":r("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":F==="pdf",className:`pdf-tab${F==="pdf"?" active":""}`,onClick:()=>oe("pdf"),title:Rn?r("editor.pdfCompiledAtFor",{file:x,time:new Date(Rn).toLocaleString(we.resolvedLanguage)}):r("editor.currentMainDocument",{path:x}),children:[o.jsx(Wn,{size:16}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",Dh,qa&&o.jsx("small",{children:qa})]})]}),o.jsxs("button",{role:"tab","aria-selected":F==="diagnostics",className:`diagnostics-tab${F==="diagnostics"?" active":""}`,onClick:()=>le("diagnostics"),children:[o.jsx(bo,{size:14}),r("editor.outputTabs"),o.jsx("span",{children:Nh})]})]}),Wa&&o.jsxs("a",{className:"pdf-download-top",href:Wa,download:!0,title:r("editor.downloadPdf"),"aria-label":r("editor.downloadPdf"),children:[o.jsx(Bs,{size:15}),o.jsx("span",{children:r("editor.downloadPdf")})]})]}),F==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":r("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":Q==="log",className:Q==="log"?"active":"",onClick:()=>oe("log"),children:[o.jsx(bo,{size:13}),r("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":Q==="warnings",className:Q==="warnings"?"active":"",onClick:()=>oe("warnings"),children:[o.jsx(Hs,{size:13}),r("editor.warnings"),o.jsx("span",{children:Ln.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":Q==="errors",className:Q==="errors"?"active":"",onClick:()=>oe("errors"),children:[o.jsx(Go,{size:13}),r("editor.errors"),o.jsx("span",{children:Ln.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":Q==="artifacts",className:Q==="artifacts"?"active":"",onClick:()=>oe("artifacts"),children:[o.jsx(hd,{size:13}),r("editor.artifacts"),o.jsx("span",{children:Oi.length})]})]}),o.jsxs("div",{className:`preview-content preview-${F} ${F==="diagnostics"?`preview-${Q}`:""}`,children:[F==="pdf"&&(mn?o.jsx(h.Suspense,{fallback:o.jsx("div",{className:"preview-empty",children:o.jsx("span",{children:r("common.loading")})}),children:o.jsx(xb,{url:mn,target:Cs,compiling:Ps,onViewportLocation:(y,k,M)=>Ci({page:y,x:k,y:M})})}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Wn,{size:28}),o.jsx("strong",{children:r("editor.preview")}),o.jsx("span",{children:r("editor.previewHint")})]})),F==="diagnostics"&&Q==="log"&&o.jsx(ro,{lines:wr?wr.split(`
13
+ `)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function rb({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:a}=Pe(),c=l=>`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(l)}&download=1`;return n.length?o.jsxs("div",{className:"artifact-browser",children:[o.jsx("div",{className:"artifact-list",children:n.map(l=>o.jsxs("div",{className:`artifact-row${s?.path===l.path?" active":""}`,children:[o.jsxs("button",{type:"button",disabled:!l.viewable,title:l.viewable?a("editor.viewArtifact"):a("editor.downloadToView"),onClick:()=>i(l),children:[o.jsx(Wn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:l.path}),o.jsx("small",{children:ob(l.size)})]})]}),o.jsx("a",{href:c(l.path),title:a("editor.downloadArtifact"),"aria-label":a("editor.downloadArtifact"),children:o.jsx(Bs,{size:14})})]},l.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(yn,{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:c(s.path),children:[o.jsx(Bs,{size:13}),a("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Wn,{size:24}),o.jsx("span",{children:a("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(hd,{size:26}),o.jsx("span",{children:a("editor.noArtifacts")})]})}function ib(t,e){if(!t)return null;const n=e.filter(c=>c.type==="file").map(c=>c.path),s=t.replaceAll("\\","/").replace(/^\.\//,"");if(n.includes(s))return s;const r=n.filter(c=>s.endsWith(`/${c}`));if(r.length===1)return r[0];const i=s.split("/").at(-1),a=n.filter(c=>c.split("/").at(-1)===i);return a.length===1?a[0]:null}function ob(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function ab(t){return t instanceof Error&&t.name==="AbortError"}function cb({projectId:t,activeFile:e,permission:n,revision:s,selection:r,save:i,onError:a,onAdded:c}){const[l,d]=h.useState([]),[f,u]=h.useState(null),[m,p]=h.useState(!1),[g,x]=h.useState(""),b=h.useRef(null),j=h.useRef(e),C=h.useRef(i),N=h.useRef(a),T=h.useRef(c);j.current=e,C.current=i,N.current=a,T.current=c;const _=async P=>{b.current?.abort();const R=new AbortController;b.current=R;try{const S=await A(`/api/projects/${t}/comments?path=${encodeURIComponent(P)}`,{signal:R.signal});j.current===P&&d(S.comments)}catch(S){!ab(S)&&j.current===P&&d([])}finally{b.current===R&&(b.current=null)}};return h.useEffect(()=>{u(null)},[t,e]),h.useEffect(()=>(e?_(e):d([]),()=>{b.current?.abort(),b.current=null}),[t,e,s]),{comments:l,focusComment:f,setFocusComment:u,commentOpen:m,setCommentOpen:p,commentText:g,setCommentText:x,addComment:async()=>{if(!(!g.trim()||!e))try{if(n!=="read"&&!await C.current())return;await A(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:e,content:g,...r})}),await _(e),p(!1),x(""),T.current()}catch(P){N.current(V(P))}},toggleComment:async P=>{try{await A(`/api/projects/${t}/comments/${P.id}`,{method:"PATCH",body:JSON.stringify({resolved:!P.resolved})}),await _(e)}catch(R){N.current(V(R))}},replyToComment:async(P,R)=>{try{return await A(`/api/projects/${t}/comments/${P.id}/replies`,{method:"POST",body:JSON.stringify({content:R})}),await _(e),!0}catch(S){return N.current(V(S)),!1}},editComment:async(P,R)=>{try{return await A(`/api/projects/${t}/comments/${P.id}`,{method:"PATCH",body:JSON.stringify({content:R})}),await _(e),!0}catch(S){return N.current(V(S)),!1}},deleteComment:async P=>{try{return await A(`/api/projects/${t}/comments/${P.id}`,{method:"DELETE"}),await _(e),u(R=>R?.id===P.id?null:R),!0}catch(R){return N.current(V(R)),!1}},editCommentReply:async(P,R,S)=>{try{return await A(`/api/projects/${t}/comments/${P.id}/replies/${R}`,{method:"PATCH",body:JSON.stringify({content:S})}),await _(e),!0}catch(F){return N.current(V(F)),!1}},deleteCommentReply:async(P,R)=>{try{return await A(`/api/projects/${t}/comments/${P.id}/replies/${R}`,{method:"DELETE"}),await _(e),!0}catch(S){return N.current(V(S)),!1}}}}function lb(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 db(t,e,n,s){const[r]=h.useState(()=>new Yx(t,e)),[i,a]=h.useState("connecting"),[c,l]=h.useState(!1),[d,f]=h.useState([]),[u,m]=h.useState(null),[p,g]=h.useState(null),[x,b]=h.useState(""),[j,C]=h.useState(""),[N,T]=h.useState(!1),_=h.useRef(n),L=h.useRef(s);return _.current=n,L.current=s,h.useEffect(()=>{const q=ol(r.meta.get("compileStates"));m(q[n]??null)},[n,r]),h.useEffect(()=>{const q=()=>f(r.sessions()),v=()=>{l(!1),f([]),m(null),g(null),b(""),C(""),L.current()},O=({status:S})=>{a(S),S!=="connected"&&v()},Z=S=>{l(S),S||v()},W=()=>{a("disconnected"),v()},P=()=>{const S=r.meta.get("filesEvent");lb(S)&&g(S);const F=r.meta.get("commentsRevision");typeof F=="string"&&b(F);const le=r.meta.get("dictionaryRevision");typeof le=="string"&&C(le);const Q=ol(r.meta.get("compileStates"));m(Q[_.current]??null)};r.awareness.on("change",q),r.provider.on("status",O),r.provider.on("sync",Z),r.provider.on("connection-close",W),r.provider.on("connection-error",W),r.meta.observe(P);const R=r.onDraftReady(()=>T(!0));return q(),P(),a(r.connected?"connected":"connecting"),l(r.synced),()=>{r.awareness.off("change",q),r.provider.off("status",O),r.provider.off("sync",Z),r.provider.off("connection-close",W),r.provider.off("connection-error",W),r.meta.unobserve(P),R(),r.destroy()}},[r]),{collaboration:r,status:i,synced:c,activeSessions:d,compileState:u,setCompileState:m,filesEvent:p,commentsRevision:x,dictionaryRevision:j,localDraftReady:N,reconnect:()=>{a("connecting"),l(!1),f([]),m(null),r.reconnect()}}}function Ls(t){return t instanceof Error&&t.name==="AbortError"}function ub({projectId:t,project:e,mainFile:n,collaborationSynced:s,sharedState:r,onSharedState:i,save:a,loadOutline:c,onPreviewTab:l,onError:d,onCompileStart:f,onCompileSuccess:u,onPdfChanged:m}){const{t:p}=Pe(),[g,x]=h.useState(""),[b,j]=h.useState(null),[C,N]=h.useState(""),[T,_]=h.useState(null),[L,E]=h.useState(null),[q,v]=h.useState([]),[O,Z]=h.useState(null),[W,P]=h.useState(!1),[R,S]=h.useState(()=>new Set),[F,le]=h.useState(""),Q=h.useRef(n),ge=h.useRef(null),oe=h.useRef(null),ae=h.useRef(new Map),he=h.useRef(null),Ce=h.useRef(()=>{}),B=h.useRef({onSharedState:i,save:a,loadOutline:c,onPreviewTab:l,onError:d,onCompileStart:f,onCompileSuccess:u,onPdfChanged:m});Q.current=n,B.current={onSharedState:i,save:a,loadOutline:c,onPreviewTab:l,onError:d,onCompileStart:f,onCompileSuccess:u,onPdfChanged:m};const D=H=>{he.current!==H&&(he.current=H,B.current.onCompileSuccess())},ye=async(H,X)=>{X||(oe.current?.abort(),oe.current=new AbortController,X=oe.current.signal);try{const z=H?`?mainFile=${encodeURIComponent(H)}`:"",ee=await A(`/api/projects/${t}/compile/artifacts${z}`,{signal:X});Q.current===H&&(v(ee.artifacts),Z(null))}catch(z){!Ls(z)&&Q.current===H&&(v([]),Z(null))}finally{oe.current?.signal===X&&(oe.current=null)}};h.useEffect(()=>{ge.current?.abort();const H=new AbortController;if(ge.current=H,N(""),_(null),E(null),x(""),j(null),v([]),Z(null),B.current.onPdfChanged(),!e||!n)return()=>H.abort();const X=`?mainFile=${encodeURIComponent(n)}`,z=A(`/api/projects/${t}/compile/artifacts${X}`,{signal:H.signal}).catch(ee=>{if(Ls(ee))throw ee;return{artifacts:[]}});return Promise.all([A(`/api/projects/${t}/compile/latest${X}`,{signal:H.signal}),z,B.current.loadOutline(H.signal,n)]).then(([ee,mt])=>{H.signal.aborted||ee.mainFile!==Q.current||(v(mt.artifacts),N(ee.latestRun?.log??""),_(ee.latestRun?.diagnostics??null),E(ee.latestRun?.status==="succeeded"||ee.latestRun?.status==="failed"?ee.latestRun.status:null),ee.latestRun?.requestedBy&&(ee.latestRun.status==="queued"||ee.latestRun.status==="running")&&B.current.onSharedState({mainFile:n,runId:ee.latestRun.id,status:ee.latestRun.status,requestedBy:ee.latestRun.requestedBy,updatedAt:new Date().toISOString()}),ee.pdfUrl&&(x(ee.pdfUrl),j(ee.pdfCompiledAt),B.current.onPreviewTab("pdf")))}).catch(ee=>{!Ls(ee)&&Q.current===n&&B.current.onError(V(ee))}).finally(()=>{ge.current===H&&(ge.current=null)}),()=>H.abort()},[e?.id,t,n]),h.useEffect(()=>{if(!r||r.mainFile!==n||r.status!=="succeeded"&&r.status!=="failed")return;let H=!1;ge.current?.abort();const X=new AbortController;return ge.current=X,A(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:X.signal}).then(z=>{H||z.mainFile!==Q.current||z.latestRun?.id!==r.runId||(N(z.latestRun.log),_(z.latestRun.diagnostics),E(r.status==="succeeded"?"succeeded":"failed"),r.status==="succeeded"&&z.pdfUrl?(B.current.onPdfChanged(),x(z.pdfUrl),j(z.pdfCompiledAt),B.current.onPreviewTab("pdf"),D(r.runId),ye(n)):r.status==="failed"&&B.current.onPreviewTab(z.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(z=>{!Ls(z)&&!H&&B.current.onError(V(z))}),()=>{H=!0,X.abort(),ge.current===X&&(ge.current=null)}},[r?.runId,r?.status,r?.mainFile,n,t]);const ke=async()=>{if(!e||!n||e.permission==="read"||!s||ae.current.has(n)||r?.mainFile===n&&(r.status==="queued"||r.status==="running"))return;const H=n;S(z=>new Set([...z,H])),B.current.onCompileStart(),le(""),N(""),_(null),E(null),B.current.onPreviewTab(g?"pdf":"log");const X=new AbortController;ae.current.set(H,X);try{if(!await B.current.save())return;const z=await A(`/api/projects/${t}/compile`,{method:"POST",signal:X.signal,body:JSON.stringify({mainFile:H})});if(z.mainFile!==Q.current)return;N(z.log),_(z.diagnostics),E(z.ok?"succeeded":"failed"),z.skipped&&le(p("editor.upToDate")),z.pdfUrl?(B.current.onPdfChanged(),x(z.pdfUrl),j(z.pdfCompiledAt),B.current.onPreviewTab("pdf"),z.ok&&(z.skipped?B.current.onCompileSuccess():D(z.runId))):B.current.onPreviewTab(z.diagnostics.errors.length?"errors":"log")}catch(z){!Ls(z)&&Q.current===H&&B.current.onError(V(z))}finally{ae.current.get(H)===X&&(ae.current.delete(H),S(z=>{const ee=new Set(z);return ee.delete(H),ee}))}};Ce.current=()=>{ke()},h.useEffect(()=>{if(!F)return;const H=window.setTimeout(()=>le(""),3e3);return()=>window.clearTimeout(H)},[F]),h.useEffect(()=>{const H=X=>{!(X.ctrlKey||X.metaKey)||X.key.toLocaleLowerCase()!=="s"||(X.preventDefault(),X.stopPropagation(),X.repeat||Ce.current())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[]),h.useEffect(()=>()=>{ge.current?.abort(),oe.current?.abort();for(const H of ae.current.values())H.abort();ae.current.clear()},[]);const Be=async H=>{if(H.viewable){P(!0);try{const X=await A(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(H.path)}`);Z(X)}catch(X){B.current.onError(V(X))}finally{P(!1)}}};return{pdfUrl:g,pdfCompiledAt:b,compileLog:C,compileDiagnostics:T,compileOutcome:L,artifacts:q,artifactPreview:O,artifactLoading:W,editorNotice:F,localCompiling:R.has(n),compile:ke,viewArtifact:Be}}const ll=10*1024*1024,hb=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 dl(t){return t instanceof Error&&t.name==="AbortError"}function Fs(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function zn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function fb(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!hb.has(e)}function Lo(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function ul(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":fb(t)?"text":"unsupported"}function pb(t,e){return`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`}function mb({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:a,onActiveFile:c,onActiveMainFile:l,onRootDocuments:d}){const{t:f}=Pe(),[u,m]=h.useState([]),[p,g]=h.useState(!1),[x,b]=h.useState(""),[j,C]=h.useState(null),[N,T]=h.useState(!1),[_,L]=h.useState(!1),[E,q]=h.useState(""),[v,O]=h.useState(""),[Z,W]=h.useState(""),[P,R]=h.useState(new Set),[S,F]=h.useState(null),[le,Q]=h.useState(""),[ge,oe]=h.useState(null),[ae,he]=h.useState(!1),[Ce,B]=h.useState(null),[D,ye]=h.useState(!1),ke=h.useRef(null),Be=h.useRef(null),H=async(U={})=>{ke.current?.abort(),ke.current=null;const re=U.signal?null:new AbortController;re&&(ke.current=re);try{const xe=await A(`/api/projects/${t}/files`,{signal:U.signal??re?.signal});return(!U.isCurrent||U.isCurrent())&&m(xe.files),xe.files}catch(xe){if(!dl(xe))throw xe;return}finally{re&&ke.current===re&&(ke.current=null)}},X=async()=>{if(!(!x.trim()||x.trim().endsWith("/"))){O("");try{await A(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:x,content:""})}),await H(),c(x),R(U=>new Set([...U,...Fs(x)])),g(!1),b("")}catch(U){O(V(U))}}},z=async()=>{if(!E.trim())return;O("");const U=Z?`${Z}/${E.trim()}`:E.trim();try{const re=await A(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:U})});await H(),R(xe=>new Set([...xe,...Fs(re.path),re.path])),W(re.path),L(!1),q("")}catch(re){O(V(re))}},ee=async(U,re=new Set,xe=Z)=>{if(!U.length)return;const et=e.maxUploadSizeMB??50;if(U.find(ie=>ie.size>et*1024*1024))return i(f("errors.fileTooLarge",{size:et}));const Oe=xe,He=U.map(ie=>Oe?`${Oe}/${ie.name}`:ie.name),ot=new Map;for(const ie of He)ot.set(ie,(ot.get(ie)??0)+1);const vt=[...ot.entries()].filter(([,ie])=>ie>1).map(([ie])=>ie);if(vt.length)return i(f("errors.duplicateUploadNames",{files:vt.join(", ")}));const St=new Set(u.map(ie=>ie.path)),tt=[...new Set(He.filter(ie=>St.has(ie)&&!re.has(ie)))];if(tt.length){B({files:U,directory:Oe,collisions:tt});return}B(null),ye(!0);try{const ie=new URLSearchParams;Oe&&ie.set("directory",Oe);let jt="";for(const[dt,Re]of U.entries()){const Ct=He[dt];ie.delete("overwrite"),re.has(Ct)&&ie.set("overwrite","1");const nt=ie.toString()?`?${ie.toString()}`:"",hn=new FormData;hn.append("file",Re);const ne=await fetch(`/api/projects/${t}/upload${nt}`,{method:"POST",body:hn}),Ue=await ne.json().catch(()=>({}));if(!ne.ok){if(ne.status===409&&!re.has(Ct)&&Ue.code==="FILE_EXISTS"){dt>0&&await H(),B({files:U.slice(dt),directory:Oe,collisions:[typeof Ue.path=="string"?Ue.path:Ct]});return}throw new Error(ne.status===409?f("errors.pathConflict"):Fo(Ue,ne.status,"errors.upload"))}typeof Ue.path=="string"&&Lo(Ue.path)&&(jt=Ue.path)}await H(),jt&&c(jt)}catch(ie){i(V(ie))}finally{ye(!1)}},mt=async U=>{await ee(Array.from(U.target.files??[])),U.target.value=""},Xt=async U=>{Be.current?.abort(),Be.current=null,T(!1);const re=pb(t,U.path);if((U.size??0)>ll){C({path:U.path,kind:"large",size:U.size??0,url:re});return}const xe=ul(U.path);if(xe!=="text"){C({path:U.path,kind:xe,size:U.size??0,url:re});return}C({path:U.path,kind:xe,size:U.size??0,url:re,content:""}),T(!0);const et=new AbortController;Be.current=et;try{const ce=await fetch(re,{signal:et.signal}),Oe=await ce.text();if(!ce.ok)throw new Error(Oe||f("errors.request",{status:ce.status}));C(He=>He?.path===U.path?{...He,content:Oe}:He)}catch(ce){dl(ce)||(C(null),i(V(ce)))}finally{Be.current===et&&(Be.current=null,T(!1))}},un=U=>{const re=ul(U.path);(U.size??0)>ll||re!=="text"||!Lo(U.path)?Xt(U):c(U.path)},At=async()=>{if(S){O("");try{if(!await r())return;const U=await A(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:S.path,destinationDirectory:le})}),re=ce=>ce===S.path?U.path:ce.startsWith(`${S.path}/`)?`${U.path}${ce.slice(S.path.length)}`:ce;c(ce=>re(ce)),l(ce=>re(ce)),d(ce=>new Set([...ce].map(re))),W(ce=>ce&&re(ce));const[xe,et]=await Promise.all([A(`/api/projects/${t}/files`),A(`/api/projects/${t}`)]);m(xe.files),a(et.project),R(ce=>new Set([...ce,...Fs(U.path),le].filter(Boolean))),F(null),Q("")}catch(U){O(V(U))}}},Zt=async()=>{if(ge){O("");try{if(s&&!await r())return;await A(`/api/projects/${t}/file?path=${encodeURIComponent(ge.path)}`,{method:"DELETE"}),oe(null)}catch(U){O(V(U))}}};h.useEffect(()=>()=>{ke.current?.abort(),Be.current?.abort()},[]),h.useEffect(()=>{Be.current?.abort(),Be.current=null,T(!1)},[n]);const Ft=u.filter(U=>U.type==="directory"),It=u.filter(U=>Fs(U.path).every(re=>P.has(re)));return{files:u,setFiles:m,loadFiles:H,newFileOpen:p,setNewFileOpen:g,newFilePath:x,setNewFilePath:b,resourcePreview:j,setResourcePreview:C,resourcePreviewLoading:N,setResourcePreviewLoading:T,newFolderOpen:_,setNewFolderOpen:L,newFolderName:E,setNewFolderName:q,fileDialogError:v,setFileDialogError:O,selectedFolder:Z,setSelectedFolder:W,expandedFolders:P,setExpandedFolders:R,moveEntry:S,setMoveEntry:F,moveDestination:le,setMoveDestination:Q,deleteEntry:ge,setDeleteEntry:oe,fileDragActive:ae,setFileDragActive:he,uploadConflict:Ce,setUploadConflict:B,uploadingFiles:D,directoryEntries:Ft,visibleEntries:It,createFile:X,createFolder:z,uploadFiles:ee,upload:mt,openFile:un,movePath:At,removePath:Zt}}function gb({active:t,activeFile:e,content:n,dictionaryWords:s}){const[r,i]=h.useState([]),[a,c]=h.useState(""),[l,d]=h.useState(""),[f,u]=h.useState(0),[m,p]=h.useState(null),g=h.useRef(0),x=h.useRef(n),b=h.useRef(e),j=h.useRef(0);x.current=n,b.current=e,h.useEffect(()=>{i([]),c(""),d(""),p(null)},[e,s]),h.useEffect(()=>{u(_=>r.length?Math.min(_,r.length-1):0)},[r]),h.useEffect(()=>{const _=++g.current;if(!t||!e){i([]),c(""),d(""),p(null);return}const L=n,E=e,q=window.setTimeout(()=>{Jt(async()=>{const{checkSpelling:v}=await import("./spellCheck-ClNG2x_t.js");return{checkSpelling:v}},__vite__mapDeps([2,1])).then(({checkSpelling:v})=>{if(_!==g.current||x.current!==L||b.current!==E)return;const O=v(L,s);_!==g.current||x.current!==L||b.current!==E||(i(O),c(L),d(E),u(0),p(null))}).catch(()=>{})},700);return()=>window.clearTimeout(q)},[t,e,n,s]);const C=l===e&&a===n,N=h.useMemo(()=>C?{total:r.length,unique:new Set(r.map(_=>_.word.toLocaleLowerCase("en-US"))).size}:null,[C,r]);return{issues:C?r:[],jump:C?m:null,index:f,summary:N,jumpToIssue:_=>{if(!r.length)return;const L=Math.max(0,Math.min(_,r.length-1)),E=r[L];u(L),p({from:E.from,to:E.to,nonce:++j.current})}}}function hl(t){return t instanceof Error&&t.name==="AbortError"}function yb({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[a,c]=h.useState(null),[l,d]=h.useState(null),[f,u]=h.useState(null),m=h.useRef(null),p=h.useRef(0),g=h.useRef(n),x=h.useRef(s),b=h.useRef(r),j=h.useRef(i);g.current=n,x.current=s,b.current=r,j.current=i,h.useEffect(()=>(m.current?.abort(),m.current=null,c(null),d(null),u(null),()=>m.current?.abort()),[t,e]);const C=(L,E,q)=>{u({path:L,line:E,column:q,nonce:++p.current}),g.current!==L&&x.current(L)},N=async(L,E,q,v={})=>{m.current?.abort();const O=new AbortController;m.current=O;try{const Z=await A(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(L)}&line=${E}&column=${q}`,{signal:O.signal});if(m.current!==O)return;c({...Z,nonce:++p.current}),j.current()}catch(Z){!hl(Z)&&!v.silent&&b.current(V(Z))}finally{m.current===O&&(m.current=null)}},T=async(L,E,q)=>{m.current?.abort();const v=new AbortController;m.current=v;try{const O=await A(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${L}&x=${E}&y=${q}`,{signal:v.signal});if(m.current!==v)return;C(O.path,O.line,O.column)}catch(O){hl(O)||b.current(V(O))}finally{m.current===v&&(m.current=null)}};return{pdfTarget:a,pdfViewport:l,sourceJump:f,setPdfViewport:d,clearPdfViewport:()=>d(null),jumpToSource:C,syncSourceToPdf:N,syncPdfToSource:T,syncVisiblePdfToSource:()=>{l&&T(l.page,l.x,l.y)}}}function Ju(t,e){return`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function fl(t,e){try{const n=window.localStorage.getItem(Ju(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function wb(t,e){const[n,s]=h.useState(()=>fl(t,e));return h.useEffect(()=>{s(fl(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Ju(t,e),i)}catch{}}}}const Yu=()=>Jt(()=>import("./PdfPreview-YbXIaedo.js"),__vite__mapDeps([3,1,4,5])),xb=h.lazy(()=>Yu().then(t=>({default:t.PdfPreview}))),bb=h.lazy(()=>Jt(()=>import("./LatexEditor-ytqaJMkb.js"),__vite__mapDeps([6,1,7])).then(t=>({default:t.LatexEditor}))),vb=h.lazy(()=>Jt(()=>import("./GitDialog-Cf5wW5Wn.js"),__vite__mapDeps([8,1,5])).then(t=>({default:t.GitDialog}))),Sb=h.lazy(()=>Jt(()=>import("./HistoryDialog-CXb-MzXH.js"),__vite__mapDeps([9,1,0])).then(t=>({default:t.HistoryDialog}))),jb=h.lazy(()=>Jt(()=>import("./ProjectNavigationDialogs-BMz-OL3a.js"),__vite__mapDeps([10,1])).then(t=>({default:t.ProjectSearchDialog}))),Cb=h.lazy(()=>Jt(()=>import("./ProjectNavigationDialogs-BMz-OL3a.js"),__vite__mapDeps([10,1])).then(t=>({default:t.QuickOpenDialog}))),kb=h.lazy(()=>Jt(()=>import("./SystemMetricsDialog-BLfDSaDc.js"),__vite__mapDeps([11,1])).then(t=>({default:t.SystemMetricsDialog}))),Xe=8;function qn(t){return t instanceof Error&&t.name==="AbortError"}function Eb(){const{t}=Pe(),[e,n]=h.useState({siteName:"TexLite",adminEmail:""}),[s,r]=h.useState(),[i,a]=h.useState(()=>typeof window>"u"?null:Tr(window.location.pathname)),[c,l]=h.useState(null);h.useEffect(()=>{const m=Tr(window.location.pathname);if(m&&window.location.pathname!==Hi(m)){const x={texliteRoute:"project",projectId:m,fromDashboard:!1};window.history.replaceState(x,"",Hi(m))}const p=()=>a(Tr(window.location.pathname)),g=()=>{if(l(null),r(null),Tr(window.location.pathname)){const x={texliteRoute:"dashboard"};window.history.replaceState(x,"","/"),a(null)}};return window.addEventListener("popstate",p),window.addEventListener("texlite:session-expired",g),()=>{window.removeEventListener("popstate",p),window.removeEventListener("texlite:session-expired",g)}},[]);const d=m=>{const p=Hi(m);if(window.location.pathname!==p){const g={texliteRoute:"project",projectId:m,fromDashboard:!0};window.history.pushState(g,"",p)}a(m)},f=()=>{const m=window.history.state;if(Wm(m)&&m.fromDashboard){window.history.back();return}const p={texliteRoute:"dashboard"};window.history.replaceState(p,"","/"),a(null)};if(h.useEffect(()=>{A("/api/config").then(m=>{n(m),document.title=m.siteName}),A("/api/me").then(({user:m})=>r(m)).catch(m=>{m instanceof Ao&&m.status,r(null)})},[]),s===void 0)return o.jsx("div",{className:"center-card",children:t("common.loading")});if(!s)return o.jsx(Nb,{site:e,onLogin:r});if(s.mustChangePassword)return o.jsx(Db,{site:e,user:s,onChanged:m=>r(m)});if(i)return o.jsx(Pb,{site:e,user:s,projectId:i,onBack:f},i);const u=c?.userId===s.id?c:null;return o.jsx(Tb,{site:e,user:s,initialData:u?{projects:u.projects,tags:u.tags,pagination:u.pagination}:null,onDataChange:(m,p,g)=>l({userId:s.id,projects:m,tags:p,pagination:g}),onUser:m=>{(!m||m.id!==s.id)&&l(null),r(m),m||f()},onOpenProject:d})}function bi({siteName:t,compact:e=!1,auth:n=!1}){return o.jsx("span",{className:`site-logo${e?" compact":""}${n?" auth-logo":""}`,children:o.jsx("img",{src:"/logo.svg",alt:t})})}function Ta(){const{t}=Pe();return o.jsxs("footer",{className:"site-footer",children:[o.jsxs("span",{children:[t("footer.copyright",{year:new Date().getFullYear()})," ",o.jsxs("a",{href:"https://github.com/SWUFE-DB-Group/TexLite",target:"_blank",rel:"noreferrer",children:["TexLite v",Fh]})]}),o.jsx("span",{children:t("footer.credit")})]})}function Db({site:t,user:e,onChanged:n}){const{t:s}=Pe(),[r,i]=h.useState(""),[a,c]=h.useState(""),[l,d]=h.useState(""),[f,u]=h.useState(""),m=async p=>{if(p.preventDefault(),a!==l)return u(s("auth.mismatch"));if(a.length<Xe)return u(s("auth.passwordMinimum",{count:Xe}));try{await A("/api/me/password",{method:"PUT",body:JSON.stringify({currentPassword:r,newPassword:a})}),n({...e,mustChangePassword:!1})}catch(g){u(V(g))}};return o.jsxs("main",{className:"login-page",children:[o.jsx(Wo,{}),o.jsxs("form",{className:"login-card",onSubmit:m,children:[o.jsx(bi,{siteName:t.siteName,auth:!0}),o.jsx("h1",{className:"sr-only",children:t.siteName}),o.jsx("p",{className:"muted",children:s("auth.firstLogin")}),o.jsxs("label",{children:[s("auth.currentPassword"),o.jsx("input",{type:"password",value:r,onChange:p=>i(p.target.value)})]}),o.jsxs("label",{children:[s("auth.newPassword"),o.jsx("input",{type:"password",minLength:Xe,autoComplete:"new-password",value:a,onChange:p=>c(p.target.value)}),o.jsx("small",{className:"field-hint",children:s("auth.passwordMinimum",{count:Xe})})]}),o.jsxs("label",{children:[s("auth.confirmPassword"),o.jsx("input",{type:"password",minLength:Xe,autoComplete:"new-password",value:l,onChange:p=>d(p.target.value)})]}),f&&o.jsx("p",{className:"error",children:f}),o.jsx("button",{className:"primary",children:s("auth.updatePassword")})]}),o.jsx(Ta,{})]})}function Nb({site:t,onLogin:e}){const{t:n}=Pe(),[s,r]=h.useState(""),[i,a]=h.useState(""),[c,l]=h.useState(""),d=async f=>{f.preventDefault(),l("");try{const u=await A("/api/auth/login",{method:"POST",body:JSON.stringify({username:s,password:i})});e(u.user)}catch(u){l(V(u))}};return o.jsxs("main",{className:"login-page",children:[o.jsx(Wo,{}),o.jsxs("form",{className:"login-card",onSubmit:d,children:[o.jsx(bi,{siteName:t.siteName,auth:!0}),o.jsx("h1",{className:"sr-only",children:t.siteName}),o.jsx("p",{className:"muted",children:n("auth.tagline")}),o.jsxs("label",{children:[n("auth.username"),o.jsx("input",{autoFocus:!0,value:s,onChange:f=>r(f.target.value)})]}),o.jsxs("label",{children:[n("auth.password"),o.jsx("input",{type:"password",value:i,onChange:f=>a(f.target.value)})]}),c&&o.jsx("p",{className:"error",children:c}),o.jsx("button",{className:"primary",type:"submit",children:n("auth.login")}),t.adminEmail&&o.jsx("small",{className:"support",children:n("auth.contact",{email:t.adminEmail})})]}),o.jsx(Ta,{})]})}function Tb({site:t,user:e,initialData:n,onDataChange:s,onUser:r,onOpenProject:i}){const{t:a}=Pe(),[c,l]=h.useState(()=>n?.projects??[]),[d,f]=h.useState(()=>n?.tags??[]),[u,m]=h.useState(()=>n?.pagination??{page:1,pageSize:20,total:n?.projects.length??0,totalPages:n?.projects.length?1:0}),[p,g]=h.useState(!!n),[x,b]=h.useState(!1),[j,C]=h.useState(!1),[N,T]=h.useState(""),[_,L]=h.useState(!1),[E,q]=h.useState(""),[v,O]=h.useState(!1),[Z,W]=h.useState(""),[P,R]=h.useState(null),[S,F]=h.useState(""),le=h.useRef(null),[Q,ge]=h.useState(!1),[oe,ae]=h.useState(""),[he,Ce]=h.useState(""),[B,D]=h.useState(!1),[ye,ke]=h.useState(""),[Be,H]=h.useState("blue"),[X,z]=h.useState(null),[ee,mt]=h.useState(null),[Xt,un]=h.useState(""),[At,Zt]=h.useState(null),[Ft,It]=h.useState(""),[U,re]=h.useState(!1),[xe,et]=h.useState(null),[ce,Oe]=h.useState(null),[He,ot]=h.useState([]),[vt,St]=h.useState(""),[tt,ie]=h.useState(!1),[jt,dt]=h.useState(""),[Re,Ct]=h.useState(()=>localStorage.getItem("texlite-project-view")==="list"?"list":"grid"),[nt,hn]=h.useState(()=>localStorage.getItem("texlite-project-sort")==="created"?"created":"updated"),[ne,Ue]=h.useState(!1),[Mt,$t]=h.useState(""),[Ee,Je]=h.useState(1),[xs,vi]=h.useState(""),ze=h.useRef(0),kt=h.useRef(null),qe=(w,te,se,Se,Ve)=>`${w?"archived":"active"}|${te}|${se}|${Se}|${Ve}`,bs=qe(ne,Ee,oe,he,nt),st=(w,te,se,Se,Ve)=>{const Le=new URLSearchParams({page:String(te),pageSize:"20",sort:Ve});w&&Le.set("archived","1"),se.trim()&&Le.set("search",se.trim()),Se&&Le.set("tag",Se);const at=qe(w,te,se,Se,Ve),pn=++ze.current;kt.current?.abort();const On=new AbortController;return kt.current=On,Promise.all([A(`/api/projects?${Le.toString()}`,{signal:On.signal}),A("/api/tags",{signal:On.signal})]).then(([Qt,Ts])=>{pn===ze.current&&(l(Qt.projects),f(Ts.tags),m(Qt.pagination),Je(Qt.pagination.page),g(!0),vi(at))}).catch(Qt=>{!qn(Qt)&&pn===ze.current&&T(V(Qt))}).finally(()=>{kt.current===On&&(kt.current=null)})};h.useEffect(()=>(st(ne,Ee,oe,he,nt),()=>kt.current?.abort()),[ne,Ee,oe,he,nt]),h.useEffect(()=>{p&&!ne&&xs===bs&&s(c,d,u)},[c,d,u,p,xs,bs,ne]);const vs=w=>{Ct(w),localStorage.setItem("texlite-project-view",w)},ve=w=>{hn(w),Je(1),localStorage.setItem("texlite-project-sort",w)},ur=w=>{Ue(w),Je(1)},Ss=w=>{Ce(w),Je(1)},js=async()=>{if(E.trim())try{const{project:w}=await A("/api/projects",{method:"POST",body:JSON.stringify({name:E})});L(!1),q("");const te=ne||Ee!==1?c:[w,...c].slice(0,u.pageSize),se=ne?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(te),m(se),ne||s(te,d,se),i(w.id)}catch(w){T(V(w))}},Si=async()=>{if(!P)return;const w=t.maxUploadSizeMB??50;if(P.size>w*1024*1024)return F(a("errors.fileTooLarge",{size:w}));ge(!0),F("");const te=new FormData;te.append("file",P);try{const se=await fetch(`/api/projects/import?name=${encodeURIComponent(Z.trim())}`,{method:"POST",body:te}),Se=await se.json();if(!se.ok)throw new Error(Fo(Se,se.status,"errors.upload"));const Ve=Se.project,Le=ne||Ee!==1?c:[Ve,...c].slice(0,u.pageSize),at=ne?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(Le),m(at),ne||s(Le,d,at),O(!1),R(null),W(""),i(Ve.id)}catch(se){F(V(se))}finally{ge(!1)}},Cs=w=>{if(w&&!w.name.toLocaleLowerCase().endsWith(".zip")){F(a("errors.zipOnly"));return}F(""),R(w),w&&!Z&&W(w.name.replace(/\.zip$/i,""))},ji=async()=>{await A("/api/auth/logout",{method:"POST"}),r(null)},hr=async()=>{if(ye.trim())try{const w=await A("/api/tags",{method:"POST",body:JSON.stringify({name:ye,color:Be})});f(te=>[...te,w.tag].sort((se,Se)=>se.name.localeCompare(Se.name))),D(!1),ke(""),H("blue")}catch(w){T(V(w))}},Ci=async w=>{if(!X)return;const te=X.tags.some(se=>se.id===w.id);try{const Se=(await A(te?`/api/projects/${X.id}/tags/${w.id}`:`/api/projects/${X.id}/tags`,te?{method:"DELETE"}:{method:"POST",body:JSON.stringify({tagId:w.id})})).project;z(Se),l(Ve=>Ve.map(Le=>Le.id===Se.id?Se:Le))}catch(se){T(V(se))}},ks=async()=>{if(!(!ee||!Xt.trim()))try{const w=await A(`/api/projects/${ee.id}`,{method:"PATCH",body:JSON.stringify({name:Xt})});l(te=>te.map(se=>se.id===w.project.id?w.project:se)),mt(null),un("")}catch(w){T(V(w))}},fn=async()=>{if(!(!At||!Ft.trim())){re(!0),T("");try{await A(`/api/projects/${At.id}/duplicate`,{method:"POST",body:JSON.stringify({name:Ft})}),Zt(null),It(""),st(ne,Ee,oe,he,nt)}catch(w){T(V(w))}finally{re(!1)}}},Es=async()=>{if(xe)try{await A(`/api/projects/${xe.id}`,{method:"DELETE"}),l(Ve=>Ve.filter(Le=>Le.id!==xe.id));const w=Math.max(0,u.total-1),te=Math.ceil(w/u.pageSize),se=te===0?1:Math.min(Ee,te),Se={...u,page:se,total:w,totalPages:te};m(Se),et(null),se!==Ee?Je(se):st(ne,Ee,oe,he,nt)}catch(w){T(V(w))}},fr=async w=>{Oe(w),St(""),ot([]),dt(""),ie(!0);try{const te=await A("/api/users");ot(te.users.filter(se=>se.id!==w.ownerId))}catch(te){dt(V(te))}finally{ie(!1)}},Ut=async()=>{if(!(!ce||!vt)){ie(!0),dt("");try{await A(`/api/projects/${ce.id}/owner`,{method:"PUT",body:JSON.stringify({userId:vt})}),Oe(null),St(""),st(ne,Ee,oe,he,nt)}catch(w){dt(V(w))}finally{ie(!1)}}},Ds=async w=>{const te=!ne;$t(w.id),T("");try{await A(`/api/projects/${w.id}/archive`,{method:te?"PUT":"DELETE"});const se=c.filter(pn=>pn.id!==w.id);l(se);const Se=Math.max(0,u.total-1),Ve=Math.ceil(Se/u.pageSize),Le=Ve===0?1:Math.min(Ee,Ve),at={...u,page:Le,total:Se,totalPages:Ve};m(at),ne||s(se,d,at),Le!==Ee?Je(Le):st(ne,Ee,oe,he,nt)}catch(se){T(V(se))}finally{$t("")}},Nn=c,Ns=["red","orange","yellow","green","blue","purple","gray"],Tn=w=>new Date(w).toLocaleString(we.resolvedLanguage);return o.jsxs("div",{className:"page",children:[o.jsxs("header",{className:"topbar",children:[o.jsx("span",{className:"site-title",children:t.siteName}),o.jsx(bi,{siteName:t.siteName}),o.jsxs("div",{className:"top-actions",children:[e.role==="admin"&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{className:"ghost",onClick:()=>C(!0),children:[o.jsx(am,{"aria-hidden":!0,size:14}),a("metrics.title")]}),o.jsxs("button",{className:"ghost",onClick:()=>b(!x),children:[x?o.jsx(od,{"aria-hidden":!0,size:14}):o.jsx(qs,{"aria-hidden":!0,size:14}),a(x?"users.back":"users.manage")]})]}),o.jsx(Wo,{compact:!0}),o.jsxs("span",{className:"top-user-identity",children:[o.jsx("strong",{children:e.displayName}),o.jsxs("small",{children:["@",e.username]})]}),o.jsx("button",{className:"ghost",onClick:ji,children:a("auth.logout")})]})]}),x?o.jsx(_b,{currentUser:e}):o.jsxs("main",{className:"dashboard",children:[o.jsxs("div",{className:"section-title",children:[o.jsxs("div",{children:[o.jsxs("h1",{children:[o.jsx(Vr,{"aria-hidden":!0,size:25}),a("projects.title")]}),o.jsx("p",{className:"muted",children:e.canCreateProjects?a("projects.subtitle"):a("projects.restricted")})]}),o.jsxs("div",{className:"section-actions",children:[o.jsxs("button",{onClick:()=>D(!0),children:[o.jsx(jc,{"aria-hidden":!0,size:15}),a("tags.create")]}),e.canCreateProjects&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>{F(""),O(!0)},children:[o.jsx(Hr,{"aria-hidden":!0,size:15}),a("projects.upload")]}),o.jsxs("button",{className:"primary",onClick:()=>L(!0),children:[o.jsx(dd,{"aria-hidden":!0,size:15}),a("projects.new")]})]})]})]}),N&&o.jsx("p",{className:"error",children:N}),o.jsxs("div",{className:"project-toolbar",children:[o.jsx("input",{type:"search",placeholder:a("projects.search"),value:oe,onChange:w=>{ae(w.target.value),Je(1)}}),o.jsxs("div",{className:"project-scope",role:"tablist","aria-label":a("projects.scope"),children:[o.jsxs("button",{className:ne?"":"active",onClick:()=>ur(!1),role:"tab","aria-selected":!ne,children:[o.jsx(Vr,{size:14}),a("projects.active")]}),o.jsxs("button",{className:ne?"active":"",onClick:()=>ur(!0),role:"tab","aria-selected":ne,children:[o.jsx(xc,{size:14}),a("projects.archived")]})]}),o.jsxs("div",{className:"tag-filters",children:[o.jsx("button",{className:he?"":"active",onClick:()=>Ss(""),children:a("projects.allTags")}),d.map(w=>o.jsxs("button",{className:he===w.id?"active":"",onClick:()=>Ss(he===w.id?"":w.id),children:[o.jsx(io,{color:w.color}),w.name]},w.id))]}),o.jsxs("label",{className:"project-sort",children:[o.jsx(lm,{size:14}),o.jsx("span",{children:a("projects.sortBy")}),o.jsxs("select",{value:nt,onChange:w=>ve(w.target.value),children:[o.jsx("option",{value:"updated",children:a("projects.sortModified")}),o.jsx("option",{value:"created",children:a("projects.sortCreated")})]})]}),o.jsxs("div",{className:"view-toggle",children:[o.jsx("button",{className:Re==="grid"?"active":"",onClick:()=>vs("grid"),title:a("projects.grid"),children:"▦"}),o.jsx("button",{className:Re==="list"?"active":"",onClick:()=>vs("list"),title:a("projects.list"),children:"☷"})]})]}),o.jsxs("div",{className:`project-grid ${Re==="list"?"list-view":""}`,children:[Nn.map(w=>o.jsxs("article",{className:`project-card${w.ownerId===e.id?" owned-project":""}`,children:[Re==="grid"&&w.ownerId===e.id&&o.jsxs("button",{className:"project-transfer-action",title:a("projects.transferOwnership"),onClick:()=>{fr(w)},children:[o.jsx(zi,{"aria-hidden":!0,size:13}),a("projects.transfer")]}),o.jsxs("button",{className:"project-card-open",onClick:()=>i(w.id),children:[o.jsx("span",{className:"owner-badge",title:w.ownerDisplayName??w.ownerUsername,children:w.ownerDisplayName??w.ownerUsername}),o.jsxs("span",{className:"project-card-main",children:[o.jsx("strong",{children:w.name}),o.jsx("span",{className:"project-tags",children:w.tags?.map(te=>o.jsx("span",{className:`tag tag-${te.color}`,children:te.name},te.id))})]}),o.jsxs("dl",{className:"project-meta",children:[o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(dm,{"aria-hidden":!0,size:13}),a("projects.created")]}),o.jsx("dd",{children:o.jsx("time",{dateTime:w.createdAt,children:Tn(w.createdAt)})})]}),o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(ud,{"aria-hidden":!0,size:13}),a("projects.modified")]}),o.jsxs("dd",{title:a("projects.modifiedByUser",{time:Tn(w.updatedAt),user:w.lastModifiedDisplayName??w.lastModifiedUsername??a("projects.deletedUser")}),children:[o.jsx("time",{dateTime:w.updatedAt,children:Tn(w.updatedAt)}),o.jsxs("span",{className:"project-modified-by",children:[" · ",a("projects.byUser",{user:w.lastModifiedDisplayName??w.lastModifiedUsername??a("projects.deletedUser")})]})]})]})]})]}),o.jsxs("div",{className:"project-card-actions",children:[o.jsxs("button",{onClick:()=>z(w),children:[o.jsx(jc,{"aria-hidden":!0,size:14}),a("tags.assign")]}),w.permission==="owner"&&o.jsxs("button",{onClick:()=>{mt(w),un(w.name)},children:[o.jsx(xo,{"aria-hidden":!0,size:14}),a("projects.rename")]}),(e.role==="admin"||e.canCreateProjects)&&o.jsxs("button",{onClick:()=>{Zt(w),It(`${w.name} (1)`)},children:[o.jsx(mm,{"aria-hidden":!0,size:14}),a("projects.duplicate")]}),o.jsxs("a",{href:`/api/projects/${w.id}/download`,download:!0,children:[o.jsx(Bs,{"aria-hidden":!0,size:14}),a("projects.download")]}),o.jsxs("button",{disabled:Mt===w.id,onClick:()=>{Ds(w)},children:[ne?o.jsx(cm,{"aria-hidden":!0,size:14}):o.jsx(xc,{"aria-hidden":!0,size:14}),a(ne?"projects.unarchive":"projects.archive")]}),Re==="list"&&w.ownerId===e.id&&o.jsxs("button",{onClick:()=>{fr(w)},children:[o.jsx(zi,{"aria-hidden":!0,size:14}),a("projects.transfer")]}),w.permission==="owner"&&o.jsxs("button",{className:"danger-text",onClick:()=>et(w),children:[o.jsx(ss,{"aria-hidden":!0,size:14}),a("common.delete")]})]})]},w.id)),Nn.length===0&&(c.length===0?ne?o.jsx("div",{className:"empty",children:a("projects.noArchived")}):o.jsxs("div",{className:"project-empty",children:[o.jsx("span",{className:"project-empty-icon",children:o.jsx(Rm,{size:28})}),o.jsx("h2",{children:a("projects.emptyTitle")}),o.jsx("p",{children:e.canCreateProjects?a("projects.emptyDescription"):a("projects.emptyRestricted")})]}):o.jsx("div",{className:"empty",children:a("projects.noMatches")}))]}),u.totalPages>1&&o.jsxs("nav",{className:"project-pagination","aria-label":a("projects.pagination"),children:[o.jsxs("button",{disabled:u.page<=1,onClick:()=>Je(w=>Math.max(1,w-1)),title:a("projects.previousPage"),children:[o.jsx(ld,{size:15}),a("projects.previousPage")]}),o.jsx("span",{children:a("projects.pageOf",{page:u.page,totalPages:u.totalPages,count:u.total})}),o.jsxs("button",{disabled:u.page>=u.totalPages,onClick:()=>Je(w=>Math.min(u.totalPages,w+1)),title:a("projects.nextPage"),children:[o.jsx(Ko,{size:15}),a("projects.nextPage")]})]}),o.jsx(Ie,{open:_,title:a("projects.new"),description:a("projects.newDescription"),onOpenChange:L,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>L(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{js()},children:a("common.create")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:E,onChange:w=>q(w.target.value),onKeyDown:w=>{w.key==="Enter"&&js()}})]})}),o.jsx(Ie,{open:v,title:a("projects.upload"),description:a("projects.uploadDescription",{size:t.maxUploadSizeMB??50}),onOpenChange:w=>{O(w),w||F("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>{O(!1),F("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:!P||Q,onClick:()=>{Si()},children:a(Q?"projects.importing":"projects.import")})]}),children:o.jsxs("div",{className:"form-stack",children:[S&&o.jsx("p",{className:"error import-error",children:S}),o.jsxs("div",{className:`upload-picker${P?" has-file":""}`,onDragOver:w=>{w.preventDefault(),w.dataTransfer.dropEffect="copy"},onDrop:w=>{w.preventDefault(),Cs(w.dataTransfer.files[0]??null)},children:[o.jsx("input",{ref:le,className:"sr-only",type:"file",accept:".zip,application/zip",onChange:w=>Cs(w.target.files?.[0]??null)}),o.jsx(wo,{size:34}),o.jsxs("div",{className:"upload-picker-copy",children:[o.jsx("strong",{children:P?.name??a("projects.chooseZip")}),o.jsx("span",{children:P?a("projects.selectedFileSize",{size:Xu(P.size)}):a("projects.dropZip")})]}),o.jsxs("button",{type:"button",onClick:()=>le.current?.click(),children:[o.jsx(Hr,{size:15}),a("projects.browse")]}),P&&o.jsx("button",{className:"upload-clear",type:"button",title:a("projects.clearFile"),"aria-label":a("projects.clearFile"),onClick:()=>{Cs(null),le.current&&(le.current.value="")},children:o.jsx(Jo,{size:14})})]}),o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{value:Z,onChange:w=>W(w.target.value)})]})]})}),o.jsx(Ie,{open:B,title:a("tags.create"),description:a("tags.createDescription"),onOpenChange:D,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>D(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{hr()},children:a("common.create")})]}),children:o.jsxs("div",{className:"form-stack",children:[o.jsxs("label",{className:"form-field",children:[a("tags.name"),o.jsx("input",{autoFocus:!0,value:ye,onChange:w=>ke(w.target.value)})]}),o.jsxs("fieldset",{className:"color-picker",children:[o.jsx("legend",{children:a("tags.color")}),Ns.map(w=>o.jsxs("label",{className:Be===w?"active":"",children:[o.jsx("input",{type:"radio",name:"dashboard-tag-color",checked:Be===w,onChange:()=>H(w)}),o.jsx(io,{color:w}),a(`tags.${w}`)]},w))]})]})}),o.jsx(Ie,{open:!!X,title:a("tags.assignTitle",{project:X?.name??""}),description:a("tags.assignDescription"),onOpenChange:w=>{w||z(null)},footer:o.jsx("button",{onClick:()=>z(null),children:a("common.close")}),children:o.jsxs("div",{className:"tag-assignment-list",children:[d.map(w=>o.jsxs("label",{children:[o.jsx("input",{type:"checkbox",checked:!!X?.tags.some(te=>te.id===w.id),onChange:()=>{Ci(w)}}),o.jsx(io,{color:w.color}),o.jsx("span",{children:w.name})]},w.id)),d.length===0&&o.jsx("p",{className:"muted",children:a("tags.empty")})]})}),o.jsx(Ie,{open:!!ee,title:a("projects.renameTitle"),onOpenChange:w=>{w||mt(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>mt(null),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ks()},children:a("projects.rename")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:Xt,onChange:w=>un(w.target.value),onKeyDown:w=>{w.key==="Enter"&&ks()}})]})}),o.jsx(Ie,{open:!!At,title:a("projects.duplicateTitle"),description:a("projects.duplicateDescription",{project:At?.name??""}),onOpenChange:w=>{!w&&!U&&(Zt(null),It(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:U,onClick:()=>{Zt(null),It("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:U||!Ft.trim(),onClick:()=>{fn()},children:a(U?"projects.duplicating":"projects.duplicate")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:Ft,onChange:w=>It(w.target.value),onKeyDown:w=>{w.key==="Enter"&&fn()}})]})}),o.jsx(Ie,{open:!!ce,title:a("projects.transferOwnership"),description:a("projects.transferDescription",{project:ce?.name??""}),onOpenChange:w=>{!w&&!tt&&(Oe(null),St(""),dt(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:tt,onClick:()=>{Oe(null),St(""),dt("")},children:a("common.cancel")}),o.jsxs("button",{className:"primary",disabled:tt||!vt,onClick:()=>{Ut()},children:[tt?o.jsx(yn,{className:"spin",size:14}):o.jsx(zi,{size:14}),a("projects.transfer")]})]}),children:o.jsxs("div",{className:"form-stack",children:[jt&&o.jsx("p",{className:"error dialog-error",children:jt}),o.jsxs("label",{className:"form-field",children:[a("projects.newOwner"),o.jsxs("select",{disabled:tt||He.length===0,value:vt,onChange:w=>St(w.target.value),children:[o.jsx("option",{value:"",children:tt?a("common.loading"):He.length>0?a("projects.chooseNewOwner"):a("projects.noTransferUsers")}),He.map(w=>o.jsxs("option",{value:w.id,children:[w.displayName??w.username," (@",w.username,")"]},w.id))]})]}),o.jsxs("p",{className:"warning",children:[o.jsx(Hs,{size:15}),a("projects.transferWarning")]})]})}),o.jsx(Vs,{open:!!xe,title:a("projects.deleteTitle"),description:a("projects.deleteDescription",{project:xe?.name??""}),confirmLabel:a("common.delete"),danger:!0,onCancel:()=>et(null),onConfirm:()=>{Es()}})]}),j&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(kb,{open:!0,onOpenChange:C})}),o.jsx(Ta,{})]})}function io({color:t}){return o.jsx("span",{className:`tag-dot tag-${t}`})}function Ob(t=10){const e="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%",n=crypto.getRandomValues(new Uint8Array(t));return Array.from(n,s=>e[s%e.length]).join("")}function _b({currentUser:t}){const{t:e}=Pe(),[n,s]=h.useState([]),[r,i]=h.useState(""),[a,c]=h.useState(!1),[l,d]=h.useState({username:"",displayName:"",password:"",role:"user",canCreateProjects:!1}),[f,u]=h.useState(null),[m,p]=h.useState(""),[g,x]=h.useState(null),[b,j]=h.useState(!1),C=()=>A("/api/admin/users").then(({users:v})=>s(v)).catch(v=>i(V(v)));h.useEffect(()=>{C()},[]);const N=async()=>{if(l.password.length<Xe)return i(e("auth.passwordMinimum",{count:Xe}));try{await A("/api/admin/users",{method:"POST",body:JSON.stringify({username:l.username,displayName:l.displayName||l.username,password:l.password,role:l.role,canCreateProjects:l.canCreateProjects})}),c(!1),d({username:"",displayName:"",password:"",role:"user",canCreateProjects:!1}),await C()}catch(v){i(V(v))}},T=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({disabled:!v.disabled})}),await C()}catch(O){i(V(O))}},_=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({role:v.role==="admin"?"user":"admin"})}),await C()}catch(O){i(V(O))}},L=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({canCreateProjects:!v.canCreateProjects})}),await C()}catch(O){i(V(O))}},E=async()=>{if(!(!f||!m)){if(m.length<Xe)return i(e("auth.passwordMinimum",{count:Xe}));try{await A(`/api/admin/users/${f.id}`,{method:"PATCH",body:JSON.stringify({password:m})}),u(null),p("")}catch(v){i(V(v))}}},q=async()=>{if(g)try{await A(`/api/admin/users/${g.id}`,{method:"DELETE",body:JSON.stringify({deleteProjects:b})}),x(null),j(!1),await C()}catch(v){i(V(v))}};return o.jsxs("main",{className:"dashboard",children:[o.jsxs("div",{className:"section-title",children:[o.jsxs("div",{children:[o.jsxs("h1",{children:[o.jsx(qs,{"aria-hidden":!0,size:25}),e("users.manage")]}),o.jsx("p",{className:"muted",children:e("users.onlyAdmin")})]}),o.jsxs("button",{className:"primary icon-button",onClick:()=>c(!0),children:[o.jsx(fd,{"aria-hidden":!0,size:15}),e("users.add")]})]}),r&&o.jsx("p",{className:"error",children:r}),o.jsx("div",{className:"table-card",children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:e("common.user")}),o.jsx("th",{children:e("users.role")}),o.jsx("th",{children:e("users.createProjects")}),o.jsx("th",{children:e("users.ownedProjects")}),o.jsx("th",{children:e("users.status")}),o.jsx("th",{children:e("users.actions")})]})}),o.jsx("tbody",{children:n.map(v=>o.jsxs("tr",{children:[o.jsxs("td",{children:[o.jsx("strong",{children:v.displayName}),o.jsxs("small",{children:["@",v.username]})]}),o.jsx("td",{children:v.role==="admin"?e("common.admin"):e("common.user")}),o.jsx("td",{children:v.canCreateProjects?e("users.allow"):e("users.deny")}),o.jsx("td",{children:v.ownedProjects}),o.jsx("td",{children:v.disabled?e("common.disabled"):e("common.normal")}),o.jsxs("td",{children:[o.jsx("button",{disabled:v.id===t.id,onClick:()=>T(v),children:v.disabled?e("users.enable"):e("users.disable")}),o.jsx("button",{disabled:v.id===t.id,onClick:()=>_(v),children:v.role==="admin"?e("users.demote"):e("users.promote")}),o.jsx("button",{disabled:v.role==="admin",onClick:()=>L(v),children:v.canCreateProjects?e("users.denyCreate"):e("users.allowCreate")}),o.jsx("button",{onClick:()=>{u(v),p("")},children:e("users.resetPassword")}),o.jsx("button",{className:"danger-text",disabled:v.id===t.id,onClick:()=>{x(v),j(!1)},children:e("common.delete")})]})]},v.id))})]})}),o.jsx(Ie,{open:a,title:e("users.add"),description:e("users.addDescription"),onOpenChange:c,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>c(!1),children:e("common.cancel")}),o.jsx("button",{className:"primary",disabled:l.password.length<Xe,onClick:()=>{N()},children:e("users.createUser")})]}),children:o.jsxs("div",{className:"form-stack",children:[o.jsxs("label",{className:"form-field",children:[e("auth.username"),o.jsx("input",{value:l.username,onChange:v=>d({...l,username:v.target.value})})]}),o.jsxs("label",{className:"form-field",children:[e("users.displayName"),o.jsx("input",{value:l.displayName,onChange:v=>d({...l,displayName:v.target.value})})]}),o.jsxs("label",{className:"form-field",children:[e("users.initialPassword"),o.jsxs("span",{className:"password-generator",children:[o.jsx("input",{minLength:Xe,autoComplete:"new-password",value:l.password,onChange:v=>d({...l,password:v.target.value})}),o.jsxs("button",{type:"button",title:e("users.generatePassword"),onClick:()=>d({...l,password:Ob()}),children:[o.jsx(gm,{size:15}),e("users.randomPassword")]})]}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Xe})})]}),o.jsxs("label",{className:"form-field",children:[e("users.role"),o.jsxs("select",{value:l.role,onChange:v=>d({...l,role:v.target.value}),children:[o.jsx("option",{value:"user",children:e("common.user")}),o.jsx("option",{value:"admin",children:e("common.admin")})]})]}),o.jsxs("label",{className:"checkbox-field",children:[o.jsx("input",{type:"checkbox",checked:l.canCreateProjects||l.role==="admin",disabled:l.role==="admin",onChange:v=>d({...l,canCreateProjects:v.target.checked})})," ",e("users.allowCreate")]})]})}),o.jsx(Ie,{open:!!f,title:e("users.resetPassword"),description:e("users.resetDescription",{username:f?.username??""}),onOpenChange:v=>{v||u(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>u(null),children:e("common.cancel")}),o.jsx("button",{className:"primary",disabled:m.length<Xe,onClick:()=>{E()},children:e("users.reset")})]}),children:o.jsxs("label",{className:"form-field",children:[e("auth.newPassword"),o.jsx("input",{autoFocus:!0,type:"password",minLength:Xe,autoComplete:"new-password",value:m,onChange:v=>p(v.target.value)}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Xe})})]})}),o.jsx(Ie,{open:!!g,title:e("users.deleteTitle"),description:e("users.deleteDescription",{username:g?.username??""}),onOpenChange:v=>{v||x(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>x(null),children:e("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{q()},children:e("users.deleteTitle")})]}),children:o.jsxs("fieldset",{className:"choice-group",children:[o.jsx("legend",{children:e("users.ownedChoice",{count:g?.ownedProjects??0})}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",checked:!b,onChange:()=>j(!1)})," ",e("users.transferProjects")]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",checked:b,onChange:()=>j(!0)})," ",e("users.deleteProjects")]})]})})]})}function Pb({site:t,user:e,projectId:n,onBack:s}){const{t:r}=Pe(),[i,a]=h.useState(null),[c,l]=h.useState([]),[d,f]=h.useState(null),[u,m]=h.useState([]),[p,g]=h.useState(""),[x,b]=h.useState(""),[j,C]=h.useState(new Set),[N,T]=h.useState(""),[_,L]=h.useState(""),[E,q]=h.useState(!1),[v,O]=h.useState("editor.saved"),[Z,W]=h.useState(null),[P,R]=h.useState({line:1,column:1}),S=h.useRef(P),[F,le]=h.useState("pdf"),[Q,ge]=h.useState("log"),oe=y=>{if(y==="pdf"){le("pdf");return}ge(y),le("diagnostics")},{workspaceLayout:ae,setWorkspaceLayout:he}=wb(e.id,n),[Ce,B]=h.useState(""),[D,ye]=h.useState(""),[ke,Be]=h.useState({selectedText:"",startOffset:0,endOffset:0}),H=h.useRef({selectedText:"",startOffset:0,endOffset:0}),X=y=>{H.current=y,Be(y)},[z,ee]=h.useState(null),[mt,Xt]=h.useState(!1),[un,At]=h.useState(!1),[Zt,Ft]=h.useState(!1),[It,U]=h.useState(!1),[re,xe]=h.useState(!1),[et,ce]=h.useState(!1),[Oe,He]=h.useState(!1),[ot,vt]=h.useState(()=>kc(e.id,n)),St=h.useRef(null),tt=h.useRef(null),ie=h.useRef(0),jt=h.useRef(0),dt=h.useRef(""),Re=h.useRef(""),Ct=h.useRef(""),nt=h.useRef(""),hn=h.useRef(0),ne=h.useRef(null),Ue=h.useRef(null),Mt=h.useRef(null),$t=h.useRef(null),Ee=h.useRef(!1),Je=h.useRef(null),xs=h.useRef(s);xs.current=s,Ct.current=x;const vi=(y,k)=>{const M={line:y,column:k};S.current=M,R(M)},{collaboration:ze,status:kt,synced:qe,activeSessions:bs,compileState:st,setCompileState:vs,filesEvent:ve,commentsRevision:ur,dictionaryRevision:Ss,localDraftReady:js,reconnect:Si}=db(n,e,x,()=>O("editor.offlineDraft")),{pdfTarget:Cs,pdfViewport:ji,sourceJump:hr,setPdfViewport:Ci,clearPdfViewport:ks,jumpToSource:fn,syncSourceToPdf:Es,syncVisiblePdfToSource:fr}=yb({projectId:n,mainFile:x,activeFile:p,onActiveFile:g,onError:B,onShowPdf:()=>oe("pdf")}),Ut=gb({active:!!(i&&p&&qe&&ot.spellCheck),activeFile:p,content:N,dictionaryWords:c});h.useEffect(()=>{vt(kc(e.id,n))},[e.id,n]);const Ds=y=>{dt.current=y,T(y)};h.useEffect(()=>{Re.current=p,S.current={line:1,column:1},R({line:1,column:1}),X({selectedText:"",startOffset:0,endOffset:0})},[p]),h.useEffect(()=>{if(!E)return;const y=k=>{k.preventDefault(),k.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[E]),h.useEffect(()=>{if(kt!=="disconnected")return;const y=new AbortController;return A(`/api/projects/${n}`,{signal:y.signal}).then(({project:k})=>{y.signal.aborted||(a(k),B(""))}).catch(k=>{if(!qn(k)){if(k instanceof Ao&&[401,403,404].includes(k.status)){B(V(k)),xs.current();return}B(r("errors.collaborationUnavailable"))}}),()=>y.abort()},[kt,n,r]);const Nn=async(y={})=>{ne.current?.abort(),ne.current=null;const k=y.signal?null:new AbortController;k&&(ne.current=k);try{const M=await A(`/api/projects/${n}/completions`,{signal:y.signal??k?.signal});(!y.isCurrent||y.isCurrent())&&f(M.index)}catch(M){if(qn(M))return;(!y.isCurrent||y.isCurrent())&&f(null)}finally{k&&ne.current===k&&(ne.current=null)}},Ns=async(y={},k=Ct.current)=>{Ue.current?.abort(),Ue.current=null;const M=y.signal?null:new AbortController;M&&(Ue.current=M);try{const J=k?`?mainFile=${encodeURIComponent(k)}`:"",fe=await A(`/api/projects/${n}/outline${J}`,{signal:y.signal??M?.signal});(!y.isCurrent||y.isCurrent())&&m(fe.outline)}catch(J){!qn(J)&&(!y.isCurrent||y.isCurrent())&&m([])}finally{M&&Ue.current===M&&(Ue.current=null)}},Tn=async(y={})=>{Mt.current?.abort(),Mt.current=null;const k=y.signal?null:new AbortController;k&&(Mt.current=k);try{const M=await A(`/api/projects/${n}/dictionary`,{signal:y.signal??k?.signal});(!y.isCurrent||y.isCurrent())&&l(M.words)}catch(M){if(qn(M))return;(!y.isCurrent||y.isCurrent())&&l([])}finally{k&&Mt.current===k&&(Mt.current=null)}};h.useEffect(()=>{let y=!1;const k=++hn.current,M=new AbortController,J=()=>!y&&hn.current===k;let fe=!1;nt.current="",a(null),pn([]),m([]),g(""),b(""),C(new Set),T(""),L(""),vs(null),ks(),f(null),l([]),Yu();const Ye=A(`/api/projects/${n}`,{signal:M.signal}).then(We=>{J()&&(fe=!0,a(We.project),g(We.project.mainFile),b(We.project.mainFile),C(new Set([We.project.mainFile])),Ra(new Set(Fs(We.project.mainFile))))}).catch(We=>{J()&&B(V(We))}),de=A(`/api/projects/${n}/files`,{signal:M.signal}).then(We=>{J()&&pn(We.files)}).catch(We=>{J()&&B(V(We))});return Promise.allSettled([Ye,de]).then(()=>{!J()||!fe||window.setTimeout(()=>{J()&&Promise.all([Nn({signal:M.signal,isCurrent:J}),Tn({signal:M.signal,isCurrent:J})])},0)}),()=>{y=!0,M.abort(),ne.current?.abort(),ne.current=null,Ue.current?.abort(),Ue.current=null,Mt.current?.abort(),Mt.current=null,$t.current?.abort(),$t.current=null}},[n]),h.useEffect(()=>{Ss&&Tn()},[Ss,n]),h.useEffect(()=>{i&&ze.setPermission(i.permission)},[ze,i?.permission]),h.useEffect(()=>{if(!ve)return;const y=ve.kind==="delete"&&!!ve.path&&zn(ve.path,Re.current),k=ve.kind==="delete"&&!!ve.path&&zn(ve.path,Ct.current);if(ve.kind==="move"&&ve.source&&ve.destination){const J=ve.source,fe=ve.destination,Ye=de=>de===J?fe:de.startsWith(`${J}/`)?`${fe}${de.slice(J.length)}`:de;g(de=>Ye(de)),b(de=>Ye(de)),C(de=>new Set([...de].map(Ye))),pr(de=>de&&Ye(de))}y&&(g(""),L(""),Ds(""),ye(r("editor.fileDeletedByCollaborator",{path:ve.path}))),ve.kind==="delete"&&ve.path&&(C(J=>new Set([...J].filter(fe=>!zn(ve.path,fe)))),pr(J=>zn(ve.path,J)?"":J),_a(J=>J&&zn(ve.path,J.path)?null:J)),$t.current?.abort();const M=new AbortController;$t.current=M,Promise.all([On({signal:M.signal}),A(`/api/projects/${n}`,{signal:M.signal})]).then(([J,fe])=>{if(a(fe.project),k&&b(fe.project.mainFile),y&&J){const Ye=J.find(de=>de.type==="file"&&de.path===fe.project.mainFile)??J.find(de=>de.type==="file"&&Lo(de.path));g(Ye?.path??"")}Nn({signal:M.signal}),Ns({signal:M.signal},k?fe.project.mainFile:Ct.current)}).catch(J=>{qn(J)}).finally(()=>{$t.current===M&&($t.current=null)})},[ve?.revision]),h.useEffect(()=>{if(ze.setActiveFile(p),!p)return;L(""),O("editor.loading");const y=ze.getText(p),k=(M,J)=>{Ds(y.toString()),L(p),J?.local&&i?.permission!=="read"?(ie.current+=1,q(!0),O("editor.pending")):ie.current<=jt.current&&O(Z?"editor.savedAt":"editor.saved")};return y.observe(k),(qe||js)&&k(),()=>{y.unobserve(k)}},[p,ze,qe,js,i?.permission]),h.useEffect(()=>{!p||_!==p||nt.current===p||(nt.current=p,!(!p.toLocaleLowerCase().endsWith(".tex")||!Rb(N))&&(C(y=>new Set([...y,p])),b(p)))},[p,_,N]);const w=async()=>{if(!qe)throw new Error("Collaboration is not synchronized");const y=ie.current,k=await ze.flush();return jt.current=Math.max(jt.current,y),W(k.persistedAt),/\.tex$/i.test(Re.current)&&Ns(),ie.current===y?(q(!1),O("editor.savedAt")):O("editor.pending"),k};h.useEffect(()=>{if(!E||!p)return;if(!qe){O("editor.offlineDraft");return}O("editor.pending");const y=window.setTimeout(()=>{O("editor.saving"),w().catch(()=>{O(ze.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(y)},[N,E,p,qe]);const te=async()=>{if(!i||i.permission==="read"||!qe||!p)return!1;O("editor.saving");try{return await w(),Nn(),!0}catch{return O("editor.saveFailed"),B(r("errors.collaborationUnavailable")),!1}},se=async(y,k)=>(await A(`/api/projects/${n}/format`,{method:"POST",body:JSON.stringify({path:y,source:k})})).formatted,Se=async()=>{if(!ot.formatOnCompile||!i||i.permission==="read"||!qe||!Bi(Re.current)||Ee.current)return;const y=Re.current,k=ze.getText(y),M=k.toString();Ee.current=!0,He(!0);try{const J=await se(y,M),fe=await Ec(M,J);if(Re.current!==y||k.toString()!==M)throw new Error(r("editor.formatSourceChanged"));fe.length&&ze.applyTextEdits(y,fe)}catch(J){B(r("editor.formatFailedContinue",{message:V(J)}))}finally{Ee.current=!1,He(!1)}},Ve=async()=>(Je.current&&await Je.current,await Se(),te()),Le=async()=>{if(!i||i.permission==="read"||!qe||Ee.current||!Bi(Re.current))return;const y=H.current;if(!y.selectedText.trim()){ye(r("editor.formatSelectionRequired"));return}const k=Re.current,{startOffset:M,endOffset:J,selectedText:fe}=y,Ye=ze.getText(k);if(Ye.toString().slice(M,J)!==fe){B(r("editor.formatSelectionChanged"));return}Ee.current=!0,He(!0);let de=()=>{};const We=new Promise(Et=>{de=Et});Je.current=We;try{const Et=Um(fe,await se(k,fe)),Ga=await Ec(fe,Et,M);if(Re.current!==k||Ye.toString().slice(M,J)!==fe){B(r("editor.formatSelectionChanged"));return}Ga.length&&ze.applyTextEdits(k,Ga),B(""),ye(r("editor.formatSelectionComplete"))}catch(Et){B(r("editor.formatFailed",{message:V(Et)}))}finally{Ee.current=!1,He(!1),de(),Je.current===We&&(Je.current=null)}},{files:at,setFiles:pn,loadFiles:On,newFileOpen:Qt,setNewFileOpen:Ts,newFilePath:Zu,setNewFilePath:Oa,resourcePreview:De,setResourcePreview:_a,resourcePreviewLoading:Qu,setResourcePreviewLoading:eh,newFolderOpen:th,setNewFolderOpen:ki,newFolderName:nh,setNewFolderName:Pa,fileDialogError:en,setFileDialogError:_n,selectedFolder:zt,setSelectedFolder:pr,expandedFolders:sh,setExpandedFolders:Ra,moveEntry:Os,setMoveEntry:mr,moveDestination:rh,setMoveDestination:Ei,deleteEntry:Pn,setDeleteEntry:gr,fileDragActive:La,setFileDragActive:Di,uploadConflict:Ni,setUploadConflict:Aa,uploadingFiles:yr,directoryEntries:ih,visibleEntries:oh,createFile:ah,createFolder:Fa,uploadFiles:Ia,upload:ch,openFile:Ma,movePath:lh,removePath:dh}=mb({projectId:n,site:t,activeFile:p,dirty:E,save:te,onError:B,onProject:a,onActiveFile:g,onActiveMainFile:b,onRootDocuments:C}),{comments:_s,focusComment:uh,setFocusComment:$a,commentOpen:hh,setCommentOpen:Ti,commentText:fh,setCommentText:ph,addComment:mh,toggleComment:gh,replyToComment:yh,editComment:wh,deleteComment:xh,editCommentReply:bh,deleteCommentReply:vh}=cb({projectId:n,activeFile:p,permission:i?.permission,revision:ur,selection:ke,save:te,onError:B,onAdded:()=>ee("comments")}),{pdfUrl:mn,pdfCompiledAt:Rn,compileLog:wr,compileDiagnostics:xr,compileOutcome:br,artifacts:Oi,artifactPreview:Sh,artifactLoading:jh,editorNotice:Ua,localCompiling:_i,compile:Ch,viewArtifact:kh}=ub({projectId:n,project:i,mainFile:x,collaborationSynced:qe,sharedState:st,onSharedState:vs,save:Ve,loadOutline:(y,k)=>Ns({signal:y},k),onPreviewTab:oe,onError:B,onCompileStart:()=>{B(""),ye("")},onCompileSuccess:()=>{const y=Re.current;y&&Es(y,S.current.line,S.current.column,{silent:!0})},onPdfChanged:ks});h.useEffect(()=>{const y=k=>{(k.ctrlKey||k.metaKey)&&(!k.shiftKey&&k.key.toLocaleLowerCase()==="p"?(k.preventDefault(),xe(!0)):k.shiftKey&&k.key.toLocaleLowerCase()==="f"&&(k.preventDefault(),ce(!0)))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[]);const Eh=y=>{vt(y),Im(e.id,n,y)},za=()=>{tt.current?.isCollapsed()?tt.current.expand():tt.current?.collapse()},Va=h.useMemo(()=>u.length?u:Lb(N).map(y=>({...y,path:p})),[u,N,p]),Ln=h.useMemo(()=>zm(wr,br),[wr,br]),An=ae!=="pdf-only",Ba=ae!=="editor-only",vr=y=>{he(y),y==="pdf-only"&&oe("pdf")},Pi=Pn?bs.filter(y=>y.filePath&&zn(Pn.path,y.filePath)):[];if(!i)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:Ce||r("common.loading")}),Ce&&o.jsx("button",{className:"primary",onClick:s,children:r("editor.backToProjects")})]});const Vt=i.permission==="read"||!qe,Sr=st?.mainFile===x&&(st.status==="queued"||st.status==="running"),Ps=_i||Sr,Ha=p?ze.getText(p):null,qa=Rn?new Date(Rn).toLocaleString(we.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Dh=x.split("/").at(-1)??x,Nh=Ln.warnings.length+Ln.errors.length+Oi.length,Wa=mn?`${mn}${mn.includes("?")?"&":"?"}download=1`:"",Ka=Ps?Sr?st?.status==="queued"?r("editor.compileQueued"):r("editor.compilingBy",{name:st?.requestedBy.name??r("common.user")}):r("editor.compiling"):br==="failed"?mn&&Rn?r("editor.compileFailedRetained",{time:new Date(Rn).toLocaleString(we.resolvedLanguage)}):r("editor.compileFailedNoPdf"):"",Th=v==="editor.savedAt"&&Z?r("editor.savedAt",{time:new Date(Z).toLocaleTimeString(we.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):r(v);return o.jsxs("div",{className:"workspace",children:[o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:r("editor.backToProjects"),"aria-label":r("editor.backToProjects"),onClick:s,children:o.jsx(od,{size:18})}),o.jsx(bi,{siteName:t.siteName,compact:!0}),o.jsxs("div",{className:"project-heading",children:[o.jsx("strong",{children:i.name}),o.jsxs("small",{children:[p," · ",Th]})]}),ot.vimMode&&o.jsxs("span",{className:"vim-status-badge",title:r("editor.vimOnHint"),children:[o.jsx(vm,{size:14}),r("editor.vimOn")]}),o.jsx(Qx,{sessions:bs,status:kt}),kt==="disconnected"&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:r("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:Si,children:r("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[An&&o.jsxs("button",{className:mt?"":"active",onClick:za,children:[mt?o.jsx(km,{size:15}):o.jsx(Sc,{size:15}),r("common.files")]}),o.jsx(eb,{value:ae,onChange:vr}),o.jsxs("button",{onClick:()=>U(!0),children:[o.jsx(ud,{size:15}),r("history.title")]}),o.jsxs("button",{onClick:()=>At(!0),children:[o.jsx(qs,{size:15}),r("projectSettings.share")]}),i.ownerId===e.id&&o.jsxs("button",{onClick:()=>Ft(!0),children:[o.jsx(bm,{size:15}),"Git"]}),An&&i.permission!=="read"&&Bi(p)&&o.jsxs("button",{title:ke.selectedText.trim()?r("editor.formatSelection"):r("editor.formatSelectionHint"),onMouseDown:y=>y.preventDefault(),onClick:()=>{Le()},disabled:Vt||Oe||!qe,children:[Oe?o.jsx(yn,{className:"spin",size:15}):o.jsx(id,{size:15}),r(Oe?"editor.formatting":"editor.formatSelection")]}),o.jsxs("button",{onClick:()=>Ti(!0),disabled:!p,children:[o.jsx(jm,{size:15}),r("editor.addComment")]}),o.jsxs("button",{className:z==="comments"?"active":"",onClick:()=>ee(z==="comments"?null:"comments"),children:[o.jsx(Cm,{size:15}),r("common.comments")," ",_s.filter(y=>!y.resolved).length||""]}),o.jsxs("button",{className:z==="settings"?"active":"",onClick:()=>ee(z==="settings"?null:"settings"),children:[o.jsx(Lr,{size:15}),r("common.settings")]}),o.jsxs("button",{className:"compile",title:Sr?r("editor.compilingBy",{name:st?.requestedBy.name??""}):r("editor.compileShortcut"),onClick:Ch,disabled:Ps||Oe||Vt||!qe,children:[Ps?o.jsx(yn,{className:"spin",size:15}):o.jsx(Nm,{size:15}),Sr?r("editor.compilingBy",{name:st?.requestedBy.name??""}):_i?r("editor.compiling"):r("editor.compile",{engine:i.engine})]})]})]}),Ka&&o.jsxs("div",{className:`compile-status-strip${br==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(yn,{className:Ps?"spin":"",size:14}),o.jsx("span",{children:Ka})]}),Ce&&o.jsx("div",{className:"toast",onClick:()=>B(""),children:Ce}),D&&o.jsx("div",{className:"toast success",onClick:()=>ye(""),children:D}),o.jsxs(Ph,{autoSaveId:"texlite-workspace-layout",direction:"horizontal",className:"work-grid",children:[An&&o.jsx(jr,{id:"files",order:1,ref:tt,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>Xt(!0),onExpand:()=>Xt(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${La?" drop-active":""}`,onDragEnter:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),!Vt&&!yr&&Di(!0))},onDragOver:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),y.dataTransfer.dropEffect=Vt||yr?"none":"copy")},onDragLeave:y=>{y.currentTarget.contains(y.relatedTarget)||Di(!1)},onDrop:y=>{y.preventDefault(),Di(!1),!Vt&&!yr&&Ia(Array.from(y.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("span",{children:[o.jsx(Wn,{size:14}),r("common.files")]}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{"aria-label":r("navigation.quickOpen"),title:`${r("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>xe(!0),children:o.jsx(wm,{size:15})}),o.jsx("button",{"aria-label":r("navigation.projectSearch"),title:`${r("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>ce(!0),children:o.jsx(_m,{size:15})}),!Vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:yr,"aria-label":r("editor.uploadAttachment"),title:r("editor.uploadTo",{folder:zt||r("editor.projectRoot")}),onClick:()=>St.current?.click(),children:o.jsx(Hr,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFolder"),title:r("editor.newFolder"),onClick:()=>{Pa(""),ki(!0)},children:o.jsx(dd,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFile"),title:r("editor.newFile"),onClick:()=>{Oa(zt?`${zt}/`:""),Ts(!0)},children:o.jsx(ym,{size:15})}),o.jsx("input",{ref:St,type:"file",multiple:!0,hidden:!0,onChange:y=>{ch(y)}})]}),o.jsx("button",{"aria-label":r("editor.collapseFiles"),title:r("editor.collapseFiles"),onClick:za,children:o.jsx(Sc,{size:15})})]})]}),La&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(Hr,{size:24}),o.jsx("strong",{children:r("editor.dropFiles")}),o.jsx("span",{children:r("editor.uploadTo",{folder:zt||r("editor.projectRoot")})})]}),o.jsxs("div",{className:"folder-target",title:zt||r("editor.projectRoot"),children:[o.jsx(Vr,{size:13}),o.jsx("span",{children:zt||r("editor.projectRoot")})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${ot.fontSize}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${zt===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>pr(""),children:[o.jsx(Vr,{size:15}),o.jsx("span",{children:r("editor.projectRoot")})]})}),oh.map(y=>{const k=y.path.split("/").length-1,M=y.path.split("/").at(-1),J=sh.has(y.path),fe=j.has(y.path),Ye=x===y.path,de=y.path!==i.mainFile&&!i.mainFile.startsWith(`${y.path}/`);return y.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${zt===y.path?" selected":""}`,style:{paddingLeft:`${k*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",title:y.path,onClick:()=>{pr(y.path),Ra(We=>{const Et=new Set(We);return Et.has(y.path)?Et.delete(y.path):Et.add(y.path),Et})},children:[J?o.jsx(cd,{size:13}):o.jsx(Ko,{size:13}),o.jsx(xm,{size:14}),o.jsx("span",{children:M})]}),!Vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:r("editor.move"),"aria-label":r("editor.move"),onClick:()=>{mr(y),Ei("")},children:o.jsx(vc,{size:13})}),de&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),_n("")},children:o.jsx(ss,{size:13})})]})]},y.path):o.jsxs("div",{className:`file-entry${p===y.path?" active":""}${fe?" root-document":""}${Ye?" compile-target":""}`,style:{paddingLeft:`${k*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",title:Ye?r("editor.currentMainDocument",{path:y.path}):fe?r("editor.mainDocumentCandidate",{path:y.path}):y.path,onClick:()=>Ma(y),children:[fe?o.jsx(ad,{size:13}):o.jsx(Wn,{size:13}),o.jsx("span",{children:M}),Ye&&o.jsx("small",{children:r("editor.currentMainShort")})]}),!Vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:r("editor.move"),"aria-label":r("editor.move"),onClick:()=>{mr(y),Ei("")},children:o.jsx(vc,{size:13})}),de&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),_n("")},children:o.jsx(ss,{size:13})})]})]},y.path)})]})]}),o.jsxs("section",{className:"outline-panel",children:[o.jsx("div",{className:"panel-title",children:o.jsxs("span",{children:[o.jsx(Sm,{size:14}),r("common.outline")]})}),o.jsxs("div",{className:"outline",children:[Va.map((y,k)=>o.jsxs("button",{className:`outline-item${p===y.path&&P.line===y.line?" current":""}`,title:`${y.path}:${y.line}`,onClick:()=>{fn(y.path,y.line,1),Es(y.path,y.line,1)},children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${y.level*12}px`}}),o.jsx("small",{children:y.path===p?y.line:y.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:y.title})]},`${y.path}-${y.line}-${k}`)),Va.length===0&&o.jsx("p",{className:"muted padded",children:r("editor.noOutline")})]})]})]})}),An&&o.jsx(Ri,{className:"resize-handle",children:o.jsx(Vi,{size:12})}),An&&o.jsx(jr,{id:"source",order:2,defaultSize:42,minSize:22,children:o.jsxs("main",{className:"source-panel",children:[o.jsx(h.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(yn,{className:"spin",size:22}),o.jsx("span",{children:r("common.loading")})]}),children:o.jsx(bb,{value:N,readOnly:Vt,comments:_s,focusComment:uh,preferences:ot,completionIndex:d,spellCheckWords:c,spellCheckIssues:Ut.issues,spellCheckJump:Ut.jump,jumpTo:_===p&&hr?.path===p?hr:null,searchRequest:0,collaboration:Ha?{text:Ha,awareness:ze.awareness}:void 0,onChange:Ds,onSelection:(y,k,M)=>X({selectedText:y,startOffset:k,endOffset:M}),onCommentClick:y=>{const k=_s.find(M=>M.id===y);k&&($a({...k}),ee("comments"))},onCursor:vi},p)}),Ua&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:Ua})]})}),An&&Ba&&o.jsxs(Ri,{className:"resize-handle sync-resize-handle",children:[o.jsx(Vi,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:y=>y.stopPropagation(),children:[o.jsx("button",{disabled:!ji,title:r("editor.showInSource"),"aria-label":r("editor.showInSource"),onClick:fr,children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!p||!mn,title:r("editor.showInPdf"),"aria-label":r("editor.showInPdf"),onClick:()=>{Es(p,P.line,P.column)},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),Ba&&o.jsx(jr,{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":r("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":F==="pdf",className:`pdf-tab${F==="pdf"?" active":""}`,onClick:()=>oe("pdf"),title:Rn?r("editor.pdfCompiledAtFor",{file:x,time:new Date(Rn).toLocaleString(we.resolvedLanguage)}):r("editor.currentMainDocument",{path:x}),children:[o.jsx(Wn,{size:16}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",Dh,qa&&o.jsx("small",{children:qa})]})]}),o.jsxs("button",{role:"tab","aria-selected":F==="diagnostics",className:`diagnostics-tab${F==="diagnostics"?" active":""}`,onClick:()=>le("diagnostics"),children:[o.jsx(bo,{size:14}),r("editor.outputTabs"),o.jsx("span",{children:Nh})]})]}),Wa&&o.jsxs("a",{className:"pdf-download-top",href:Wa,download:!0,title:r("editor.downloadPdf"),"aria-label":r("editor.downloadPdf"),children:[o.jsx(Bs,{size:15}),o.jsx("span",{children:r("editor.downloadPdf")})]})]}),F==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":r("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":Q==="log",className:Q==="log"?"active":"",onClick:()=>oe("log"),children:[o.jsx(bo,{size:13}),r("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":Q==="warnings",className:Q==="warnings"?"active":"",onClick:()=>oe("warnings"),children:[o.jsx(Hs,{size:13}),r("editor.warnings"),o.jsx("span",{children:Ln.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":Q==="errors",className:Q==="errors"?"active":"",onClick:()=>oe("errors"),children:[o.jsx(Go,{size:13}),r("editor.errors"),o.jsx("span",{children:Ln.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":Q==="artifacts",className:Q==="artifacts"?"active":"",onClick:()=>oe("artifacts"),children:[o.jsx(hd,{size:13}),r("editor.artifacts"),o.jsx("span",{children:Oi.length})]})]}),o.jsxs("div",{className:`preview-content preview-${F} ${F==="diagnostics"?`preview-${Q}`:""}`,children:[F==="pdf"&&(mn?o.jsx(h.Suspense,{fallback:o.jsx("div",{className:"preview-empty",children:o.jsx("span",{children:r("common.loading")})}),children:o.jsx(xb,{url:mn,target:Cs,compiling:Ps,onViewportLocation:(y,k,M)=>Ci({page:y,x:k,y:M})})}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Wn,{size:28}),o.jsx("strong",{children:r("editor.preview")}),o.jsx("span",{children:r("editor.previewHint")})]})),F==="diagnostics"&&Q==="log"&&o.jsx(ro,{lines:wr?wr.split(`
14
14
  `):[],empty:r(_i?"editor.compiling":"editor.noLog")}),F==="diagnostics"&&Q==="warnings"&&(xr?o.jsx(cl,{tone:"warning",diagnostics:xr.warnings,files:at,empty:r("editor.noWarnings"),onJump:(y,k,M)=>{ae==="pdf-only"&&vr("editor-pdf"),fn(y,k,M)}}):o.jsx(ro,{tone:"warning",lines:Ln.warnings,empty:r("editor.noWarnings")})),F==="diagnostics"&&Q==="errors"&&(xr?o.jsx(cl,{tone:"error",diagnostics:xr.errors,files:at,empty:r("editor.noErrors"),onJump:(y,k,M)=>{ae==="pdf-only"&&vr("editor-pdf"),fn(y,k,M)}}):o.jsx(ro,{tone:"error",lines:Ln.errors,empty:r("editor.noErrors")})),F==="diagnostics"&&Q==="artifacts"&&o.jsx(rb,{projectId:n,mainFile:x,artifacts:Oi,preview:Sh,loading:jh,onView:y=>{kh(y)}})]})]})}),z&&o.jsxs(o.Fragment,{children:[o.jsx(Ri,{className:"resize-handle",children:o.jsx(Vi,{size:12})}),o.jsx(jr,{id:"context",order:4,defaultSize:20,minSize:15,maxSize:38,children:o.jsxs("aside",{className:"context-panel",children:[o.jsxs("div",{className:"drawer-title",children:[o.jsx("strong",{children:r(z==="comments"?"editor.sourceComments":"editor.projectSettings")}),o.jsx("button",{"aria-label":r("common.close"),onClick:()=>ee(null),children:o.jsx(Jo,{size:17})})]}),z==="comments"&&o.jsxs("div",{className:"comments",children:[_s.map(y=>o.jsx(tb,{comment:y,currentUserId:e.id,onFocus:()=>$a({...y}),onToggle:()=>{gh(y)},onReply:k=>yh(y,k),onEdit:k=>wh(y,k),onDelete:()=>xh(y),onEditReply:(k,M)=>bh(y,k,M),onDeleteReply:k=>vh(y,k)},y.id)),_s.length===0&&o.jsx("p",{className:"muted padded",children:r("editor.noComments")})]}),z==="settings"&&o.jsx(sb,{project:i,projectId:n,site:t,files:at,dictionaryWords:c,onDictionaryChange:l,editorPreferences:ot,onEditorPreferences:Eh,spellCheckCount:Ut.summary?.total??null,spellCheckUniqueCount:Ut.summary?.unique??null,spellCheckIndex:Ut.summary?Ut.index:-1,onSpellCheckNavigate:Ut.jumpToIssue,onProject:a})]})})]})]}),o.jsxs(Ie,{open:!!De,extraWide:De?.kind==="image"||De?.kind==="pdf"||De?.kind==="text",title:De?.path??"",description:De?.kind==="large"?r("editor.resourceTooLarge",{size:Xu(De.size),limit:"10 MB"}):r(`editor.resourcePreview.${De?.kind??"text"}`),onOpenChange:y=>{y||(_a(null),eh(!1))},footer:De&&o.jsxs("a",{className:"primary resource-download",href:`${De.url}&download=1`,download:!0,children:[o.jsx(Bs,{size:14}),r("editor.downloadResource")]}),children:[De?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(wo,{size:34}),o.jsx("strong",{children:r("editor.resourceTooLargeTitle")}),o.jsx("span",{children:r("editor.resourceTooLargeDescription")})]}),De?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(wo,{size:34}),o.jsx("strong",{children:r("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:r("editor.resourceUnsupportedDescription")})]}),De?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:De.url,alt:De.path})}),De?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:De.url,title:De.path}),De?.kind==="text"&&(Qu?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(yn,{className:"spin",size:24}),o.jsx("span",{children:r("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:De.content}))]}),o.jsx(Vs,{open:!!Ni,title:r("editor.uploadOverwriteTitle"),description:r("editor.uploadOverwriteDescription",{files:Ni?.collisions.join(", ")??""}),confirmLabel:r("editor.uploadOverwrite"),danger:!0,onCancel:()=>Aa(null),onConfirm:()=>{const y=Ni;Aa(null),y&&Ia(y.files,new Set(y.collisions),y.directory)}}),o.jsx(Ie,{open:Qt,title:r("editor.newFile"),description:r("editor.newFileDescription"),onOpenChange:y=>{Ts(y),y||_n("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Ts(!1),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ah()},children:r("common.create")})]}),children:o.jsxs(o.Fragment,{children:[en&&o.jsx("p",{className:"error dialog-error",children:en}),o.jsxs("label",{className:"form-field",children:[r("editor.filePath"),o.jsx("input",{autoFocus:!0,value:Zu,onChange:y=>Oa(y.target.value)})]})]})}),o.jsx(Ie,{open:th,title:r("editor.newFolder"),description:r("editor.folderDestination",{folder:zt||r("editor.projectRoot")}),onOpenChange:y=>{ki(y),y||_n("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ki(!1),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Fa()},children:r("common.create")})]}),children:o.jsxs(o.Fragment,{children:[en&&o.jsx("p",{className:"error dialog-error",children:en}),o.jsxs("label",{className:"form-field",children:[r("editor.folderName"),o.jsx("input",{autoFocus:!0,value:nh,onChange:y=>Pa(y.target.value),onKeyDown:y=>{y.key==="Enter"&&Fa()}})]})]})}),o.jsx(Ie,{open:!!Os,title:r("editor.moveTitle",{name:Os?.path.split("/").at(-1)??""}),description:r("editor.moveDescription"),onOpenChange:y=>{y||(mr(null),_n(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>mr(null),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{lh()},children:r("editor.move")})]}),children:o.jsxs(o.Fragment,{children:[en&&o.jsx("p",{className:"error dialog-error",children:en}),o.jsxs("label",{className:"form-field",children:[r("editor.destinationFolder"),o.jsxs("select",{value:rh,onChange:y=>Ei(y.target.value),children:[o.jsx("option",{value:"",children:r("editor.projectRoot")}),ih.filter(y=>Os?.type!=="directory"||y.path!==Os.path&&!y.path.startsWith(`${Os.path}/`)).map(y=>o.jsx("option",{value:y.path,children:y.path},y.path))]})]})]})}),o.jsx(Ie,{open:!!Pn,title:r("editor.deletePathTitle",{name:Pn?.path.split("/").at(-1)??""}),description:Pi.length?r("editor.deletePathActiveDescription",{path:Pn?.path??"",users:[...new Set(Pi.map(y=>y.name))].join(", ")}):r("editor.deletePathDescription",{path:Pn?.path??""}),onOpenChange:y=>{y||(gr(null),_n(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>gr(null),children:r("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{dh()},children:r("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[en&&o.jsx("p",{className:"error dialog-error",children:en}),Pi.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(Hs,{size:15}),r("editor.deletePathWillClose")]})]})}),o.jsxs(Ie,{open:hh,title:r("editor.addComment"),description:ke.selectedText?r("editor.commentDescription",{count:ke.endOffset-ke.startOffset}):r("editor.pointComment"),onOpenChange:Ti,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Ti(!1),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{mh()},children:r("editor.addComment")})]}),children:[o.jsxs("label",{className:"form-field",children:[r("editor.commentContent"),o.jsx("textarea",{autoFocus:!0,rows:5,value:fh,onChange:y=>ph(y.target.value)})]}),ke.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:ke.selectedText})]}),o.jsx(nb,{open:un,onOpenChange:At,project:i,projectId:n}),re&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Cb,{open:!0,files:at,onOpenChange:xe,onOpenFile:y=>{const k=at.find(M=>M.path===y);k&&Ma(k)}})}),et&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(jb,{open:!0,project:i,onOpenChange:ce,onJump:(y,k,M)=>{ae==="pdf-only"&&vr("editor-pdf"),fn(y,k,M)}})}),It&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Sb,{open:!0,onOpenChange:U,project:i,onBeforeMutation:i.permission==="read"?async()=>!0:te})}),i.ownerId===e.id&&Zt&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(vb,{open:!0,onOpenChange:Ft,project:i,onBeforeMutation:te})})]})}function Rb(t){const n=t.split(new RegExp("(?<=\\n)")).map(s=>{for(let r=0;r<s.length;r+=1){if(s[r]!=="%")continue;let i=0;for(let a=r-1;a>=0&&s[a]==="\\";a-=1)i+=1;if(i%2===0)return`${s.slice(0,r)}${s.endsWith(`
15
15
  `)?`
16
16
  `:""}`}return s}).join("").replace(/\\verb\*?([^\s]).*?\1/g,"").replace(/\\begin\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}[\s\S]*?\\end\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}/g,"");return/\\documentclass\s*(?:\[[^\]]*\]\s*)?\{/.test(n)}function Xu(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Lb(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`