texlite 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/client/assets/{BinaryModule-Aj1vLnwf-DrR-dr9z.js → BinaryModule-Aj1vLnwf-vCI86hxN.js} +1 -1
- package/dist/client/assets/{GitDialog-BNJvWeoG.js → GitDialog-DPK1_Lf7.js} +1 -1
- package/dist/client/assets/{HistoryDialog-tBeFz_IG.js → HistoryDialog-wKZ0ECpn.js} +1 -1
- package/dist/client/assets/{LatexEditor-CEtxGHGh.js → LatexEditor-0ijwz3Ud.js} +25 -25
- package/dist/client/assets/{PdfPreview-CfolZ_vp.js → PdfPreview-BaOpY89K.js} +1 -1
- package/dist/client/assets/{ProjectNavigationDialogs-CO6Pu3yg.js → ProjectNavigationDialogs-CYY6XsGS.js} +1 -1
- package/dist/client/assets/{SystemMetricsDialog-DuOeZDPw.js → SystemMetricsDialog-D960tY84.js} +1 -1
- package/dist/client/assets/binary-B_l95ePC.js +1 -0
- package/dist/client/assets/{index-BH1SnL1-.js → index-BNDmKLSB.js} +1 -1
- package/dist/client/assets/{index-DIKn1Ihd.js → index-BzkNLkyK.js} +4 -4
- package/dist/client/assets/index-CUa7L47p.css +1 -0
- package/dist/client/assets/{plus-yvkxQFZU.js → plus-Dd-ee1VQ.js} +1 -1
- package/dist/client/assets/{spellCheck-BsMZuUSw.js → spellCheck-C1kZMEs3.js} +3 -3
- package/dist/client/index.html +2 -2
- package/package.json +1 -1
- package/dist/client/assets/binary-DJ-aNxyD.js +0 -1
- package/dist/client/assets/index-DlxzfyKI.css +0 -1
|
@@ -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-
|
|
2
|
-
import{i as Ih,r as h,j as o,R as er,a as yl,b as Mh,u as _e,P as $h,c as Cr,d as Li,e as Uh}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 zh="modulepreload",Vh=function(t){return"/"+t},Za={},Qt=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=Vh(d),d in Za)return;Za[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":zh,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)})},Bh="0.5.2";var Ai={};const K=t=>typeof t=="string",Ls=()=>{let t,e;const n=new Promise((s,r)=>{t=s,e=r});return n.resolve=t,n.reject=e,n},Qa=t=>t==null?"":""+t,Hh=(t,e,n)=>{t.forEach(s=>{e[s]&&(n[s]=e[s])})},qh=/###/g,ec=t=>t&&t.indexOf("###")>-1?t.replace(qh,"."):t,tc=t=>!t||K(t),Is=(t,e,n)=>{const s=K(e)?e.split("."):e;let r=0;for(;r<s.length-1;){if(tc(t))return{};const i=ec(s[r]);!t[i]&&n&&(t[i]=new n),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++r}return tc(t)?{}:{obj:t,k:ec(s[r])}},nc=(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},Wh=(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]},Kh=(t,e,n)=>{const s=$r(t,n);return s!==void 0?s:$r(e,n)},wl=(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]):wl(t[s],e[s],n):t[s]=e[s]);return t},vn=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Gh={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Jh=t=>K(t)?t.replace(/[&<>"'\/]/g,e=>Gh[e]):t;class Yh{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 Xh=[" ",",","?","!",";"],Zh=new Yh(20),Qh=(t,e,n)=>{e=e||"",n=n||"";const s=Xh.filter(a=>e.indexOf(a)<0&&n.indexOf(a)<0);if(s.length===0)return!0;const r=Zh.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},ao=(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,"-"),ef={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||ef,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 Pt=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 sc 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:ao(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),nc(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?wl(l,s,i):l={...l,...s},nc(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 xl={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 bl=Symbol("i18next/PATH_KEY");function tf(){const t=[],e=Object.create(null);let n;return e.get=(s,r)=>(n?.revoke?.(),r===bl?t:(t.push(r),n=Proxy.revocable(s,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function ts(t,e){const{[bl]:n}=t(tf()),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 rc={},Fi=t=>!K(t)&&typeof t!="boolean"&&typeof t!="number";class zr extends oi{constructor(e,n={}){super(),Hh(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Pt.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=Fi(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&&!Qh(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=ts(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(_=>typeof _=="function"?ts(_,{...this.options,...r}):String(_));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,C=["[object Number]","[object Function]","[object RegExp]"],k=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,D=!this.i18nFormat||this.i18nFormat.handleAsObject,T=r.count!==void 0&&!K(r.count),O=zr.hasDefaultValue(r),F=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${F}`]||r[`defaultValue${E}`]||r.defaultValue;let P=g;D&&!g&&O&&(P=v);const X=Fi(P),W=Object.prototype.toString.apply(P);if(D&&P&&X&&C.indexOf(W)<0&&!(K(k)&&Array.isArray(P))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const _=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,P,{...r,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return i?(p.res=_,p.usedParams=this.getUsedParamsDetails(r),p):_}if(a){const _=Array.isArray(P),R=_?[]:{},S=_?b:x;for(const M in P)if(Object.prototype.hasOwnProperty.call(P,M)){const ue=`${S}${a}${M}`;O&&!g?R[M]=this.translate(ue,{...r,defaultValue:Fi(v)?v[M]:void 0,joinArrays:!1,ns:l}):R[M]=this.translate(ue,{...r,joinArrays:!1,ns:l}),R[M]===ue&&(R[M]=P[M])}g=R}}else if(D&&K(k)&&Array.isArray(g))g=g.join(k),g&&(g=this.extendTranslation(g,e,r,s));else{let _=!1,R=!1;!this.isValidLookup(g)&&O&&(_=!0,g=v),this.isValidLookup(g)||(R=!0,g=c);const M=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&R?void 0:g,ue=O&&v!==g&&this.options.updateMissing;if(R||_||ue){if(this.logger.log(ue?"updateKey":"missingKey",u,d,c,ue?v:g),a){const ee=this.resolve(c,{...r,keySeparator:!1});ee&&ee.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 se=[];const be=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&be&&be[0])for(let ee=0;ee<be.length;ee++)se.push(be[ee]);else this.options.saveMissingTo==="all"?se=this.languageUtils.toResolveHierarchy(r.lng||this.language):se.push(r.lng||this.language);const Q=(ee,ce,xe)=>{const ie=O&&xe!==g?xe:M;this.options.missingKeyHandler?this.options.missingKeyHandler(ee,d,ce,ie,ue,r):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(ee,d,ce,ie,ue,r),this.emit("missingKey",ee,d,ce,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&T?se.forEach(ee=>{const ce=this.pluralResolver.getSuffixes(ee,r);q&&r[`defaultValue${this.options.pluralSeparator}zero`]&&ce.indexOf(`${this.options.pluralSeparator}zero`)<0&&ce.push(`${this.options.pluralSeparator}zero`),ce.forEach(xe=>{Q([ee],c+xe,r[`defaultValue${xe}`]||v)})}):Q(se,c,v))}g=this.extendTranslation(g,e,r,p,s),R&&g===c&&this.options.appendNamespaceToMissingKey&&(g=`${d}${f}${c}`),(R||_)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${f}${c}`:c,_?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=xl.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"?ts(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,!rc[`${x[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(rc[`${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(C=>{if(this.isValidLookup(s))return;a=C;const k=[f];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(k,f,C,b,n);else{let T;m&&(T=this.pluralResolver.getSuffix(C,n.count,n));const O=`${this.options.pluralSeparator}zero`,F=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(n.ordinal&&T.indexOf(F)===0&&k.push(f+T.replace(F,this.options.pluralSeparator)),k.push(f+T),p&&k.push(f+O)),g){const E=`${f}${this.options.contextSeparator||"_"}${n.context}`;k.push(E),m&&(n.ordinal&&T.indexOf(F)===0&&k.push(E+T.replace(F,this.options.pluralSeparator)),k.push(E+T),p&&k.push(E+O))}}let D;for(;D=k.pop();)this.isValidLookup(s)||(i=D,s=this.getResource(C,b,D,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 ic{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Pt.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 oc={zero:0,one:1,two:2,few:3,many:4,other:5},ac={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class nf{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Pt.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!"),ac;if(!e.match(/-|_/))return ac;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)=>oc[r]-oc[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 cc=(t,e,n,s=".",r=!0)=>{let i=Kh(t,e,n);return!i&&r&&K(n)&&(i=ao(t,n,s),i===void 0&&(i=ao(e,n,s))),i},Ii=t=>t.replace(/\$/g,"$$$$");class lc{constructor(e={}){this.logger=Pt.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:C,alwaysFormat:k}=e.interpolation;this.escape=n!==void 0?n:Jh,this.escapeValue=s!==void 0?s:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=i?vn(i):a||"{{",this.suffix=c?vn(c):l||"}}",this.formatSeparator=d||",",this.unescapePrefix=f?"":u||"-",this.unescapeSuffix=this.unescapePrefix?"":f||"",this.nestingPrefix=m?vn(m):p||vn("$t("),this.nestingSuffix=g?vn(g):x||vn(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=C||1e3,this.alwaysFormat=k!==void 0?k:!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 C=cc(n,l,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(C,void 0,s,{...r,...n,interpolationkey:p}):C}const g=p.split(this.formatSeparator),x=g.shift().trim(),b=g.join(this.formatSeparator).trim();return this.format(cc(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=>Ii(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?Ii(this.escape(p)):Ii(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=Qa(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(`${vn(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=Qa(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 sf=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}},dc=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)}},rf=t=>(e,n,s)=>t(Us(n),s)(e);class of{constructor(e={}){this.logger=Pt.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const s=n.cacheInBuiltFormats?dc:rf;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()]=dc(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}=sf(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 af=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class cf 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=Pt.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=>{Wh(l.loaded,[i],a),af(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 Mi=()=>({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}),uc=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),jr=()=>{},lf=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})},vl="__i18next_supportNoticeShown",df=()=>!!(typeof globalThis<"u"&&globalThis[vl]||typeof process<"u"&&Ai&&Ai.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&Ai),uf=()=>{typeof globalThis<"u"&&(globalThis[vl]=!0)},hf=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=uc(e),this.services={},this.logger=Pt,this.modules={external:[]},lf(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=Mi();this.options={...s,...this.options,...uc(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&&!hf(this)&&!df()&&(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 💙"),uf());const r=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Pt.init(r(this.modules.logger),this.options):Pt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=of;const f=new ic(this.options);this.store=new sc(this.options.resources,this.options);const u=this.services;u.logger=Pt,u.resourceStore=this.store,u.languageUtils=f,u.pluralResolver=new nf(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 lc(this.options),u.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},u.backendConnector=new cf(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=jr),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=Ls(),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=jr){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=Ls();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=jr),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"&&xl.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=Ls();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=ts(l.keyPrefix,d));const f=this.options.keySeparator||".";let u;return l.keyPrefix&&Array.isArray(i)?u=i.map(m=>(typeof m=="function"&&(m=ts(m,d)),`${l.keyPrefix}${f}${m}`)):(typeof i=="function"&&(i=ts(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=Ls();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=Ls();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 ic(Mi());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=jr){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 sc(c,r),i.services.resourceStore=i.store}if(e.interpolation){const l={...Mi().interpolation,...this.options.interpolation,...e.interpolation},d={...r,interpolation:l};i.services.interpolator=new lc(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:ff,forEach:pf}=[];function mf(t){return pf.call(ff.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function gf(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 hc=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,yf=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(!hc.test(s.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${s.domain}`}if(s.path){if(!hc.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},fc={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=yf(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 wf={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return fc.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:r,cookieOptions:i}=e;n&&typeof document<"u"&&fc.create(n,t,s,r,i)}},xf={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}},bf={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 Vn=null;const pc=()=>{if(Vn!==null)return Vn;try{if(Vn=typeof window<"u"&&window.localStorage!==null,!Vn)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Vn=!1}return Vn};var vf={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&pc())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&pc()&&window.localStorage.setItem(n,t)}};let Bn=null;const mc=()=>{if(Bn!==null)return Bn;try{if(Bn=typeof window<"u"&&window.sessionStorage!==null,!Bn)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Bn=!1}return Bn};var Sf={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&mc())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&mc()&&window.sessionStorage.setItem(n,t)}},Cf={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}},jf={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}},kf={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}},Ef={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 Sl=!1;try{document.cookie,Sl=!0}catch{}const Cl=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Sl||Cl.splice(1,1);const Df=()=>({order:Cl,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class jl{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=mf(n,this.options||{},Df()),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(wf),this.addDetector(xf),this.addDetector(vf),this.addDetector(Sf),this.addDetector(Cf),this.addDetector(jf),this.addDetector(kf),this.addDetector(Ef),this.addDetector(bf)}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&&!gf(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)}))}}jl.type="languageDetector";const Nf={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:"中文"},Tf={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"},Of={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"},Pf={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"},_f={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",clean:"Recovery",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",cleanTitle:"Compilation recovery",cleanDescription:"Use these advanced actions only when compilation is stuck, a previous error is left behind, or generated output is inconsistent. They do not change source files, project settings, comments, history, or Git data.",cleanCache:"Force a clean rebuild",cleanCacheDescription:"Use after a compilation failure or stale latexmk state. Removes the incremental cache while keeping the current successful PDF.",cleanArtifacts:"Remove generated output",cleanArtifactsDescription:"Use when generated files are inconsistent. Removes the PDF, SyncTeX, logs, and intermediate files for this root document.",cleanCacheConfirmTitle:"Force a clean rebuild?",cleanCacheConfirmDescription:"This recovery action removes the incremental latexmk cache. The current PDF remains visible, and the next compilation starts from a clean cache.",cleanArtifactsConfirmTitle:"Remove generated output?",cleanArtifactsConfirmDescription:"This recovery action removes the current PDF and all generated files for this root document. Source files are not affected.",cleanConfirm:"Run recovery",cleanCacheComplete:"Recovery cache cleared. The next compilation will be a full rebuild.",cleanArtifactsComplete:"Generated compilation output removed.",cleanBusy:"This root document is compiling. Try recovery again after it finishes.",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.",writingSuggestions:"Writing suggestions",noWritingSuggestions:"No suggestions available",removeText:"Remove text",replaceWith:"Replace with {{word}}",spellCheckReadOnly:"Read-only: choose a suggestion in an editor with write permission.",spellCheckSourceChanged:"The source changed before the writing correction could be applied.",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",pdfLink:"PDF link",pdfLinks:"PDF links",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"}},Rf={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."},Lf={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"}},Af={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-C1kZMEs3.js","assets/PdfPreview-BaOpY89K.js","assets/pdf-DPnwNQHb.js","assets/plus-Dd-ee1VQ.js","assets/LatexEditor-0ijwz3Ud.js","assets/editor-DMLs-XWi.js","assets/GitDialog-DPK1_Lf7.js","assets/HistoryDialog-wKZ0ECpn.js","assets/ProjectNavigationDialogs-CYY6XsGS.js","assets/SystemMetricsDialog-D960tY84.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{i as Ih,r as h,j as o,R as er,a as yl,b as Mh,u as _e,P as $h,c as Cr,d as Li,e as Uh}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 zh="modulepreload",Vh=function(t){return"/"+t},Za={},Qt=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=Vh(d),d in Za)return;Za[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":zh,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)})},Bh="0.5.4";var Ai={};const K=t=>typeof t=="string",Ls=()=>{let t,e;const n=new Promise((s,r)=>{t=s,e=r});return n.resolve=t,n.reject=e,n},Qa=t=>t==null?"":""+t,Hh=(t,e,n)=>{t.forEach(s=>{e[s]&&(n[s]=e[s])})},qh=/###/g,ec=t=>t&&t.indexOf("###")>-1?t.replace(qh,"."):t,tc=t=>!t||K(t),Is=(t,e,n)=>{const s=K(e)?e.split("."):e;let r=0;for(;r<s.length-1;){if(tc(t))return{};const i=ec(s[r]);!t[i]&&n&&(t[i]=new n),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++r}return tc(t)?{}:{obj:t,k:ec(s[r])}},nc=(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},Wh=(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]},Kh=(t,e,n)=>{const s=$r(t,n);return s!==void 0?s:$r(e,n)},wl=(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]):wl(t[s],e[s],n):t[s]=e[s]);return t},vn=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Gh={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Jh=t=>K(t)?t.replace(/[&<>"'\/]/g,e=>Gh[e]):t;class Yh{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 Xh=[" ",",","?","!",";"],Zh=new Yh(20),Qh=(t,e,n)=>{e=e||"",n=n||"";const s=Xh.filter(a=>e.indexOf(a)<0&&n.indexOf(a)<0);if(s.length===0)return!0;const r=Zh.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},ao=(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,"-"),ef={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||ef,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 Pt=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 sc 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:ao(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),nc(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?wl(l,s,i):l={...l,...s},nc(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 xl={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 bl=Symbol("i18next/PATH_KEY");function tf(){const t=[],e=Object.create(null);let n;return e.get=(s,r)=>(n?.revoke?.(),r===bl?t:(t.push(r),n=Proxy.revocable(s,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function ts(t,e){const{[bl]:n}=t(tf()),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 rc={},Fi=t=>!K(t)&&typeof t!="boolean"&&typeof t!="number";class zr extends oi{constructor(e,n={}){super(),Hh(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Pt.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=Fi(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&&!Qh(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=ts(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(_=>typeof _=="function"?ts(_,{...this.options,...r}):String(_));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,C=["[object Number]","[object Function]","[object RegExp]"],k=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,D=!this.i18nFormat||this.i18nFormat.handleAsObject,T=r.count!==void 0&&!K(r.count),O=zr.hasDefaultValue(r),F=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${F}`]||r[`defaultValue${E}`]||r.defaultValue;let P=g;D&&!g&&O&&(P=v);const X=Fi(P),W=Object.prototype.toString.apply(P);if(D&&P&&X&&C.indexOf(W)<0&&!(K(k)&&Array.isArray(P))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const _=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,P,{...r,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return i?(p.res=_,p.usedParams=this.getUsedParamsDetails(r),p):_}if(a){const _=Array.isArray(P),R=_?[]:{},S=_?b:x;for(const M in P)if(Object.prototype.hasOwnProperty.call(P,M)){const ue=`${S}${a}${M}`;O&&!g?R[M]=this.translate(ue,{...r,defaultValue:Fi(v)?v[M]:void 0,joinArrays:!1,ns:l}):R[M]=this.translate(ue,{...r,joinArrays:!1,ns:l}),R[M]===ue&&(R[M]=P[M])}g=R}}else if(D&&K(k)&&Array.isArray(g))g=g.join(k),g&&(g=this.extendTranslation(g,e,r,s));else{let _=!1,R=!1;!this.isValidLookup(g)&&O&&(_=!0,g=v),this.isValidLookup(g)||(R=!0,g=c);const M=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&R?void 0:g,ue=O&&v!==g&&this.options.updateMissing;if(R||_||ue){if(this.logger.log(ue?"updateKey":"missingKey",u,d,c,ue?v:g),a){const ee=this.resolve(c,{...r,keySeparator:!1});ee&&ee.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 se=[];const be=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&be&&be[0])for(let ee=0;ee<be.length;ee++)se.push(be[ee]);else this.options.saveMissingTo==="all"?se=this.languageUtils.toResolveHierarchy(r.lng||this.language):se.push(r.lng||this.language);const Q=(ee,ce,xe)=>{const ie=O&&xe!==g?xe:M;this.options.missingKeyHandler?this.options.missingKeyHandler(ee,d,ce,ie,ue,r):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(ee,d,ce,ie,ue,r),this.emit("missingKey",ee,d,ce,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&T?se.forEach(ee=>{const ce=this.pluralResolver.getSuffixes(ee,r);q&&r[`defaultValue${this.options.pluralSeparator}zero`]&&ce.indexOf(`${this.options.pluralSeparator}zero`)<0&&ce.push(`${this.options.pluralSeparator}zero`),ce.forEach(xe=>{Q([ee],c+xe,r[`defaultValue${xe}`]||v)})}):Q(se,c,v))}g=this.extendTranslation(g,e,r,p,s),R&&g===c&&this.options.appendNamespaceToMissingKey&&(g=`${d}${f}${c}`),(R||_)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${f}${c}`:c,_?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=xl.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"?ts(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,!rc[`${x[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(rc[`${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(C=>{if(this.isValidLookup(s))return;a=C;const k=[f];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(k,f,C,b,n);else{let T;m&&(T=this.pluralResolver.getSuffix(C,n.count,n));const O=`${this.options.pluralSeparator}zero`,F=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(n.ordinal&&T.indexOf(F)===0&&k.push(f+T.replace(F,this.options.pluralSeparator)),k.push(f+T),p&&k.push(f+O)),g){const E=`${f}${this.options.contextSeparator||"_"}${n.context}`;k.push(E),m&&(n.ordinal&&T.indexOf(F)===0&&k.push(E+T.replace(F,this.options.pluralSeparator)),k.push(E+T),p&&k.push(E+O))}}let D;for(;D=k.pop();)this.isValidLookup(s)||(i=D,s=this.getResource(C,b,D,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 ic{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Pt.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 oc={zero:0,one:1,two:2,few:3,many:4,other:5},ac={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class nf{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Pt.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!"),ac;if(!e.match(/-|_/))return ac;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)=>oc[r]-oc[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 cc=(t,e,n,s=".",r=!0)=>{let i=Kh(t,e,n);return!i&&r&&K(n)&&(i=ao(t,n,s),i===void 0&&(i=ao(e,n,s))),i},Ii=t=>t.replace(/\$/g,"$$$$");class lc{constructor(e={}){this.logger=Pt.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:C,alwaysFormat:k}=e.interpolation;this.escape=n!==void 0?n:Jh,this.escapeValue=s!==void 0?s:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=i?vn(i):a||"{{",this.suffix=c?vn(c):l||"}}",this.formatSeparator=d||",",this.unescapePrefix=f?"":u||"-",this.unescapeSuffix=this.unescapePrefix?"":f||"",this.nestingPrefix=m?vn(m):p||vn("$t("),this.nestingSuffix=g?vn(g):x||vn(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=C||1e3,this.alwaysFormat=k!==void 0?k:!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 C=cc(n,l,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(C,void 0,s,{...r,...n,interpolationkey:p}):C}const g=p.split(this.formatSeparator),x=g.shift().trim(),b=g.join(this.formatSeparator).trim();return this.format(cc(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=>Ii(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?Ii(this.escape(p)):Ii(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=Qa(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(`${vn(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=Qa(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 sf=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}},dc=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)}},rf=t=>(e,n,s)=>t(Us(n),s)(e);class of{constructor(e={}){this.logger=Pt.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const s=n.cacheInBuiltFormats?dc:rf;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()]=dc(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}=sf(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 af=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class cf 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=Pt.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=>{Wh(l.loaded,[i],a),af(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 Mi=()=>({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}),uc=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),jr=()=>{},lf=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})},vl="__i18next_supportNoticeShown",df=()=>!!(typeof globalThis<"u"&&globalThis[vl]||typeof process<"u"&&Ai&&Ai.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&Ai),uf=()=>{typeof globalThis<"u"&&(globalThis[vl]=!0)},hf=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=uc(e),this.services={},this.logger=Pt,this.modules={external:[]},lf(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=Mi();this.options={...s,...this.options,...uc(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&&!hf(this)&&!df()&&(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 💙"),uf());const r=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Pt.init(r(this.modules.logger),this.options):Pt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=of;const f=new ic(this.options);this.store=new sc(this.options.resources,this.options);const u=this.services;u.logger=Pt,u.resourceStore=this.store,u.languageUtils=f,u.pluralResolver=new nf(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 lc(this.options),u.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},u.backendConnector=new cf(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=jr),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=Ls(),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=jr){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=Ls();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=jr),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"&&xl.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=Ls();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=ts(l.keyPrefix,d));const f=this.options.keySeparator||".";let u;return l.keyPrefix&&Array.isArray(i)?u=i.map(m=>(typeof m=="function"&&(m=ts(m,d)),`${l.keyPrefix}${f}${m}`)):(typeof i=="function"&&(i=ts(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=Ls();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=Ls();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 ic(Mi());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=jr){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 sc(c,r),i.services.resourceStore=i.store}if(e.interpolation){const l={...Mi().interpolation,...this.options.interpolation,...e.interpolation},d={...r,interpolation:l};i.services.interpolator=new lc(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:ff,forEach:pf}=[];function mf(t){return pf.call(ff.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function gf(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 hc=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,yf=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(!hc.test(s.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${s.domain}`}if(s.path){if(!hc.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},fc={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=yf(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 wf={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return fc.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:s,cookieDomain:r,cookieOptions:i}=e;n&&typeof document<"u"&&fc.create(n,t,s,r,i)}},xf={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}},bf={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 Vn=null;const pc=()=>{if(Vn!==null)return Vn;try{if(Vn=typeof window<"u"&&window.localStorage!==null,!Vn)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Vn=!1}return Vn};var vf={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&pc())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&pc()&&window.localStorage.setItem(n,t)}};let Bn=null;const mc=()=>{if(Bn!==null)return Bn;try{if(Bn=typeof window<"u"&&window.sessionStorage!==null,!Bn)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Bn=!1}return Bn};var Sf={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&mc())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&mc()&&window.sessionStorage.setItem(n,t)}},Cf={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}},jf={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}},kf={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}},Ef={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 Sl=!1;try{document.cookie,Sl=!0}catch{}const Cl=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Sl||Cl.splice(1,1);const Df=()=>({order:Cl,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class jl{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=mf(n,this.options||{},Df()),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(wf),this.addDetector(xf),this.addDetector(vf),this.addDetector(Sf),this.addDetector(Cf),this.addDetector(jf),this.addDetector(kf),this.addDetector(Ef),this.addDetector(bf)}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&&!gf(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)}))}}jl.type="languageDetector";const Nf={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:"中文"},Tf={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"},Of={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"},Pf={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"},_f={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",clean:"Recovery",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",cleanTitle:"Compilation recovery",cleanDescription:"Use these advanced actions only when compilation is stuck, a previous error is left behind, or generated output is inconsistent. They do not change source files, project settings, comments, history, or Git data.",cleanCache:"Force a clean rebuild",cleanCacheDescription:"Use after a compilation failure or stale latexmk state. Removes the incremental cache while keeping the current successful PDF.",cleanArtifacts:"Remove generated output",cleanArtifactsDescription:"Use when generated files are inconsistent. Removes the PDF, SyncTeX, logs, and intermediate files for this root document.",cleanCacheConfirmTitle:"Force a clean rebuild?",cleanCacheConfirmDescription:"This recovery action removes the incremental latexmk cache. The current PDF remains visible, and the next compilation starts from a clean cache.",cleanArtifactsConfirmTitle:"Remove generated output?",cleanArtifactsConfirmDescription:"This recovery action removes the current PDF and all generated files for this root document. Source files are not affected.",cleanConfirm:"Run recovery",cleanCacheComplete:"Recovery cache cleared. The next compilation will be a full rebuild.",cleanArtifactsComplete:"Generated compilation output removed.",cleanBusy:"This root document is compiling. Try recovery again after it finishes.",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.",writingSuggestions:"Writing suggestions",noWritingSuggestions:"No suggestions available",removeText:"Remove text",replaceWith:"Replace with {{word}}",spellCheckReadOnly:"Read-only: choose a suggestion in an editor with write permission.",spellCheckSourceChanged:"The source changed before the writing correction could be applied.",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",pdfLink:"PDF link",pdfLinks:"PDF links",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"}},Rf={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."},Lf={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"}},Af={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",writingCheckDescription:"Harper runs locally in a worker. Spelling issues use a red wavy underline; grammar issues use yellow. Right-click an issue for suggestions.",projectConfiguration:"Project configuration",fontFamily:"English font",fontSize:"Font size",lineHeight:"Line spacing",dictionary:"Project dictionary",dictionaryDescription:"Words added here are imported into Harper's custom dictionary and ignored by spelling checks 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:"Spelling and grammar 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",writingIssues:"{{count}} writing issues ({{uniqueCount}} unique)",noWritingIssues:"No spelling or grammar issues found.",spellCheckFirst:"First writing issue",spellCheckPrevious:"Previous writing issue",spellCheckNext:"Next writing issue",spellCheckLast:"Last writing 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"},Ff={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"},If={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"}}},Mf={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"},$f={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."}},Uf={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."},zf={copyright:"© {{year}}",credit:"Designed and developed by CHEN Zhongpu"},Vf={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"},Bf={common:Nf,auth:Tf,projects:Of,users:Pf,editor:_f,navigation:Rf,history:Lf,projectSettings:Af,git:Ff,metrics:If,tags:Mf,errors:$f,apiErrors:Uf,footer:zf,completions:Vf},Hf={cancel:"取消",create:"创建",add:"添加",remove:"移除",delete:"删除",close:"关闭",user:"用户",permission:"权限",readOnly:"只读",readWrite:"读写",settings:"设置",comments:"批注",files:"文件",outline:"大纲",loading:"正在载入…",enabled:"允许",disabled:"禁止",normal:"正常",admin:"管理员",language:"语言",languageEnglish:"English",languageChinese:"中文"},qf={tagline:"轻量 LaTeX 写作环境",username:"用户名",password:"密码",login:"登录",contact:"需要账号?请联系 {{email}}",firstLogin:"首次登录,请修改初始密码",currentPassword:"当前密码",newPassword:"新密码",confirmPassword:"确认新密码",updatePassword:"更新密码",mismatch:"两次输入的新密码不一致",passwordMinimum:"至少 {{count}} 位",sessionExpired:"登录状态已过期,请重新登录。",logout:"退出"},Wf={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:"清除已选文件"},Kf={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:"永久删除项目及全部文件"},Gf={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:"产物",clean:"故障恢复",noLog:"编译后将在此显示日志。",noWarnings:"最近一次编译没有警告。",noErrors:"最近一次编译没有错误。",projectRoot:"项目根目录",uploadTo:"上传到 {{folder}}",dropFiles:"拖放文件以上传",newFolder:"新建文件夹",folderName:"文件夹名称",folderDestination:"文件夹将创建在 {{folder}} 中。",uploadOverwriteTitle:"文件已存在",uploadOverwriteDescription:"以下文件已经存在:{{files}}。要覆盖它们吗?",uploadOverwrite:"覆盖文件",noArtifacts:"编译后将在此显示输出产物。",selectArtifact:"选择一个文本产物进行预览。",viewArtifact:"查看产物",downloadArtifact:"下载产物",downloadToView:"该产物需要下载后查看",cleanTitle:"编译故障恢复",cleanDescription:"这里只提供高级故障恢复操作:仅在编译卡住、历史错误状态残留或生成产物异常时使用。不会修改源码、项目设置、批注、历史或 Git 数据。",cleanCache:"强制完整重编译",cleanCacheDescription:"仅在编译失败或 latexmk 缓存状态异常时使用。删除增量缓存,但保留当前成功的 PDF。",cleanArtifacts:"删除生成输出",cleanArtifactsDescription:"仅在生成产物状态异常时使用。删除该主文档的 PDF、SyncTeX、日志和中间文件。",cleanCacheConfirmTitle:"强制完整重编译?",cleanCacheConfirmDescription:"此故障恢复操作会删除 latexmk 增量缓存。当前 PDF 会保留,下一次编译将从干净缓存开始。",cleanArtifactsConfirmTitle:"删除生成输出?",cleanArtifactsConfirmDescription:"此故障恢复操作会删除当前 PDF 以及该主文档的全部生成文件,但不会影响源码。",cleanConfirm:"执行恢复",cleanCacheComplete:"故障恢复缓存已清理,下一次编译将完整执行。",cleanArtifactsComplete:"编译生成输出已删除。",cleanBusy:"当前主文档正在编译,请完成后再执行故障恢复。",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:"格式化期间所选源码已发生变化,请重新选择后再试。",writingSuggestions:"写作建议",noWritingSuggestions:"没有可用的修改建议",removeText:"删除文本",replaceWith:"替换为 {{word}}",spellCheckReadOnly:"当前为只读,需要编辑权限才能替换。",spellCheckSourceChanged:"源码在应用写作修正前发生了变化。",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:"适合宽度",pdfLink:"PDF 链接",pdfLinks:"PDF 链接",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:"正则表达式无效"}},Jf={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}} 项。"},Yf={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:"安全检查点"}},Xf={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:"保存编译器设置",writingCheckDescription:"Harper 在浏览器本地 worker 中运行。拼写问题使用红色波浪线,语法问题使用黄色波浪线;右键问题可以查看修改建议。",projectConfiguration:"项目配置",fontFamily:"英文字体",fontSize:"字体大小",lineHeight:"行间距",dictionary:"项目词典",dictionaryDescription:"添加到这里的词会导入 Harper 的自定义词典,并在本项目的拼写检查中忽略;具有编辑权限的用户可以维护此列表。",dictionaryPlaceholder:"添加自定义词",addWord:"添加词",dictionaryEmpty:"暂未添加自定义词。",lineWrapping:"自动换行",spellCheck:"拼写和语法检查",vimMode:"Vim 键位",vimModeDescription:"在当前编辑器中使用 Vim 的普通、插入和可视模式。",vimHelp:"查看帮助",formatOnCompile:"编译前自动格式化 LaTeX",formatOnCompileDescription:"默认关闭;格式化会在服务器编译前执行。",formatRequiresWrite:"需要项目编辑权限才能使用格式化。",formatterDescription:"格式化使用宿主机上的可选 tex-fmt 命令。",formatterInstall:"安装或查看 tex-fmt 文档",writingIssues:"发现 {{count}} 个写作问题(去重后 {{uniqueCount}} 个)",noWritingIssues:"未发现拼写或语法问题。",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:"宽松"},Zf={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:"确认撤销"},Qf={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:"生成补全索引"}}},ep={title:"标签",add:"添加标签",create:"新建标签",createDescription:"创建仅自己可见的可复用彩色标签,用于整理项目。",assign:"标签",assignTitle:"“{{project}}”的标签",assignDescription:"勾选你为此项目设置的私有标签;其他用户拥有各自的标签。",empty:"请先创建标签。",allAssigned:"所有可用标签均已添加。",name:"标签名称",color:"颜色",filter:"筛选",red:"红色",orange:"橙色",yellow:"黄色",green:"绿色",blue:"蓝色",purple:"紫色",gray:"灰色"},tp={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:"请求格式无效。"}},np={historyVersionNotFound:"所选历史版本已不存在。",historyFileNotFound:"所选历史版本中没有这个文件。",historyPreviewUnsupported:"这个历史文件不能作为文本比较。",searchInvalid:"请输入有效的搜索内容。",gitUnavailable:"Git 集成功能不可用。请在宿主机安装 Git,或修正配置中的 git.binary 后重试。",formatterUnavailable:"宿主机未安装 tex-fmt。请访问 https://github.com/wgunderwood/tex-fmt 安装后重启 TexLite。",formatFailed:"tex-fmt 无法格式化这段源码。",mainDocumentInvalid:"所选文件不是有效的 LaTeX 主文档。"},sp={copyright:"© {{year}}",credit:"Designed and developed by CHEN Zhongpu"},rp={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 命令"},ip={common:Hf,auth:qf,projects:Wf,users:Kf,editor:Gf,navigation:Jf,history:Yf,projectSettings:Xf,git:Zf,metrics:Qf,tags:ep,errors:tp,apiErrors:np,footer:sp,completions:rp};we.use(jl).use(Ih).init({resources:{en:{translation:Bf},zh:{translation:ip}},fallbackLng:"en",supportedLngs:["en","zh"],nonExplicitSupportedLngs:!0,interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator"],caches:["localStorage"]}});class Io 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 Io(Mo(r,n.status),n.status,kl(r));return r}function Mo(t,e,n="errors.request"){const s=typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:"",r=kl(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",COMPILE_CLEAN_BUSY:"editor.cleanBusy"}[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 kl(t){return typeof t!="object"||t===null||!("code"in t)||typeof t.code!="string"?null:t.code}var op=Object.defineProperty,vs=(t,e)=>op(t,"name",{value:e,configurable:!0}),El=!!(typeof window<"u"&&window.document&&window.document.createElement);function an(t,e,{checkForDefaultPrevented:n=!0}={}){return vs(function(r){if(t?.(r),n===!1||!r||!r.defaultPrevented)return e?.(r)},"handleEvent")}vs(an,"composeEventHandlers");function ap(t){if(!El)throw new Error("Cannot access window outside of the DOM");return t?.ownerDocument?.defaultView??window}vs(ap,"getOwnerWindow");function co(t){if(!El)throw new Error("Cannot access document outside of the DOM");return t?.ownerDocument??document}vs(co,"getOwnerDocument");function Dl(t,e=!1){const{activeElement:n}=co(t);if(!n?.nodeName)return null;if(Nl(n)&&n.contentDocument)return Dl(n.contentDocument.body,e);if(e){const s=n.getAttribute("aria-activedescendant");if(s){const r=co(n).getElementById(s);if(r)return r}}return n}vs(Dl,"getActiveElement");function Nl(t){return t.tagName==="IFRAME"}vs(Nl,"isFrame");var cp=Object.defineProperty,$o=(t,e)=>cp(t,"name",{value:e,configurable:!0});function lo(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}$o(lo,"setRef");function Tl(...t){return e=>{let n=!1;const s=t.map(r=>{const i=lo(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():lo(t[r],null)}}}}$o(Tl,"composeRefs");function Ss(...t){return h.useCallback(Tl(...t),t)}$o(Ss,"useComposedRefs");var lp=Object.defineProperty,ft=(t,e)=>lp(t,"name",{value:e,configurable:!0});function dp(t,e){const n=h.createContext(e);n.displayName=t+"Context";const s=ft(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 ft(r,"useContext"),[s,r]}ft(dp,"createContext");function Ol(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=ft(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 ft(f,"useContext"),[d,f]}ft(s,"createContext");const r=ft(()=>{const i=n.map(a=>h.createContext(a));return ft(function(c){const l=c?.[t]||i;return h.useMemo(()=>({[`__scope${t}`]:{...c,[t]:l}}),[c,l])},"useScope")},"createScope");return r.scopeName=t,[s,Pl(r,...e)]}ft(Ol,"createContextScope");function Pl(...t){const e=t[0];if(t.length===1)return e;const n=ft(()=>{const s=t.map(r=>({useScope:r(),scopeName:r.scopeName}));return ft(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}ft(Pl,"composeContextScopes");var cn=globalThis?.document?h.useLayoutEffect:()=>{},up=Object.defineProperty,hp=(t,e)=>up(t,"name",{value:e,configurable:!0}),fp=er[" useId ".trim().toString()]||(()=>{}),pp=0;function Rr(t){const[e,n]=h.useState(fp());return cn(()=>{t||n(s=>s??String(pp++))},[t]),t||(e?`radix-${e}`:"")}hp(Rr,"useId");var mp=Object.defineProperty,gp=(t,e)=>mp(t,"name",{value:e,configurable:!0}),gc=er[" useEffectEvent ".trim().toString()],yc=er[" useInsertionEffect ".trim().toString()];function _l(t){if(typeof gc=="function")return gc(t);const e=h.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof yc=="function"?yc(()=>{e.current=t}):cn(()=>{e.current=t}),h.useMemo(()=>((...n)=>e.current?.(...n)),[])}gp(_l,"useEffectEvent");var yp=Object.defineProperty,tr=(t,e)=>yp(t,"name",{value:e,configurable:!0}),wp=er[" useInsertionEffect ".trim().toString()]||cn;function Rl({prop:t,defaultProp:e,onChange:n=tr(()=>{},"onChange"),caller:s}){const[r,i,a]=Ll({defaultProp:e,onChange:n}),c=t!==void 0,l=c?t:r,d=h.useCallback(f=>{if(c){const u=Al(f)?f(t):f;u!==t&&a.current?.(u)}else i(f)},[c,t,i,a]);return[l,d]}tr(Rl,"useControllableState");function Ll({defaultProp:t,onChange:e}){const[n,s]=h.useState(t),r=h.useRef(n),i=h.useRef(e);return wp(()=>{i.current=e},[e]),h.useEffect(()=>{r.current!==n&&(i.current?.(n),r.current=n)},[n,r]),[n,s,i]}tr(Ll,"useUncontrolledState");function Al(t){return typeof t=="function"}tr(Al,"isFunction");var wc=Symbol("RADIX:SYNC_STATE");function xp(t,e,n,s){const{prop:r,defaultProp:i,onChange:a,caller:c}=e,l=r!==void 0,d=_l(a),f=[{...n,state:i}];s&&f.push(s);const[u,m]=h.useReducer((b,C)=>{if(C.type===wc)return{...b,state:C.state};const k=t(b,C);return l&&!Object.is(k.state,b.state)&&d(k.state),k},...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:wc,state:r})},[r,u.state,l]),[x,m]}tr(xp,"useControllableStateReducer");var bp=Object.defineProperty,Et=(t,e)=>bp(t,"name",{value:e,configurable:!0});function Uo(t){const e=h.forwardRef((n,s)=>{let{children:r,...i}=n,a=null,c=!1;const l=[];uo(r)&&typeof kr=="function"&&(r=kr(r._payload)),h.Children.forEach(r,m=>{if($l(m)){c=!0;const p=m;let g="child"in p.props?p.props.child:p.props.children;uo(g)&&typeof kr=="function"&&(g=kr(g._payload)),a=Sp(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?Ml(a):void 0,f=Ss(s,d);if(!a){if(r||r===0)throw new Error(c?kp(t):jp(t));return r}const u=Il(i,a.props??{});return a.type!==h.Fragment&&(u.ref=s?f:d),h.cloneElement(a,u)});return e.displayName=`${t}.Slot`,e}Et(Uo,"createSlot");var Fl=Symbol.for("radix.slottable");function vp(t){const e=Et(n=>"child"in n?n.children(n.child):n.children,"Slottable");return e.displayName=`${t}.Slottable`,e.__radixId=Fl,e}Et(vp,"createSlottable");var Sp=Et((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 Il(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}}Et(Il,"mergeProps");function Ml(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)}Et(Ml,"getElementRef");function $l(t){return h.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Fl}Et($l,"isSlottable");var Cp=Symbol.for("react.lazy");function uo(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===Cp&&"_payload"in t&&Ul(t._payload)}Et(uo,"isLazyComponent");function Ul(t){return typeof t=="object"&&t!==null&&"then"in t}Et(Ul,"isPromiseLike");var jp=Et(t=>`${t} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),kp=Et(t=>`${t} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),kr=er[" use ".trim().toString()],Ep=Object.defineProperty,Dp=(t,e)=>Ep(t,"name",{value:e,configurable:!0}),Np=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Dn=Np.reduce((t,e)=>{const n=Uo(`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 zl(t,e){t&&yl.flushSync(()=>t.dispatchEvent(e))}Dp(zl,"dispatchDiscreteCustomEvent");var Tp=Object.defineProperty,Op=(t,e)=>Tp(t,"name",{value:e,configurable:!0});function ls(t){const e=h.useRef(t);return h.useEffect(()=>{e.current=t}),h.useMemo(()=>((...n)=>e.current?.(...n)),[])}Op(ls,"useCallbackRef");var Pp=Object.defineProperty,Me=(t,e)=>Pp(t,"name",{value:e,configurable:!0}),ho="dismissableLayer.update",_p="dismissableLayer.pointerDownOutside",Rp="dismissableLayer.focusOutside",xc,Vl=h.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Lp=h.forwardRef(Me(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(Vl),[m,p]=h.useState(null),g=m?.ownerDocument??globalThis?.document,[,x]=h.useState({}),b=Ss(n,p),C=Array.from(u.layers),[k]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),D=k?C.indexOf(k):-1,T=m?C.indexOf(m):-1,O=u.layersWithOutsidePointerEventsDisabled.size>0,F=T>=D,E=h.useRef(!1),q=Hl(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 _=[...u.branches].some(R=>R.contains(W));return F&&!_},[u.branches,F])}),v=ql(W=>{if(r&&E.current)return;const _=W.target;[...u.branches].some(S=>S.contains(_))||(c?.(W),l?.(W),W.defaultPrevented||d?.())},g),P=m?T===C.length-1:!1,X=ls(W=>{W.key==="Escape"&&(i?.(W),!W.defaultPrevented&&d&&(W.preventDefault(),d()))});return h.useEffect(()=>{if(P)return g.addEventListener("keydown",X,{capture:!0}),()=>g.removeEventListener("keydown",X,{capture:!0})},[g,P,X]),h.useEffect(()=>{if(m)return s&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(xc=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(m)),u.layers.add(m),fo(),()=>{s&&(u.layersWithOutsidePointerEventsDisabled.delete(m),u.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=xc))}},[m,g,s,u]),h.useEffect(()=>()=>{m&&(u.layers.delete(m),u.layersWithOutsidePointerEventsDisabled.delete(m),fo())},[m,u]),h.useEffect(()=>{const W=Me(()=>x({}),"handleUpdate");return document.addEventListener(ho,W),()=>document.removeEventListener(ho,W)},[]),o.jsx(Dn.div,{...f,ref:b,style:{pointerEvents:O?F?"auto":"none":void 0,...e.style},onFocusCapture:an(e.onFocusCapture,v.onFocusCapture),onBlurCapture:an(e.onBlurCapture,v.onBlurCapture),onPointerDownCapture:an(e.onPointerDownCapture,q.onPointerDownCapture)})},"DismissableLayer"));function Bl(){const t=h.useContext(Vl),[e,n]=h.useState(null);return h.useEffect(()=>{if(e)return t.dismissableSurfaces.add(e),()=>{t.dismissableSurfaces.delete(e)}},[e,t.dismissableSurfaces]),n}Me(Bl,"useDismissableLayerSurface");var Ap=Me(()=>!0,"IS_TRUE");function Hl(t,e){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:s=!1,isDeferredPointerDownOutsideRef:r,dismissableSurfaces:i,shouldHandlePointerDownOutside:a=Ap}=e,c=ls(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()}Me(m,"resetOutsideInteraction");function p(){return Array.from(f.current.values()).some(Boolean)}Me(p,"isOutsideInteractionIntercepted");function g(D){if(!d.current)return;const T=D.target;T instanceof Node&&[...i].some(F=>F.contains(T))||f.current.set(D.type,!0),D.type==="click"&&window.setTimeout(()=>{d.current&&u.current()},0)}Me(g,"handleInteractionCapture");function x(D){d.current&&f.current.set(D.type,!1)}Me(x,"handleInteractionBubble");const b=Me(D=>{if(D.target&&!l.current){let T=function(){n.removeEventListener("click",u.current);const F=p();m(),F||zo(_p,c,O,{discrete:!0})};if(Me(T,"handleAndDispatchPointerDownOutsideEvent"),!a(D.target)){n.removeEventListener("click",u.current),m(),l.current=!1;return}const O={originalEvent:D};d.current=!0,r.current=s&&D.button===0,f.current.clear(),!s||D.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"),C=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const D of C)n.addEventListener(D,g,!0),n.addEventListener(D,x);const k=window.setTimeout(()=>{n.addEventListener("pointerdown",b)},0);return()=>{window.clearTimeout(k),n.removeEventListener("pointerdown",b),n.removeEventListener("click",u.current);for(const D of C)n.removeEventListener(D,g,!0),n.removeEventListener(D,x)}},[n,c,s,r,i,a]),{onPointerDownCapture:Me(()=>l.current=!0,"onPointerDownCapture")}}Me(Hl,"usePointerDownOutside");function ql(t,e=globalThis?.document){const n=ls(t),s=h.useRef(!1);return h.useEffect(()=>{const r=Me(i=>{i.target&&!s.current&&zo(Rp,n,{originalEvent:i},{discrete:!1})},"handleFocus");return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,n]),{onFocusCapture:Me(()=>s.current=!0,"onFocusCapture"),onBlurCapture:Me(()=>s.current=!1,"onBlurCapture")}}Me(ql,"useFocusOutside");function fo(){const t=new CustomEvent(ho);document.dispatchEvent(t)}Me(fo,"dispatchUpdate");function zo(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?zl(r,i):r.dispatchEvent(i)}Me(zo,"handleAndDispatchCustomEvent");var Fp=Object.defineProperty,Qe=(t,e)=>Fp(t,"name",{value:e,configurable:!0}),$i="focusScope.autoFocusOnMount",Ui="focusScope.autoFocusOnUnmount",bc={bubbles:!1,cancelable:!0},Ip=h.forwardRef(Qe(function(e,n){const{loop:s=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...c}=e,[l,d]=h.useState(null),f=ls(i),u=ls(a),m=h.useRef(null),p=Ss(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 O=T.target;l.contains(O)?m.current=O:Kt(m.current,{select:!0})},C=function(T){if(g.paused||!l)return;const O=T.relatedTarget;O!==null&&(l.contains(O)||Kt(m.current,{select:!0}))},k=function(T){if(document.activeElement===document.body)for(const F of T)F.removedNodes.length>0&&Kt(l)};Qe(b,"handleFocusIn"),Qe(C,"handleFocusOut"),Qe(k,"handleMutations"),document.addEventListener("focusin",b),document.addEventListener("focusout",C);const D=new MutationObserver(k);return l&&D.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",C),D.disconnect()}}},[r,l,g.paused]),h.useEffect(()=>{if(l){vc.add(g);const b=document.activeElement;if(!l.contains(b)){const k=new CustomEvent($i,bc);l.addEventListener($i,f),l.dispatchEvent(k),k.defaultPrevented||(Wl(Xl(Vo(l)),{select:!0}),document.activeElement===b&&Kt(l))}return()=>{l.removeEventListener($i,f),setTimeout(()=>{const k=new CustomEvent(Ui,bc);l.addEventListener(Ui,u),l.dispatchEvent(k),k.defaultPrevented||Kt(b??document.body,{select:!0}),l.removeEventListener(Ui,u),vc.remove(g)},0)}}},[l,f,u,g]);const x=h.useCallback(b=>{if(!s&&!r||g.paused)return;const C=b.key==="Tab"&&!b.altKey&&!b.ctrlKey&&!b.metaKey,k=document.activeElement;if(C&&k){const D=b.currentTarget,[T,O]=Kl(D);T&&O?!b.shiftKey&&k===O?(b.preventDefault(),s&&Kt(T,{select:!0})):b.shiftKey&&k===T&&(b.preventDefault(),s&&Kt(O,{select:!0})):k===D&&b.preventDefault()}},[s,r,g.paused]);return o.jsx(Dn.div,{tabIndex:-1,...c,ref:p,onKeyDown:x})},"FocusScope"));function Wl(t,{select:e=!1}={}){const n=document.activeElement;for(const s of t)if(Kt(s,{select:e}),document.activeElement!==n)return}Qe(Wl,"focusFirst");function Kl(t){const e=Vo(t),n=po(e,t),s=po(e.reverse(),t);return[n,s]}Qe(Kl,"getTabbableEdges");function Vo(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:Qe(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}Qe(Vo,"getTabbableCandidates");function po(t,e){const n=typeof e.checkVisibility=="function"&&e.checkVisibility({checkVisibilityCSS:!0});for(const s of t)if(!(n?!s.checkVisibility({checkVisibilityCSS:!0}):Gl(s,{upTo:e})))return s}Qe(po,"findVisible");function Gl(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}Qe(Gl,"isHidden");function Jl(t){return t instanceof HTMLInputElement&&"select"in t}Qe(Jl,"isSelectableInput");function Kt(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&Jl(t)&&e&&t.select()}}Qe(Kt,"focus");var vc=Yl();function Yl(){let t=[];return{add(e){const n=t[0];e!==n&&n?.pause(),t=mo(t,e),t.unshift(e)},remove(e){t=mo(t,e),t[0]?.resume()}}}Qe(Yl,"createFocusScopesStack");function mo(t,e){const n=[...t],s=n.indexOf(e);return s!==-1&&n.splice(s,1),n}Qe(mo,"arrayRemove");function Xl(t){return t.filter(e=>e.tagName!=="A")}Qe(Xl,"removeLinks");var Mp=Object.defineProperty,$p=(t,e)=>Mp(t,"name",{value:e,configurable:!0}),Up=h.forwardRef($p(function(e,n){const{container:s,...r}=e,[i,a]=h.useState(!1);cn(()=>a(!0),[]);const c=s||i&&globalThis?.document?.body;return c?yl.createPortal(o.jsx(Dn.div,{...r,ref:n}),c):null},"Portal")),zp=Object.defineProperty,Xt=(t,e)=>zp(t,"name",{value:e,configurable:!0});function Zl(t,e){return h.useReducer((n,s)=>e[n][s]??n,t)}Xt(Zl,"useStateMachine");var Bo=Xt(t=>{const{present:e,children:n}=t,s=Ql(e),r=typeof n=="function"?n({present:s.isPresent}):h.Children.only(n),i=ed(s.ref,td(r));return typeof n=="function"||s.isPresent?h.cloneElement(r,{ref:i}):null},"Presence");function Ql(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]=Zl(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??Jn(s.current),a.current=void 0):i.current="none"},[l]),cn(()=>{const f=s.current,u=r.current;if(u!==t){const p=i.current,g=Jn(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]),cn(()=>{if(e){let f;const u=e.ownerDocument.defaultView??window,m=Xt(g=>{const b=Jn(s.current).includes(CSS.escape(g.animationName));if(g.target===e&&b&&(d("ANIMATION_END"),!r.current)){const C=e.style.animationFillMode;e.style.animationFillMode="forwards",f=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=C)})}},"handleAnimationEnd"),p=Xt(g=>{g.target===e&&(i.current=Jn(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=Jn(u)}else s.current=null;n(f)},[])}}Xt(Ql,"usePresence");function go(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}Xt(go,"setRef");function ed(...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=go(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():go(s[a],null)}}},[])}Xt(ed,"useStableComposedRefs");function Jn(t){return t?.animationName||"none"}Xt(Jn,"getAnimationName");function td(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)}Xt(td,"getElementRef");var Vp=Object.defineProperty,Ho=(t,e)=>Vp(t,"name",{value:e,configurable:!0}),Er=0,Hn=null;function Bp(t){return qo(),t.children}Ho(Bp,"FocusGuards");function qo(){h.useEffect(()=>{Hn||(Hn={start:yo(),end:yo()});const{start:t,end:e}=Hn;return document.body.firstElementChild!==t&&document.body.insertAdjacentElement("afterbegin",t),document.body.lastElementChild!==e&&document.body.insertAdjacentElement("beforeend",e),Er++,()=>{Er===1&&(Hn?.start.remove(),Hn?.end.remove(),Hn=null),Er=Math.max(0,Er-1)}},[])}Ho(qo,"useFocusGuards");function yo(){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}Ho(yo,"createFocusGuard");var Hp=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},qn=new WeakMap,Dr=new WeakMap,Nr={},zi=0,nd=function(t){return t&&(t.host||nd(t.parentNode))},qp=function(t,e){return e.map(function(n){if(t.contains(n))return n;var s=nd(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})},Wp=function(t,e,n,s){var r=qp(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=(qn.get(m)||0)+1,b=(i.get(m)||0)+1;qn.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(C){console.error("aria-hidden: cannot operate on ",m,C)}})};return f(e),c.clear(),zi++,function(){a.forEach(function(u){var m=qn.get(u)-1,p=i.get(u)-1;qn.set(u,m),i.set(u,p),m||(Dr.has(u)||u.removeAttribute(s),Dr.delete(u)),p||u.removeAttribute(n)}),zi--,zi||(qn=new WeakMap,qn=new WeakMap,Dr=new WeakMap,Nr={})}},Kp=function(t,e,n){n===void 0&&(n="data-aria-hidden");var s=Array.from(Array.isArray(t)?t:[t]),r=Hp(t);return r?(s.push.apply(s,Array.from(r.querySelectorAll("[aria-live], script"))),Wp(s,r,n,"aria-hidden")):function(){return null}},Gp=Object.defineProperty,gt=(t,e)=>Gp(t,"name",{value:e,configurable:!0}),Wo="Dialog",[sd,Hb]=Ol(Wo),[Jp,Lt]=sd(Wo),Yp=gt(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]=Rl({prop:s,defaultProp:r??!1,onChange:i,caller:Wo}),[u,m]=h.useState(0),[p,g]=h.useState(0);return o.jsx(Jp,{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"),rd="DialogPortal",[Xp,id]=sd(rd,{forceMount:void 0}),Zp=gt(t=>{const{__scopeDialog:e,forceMount:n,children:s,container:r}=t,i=Lt(rd,e);return o.jsx(Xp,{scope:e,forceMount:n,children:h.Children.map(s,a=>o.jsx(Bo,{present:n||i.open,children:o.jsx(Up,{asChild:!0,container:r,children:a})}))})},"DialogPortal"),wo="DialogOverlay",Qp=h.forwardRef(gt(function(e,n){const s=id(wo,e.__scopeDialog),{forceMount:r=s.forceMount,...i}=e,a=Lt(wo,e.__scopeDialog);return a.modal?o.jsx(Bo,{present:r||a.open,children:o.jsx(tm,{...i,ref:n})}):null},"DialogOverlay")),em=Uo("DialogOverlay.RemoveScroll"),tm=h.forwardRef(gt(function(e,n){const{__scopeDialog:s,...r}=e,i=Lt(wo,s),a=Bl(),c=Ss(n,a);return o.jsx(Mh,{as:em,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(Dn.div,{"data-state":Ko(i.open),...r,ref:c,style:{pointerEvents:"auto",...r.style}})})},"DialogOverlayImpl")),zs="DialogContent",nm=h.forwardRef(gt(function(e,n){const s=id(zs,e.__scopeDialog),{forceMount:r=s.forceMount,...i}=e,a=Lt(zs,e.__scopeDialog);return o.jsx(Bo,{present:r||a.open,children:a.modal?o.jsx(sm,{...i,ref:n}):o.jsx(rm,{...i,ref:n})})},"DialogContent")),sm=h.forwardRef(gt(function(e,n){const s=Lt(zs,e.__scopeDialog),r=h.useRef(null),i=Ss(n,s.contentRef,r);return h.useEffect(()=>{const a=r.current;if(a)return Kp(a)},[]),o.jsx(od,{...e,ref:i,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:an(e.onCloseAutoFocus,a=>{a.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:an(e.onPointerDownOutside,a=>{const c=a.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;(c.button===2||l)&&a.preventDefault()}),onFocusOutside:an(e.onFocusOutside,a=>a.preventDefault())})},"DialogContentModal")),rm=h.forwardRef(gt(function(e,n){const s=Lt(zs,e.__scopeDialog),r=h.useRef(!1),i=h.useRef(!1);return o.jsx(od,{...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")),od=h.forwardRef(gt(function(e,n){const{__scopeDialog:s,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...c}=e,l=Lt(zs,s);return qo(),o.jsx(o.Fragment,{children:o.jsx(Ip,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o.jsx(Lp,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionPresent?l.descriptionId:void 0,"aria-labelledby":l.titlePresent?l.titleId:void 0,"data-state":Ko(l.open),...c,ref:n,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})},"DialogContentImpl")),im="DialogTitle",om=h.forwardRef(gt(function(e,n){const{__scopeDialog:s,...r}=e,i=Lt(im,s),{setTitleCount:a}=i;return cn(()=>(a(c=>c+1),()=>a(c=>c-1)),[a]),o.jsx(Dn.h2,{id:i.titleId,...r,ref:n})},"DialogTitle")),am="DialogDescription",cm=h.forwardRef(gt(function(e,n){const{__scopeDialog:s,...r}=e,i=Lt(am,s),{setDescriptionCount:a}=i;return cn(()=>(a(c=>c+1),()=>a(c=>c-1)),[a]),o.jsx(Dn.p,{id:i.descriptionId,...r,ref:n})},"DialogDescription")),lm="DialogClose",dm=h.forwardRef(gt(function(e,n){const{__scopeDialog:s,...r}=e,i=Lt(lm,s);return o.jsx(Dn.button,{type:"button",...r,ref:n,onClick:an(e.onClick,()=>i.onOpenChange(!1))})},"DialogClose"));function Ko(t){return t?"open":"closed"}gt(Ko,"getState");function $e({open:t,title:e,description:n,onOpenChange:s,children:r,footer:i,wide:a,extraWide:c,className:l}){const{t:d}=_e();return o.jsx(Yp,{open:t,onOpenChange:s,children:o.jsxs(Zp,{children:[o.jsx(Qp,{className:"dialog-overlay"}),o.jsxs(nm,{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(om,{children:e}),n&&o.jsx(cm,{children:n})]}),o.jsx(dm,{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 ds({open:t,title:e,description:n,confirmLabel:s,danger:r,onCancel:i,onConfirm:a}){const{t:c}=_e();return o.jsx($e,{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 Go({compact:t=!1}){const{i18n:e,t:n}=_e(),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 um=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ad=(...t)=>t.filter((e,n,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===n).join(" ").trim();var hm={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 fm=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,...hm,width:e,height:e,stroke:t,strokeWidth:s?Number(n)*24/Number(e):n,className:ad("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(fm,{ref:i,iconNode:e,className:ad(`lucide-${um(t)}`,s),...r}));return n.displayName=`${t}`,n};const pm=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 cd=I("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const mm=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 Sc=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 gm=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 ld=I("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);const Vi=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 dd=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 ym=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 wm=I("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const ud=I("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const hd=I("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);const Jo=I("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const xm=I("ChevronsLeft",[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]]);const bm=I("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);const vm=I("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Yo=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 Cc=I("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const Sm=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 Cm=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 Vs=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 xo=I("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);const bo=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 jm=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 km=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 Qn=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 fd=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 Em=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 Dm=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 Bi=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 pd=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 Nm=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 Tm=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 Gt=I("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const Om=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 Pm=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 jc=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 md=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 kc=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 _m=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 Rm=I("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const Lm=I("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const vo=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 Am=I("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const Fm=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 Im=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 So=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 Mm=I("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);const $m=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 Um=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 zm=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 Ec=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 ln=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 us=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 Dc=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 gd=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 Bs=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 Vm=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 Xo=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'}],sn={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,spellCheck:!0,vimMode:!1,formatOnCompile:!1},Bm="texlite-editor-preferences";function yd(t,e){return`${Bm}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function qb(t){return qr.find(e=>e.id===t)?.stack??qr[0].stack}function Nc(t,e){try{const n=JSON.parse(localStorage.getItem(yd(t,e))??"{}");return{font:qr.some(s=>s.id===n.font)?n.font:sn.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):sn.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):sn.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:sn.lineWrapping,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:sn.spellCheck,vimMode:typeof n.vimMode=="boolean"?n.vimMode:sn.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:sn.formatOnCompile}}catch{return sn}}function Hm(t,e,n){localStorage.setItem(yd(t,e),JSON.stringify(n))}const qm=/\.(?:tex|bib|cls|sty)$/i;function Hi(t){return qm.test(t)}function Wm(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Km(t,e){const n=Wm(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(`
|
|
@@ -9,8 +9,8 @@ $pdf_mode = 1;`,addMember:"添加成员",noMembers:"该项目尚未分享给其
|
|
|
9
9
|
${n.toString()}`)};class Iy{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Js(e),h:n}),this}else(e){return this.if(Yr,e)}done(){return(e,n)=>{for(let s=0;s<this.patterns.length;s++){const r=this.patterns[s];if(r.if.check(e))return r.h(e,n)}throw kt("Unhandled pattern")}}}const My=t=>new Iy(t),Kd=My(Yr).if(Hd,(t,e)=>Xi(e,Ac,Wr)).if(qd,(t,e)=>uy(e)).if(Ly,(t,e)=>Bc(e)).if(Ry,(t,e)=>BigInt(Xi(e,Ac,Wr))).if(Jr,(t,e)=>Wn(e,Zi(e,t.shape))).if(by,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(yy.check(r)){if(Bc(e))continue;r=r.shape}n[s]=Kd(r,e)}return n}).if(jy,(t,e)=>{const n=[],s=_d(e,0,42);for(let r=0;r<s;r++)n.push(Wn(e,t.shape));return n}).if(Rd,(t,e)=>Zi(e,t.shape)).if(Ay,(t,e)=>null).if(Ty,(t,e)=>{const n=Wn(e,t.res);return()=>n}).if(_y,(t,e)=>Wn(e,Zi(e,[ss,ms,pi,Wd,pa,fi,Ud(ss),Id(Cs("a","b","c"),ss)]))).if(Sy,(t,e)=>{const n={},s=Xi(e,0,3);for(let r=0;r<s;r++){const i=Wn(e,t.shape.keys),a=Wn(e,t.shape.values);n[i]=a}return n}).done(),Wn=(t,e)=>Kd(Js(e),t),Ft=typeof document<"u"?document:{},$y=t=>Ft.createElement(t),Uy=()=>Ft.createDocumentFragment();ze(t=>t.nodeType===Jy);const zy=t=>Ft.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const Vy=(t,e)=>(ly(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),By=t=>{const e=Uy();for(let n=0;n<t.length;n++)Gd(e,t[n]);return e},Hy=(t,e)=>(Gd(t,By(e)),t),Wb=(t,e=[],n=[])=>Hy(Vy($y(t),e),n);ze(t=>t.nodeType===Wy);const Kb=zy;ze(t=>t.nodeType===Ky);const qy=t=>eg(t,(e,n)=>`${n}:${e};`).join(""),Gd=(t,e)=>t.appendChild(e),Wy=Ft.ELEMENT_NODE,Ky=Ft.TEXT_NODE;Ft.CDATA_SECTION_NODE;Ft.COMMENT_NODE;const Gy=Ft.DOCUMENT_NODE;Ft.DOCUMENT_TYPE_NODE;const Jy=Ft.DOCUMENT_FRAGMENT_NODE;ze(t=>t.nodeType===Gy);const en=Symbol,Jd=en(),Yd=en(),Yy=en(),Xy=en(),Zy=en(),Xd=en(),Qy=en(),ma=en(),ew=en(),tw=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[];let s=0;for(;s<t.length;s++){const r=t[s];if(r===void 0)break;if(r.constructor===String||r.constructor===Number)e.push(r);else if(r.constructor===Object)break}for(s>0&&n.push(e.join(""));s<t.length;s++){const r=t[s];r instanceof Symbol||n.push(r)}return n},nw={[Jd]:Wt("font-weight","bold"),[Yd]:Wt("font-weight","normal"),[Yy]:Wt("color","blue"),[Zy]:Wt("color","green"),[Xy]:Wt("color","grey"),[Xd]:Wt("color","red"),[Qy]:Wt("color","purple"),[ma]:Wt("color","orange"),[ew]:Wt("color","black")},sw=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=ot();let r=[],i=0;for(;i<t.length;i++){const a=t[i],c=nw[a];if(c!==void 0)s.set(c.left,c.right);else{if(a===void 0)break;if(a.constructor===String||a.constructor===Number){const l=qy(s);i>0||l.length>0?(e.push("%c"+a),n.push(l)):e.push(a)}else break}}for(i>0&&(r=n,r.unshift(e.join("")));i<t.length;i++){const a=t[i];a instanceof Symbol||r.push(a)}return r},Zd=Zg?sw:tw,rw=(...t)=>{console.log(...Zd(t)),eu.forEach(e=>e.print(t))},Qd=(...t)=>{console.warn(...Zd(t)),t.unshift(ma),eu.forEach(e=>e.print(t))},eu=dn(),tu=t=>({[Symbol.iterator](){return this},next:t}),iw=(t,e)=>tu(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),Qi=(t,e)=>tu(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class mi{constructor(e,n){this.clock=e,this.len=n}}class js{constructor(){this.clients=new Map}}const gs=(t,e,n)=>e.clients.forEach((s,r)=>{const i=t.doc.store.clients.get(r);if(i!=null){const a=i[i.length-1],c=a.id.clock+a.length;for(let l=0,d=s[l];l<s.length&&d.clock<c;d=s[++l])gu(t,i,d.clock,d.len,n)}}),ow=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=jt((n+s)/2),i=t[r],a=i.clock;if(a<=e){if(e<a+i.len)return r;n=r+1}else s=r-1}return null},rr=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&ow(n,e.clock)!==null},ga=t=>{t.clients.forEach(e=>{e.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n<e.length;n++){const r=e[s-1],i=e[n];r.clock+r.len>=i.clock?e[s-1]=new mi(r.clock,Nn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},To=t=>{const e=new js;for(let n=0;n<t.length;n++)t[n].clients.forEach((s,r)=>{if(!e.clients.has(r)){const i=s.slice();for(let a=n+1;a<t.length;a++)ng(i,t[a].clients.get(r)||[]);e.clients.set(r,i)}});return ga(e),e},Ys=(t,e,n,s)=>{At(t.clients,e,()=>[]).push(new mi(n,s))},aw=()=>new js,cw=t=>{const e=aw();return t.clients.forEach((n,s)=>{const r=[];for(let i=0;i<n.length;i++){const a=n[i];if(a.deleted){const c=a.id.clock;let l=a.length;if(i+1<n.length)for(let d=n[i+1];i+1<n.length&&d.deleted;d=n[++i+1])l+=d.length;r.push(new mi(c,l))}}r.length>0&&e.clients.set(s,r)}),e},ks=(t,e)=>{$(t.restEncoder,e.clients.size),Zt(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),$(t.restEncoder,n);const r=s.length;$(t.restEncoder,r);for(let i=0;i<r;i++){const a=s[i];t.writeDsClock(a.clock),t.writeDsLen(a.len)}})},ya=t=>{const e=new js,n=G(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=G(t.restDecoder),i=G(t.restDecoder);if(i>0){const a=At(e.clients,r,()=>[]);for(let c=0;c<i;c++)a.push(new mi(t.readDsClock(),t.readDsLen()))}}return e},qc=(t,e,n)=>{const s=new js,r=G(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const a=G(t.restDecoder),c=G(t.restDecoder),l=n.clients.get(a)||[],d=De(n,a);for(let f=0;f<c;f++){const u=t.readDsClock(),m=u+t.readDsLen();if(u<d){d<m&&Ys(s,a,d,m-d);let p=_t(l,u),g=l[p];for(!g.deleted&&g.id.clock<u&&(l.splice(p+1,0,ri(e,g,u-g.id.clock)),p++);p<l.length&&(g=l[p++],g.id.clock<m);)g.deleted||(m<g.id.clock+g.length&&l.splice(p,0,ri(e,g,m-g.id.clock)),g.delete(e))}else Ys(s,a,u,m-u)}}if(s.clients.size>0){const i=new jn;return $(i.restEncoder,0),ks(i,s),i.toUint8Array()}return null},nu=Cd;class Tn extends ea{constructor({guid:e=Ag(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:c=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=nu(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new pu,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=ps(d=>{this.on("load",()=>{this.isLoaded=!0,d(this)})});const l=()=>ps(d=>{const f=u=>{(u===void 0||u===!0)&&(this.off("sync",f),d())};this.on("sync",f)});this.on("sync",d=>{d===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=d===void 0||d===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;e!==null&&!this.shouldLoad&&pe(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Zt(this.subdocs).map(e=>e.guid))}transact(e,n=null){return pe(this,e,n)}get(e,n=Ue){const s=At(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==Ue&&r!==n)if(r===Ue){const i=new n;i._map=s._map,s._map.forEach(a=>{for(;a!==null;a=a.left)a.parent=i}),i._start=s._start;for(let a=i._start;a!==null;a=a.right)a.parent=i;return i._length=s._length,this.share.set(e,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return s}getArray(e=""){return this.get(e,os)}getText(e=""){return this.get(e,xs)}getMap(e=""){return this.get(e,ws)}getXmlElement(e=""){return this.get(e,bs)}getXmlFragment(e=""){return this.get(e,kn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,Zt(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Tn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,pe(e.parent.doc,s=>{const r=n.doc;e.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class su{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return G(this.restDecoder)}readDsLen(){return G(this.restDecoder)}}class ru extends su{readLeftID(){return Y(G(this.restDecoder),G(this.restDecoder))}readRightID(){return Y(G(this.restDecoder),G(this.restDecoder))}readClient(){return G(this.restDecoder)}readInfo(){return fs(this.restDecoder)}readString(){return Ct(this.restDecoder)}readParentInfo(){return G(this.restDecoder)===1}readTypeRef(){return G(this.restDecoder)}readLen(){return G(this.restDecoder)}readAny(){return Ks(this.restDecoder)}readBuf(){return ay(Ge(this.restDecoder))}readJSON(){return JSON.parse(Ct(this.restDecoder))}readKey(){return Ct(this.restDecoder)}}class lw{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=G(this.restDecoder),this.dsCurrVal}readDsLen(){const e=G(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class ys extends lw{constructor(e){super(e),this.keys=[],G(e),this.keyClockDecoder=new Yi(Ge(e)),this.clientDecoder=new Ir(Ge(e)),this.leftClockDecoder=new Yi(Ge(e)),this.rightClockDecoder=new Yi(Ge(e)),this.infoDecoder=new zc(Ge(e),fs),this.stringDecoder=new _g(Ge(e)),this.parentInfoDecoder=new zc(Ge(e),fs),this.typeRefDecoder=new Ir(Ge(e)),this.lenDecoder=new Ir(Ge(e))}readLeftID(){return new rs(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new rs(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ks(this.restDecoder)}readBuf(){return Ge(this.restDecoder)}readJSON(){return Ks(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const n=this.stringDecoder.read();return this.keys.push(n),n}}}class iu{constructor(){this.restEncoder=Pe()}toUint8Array(){return me(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){$(this.restEncoder,e)}writeDsLen(e){$(this.restEncoder,e)}}class ir extends iu{writeLeftID(e){$(this.restEncoder,e.client),$(this.restEncoder,e.clock)}writeRightID(e){$(this.restEncoder,e.client),$(this.restEncoder,e.clock)}writeClient(e){$(this.restEncoder,e)}writeInfo(e){ko(this.restEncoder,e)}writeString(e){Yt(this.restEncoder,e)}writeParentInfo(e){$(this.restEncoder,e?1:0)}writeTypeRef(e){$(this.restEncoder,e)}writeLen(e){$(this.restEncoder,e)}writeAny(e){Ws(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){Yt(this.restEncoder,JSON.stringify(e))}writeKey(e){Yt(this.restEncoder,e)}}class ou{constructor(){this.restEncoder=Pe(),this.dsCurrVal=0}toUint8Array(){return me(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,$(this.restEncoder,n)}writeDsLen(e){e===0&&ct(),$(this.restEncoder,e-1),this.dsCurrVal+=e}}class jn extends ou{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Ji,this.clientEncoder=new Fr,this.leftClockEncoder=new Ji,this.rightClockEncoder=new Ji,this.infoEncoder=new Mc(ko),this.stringEncoder=new Cg,this.parentInfoEncoder=new Mc(ko),this.typeRefEncoder=new Fr,this.lenEncoder=new Fr}toUint8Array(){const e=Pe();return $(e,0),je(e,this.keyClockEncoder.toUint8Array()),je(e,this.clientEncoder.toUint8Array()),je(e,this.leftClockEncoder.toUint8Array()),je(e,this.rightClockEncoder.toUint8Array()),je(e,me(this.infoEncoder)),je(e,this.stringEncoder.toUint8Array()),je(e,me(this.parentInfoEncoder)),je(e,this.typeRefEncoder.toUint8Array()),je(e,this.lenEncoder.toUint8Array()),ci(e,me(this.restEncoder)),me(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Ws(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){Ws(this.restEncoder,e)}writeKey(e){const n=this.keyMap.get(e);n===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(n)}}const dw=(t,e,n,s)=>{s=Nn(s,e[0].id.clock);const r=_t(e,s);$(t.restEncoder,e.length-r),t.writeClient(n),$(t.restEncoder,s);const i=e[r];i.write(t,s-i.id.clock);for(let a=r+1;a<e.length;a++)e[a].write(t,0)},wa=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{De(e,i)>r&&s.set(i,r)}),gi(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),$(t.restEncoder,s.size),Zt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{dw(t,e.clients.get(r),r,i)})},uw=(t,e)=>{const n=ot(),s=G(t.restDecoder);for(let r=0;r<s;r++){const i=G(t.restDecoder),a=new Array(i),c=t.readClient();let l=G(t.restDecoder);n.set(c,{i:0,refs:a});for(let d=0;d<i;d++){const f=t.readInfo();switch(ai&f){case 0:{const u=t.readLen();a[d]=new pt(Y(c,l),u),l+=u;break}case 10:{const u=G(t.restDecoder);a[d]=new mt(Y(c,l),u),l+=u;break}default:{const u=(f&(Jt|at))===0,m=new ge(Y(c,l),null,(f&at)===at?t.readLeftID():null,null,(f&Jt)===Jt?t.readRightID():null,u?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,u&&(f&Hs)===Hs?t.readString():null,Fu(t,f));a[d]=m,l+=m.length}}}}return n},hw=(t,e,n)=>{const s=[];let r=Zt(n.keys()).sort((p,g)=>p-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let p=n.get(r[r.length-1]);for(;p.refs.length===p.i;)if(r.pop(),r.length>0)p=n.get(r[r.length-1]);else return null;return p};let a=i();if(a===null)return null;const c=new pu,l=new Map,d=(p,g)=>{const x=l.get(p);(x==null||x>g)&&l.set(p,g)};let f=a.refs[a.i++];const u=new Map,m=()=>{for(const p of s){const g=p.id.client,x=n.get(g);x?(x.i--,c.clients.set(g,x.refs.slice(x.i)),n.delete(g),x.i=0,x.refs=[]):c.clients.set(g,[p]),r=r.filter(b=>b!==g)}s.length=0};for(;;){if(f.constructor!==mt){const g=At(u,f.id.client,()=>De(e,f.id.client))-f.id.clock;if(g<0)s.push(f),d(f.id.client,f.id.clock-1),m();else{const x=f.getMissing(t,e);if(x!==null){s.push(f);const b=n.get(x)||{refs:[],i:0};if(b.refs.length===b.i)d(x,De(e,x)),m();else{f=b.refs[b.i++];continue}}else(g===0||g<f.length)&&(f.integrate(t,g),u.set(f.id.client,f.id.clock+f.length))}}if(s.length>0)f=s.pop();else if(a!==null&&a.i<a.refs.length)f=a.refs[a.i++];else{if(a=i(),a===null)break;f=a.refs[a.i++]}}if(c.clients.size>0){const p=new jn;return wa(p,c,new Map),$(p.restEncoder,0),{missing:l,update:p.toUint8Array()}}return null},fw=(t,e)=>wa(t,e.doc.store,e.beforeState),pw=(t,e,n,s=new ys(t))=>pe(e,r=>{r.local=!1;let i=!1;const a=r.doc,c=a.store,l=uw(s,a),d=hw(r,c,l),f=c.pendingStructs;if(f){for(const[m,p]of f.missing)if(p<De(c,m)){i=!0;break}if(d){for(const[m,p]of d.missing){const g=f.missing.get(m);(g==null||g>p)&&f.missing.set(m,p)}f.update=Zr([f.update,d.update])}}else c.pendingStructs=d;const u=qc(s,r,c);if(c.pendingDs){const m=new ys(fn(c.pendingDs));G(m.restDecoder);const p=qc(m,r,c);u&&p?c.pendingDs=Zr([u,p]):c.pendingDs=u||p}else c.pendingDs=u;if(i){const m=c.pendingStructs.update;c.pendingStructs=null,au(r.doc,m)}},n,!1),au=(t,e,n,s=ys)=>{const r=fn(e);pw(r,t,n,new s(r))},cu=(t,e,n)=>au(t,e,n,ru),mw=(t,e,n=new Map)=>{wa(t,e.store,n),ks(t,cw(e.store))},gw=(t,e=new Uint8Array([0]),n=new jn)=>{const s=lu(e);mw(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Lw(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===ir)return _w(r.map((i,a)=>a===0?i:Fw(i)));if(n.constructor===jn)return Zr(r)}return r[0]},xa=(t,e)=>gw(t,e,new ir),yw=t=>{const e=new Map,n=G(t.restDecoder);for(let s=0;s<n;s++){const r=G(t.restDecoder),i=G(t.restDecoder);e.set(r,i)}return e},lu=t=>yw(new su(fn(t))),du=(t,e)=>($(t.restEncoder,e.size),Zt(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{$(t.restEncoder,n),$(t.restEncoder,s)}),t),ww=(t,e)=>du(t,gi(e.store)),xw=(t,e=new ou)=>(t instanceof Map?du(e,t):ww(e,t),e.toUint8Array()),bw=t=>xw(t,new iu);class vw{constructor(){this.l=[]}}const Wc=()=>new vw,Kc=(t,e)=>t.l.push(e),Gc=(t,e)=>{const n=t.l,s=n.length;t.l=n.filter(r=>e!==r),s===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},uu=(t,e,n)=>la(t.l,[e,n]);class rs{constructor(e,n){this.client=e,this.clock=n}}const es=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,Y=(t,e)=>new rs(t,e),hu=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw ct()},Xr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class fu{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const Gb=t=>{const e={};return t.type&&(e.type=t.type),t.tname&&(e.tname=t.tname),t.item&&(e.item=t.item),t.assoc!=null&&(e.assoc=t.assoc),e},Jb=t=>new fu(t.type==null?null:Y(t.type.client,t.type.clock),t.tname??null,t.item==null?null:Y(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class Sw{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const Cw=(t,e,n=0)=>new Sw(t,e,n),Or=(t,e,n)=>{let s=null,r=null;return t._item===null?r=hu(t):s=Y(t._item.id.client,t._item.id.clock),new fu(s,r,e,n)},Yb=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return Or(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return Or(t,Y(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return Or(t,s.lastId,n);s=s.right}return Or(t,null,n)},jw=(t,e)=>{const n=is(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},Xb=(t,e,n=!0)=>{const s=e.store,r=t.item,i=t.type,a=t.tname,c=t.assoc;let l=null,d=0;if(r!==null){if(De(s,r.client)<=r.clock)return null;const f=n?Ro(s,r):jw(s,r),u=f.item;if(!(u instanceof ge))return null;if(l=u.parent,l._item===null||!l._item.deleted){d=u.deleted||!u.countable?0:f.diff+(c>=0?0:1);let m=u.left;for(;m!==null;)!m.deleted&&m.countable&&(d+=m.length),m=m.left}}else{if(a!==null)l=e.get(a);else if(i!==null){if(De(s,i.client)<=i.clock)return null;const{item:f}=n?Ro(s,i):{item:is(s,i)};if(f instanceof ge&&f.content instanceof It)l=f.content.type;else return null}else throw ct();c>=0?d=l._length:d=0}return Cw(l,d,t.assoc)},Zb=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&es(t.item,e.item)&&es(t.type,e.type)&&t.assoc===e.assoc,Yn=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!rr(e.ds,t.id),Oo=(t,e)=>{const n=At(t.meta,Oo,dn),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<De(s,i)&&it(t,Y(i,r))}),gs(t,e.ds,r=>{}),n.add(e))};class pu{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const gi=t=>{const e=new Map;return t.clients.forEach((n,s)=>{const r=n[n.length-1];e.set(s,r.id.clock+r.length)}),e},De=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},mu=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==e.id.clock)throw ct()}n.push(e)},_t=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let a=jt(e/(i+r.length-1)*s);for(;n<=s;){if(r=t[a],i=r.id.clock,i<=e){if(e<i+r.length)return a;n=a+1}else s=a-1;a=jt((n+s)/2)}throw ct()},kw=(t,e)=>{const n=t.clients.get(e.client);return n[_t(n,e.clock)]},is=kw,Po=(t,e,n)=>{const s=_t(e,n),r=e[s];return r.id.clock<n&&r instanceof ge?(e.splice(s+1,0,ri(t,r,n-r.id.clock)),s+1):s},it=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[Po(t,n,e.clock)]},Jc=(t,e,n)=>{const s=e.clients.get(n.client),r=_t(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pt&&s.splice(r+1,0,ri(t,i,n.clock-i.id.clock+1)),i},Ew=(t,e,n)=>{const s=t.clients.get(e.id.client);s[_t(s,e.id.clock)]=n},gu=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let a=Po(t,e,n),c;do c=e[a++],i<c.id.clock+c.length&&Po(t,e,i),r(c);while(a<e.length&&e[a].id.clock<i)};class Dw{constructor(e,n,s){this.doc=e,this.deleteSet=new js,this.beforeState=gi(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=n,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Yc=(t,e)=>e.deleteSet.clients.size===0&&!tg(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(ga(e.deleteSet),fw(t,e),ks(t,e.deleteSet),!0),Xc=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&At(t.changed,e,dn).add(n)},Mr=(t,e)=>{let n=t[e],s=t[e-1],r=e;for(;r>0;n=s,s=t[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof ge&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=e-r;return i&&t.splice(e+1-i,i),i},Nw=(t,e,n)=>{for(const[s,r]of t.clients.entries()){const i=e.clients.get(s);for(let a=r.length-1;a>=0;a--){const c=r[a],l=c.clock+c.len;for(let d=_t(i,c.clock),f=i[d];d<i.length&&f.id.clock<l;f=i[++d]){const u=i[d];if(c.clock+c.len<=u.id.clock)break;u instanceof ge&&u.deleted&&!u.keep&&n(u)&&u.gc(e,!1)}}}},Tw=(t,e)=>{t.clients.forEach((n,s)=>{const r=e.clients.get(s);for(let i=n.length-1;i>=0;i--){const a=n[i],c=ta(r.length-1,1+_t(r,a.clock+a.len-1));for(let l=c,d=r[l];l>0&&d.id.clock>=a.clock;d=r[l])l-=1+Mr(r,l)}})},yu=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,a=n._mergeStructs;try{ga(i),n.afterState=gi(n.doc.store),s.emit("beforeObserverCalls",[n,s]);const c=[];n.changed.forEach((l,d)=>c.push(()=>{(d._item===null||!d._item.deleted)&&d._callObserver(n,l)})),c.push(()=>{n.changedParentTypes.forEach((l,d)=>{d._dEH.l.length>0&&(d._item===null||!d._item.deleted)&&(l=l.filter(f=>f.target._item===null||!f.target._item.deleted),l.forEach(f=>{f.currentTarget=d,f._path=null}),l.sort((f,u)=>f.path.length-u.path.length),c.push(()=>{uu(d._dEH,l,n)}))}),c.push(()=>s.emit("afterTransaction",[n,s])),c.push(()=>{n._needFormattingCleanup&&Yw(n)})}),la(c,[])}finally{s.gc&&Nw(i,r,s.gcFilter),Tw(i,r),n.afterState.forEach((f,u)=>{const m=n.beforeState.get(u)||0;if(m!==f){const p=r.clients.get(u),g=Nn(_t(p,m),1);for(let x=p.length-1;x>=g;)x-=1+Mr(p,x)}});for(let f=a.length-1;f>=0;f--){const{client:u,clock:m}=a[f].id,p=r.clients.get(u),g=_t(p,m);g+1<p.length&&Mr(p,g+1)>1||g>0&&Mr(p,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(rw(ma,Jd,"[yjs] ",Yd,Xd,"Changed the client-id because another client seems to be using it."),s.clientID=nu()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const f=new ir;Yc(f,n)&&s.emit("update",[f.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const f=new jn;Yc(f,n)&&s.emit("updateV2",[f.toUint8Array(),n.origin,s,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:d}=n;(c.size>0||d.size>0||l.size>0)&&(c.forEach(f=>{f.clientID=s.clientID,f.collectionid==null&&(f.collectionid=s.collectionid),s.subdocs.add(f)}),d.forEach(f=>s.subdocs.delete(f)),s.emit("subdocs",[{loaded:l,added:c,removed:d},s,n]),d.forEach(f=>f.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):yu(t,e+1)}}},pe=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,a=null;t._transaction===null&&(i=!0,t._transaction=new Dw(t,n,s),r.push(t._transaction),r.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{a=e(t._transaction)}finally{if(i){const c=t._transaction===r[0];t._transaction=null,c&&yu(r,0)}}return a};class Ow{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const Zc=(t,e,n)=>{gs(t,n.deletions,s=>{s instanceof ge&&e.scope.some(r=>r===t.doc||Xr(r,s))&&Da(s,!1)})},Qc=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;pe(r,c=>{for(;e.length>0&&t.currStackItem===null;){const l=r.store,d=e.pop(),f=new Set,u=[];let m=!1;gs(c,d.insertions,p=>{if(p instanceof ge){if(p.redone!==null){let{item:g,diff:x}=Ro(l,p.id);x>0&&(g=it(c,Y(g.id.client,g.id.clock+x))),p=g}!p.deleted&&i.some(g=>g===c.doc||Xr(g,p))&&u.push(p)}}),gs(c,d.deletions,p=>{p instanceof ge&&i.some(g=>g===c.doc||Xr(g,p))&&!rr(d.insertions,p.id)&&f.add(p)}),f.forEach(p=>{m=Au(c,p,f,d.insertions,t.ignoreRemoteMapChanges,t)!==null||m});for(let p=u.length-1;p>=0;p--){const g=u[p];t.deleteFilter(g)&&(g.delete(c),m=!0)}t.currStackItem=m?d:null}c.changed.forEach((l,d)=>{l.has(null)&&d._searchMarker&&(d._searchMarker.length=0)}),s=c},t);const a=t.currStackItem;if(a!=null){const c=s.changedParentTypes;t.emit("stack-item-popped",[{stackItem:a,type:n,changedParentTypes:c,origin:t},t]),t.currStackItem=null}return a};class Qb extends ea{constructor(e,{captureTimeout:n=500,captureTransaction:s=l=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:c=hs(e)?e[0].doc:e instanceof Tn?e:e.doc}={}){super(),this.scope=[],this.doc=c,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=n,this.afterTransactionHandler=l=>{if(!this.captureTransaction(l)||!this.scope.some(b=>l.changedParentTypes.has(b)||b===this.doc)||!this.trackedOrigins.has(l.origin)&&(!l.origin||!this.trackedOrigins.has(l.origin.constructor)))return;const d=this.undoing,f=this.redoing,u=d?this.redoStack:this.undoStack;d?this.stopCapturing():f||this.clear(!1,!0);const m=new js;l.afterState.forEach((b,C)=>{const k=l.beforeState.get(C)||0,D=b-k;D>0&&Ys(m,C,k,D)});const p=un();let g=!1;if(this.lastChange>0&&p-this.lastChange<this.captureTimeout&&u.length>0&&!d&&!f){const b=u[u.length-1];b.deletions=To([b.deletions,l.deleteSet]),b.insertions=To([b.insertions,m])}else u.push(new Ow(l.deleteSet,m)),g=!0;!d&&!f&&(this.lastChange=p),gs(l,l.deleteSet,b=>{b instanceof ge&&this.scope.some(C=>C===l.doc||Xr(C,b))&&Da(b,!0)});const x=[{stackItem:u[u.length-1],origin:l.origin,type:d?"redo":"undo",changedParentTypes:l.changedParentTypes},this];g?this.emit("stack-item-added",x):this.emit("stack-item-updated",x)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=hs(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof Ue?s.doc!==this.doc:s!==this.doc)&&Qd("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,n=!0){(e&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{e&&(this.undoStack.forEach(r=>Zc(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Zc(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Qc(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Qc(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}}function*Pw(t){const e=G(t.restDecoder);for(let n=0;n<e;n++){const s=G(t.restDecoder),r=t.readClient();let i=G(t.restDecoder);for(let a=0;a<s;a++){const c=t.readInfo();if(c===10){const l=G(t.restDecoder);yield new mt(Y(r,i),l),i+=l}else if((ai&c)!==0){const l=(c&(Jt|at))===0,d=new ge(Y(r,i),null,(c&at)===at?t.readLeftID():null,null,(c&Jt)===Jt?t.readRightID():null,l?t.readParentInfo()?t.readString():t.readLeftID():null,l&&(c&Hs)===Hs?t.readString():null,Fu(t,c));yield d,i+=d.length}else{const l=t.readLen();yield new pt(Y(r,i),l),i+=l}}}}class ba{constructor(e,n){this.gen=Pw(e),this.curr=null,this.done=!1,this.filterSkips=n,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===mt);return this.curr}}class va{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const _w=t=>Zr(t,ru,ir),Rw=(t,e)=>{if(t.constructor===pt){const{client:n,clock:s}=t.id;return new pt(Y(n,s+e),t.length-e)}else if(t.constructor===mt){const{client:n,clock:s}=t.id;return new mt(Y(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new ge(Y(s,r+e),null,Y(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},Zr=(t,e=ys,n=jn)=>{if(t.length===1)return t[0];const s=t.map(f=>new e(fn(f)));let r=s.map(f=>new ba(f,!0)),i=null;const a=new n,c=new va(a);for(;r=r.filter(m=>m.curr!==null),r.sort((m,p)=>{if(m.curr.id.client===p.curr.id.client){const g=m.curr.id.clock-p.curr.id.clock;return g===0?m.curr.constructor===p.curr.constructor?0:m.curr.constructor===mt?1:-1:g}else return p.curr.id.client-m.curr.id.client}),r.length!==0;){const f=r[0],u=f.curr.id.client;if(i!==null){let m=f.curr,p=!1;for(;m!==null&&m.id.clock+m.length<=i.struct.id.clock+i.struct.length&&m.id.client>=i.struct.id.client;)m=f.next(),p=!0;if(m===null||m.id.client!==u||p&&m.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)rn(c,i.struct,i.offset),i={struct:m,offset:0},f.next();else if(i.struct.id.clock+i.struct.length<m.id.clock)if(i.struct.constructor===mt)i.struct.length=m.id.clock+m.length-i.struct.id.clock;else{rn(c,i.struct,i.offset);const g=m.id.clock-i.struct.id.clock-i.struct.length;i={struct:new mt(Y(u,i.struct.id.clock+i.struct.length),g),offset:0}}else{const g=i.struct.id.clock+i.struct.length-m.id.clock;g>0&&(i.struct.constructor===mt?i.struct.length-=g:m=Rw(m,g)),i.struct.mergeWith(m)||(rn(c,i.struct,i.offset),i={struct:m,offset:0},f.next())}}else i={struct:f.curr,offset:0},f.next();for(let m=f.curr;m!==null&&m.id.client===u&&m.id.clock===i.struct.id.clock+i.struct.length&&m.constructor!==mt;m=f.next())rn(c,i.struct,i.offset),i={struct:m,offset:0}}i!==null&&(rn(c,i.struct,i.offset),i=null),Sa(c);const l=s.map(f=>ya(f)),d=To(l);return ks(a,d),a.toUint8Array()},Lw=(t,e,n=ys,s=jn)=>{const r=lu(e),i=new s,a=new va(i),c=new n(fn(t)),l=new ba(c,!1);for(;l.curr;){const f=l.curr,u=f.id.client,m=r.get(u)||0;if(l.curr.constructor===mt){l.next();continue}if(f.id.clock+f.length>m)for(rn(a,f,Nn(m-f.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)rn(a,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=m;)l.next()}Sa(a);const d=ya(c);return ks(i,d),i.toUint8Array()},wu=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:me(t.encoder.restEncoder)}),t.encoder.restEncoder=Pe(),t.written=0)},rn=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&wu(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),$(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},Sa=t=>{wu(t);const e=t.encoder.restEncoder;$(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];$(e,s.written),ci(e,s.restEncoder)}},Aw=(t,e,n,s)=>{const r=new n(fn(t)),i=new ba(r,!1),a=new s,c=new va(a);for(let d=i.curr;d!==null;d=i.next())rn(c,e(d),0);Sa(c);const l=ya(r);return ks(a,l),a.toUint8Array()},Fw=t=>Aw(t,Kg,ys,ir),el="You must not compute changes after the event-handler fired.";class yi{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Iw(this.currentTarget,this.target))}deletes(e){return rr(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw kt(el);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let a,c;if(this.adds(i)){let l=i.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(i))if(l!==null&&this.deletes(l))a="delete",c=Wi(l.content.getContent());else return;else l!==null&&this.deletes(l)?(a="update",c=Wi(l.content.getContent())):(a="add",c=void 0)}else if(this.deletes(i))a="delete",c=Wi(i.content.getContent());else return;e.set(r,{action:a,oldValue:c})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw kt(el);const n=this.target,s=dn(),r=dn(),i=[];if(e={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let c=null;const l=()=>{c&&i.push(c)};for(let d=n._start;d!==null;d=d.right)d.deleted?this.deletes(d)&&!this.adds(d)&&((c===null||c.delete===void 0)&&(l(),c={delete:0}),c.delete+=d.length,r.add(d)):this.adds(d)?((c===null||c.insert===void 0)&&(l(),c={insert:[]}),c.insert=c.insert.concat(d.content.getContent()),s.add(d)):((c===null||c.retain===void 0)&&(l(),c={retain:0}),c.retain+=d.length);c!==null&&c.retain===void 0&&l()}this._changes=e}return e}}const Iw=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let s=0,r=e._item.parent._start;for(;r!==e._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}e=e._item.parent}return n},Je=()=>{Qd("Invalid access: Add Yjs type to a document before reading data.")},xu=80;let Ca=0;class Mw{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=Ca++}}const $w=t=>{t.timestamp=Ca++},bu=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=Ca++},Uw=(t,e,n)=>{if(t.length>=xu){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return bu(s,e,n),s}else{const s=new Mw(e,n);return t.push(s),s}},wi=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((i,a)=>Ar(e-i.index)<Ar(e-a.index)?i:a);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,$w(n));s.right!==null&&r<e;){if(!s.deleted&&s.countable){if(e<r+s.length)break;r+=s.length}s=s.right}for(;s.left!==null&&r>e;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&Ar(n.index-r)<s.parent.length/xu?(bu(n,s,r),n):Uw(t._searchMarker,s,r)},Xs=(t,e,n)=>{for(let s=t.length-1;s>=0;s--){const r=t[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){t.splice(s,1);continue}r.p=i,i.marker=!0}(e<r.index||n>0&&e===r.index)&&(r.index=Nn(e,r.index+n))}},xi=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;At(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;uu(s._eH,n,e)};class Ue{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wc(),this._dEH=Wc(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw St()}clone(){throw St()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Kc(this._eH,e)}observeDeep(e){Kc(this._dEH,e)}unobserve(e){Gc(this._eH,e)}unobserveDeep(e){Gc(this._dEH,e)}toJSON(){}}const vu=(t,e,n)=>{t.doc??Je(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let s=n-e;const r=[];let i=t._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const a=i.content.getContent();if(a.length<=e)e-=a.length;else{for(let c=e;c<a.length&&s>0;c++)r.push(a[c]),s--;e=0}}i=i.right}return r},Su=t=>{t.doc??Je();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r<s.length;r++)e.push(s[r])}n=n.right}return e},Zs=(t,e)=>{let n=0,s=t._start;for(t.doc??Je();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)e(r[i],n++,t)}s=s.right}},Cu=(t,e)=>{const n=[];return Zs(t,(s,r)=>{n.push(e(s,r,t))}),n},zw=t=>{let e=t._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),s=0,e=e.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},ju=(t,e)=>{t.doc??Je();const n=wi(t,e);let s=t._start;for(n!==null&&(s=n.p,e-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(e<s.length)return s.content.getContent()[e];e-=s.length}},Qr=(t,e,n,s)=>{let r=n;const i=t.doc,a=i.clientID,c=i.store,l=n===null?e._start:n.right;let d=[];const f=()=>{d.length>0&&(r=new ge(Y(a,De(c,a)),r,r&&r.lastId,l,l&&l.id,e,null,new En(d)),r.integrate(t,0),d=[])};s.forEach(u=>{if(u===null)d.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:d.push(u);break;default:switch(f(),u.constructor){case Uint8Array:case ArrayBuffer:r=new ge(Y(a,De(c,a)),r,r&&r.lastId,l,l&&l.id,e,null,new or(new Uint8Array(u))),r.integrate(t,0);break;case Tn:r=new ge(Y(a,De(c,a)),r,r&&r.lastId,l,l&&l.id,e,null,new ar(u)),r.integrate(t,0);break;default:if(u instanceof Ue)r=new ge(Y(a,De(c,a)),r,r&&r.lastId,l,l&&l.id,e,null,new It(u)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),f()},ku=()=>kt("Length exceeded!"),Eu=(t,e,n,s)=>{if(n>e._length)throw ku();if(n===0)return e._searchMarker&&Xs(e._searchMarker,n,s.length),Qr(t,e,null,s);const r=n,i=wi(e,n);let a=e._start;for(i!==null&&(a=i.p,n-=i.index,n===0&&(a=a.prev,n+=a&&a.countable&&!a.deleted?a.length:0));a!==null;a=a.right)if(!a.deleted&&a.countable){if(n<=a.length){n<a.length&&it(t,Y(a.id.client,a.id.clock+n));break}n-=a.length}return e._searchMarker&&Xs(e._searchMarker,r,s.length),Qr(t,e,a,s)},Vw=(t,e,n)=>{let r=(e._searchMarker||[]).reduce((i,a)=>a.index>i.index?a:i,{index:0,p:e._start}).p;if(r)for(;r.right;)r=r.right;return Qr(t,e,r,n)},Du=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,a=wi(e,n);let c=e._start;for(a!==null&&(c=a.p,n-=a.index);c!==null&&n>0;c=c.right)!c.deleted&&c.countable&&(n<c.length&&it(t,Y(c.id.client,c.id.clock+n)),n-=c.length);for(;s>0&&c!==null;)c.deleted||(s<c.length&&it(t,Y(c.id.client,c.id.clock+s)),c.delete(t),s-=c.length),c=c.right;if(s>0)throw ku();e._searchMarker&&Xs(e._searchMarker,r,-i+s)},ei=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},ja=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,a=i.clientID;let c;if(s==null)c=new En([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new En([s]);break;case Uint8Array:c=new or(s);break;case Tn:c=new ar(s);break;default:if(s instanceof Ue)c=new It(s);else throw new Error("Unexpected content type")}new ge(Y(a,De(i.store,a)),r,r&&r.lastId,null,null,e,n,c).integrate(t,0)},ka=(t,e)=>{t.doc??Je();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Nu=t=>{const e={};return t.doc??Je(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},Tu=(t,e)=>{t.doc??Je();const n=t._map.get(e);return n!==void 0&&!n.deleted},Bw=(t,e)=>{const n={};return t._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!e.sv.has(i.id.client)||i.id.clock>=(e.sv.get(i.id.client)||0));)i=i.left;i!==null&&Yn(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},Pr=t=>(t.doc??Je(),iw(t._map.entries(),e=>!e[1].deleted));class Hw extends yi{}class os extends Ue{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new os;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new os}clone(){const e=new os;return e.insert(0,this.toArray().map(n=>n instanceof Ue?n.clone():n)),e}get length(){return this.doc??Je(),this._length}_callObserver(e,n){super._callObserver(e,n),xi(this,e,new Hw(this,e))}insert(e,n){this.doc!==null?pe(this.doc,s=>{Eu(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?pe(this.doc,n=>{Vw(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?pe(this.doc,s=>{Du(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return ju(this,e)}toArray(){return Su(this)}slice(e=0,n=this.length){return vu(this,e,n)}toJSON(){return this.map(e=>e instanceof Ue?e.toJSON():e)}map(e){return Cu(this,e)}forEach(e){Zs(this,e)}[Symbol.iterator](){return zw(this)}_write(e){e.writeTypeRef(mx)}}const qw=t=>new os;class Ww extends yi{constructor(e,n,s){super(e,n),this.keysChanged=s}}class ws extends Ue{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new ws}clone(){const e=new ws;return this.forEach((n,s)=>{e.set(s,n instanceof Ue?n.clone():n)}),e}_callObserver(e,n){xi(this,e,new Ww(this,e,n))}toJSON(){this.doc??Je();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof Ue?r.toJSON():r}}),e}get size(){return[...Pr(this)].length}keys(){return Qi(Pr(this),e=>e[0])}values(){return Qi(Pr(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Qi(Pr(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Je(),this._map.forEach((n,s)=>{n.deleted||e(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?pe(this.doc,n=>{ei(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?pe(this.doc,s=>{ja(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return ka(this,e)}has(e){return Tu(this,e)}clear(){this.doc!==null?pe(this.doc,e=>{this.forEach(function(n,s,r){ei(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(gx)}}const Kw=t=>new ws,on=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&qg(t,e);class _o{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ct(),this.right.content.constructor===Ae?this.right.deleted||Es(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const tl=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===Ae?e.right.deleted||Es(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&it(t,Y(e.right.id.client,e.right.id.clock+n)),e.index+=e.right.length,n-=e.right.length),e.left=e.right,e.right=e.right.right;return e},_r=(t,e,n,s)=>{const r=new Map,i=s?wi(e,n):null;if(i){const a=new _o(i.p.left,i.p,i.index,r);return tl(t,a,n-i.index)}else{const a=new _o(null,e._start,0,r);return tl(t,a,n)}},Ou=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Ae&&on(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=t.doc,i=r.clientID;s.forEach((a,c)=>{const l=n.left,d=n.right,f=new ge(Y(i,De(r.store,i)),l,l&&l.lastId,d,d&&d.id,e,null,new Ae(c,a));f.integrate(t,0),n.right=f,n.forward()})},Es=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},Pu=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Ae&&on(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},_u=(t,e,n,s)=>{const r=t.doc,i=r.clientID,a=new Map;for(const c in s){const l=s[c],d=n.currentAttributes.get(c)??null;if(!on(d,l)){a.set(c,d);const{left:f,right:u}=n;n.right=new ge(Y(i,De(r.store,i)),f,f&&f.lastId,u,u&&u.id,e,null,new Ae(c,l)),n.right.integrate(t,0),n.forward()}}return a},eo=(t,e,n,s,r)=>{n.currentAttributes.forEach((m,p)=>{r[p]===void 0&&(r[p]=null)});const i=t.doc,a=i.clientID;Pu(n,r);const c=_u(t,e,n,r),l=s.constructor===String?new Rt(s):s instanceof Ue?new It(s):new On(s);let{left:d,right:f,index:u}=n;e._searchMarker&&Xs(e._searchMarker,n.index,l.getLength()),f=new ge(Y(a,De(i.store,a)),d,d&&d.lastId,f,f&&f.id,e,null,l),f.integrate(t,0),n.right=f,n.index=u,n.forward(),Ou(t,e,n,c)},nl=(t,e,n,s,r)=>{const i=t.doc,a=i.clientID;Pu(n,r);const c=_u(t,e,n,r);e:for(;n.right!==null&&(s>0||c.size>0&&(n.right.deleted||n.right.content.constructor===Ae));){if(!n.right.deleted)switch(n.right.content.constructor){case Ae:{const{key:l,value:d}=n.right.content,f=r[l];if(f!==void 0){if(on(f,d))c.delete(l);else{if(s===0)break e;c.set(l,d)}n.right.delete(t)}else n.currentAttributes.set(l,d);break}default:s<n.right.length&&it(t,Y(n.right.id.client,n.right.id.clock+s)),s-=n.right.length;break}n.forward()}if(s>0){let l="";for(;s>0;s--)l+=`
|
|
10
10
|
`;n.right=new ge(Y(a,De(i.store,a)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Rt(l)),n.right.integrate(t,0),n.forward()}Ou(t,e,n,c)},Ru=(t,e,n,s,r)=>{let i=e;const a=ot();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Ae){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===Ae){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&&Es(r,d)}}e=e.right}return c},Gw=(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===Ae){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},Jw=t=>{let e=0;return pe(t.doc,n=>{let s=t._start,r=t._start,i=ot();const a=Co(i);for(;r;)r.deleted===!1&&(r.content.constructor===Ae?Es(a,r.content):(e+=Ru(n,s,r,i,a),i=Co(a),s=r)),r=r.right}),e},Yw=t=>{const e=new Set,n=t.doc;for(const[s,r]of t.afterState.entries()){const i=t.beforeState.get(s)||0;r!==i&&gu(t,n.store.clients.get(s),i,r,a=>{!a.deleted&&a.content.constructor===Ae&&a.constructor!==pt&&e.add(a.parent)})}pe(n,s=>{gs(t,t.deleteSet,r=>{if(r instanceof pt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===Ae?e.add(i):Gw(s,r)});for(const r of e)Jw(r)})},sl=(t,e,n)=>{const s=n,r=Co(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case It:case On:case Rt:n<e.right.length&&it(t,Y(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&Ru(t,i,e.right,r,e.currentAttributes);const a=(e.left||e.right).parent;return a._searchMarker&&Xs(a._searchMarker,e.index,-s+n),e};class Xw 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=[];pe(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},Hg(l)||(p.attributes=Ug({},l))),f=0;break}p&&n.push(p),c=null}};for(;a!==null;){switch(a.content.constructor){case It:case On: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 Rt: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 Ae:{const{key:p,value:g}=a.content;if(this.adds(a)){if(!this.deletes(a)){const x=r.get(p)??null;on(x,g)?g!==null&&a.delete(s):(c==="retain"&&m(),on(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;on(x,g)||(c==="retain"&&m(),l[p]=x)}else if(!a.deleted){i.set(p,g);const x=l[p];x!==void 0&&(on(x,g)?x!==null&&a.delete(s):(c==="retain"&&m(),g===null?delete l[p]:l[p]=g))}a.deleted||(c==="insert"&&m(),Es(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 xs extends Ue{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Je(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new xs}clone(){const e=new xs;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new Xw(this,e,n);xi(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Je();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Rt&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?pe(this.doc,s=>{const r=new _o(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)&&eo(s,this,r,c,a.attributes||{})}else a.retain!==void 0?nl(s,this,r,a.retain,a.attributes||{}):a.delete!==void 0&&sl(s,r,a.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??Je();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(Yn(l,e)||n!==void 0&&Yn(l,n))switch(l.content.constructor){case Rt:{const u=i.get("ychange");e!==void 0&&!Yn(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&&!Yn(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 It:case On:{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 Ae:Yn(l,e)&&(d(),Es(i,l.content));break}l=l.right}d()};return e||n?pe(a,u=>{e&&Oo(u,e),n&&Oo(u,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?pe(r,i=>{const a=_r(i,this,e,!s);s||(s={},a.currentAttributes.forEach((c,l)=>{s[l]=c})),eo(i,this,a,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?pe(r,i=>{const a=_r(i,this,e,!s);eo(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?pe(s,r=>{sl(r,_r(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?pe(r,i=>{const a=_r(i,this,e,!1);a.right!==null&&nl(i,this,a,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?pe(this.doc,n=>{ei(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?pe(this.doc,s=>{ja(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return ka(this,e)}getAttributes(){return Nu(this)}_write(e){e.writeTypeRef(yx)}}const Zw=t=>new xs;class to{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Je()}[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===bs||n.constructor===kn)&&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 kn extends Ue{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 kn}clone(){const e=new kn;return e.insert(0,this.toArray().map(n=>n instanceof Ue?n.clone():n)),e}get length(){return this.doc??Je(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new to(this,e)}querySelector(e){e=e.toUpperCase();const s=new to(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),Zt(new to(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){xi(this,e,new tx(this,n,e))}toString(){return Cu(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),Zs(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?pe(this.doc,s=>{Eu(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)pe(this.doc,s=>{const r=e&&e instanceof Ue?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 kt("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?pe(this.doc,s=>{Du(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return Su(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ju(this,e)}slice(e=0,n=this.length){return vu(this,e,n)}forEach(e){Zs(this,e)}_write(e){e.writeTypeRef(xx)}}const Qw=t=>new kn;class bs extends kn{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 bs(this.nodeName)}clone(){const e=new bs(this.nodeName),n=this.getAttributes();return Vg(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof Ue?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?pe(this.doc,n=>{ei(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?pe(this.doc,s=>{ja(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return ka(this,e)}hasAttribute(e){return Tu(this,e)}getAttributes(e){return e?Bw(this,e):Nu(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 Zs(this,a=>{r.appendChild(a.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(wx),e.writeKey(this.nodeName)}}const ex=t=>new bs(t.readKey());class tx 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 ws{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(bx),e.writeKey(this.hookName)}}const nx=t=>new ti(t.readKey());class ni extends xs{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new 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(vx)}}const sx=t=>new ni;class Ea{constructor(e,n){this.id=e,this.length=n}get deleted(){throw St()}mergeWith(e){return!1}write(e,n,s){throw St()}integrate(e,n){throw St()}}const rx=0;class pt extends Ea{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),mu(e.doc.store,this)}write(e,n){e.writeInfo(rx),e.writeLen(this.length-n)}getMissing(e,n){return null}}class or{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new or(this.content)}splice(e){throw St()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const ix=t=>new or(t.readBuf());class Qs{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Qs(this.len)}splice(e){const n=new Qs(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){Ys(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 ox=t=>new Qs(t.readLen()),Lu=(t,e)=>new Tn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class ar{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 ar(Lu(this.doc.guid,this.opts))}splice(e){throw St()}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 ax=t=>new ar(Lu(t.readString(),t.readAny()));class On{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new On(this.embed)}splice(e){throw St()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const cx=t=>new On(t.readJSON());class Ae{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Ae(this.key,this.value)}splice(e){throw St()}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 lx=t=>new Ae(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 dx=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)},ux=Gr("node_env")==="development";class En{constructor(e){this.arr=e,ux&&Dd(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new En(this.arr)}splice(e){const n=new En(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 hx=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new En(n)};class Rt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Rt(this.str)}splice(e){const n=new Rt(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 fx=t=>new Rt(t.readString()),px=[qw,Kw,Zw,ex,Qw,nx,sx],mx=0,gx=1,yx=2,wx=3,xx=4,bx=5,vx=6;class It{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new It(this.type._copy())}splice(e){throw St()}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 Sx=t=>new It(px[t.readTypeRef()](t)),Ro=(t,e)=>{let n=e,s=0,r;do s>0&&(n=Y(n.client,n.clock+s)),r=is(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof ge);return{item:r,diff:s}},Da=(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 ge(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},rl=(t,e)=>Qo(t,n=>rr(n.deletions,e)),Au=(t,e,n,s,r,i)=>{const a=t.doc,c=a.store,l=a.clientID,d=e.redone;if(d!==null)return it(t,d);let f=e.parent._item,u=null,m;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||Au(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=it(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 C=u;for(;C!==null&&C.parent._item!==f;)C=C.redone===null?null:it(t,C.redone);if(C!==null&&C.parent._item===f){u=C;break}u=u.left}for(;m!==null;){let C=m;for(;C!==null&&C.parent._item!==f;)C=C.redone===null?null:it(t,C.redone);if(C!==null&&C.parent._item===f){m=C;break}m=m.right}}else{if(m=null,e.right&&!r){for(u=e;u!==null&&u.right!==null&&(u.right.redone||rr(s,u.right.id)||rl(i.undoStack,u.right.id)||rl(i.redoStack,u.right.id));)for(u=u.right;u.redone;)u=it(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=De(c,l),x=Y(l,g),b=new ge(x,u,u&&u.lastId,m,m&&m.id,p,e.parentSub,e.content.copy());return e.redone=x,Da(b,!0),b.integrate(t,0),b};class ge extends Ea{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()?Lc:0}set marker(e){(this.info&Gi)>0!==e&&(this.info^=Gi)}get marker(){return(this.info&Gi)>0}get keep(){return(this.info&Rc)>0}set keep(e){this.keep!==e&&(this.info^=Rc)}get countable(){return(this.info&Lc)>0}get deleted(){return(this.info&Ki)>0}set deleted(e){this.deleted!==e&&(this.info^=Ki)}markDeleted(){this.info|=Ki}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=De(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=De(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===rs&&this.id.client!==this.parent.client&&this.parent.clock>=De(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Jc(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=it(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===pt||this.right&&this.right.constructor===pt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===ge?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===ge&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===rs){const s=is(n,this.parent);s.constructor===pt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=Jc(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),es(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(es(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&a.has(is(e.doc.store,r.origin)))i.has(is(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),mu(e.doc.store,this),this.content.integrate(e,this),Xc(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new pt(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&&es(e.origin,this.lastId)&&this.right===e&&es(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(),Ys(e.deleteSet,this.id.client,this.id.clock,this.length),Xc(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw ct();this.content.gc(e),n?Ew(e,this,new pt(this.id,this.length)):this.content=new Qs(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:at)|(r===null?0:Jt)|(i===null?0:Hs);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=hu(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===rs?(e.writeParentInfo(!1),e.writeLeftID(c)):ct();i!==null&&e.writeString(i)}this.content.write(e,n)}}const Fu=(t,e)=>Cx[e&ai](t),Cx=[()=>{ct()},ox,dx,ix,fx,cx,lx,Sx,hx,ax,()=>{ct()}],jx=10;class mt extends Ea{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){ct()}write(e,n){e.writeInfo(jx),$(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Iu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Mu="__ $YJS$ __";Iu[Mu]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Iu[Mu]=!0;const $u=new Map;class kx{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:oy(n.newValue||"")}),Ig(this._onChange)}postMessage(e){kd.setItem(this.room,iy(ey(e)))}close(){Mg(this._onChange)}}const Ex=typeof BroadcastChannel>"u"?kx:BroadcastChannel,Na=t=>At($u,t,()=>{const e=dn(),n=new Ex(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),Dx=(t,e)=>(Na(t).subs.add(e),e),Nx=(t,e)=>{const n=Na(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),$u.delete(t)),s},Xn=(t,e,n=null)=>{const s=Na(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},Uu=0,Ta=1,zu=2,ii=(t,e)=>{$(t,Uu);const n=bw(e);je(t,n)},Vu=(t,e,n)=>{$(t,Ta),je(t,xa(e,n))},Tx=(t,e,n)=>Vu(e,n,Ge(t)),Bu=(t,e,n,s)=>{try{cu(e,Ge(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Ox=(t,e)=>{$(t,zu),je(t,e)},Px=Bu,_x=(t,e,n,s,r)=>{const i=G(t);switch(i){case Uu:Tx(t,e,n);break;case Ta:Bu(t,n,s,r);break;case zu:Px(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Rx=0,Lx=(t,e,n)=>{G(t)===Rx&&n(e,Ct(t))},no=3e4;class Ax extends wd{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=un();this.getLocalState()!==null&&no/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&no<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Oa(this,s,"timeout")},jt(no/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:un()});const a=[],c=[],l=[],d=[];e===null?d.push(n):i==null?e!=null&&a.push(n):(c.push(n),ns(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 Oa=(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:un()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},as=(t,e,n=t.states)=>{const s=e.length,r=Pe();$(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),Yt(r,JSON.stringify(c))}return me(r)},Fx=(t,e,n)=>{const s=fn(e),r=un(),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(Ct(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&&(ns(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])},Ix=t=>Bg(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),Sn=0,Hu=3,cs=1,Mx=2,cr=[];cr[Sn]=(t,e,n,s,r)=>{$(t,Sn);const i=_x(e,t,n.doc,n);s&&i===Ta&&!n.synced&&(n.synced=!0)};cr[Hu]=(t,e,n,s,r)=>{$(t,cs),je(t,as(n.awareness,Array.from(n.awareness.getStates().keys())))};cr[cs]=(t,e,n,s,r)=>{Fx(n.awareness,Ge(e),n)};cr[Mx]=(t,e,n,s,r)=>{Lx(e,n.doc,(i,a)=>$x(n,a))};const il=3e4,$x=(t,e)=>console.warn(`Permission denied to access ${t.url}.
|
|
12
|
-
${e}`),qu=(t,e,n)=>{const s=fn(e),r=Pe(),i=G(s),a=t.messageHandlers[i];return a?a(r,s,t,n,i):console.error("Unable to compute message"),r},Lo=(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,Oa(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Wu,ta(rg(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Wu=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=un();const s=qu(t,new Uint8Array(n.data),!0);na(s)>1&&e.send(me(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Lo(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=un(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Pe();if($(n,Sn),ii(n,t.doc),e.send(me(n)),t.awareness.getLocalState()!==null){const s=Pe();$(s,cs),je(s,as(t.awareness,[t.doc.clientID])),e.send(me(s))}},t.emit("status",[{status:"connecting"}])}},so=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Xn(t.bcChannel,e,t)};class Ux extends ea{constructor(e,n,s,{connect:r=!0,awareness:i=new Ax(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=cr.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=Pe();$(m,Sn),ii(m,s),this.ws.send(me(m))}},d)),this._bcSubscriber=(m,p)=>{if(p!==this){const g=qu(this,new Uint8Array(m),!1);na(g)>1&&Xn(this.bcChannel,me(g),this)}},this._updateHandler=(m,p)=>{if(p!==this){const g=Pe();$(g,Sn),Ox(g,m),so(this,me(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:m,updated:p,removed:g},x)=>{const b=m.concat(p).concat(g),C=Pe();$(C,cs),je(C,as(i,b)),so(this,me(C))},this._exitHandler=()=>{Oa(this.awareness,[s.clientID],"app closed")},hn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&il<un()-this.wsLastMessageReceived&&Lo(this,this.ws,null)},il/10),r&&this.connect()}get url(){const e=Ix(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(),hn&&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||(Dx(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Pe();$(e,Sn),ii(e,this.doc),Xn(this.bcChannel,me(e),this);const n=Pe();$(n,Sn),Vu(n,this.doc),Xn(this.bcChannel,me(n),this);const s=Pe();$(s,Hu),Xn(this.bcChannel,me(s),this);const r=Pe();$(r,cs),je(r,as(this.awareness,[this.doc.clientID])),Xn(this.bcChannel,me(r),this)}disconnectBc(){const e=Pe();$(e,cs),je(e,as(this.awareness,[this.doc.clientID],new Map)),so(this,me(e)),this.bcconnected&&(Nx(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Lo(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Wu(this),this.connectBc())}}const Pn=t=>ps((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),zx=(t,e)=>ps((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(kt(i.target.error)),r.onsuccess=i=>{const a=i.target.result;a.onversionchange=()=>{a.close()},n(a)}}),Vx=t=>Pn(indexedDB.deleteDatabase(t)),Bx=(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=>Xx(s,r))},Ku=(t,e)=>Pn(t.count(e)),Hx=(t,e)=>Pn(t.get(e)),Gu=(t,e)=>Pn(t.delete(e)),qx=(t,e,n)=>Pn(t.put(e,n)),Ao=(t,e)=>Pn(t.add(e)),Wx=(t,e,n)=>Pn(t.getAll(e,n)),Kx=(t,e,n)=>{let s=null;return Yx(t,e,r=>(s=r,!1),n).then(()=>s)},Gx=(t,e=null)=>Kx(t,e,"prev"),Jx=(t,e)=>ps((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()}}),Yx=(t,e,n,s="next")=>Jx(t.openKeyCursor(e,s),r=>n(r.key)),Xx=(t,e)=>t.objectStore(e),Zx=(t,e)=>IDBKeyRange.upperBound(t,e),Qx=(t,e)=>IDBKeyRange.lowerBound(t,e),ro="custom",Ju="updates",Yu=500,Xu=(t,e=()=>{},n=()=>{})=>{const[s]=As(t.db,[Ju]);return Wx(s,Qx(t._dbref,!1)).then(r=>{t._destroyed||(e(s),pe(t.doc,()=>{r.forEach(i=>cu(t.doc,i))},t,!1),n(s))}).then(()=>Gx(s).then(r=>{t._dbref=r+1})).then(()=>Ku(s).then(r=>{t._dbsize=r})).then(()=>s)},eb=(t,e=!0)=>Xu(t).then(n=>{(e||t._dbsize>=Yu)&&Ao(n,xa(t.doc)).then(()=>Gu(n,Zx(t._dbref,!0))).then(()=>Ku(n).then(s=>{t._dbsize=s}))});class tb extends wd{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=zx(e,s=>Bx(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=ps(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Xu(this,a=>Ao(a,xa(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,[Ju]);Ao(i,s),++this._dbsize>=Yu&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{eb(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(()=>{Vx(this.name)})}get(e){return this._db.then(n=>{const[s]=As(n,[ro],"readonly");return Hx(s,e)})}set(e,n){return this._db.then(s=>{const[r]=As(s,[ro]);return qx(r,n,e)})}del(e){return this._db.then(n=>{const[s]=As(n,[ro]);return Gu(s,e)})}}const ol=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],al=4,cl=5;function nb(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!["queued","running","succeeded","failed","cleaned"].includes(e.status??"")||e.status==="cleaned"&&e.cleanMode!=="cache"&&e.cleanMode!=="artifacts"||typeof e.updatedAt!="string"||!n||typeof n.id!="string"||typeof n.username!="string"||typeof n.name!="string"?null:e}function ll(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=nb(s);r&&r.mainFile===n&&(e[n]=r)}return e}class sb{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.persistence=new tb(`texlite:${n.id}:${e}`,this.doc),this.persistence.on("synced",()=>{this.localDraftReady=!0;for(const r of this.draftListeners)r()}),this.provider=new Ux(`${s}//${window.location.host}/api/collaboration`,e,this.doc,{disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness,this.provider.messageHandlers[al]=(r,i)=>{const a=Ct(i),c=this.flushRequests.get(a);if(!c)return;const l=G(i),d=Ct(i);window.clearTimeout(c.timer),this.flushRequests.delete(a),c.resolve({revision:l,persistedAt:d})},this.provider.messageHandlers[cl]=(r,i)=>{const a=Ct(i),c=this.epochStorageKey(),l=rb(c);if(this.epoch&&this.epoch!==a||l&&l!==a){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed")),this.persistence.clearData().then(()=>{dl(c,a),window.location.reload()});return}this.epoch=a,dl(c,a);const d=this.provider.ws;if(!d||d.readyState!==WebSocket.OPEN)return;const f=Pe();$(f,cl),Yt(f,a),d.send(me(f));const u=Pe();$(u,0),ii(u,this.doc),d.send(me(u));const m=Pe();$(m,1),je(m,as(this.awareness,[this.doc.clientID])),d.send(me(m))},this.provider.on("status",({status:r})=>{r==="disconnected"&&this.rejectFlushes(new Error("Collaboration connection closed"))}),this.updateLocalAwareness()}projectId;user;doc=new Tn;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=Pe();return $(s,al),Yt(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(me(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]=ol[Math.abs(this.doc.clientID)%ol.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 rb(t){try{return window.localStorage.getItem(t)}catch{return null}}function dl(t,e){try{window.localStorage.setItem(t,e)}catch{}}function ib(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function ob({sessions:t,status:e}){const{t:n}=_e(),[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:[ib(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 ab({value:t,onChange:e}){const{t:n}=_e(),[s,r]=h.useState(!1),i=h.useRef(null),a=[{value:"editor-pdf",icon:Cc},{value:"editor-only",icon:Rm},{value:"pdf-only",icon:Lm}];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(Cc,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(ud,{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(wm,{size:16})]},c.value)})]})]})}function cb({comment:t,currentUserId:e,onFocus:n,onToggle:s,onReply:r,onEdit:i,onDelete:a,onEditReply:c,onDeleteReply:l}){const{t:d}=_e(),[f,u]=h.useState(!1),[m,p]=h.useState(""),[g,x]=h.useState(!1),[b,C]=h.useState(t.content),[k,D]=h.useState(!1),[T,O]=h.useState(null),[F,E]=h.useState(""),[q,v]=h.useState(null),P=async S=>{S.preventDefault(),m.trim()&&await r(m)&&(p(""),u(!1))},X=async S=>{S.preventDefault(),b.trim()&&await i(b)&&x(!1)},W=async S=>{S.preventDefault(),!(!T||!F.trim())&&await c(T,F)&&O(null)},_=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??_??d("editor.deletedUser")}),_&&o.jsxs("small",{children:["@",_]})]}),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=>{X(S)},onClick:S=>S.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:4,value:b,onChange:S=>C(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:M=>{W(M)},onClick:M=>M.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:3,value:F,onChange:M=>E(M.target.value)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>O(null),children:d("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!F.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:M=>{M.stopPropagation(),O(S.id),E(S.content)},children:o.jsx(vo,{size:12})}),o.jsx("button",{className:"danger-text",title:d("editor.deleteReply"),"aria-label":d("editor.deleteReply"),onClick:M=>{M.stopPropagation(),v(S.id)},children:o.jsx(ln,{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(Im,{size:13}):o.jsx(vm,{size:13}),t.resolved?d("editor.reopen"):d("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:S=>{S.stopPropagation(),u(M=>!M)},children:[o.jsx(Fm,{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(),C(t.content),x(!0)},children:o.jsx(vo,{size:13})}),o.jsx("button",{className:"danger-text",title:d("editor.deleteComment"),"aria-label":d("editor.deleteComment"),onClick:S=>{S.stopPropagation(),D(!0)},children:o.jsx(ln,{size:13})})]})]}),f&&o.jsxs("form",{className:"comment-reply-form",onSubmit:S=>{P(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($m,{size:13}),d("editor.sendReply")]})]})]})]}),o.jsx(ds,{open:k,title:d("editor.deleteCommentTitle"),description:d("editor.deleteCommentDescription",{count:t.replies.length}),confirmLabel:d("common.delete"),danger:!0,onCancel:()=>D(!1),onConfirm:()=>{a().then(S=>{S&&D(!1)})}}),o.jsx(ds,{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 lb({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=_e(),[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(""),C=n.permission==="owner",k=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&&k()},[t,s]);const D=async()=>{if(d)try{await A(`/api/projects/${s}/members/${d}`,{method:"PUT",body:JSON.stringify({permission:u})}),f(""),m("read"),await k()}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 k()}catch(v){b(V(v))}},O=async()=>{if(p)try{await A(`/api/projects/${s}/members/${p.id}`,{method:"DELETE"}),g(null),await k()}catch(E){b(V(E))}},F=c.filter(E=>!i.some(q=>q.id===E.id));return o.jsxs(o.Fragment,{children:[o.jsx($e,{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(Bs,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),C&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:d,onChange:E=>f(E.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),F.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:()=>{D()},children:[o.jsx(gd,{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:!C,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")})]}),C&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(E),children:o.jsx(ln,{size:15})})]})]},E.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(Bs,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(ds,{open:!!p,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:p?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{O()}})]})}function db({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}=_e(),[g,x]=h.useState(t.engine),[b,C]=h.useState(""),[k,D]=h.useState(t.name),[T,O]=h.useState(t.mainFile),[F,E]=h.useState(""),[q,v]=h.useState(""),[P,X]=h.useState(""),[W,_]=h.useState("appearance"),[R,S]=h.useState(a),M=t.permission==="owner",ue=t.permission!=="read",se=t.permission!=="read";h.useEffect(()=>S(a),[a]),h.useEffect(()=>{if(!t.latexmkrc)return C("");A(`/api/projects/${e}/file?path=${encodeURIComponent(t.latexmkrc)}`).then(({content:N})=>C(N)).catch(N=>E(V(N)))},[t.latexmkrc]);const be=s.filter(N=>N.type==="file"&&/\.tex$/i.test(N.path)).map(N=>N.path),Q=[...new Set(t.mainFile.toLowerCase().endsWith(".tex")?[...be,t.mainFile]:be)].sort((N,B)=>N.localeCompare(B)),ee=async()=>{try{const N=b.trim()&&n.allowProjectLatexmkrc!==!1?".latexmkrc":null;N&&await A(`/api/projects/${e}/file`,{method:"PUT",body:JSON.stringify({path:N,content:b})});const B=await A(`/api/projects/${e}`,{method:"PATCH",body:JSON.stringify({name:k,mainFile:T,engine:g,latexmkrc:N})});m(B.project)}catch(N){E(V(N))}},ce=()=>c(R),xe=async()=>{const N=q.trim();if(N)try{const B=await A(`/api/projects/${e}/dictionary`,{method:"POST",body:JSON.stringify({word:N})});i(B.words),v(""),X("")}catch(B){X(V(B))}},ie=async N=>{try{const B=await A(`/api/projects/${e}/dictionary/${encodeURIComponent(N)}`,{method:"DELETE"});i(B.words),X("")}catch(B){X(V(B))}};return o.jsxs("div",{className:"settings padded",children:[F&&o.jsx("p",{className:"error",children:F}),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:()=>_("appearance"),children:[o.jsx(Dc,{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:()=>_("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(Dc,{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:N=>S({...R,font:N.target.value}),children:qr.map(N=>o.jsx("option",{value:N.id,children:p(N.labelKey)},N.id))})]}),o.jsxs("label",{children:[p("projectSettings.fontSize"),o.jsx("select",{value:R.fontSize,onChange:N=>S({...R,fontSize:Number(N.target.value)}),children:[12,13,14,15,16,18,20].map(N=>o.jsxs("option",{value:N,children:[N," px"]},N))})]}),o.jsxs("label",{children:[p("projectSettings.lineHeight"),o.jsxs("select",{value:R.lineHeight,onChange:N=>S({...R,lineHeight:Number(N.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:N=>S({...R,lineWrapping:N.target.checked})}),o.jsx(Vm,{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:N=>S({...R,spellCheck:N.target.checked})}),o.jsx("span",{children:p("projectSettings.spellCheck")})]}),o.jsxs("p",{className:"field-hint",children:[p("projectSettings.writingCheckDescription")," ",o.jsx("a",{href:"https://writewithharper.com/docs/harperjs/introduction",target:"_blank",rel:"noreferrer",children:"Harper.js"})]}),o.jsxs("label",{className:"editor-checkbox",children:[o.jsx("input",{type:"checkbox",checked:R.vimMode,onChange:N=>S({...R,vimMode:N.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:!ue,checked:R.formatOnCompile,onChange:N=>S({...R,formatOnCompile:N.target.checked})}),o.jsx(cd,{size:15}),o.jsx("span",{children:p("projectSettings.formatOnCompile")})]}),o.jsxs("p",{className:"field-hint",children:[p(ue?"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(zm,{size:14}),o.jsx("span",{children:l?p("projectSettings.writingIssues",{count:l,uniqueCount:d??0}):p("projectSettings.noWritingIssues")}),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(xm,{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(hd,{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(Jo,{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(bm,{size:14})})]})]}),o.jsxs("div",{className:"settings-section-title",children:[o.jsx(dd,{size:15}),o.jsx("strong",{children:p("projectSettings.dictionary")})]}),o.jsx("p",{className:"settings-description",children:p("projectSettings.dictionaryDescription")}),P&&o.jsx("p",{className:"error dictionary-error",children:P}),se&&o.jsxs("div",{className:"dictionary-add",children:[o.jsx("input",{value:q,placeholder:p("projectSettings.dictionaryPlaceholder"),onChange:N=>v(N.target.value),onKeyDown:N=>{N.key==="Enter"&&(N.preventDefault(),xe())}}),o.jsx("button",{type:"button",disabled:!q.trim(),onClick:()=>{xe()},children:p("projectSettings.addWord")})]}),o.jsxs("div",{className:"dictionary-words",children:[r.map(N=>o.jsxs("span",{className:"dictionary-word",children:[o.jsx("code",{children:N}),se&&o.jsx("button",{type:"button",title:p("common.delete"),"aria-label":`${p("common.delete")} ${N}`,onClick:()=>{ie(N)},children:o.jsx(Xo,{size:13})})]},N)),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:ce,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:!M,value:k,onChange:N=>D(N.target.value)})]}),o.jsxs("label",{children:[p("projectSettings.mainFile"),o.jsx("select",{disabled:!M||Q.length===0,value:T,onChange:N=>O(N.target.value),children:Q.map(N=>o.jsx("option",{value:N,children:N},N))})]}),o.jsxs("label",{children:[p("projectSettings.engine"),o.jsx("select",{disabled:!M,value:g,onChange:N=>x(N.target.value),children:(n.allowedEngines??["pdflatex","xelatex","lualatex"]).map(N=>o.jsx("option",{children:N},N))})]}),o.jsxs("label",{children:[p("projectSettings.latexmkrc"),o.jsx("textarea",{className:"latexmkrc-editor",rows:10,spellCheck:!1,disabled:!M||n.allowProjectLatexmkrc===!1,value:b,placeholder:p("projectSettings.latexmkrcPlaceholder"),onChange:N=>C(N.target.value)})]}),o.jsx("div",{className:"settings-actions",children:M&&o.jsxs("button",{className:"settings-save",onClick:()=>{ee()},children:[o.jsx(Br,{size:15}),p("projectSettings.saveCompiler")]})})]})]})}function ul({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=_e(),a=s==="error"?Yo:us;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((c,l)=>{const d=fb(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 io({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Yo:n==="warning"?us:So;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 ub({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:a}=_e(),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(Qn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:l.path}),o.jsx("small",{children:pb(l.size)})]})]}),o.jsx("a",{href:c(l.path),title:a("editor.downloadArtifact"),"aria-label":a("editor.downloadArtifact"),children:o.jsx(Vs,{size:14})})]},l.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(Gt,{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(Vs,{size:13}),a("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Qn,{size:24}),o.jsx("span",{children:a("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(md,{size:26}),o.jsx("span",{children:a("editor.noArtifacts")})]})}function hb({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=_e();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(us,{size:28}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanTitle")}),o.jsx("p",{children:i("editor.cleanDescription",{file:t})})]})]}),o.jsxs("div",{className:"compile-clean-actions",children:[o.jsxs("article",{children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(xo,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanCache")}),o.jsx("p",{children:i("editor.cleanCacheDescription")}),o.jsxs("button",{type:"button",disabled:e||n,onClick:s,children:[n?o.jsx(Gt,{className:"spin",size:14}):o.jsx(xo,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(ln,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanArtifacts")}),o.jsx("p",{children:i("editor.cleanArtifactsDescription")}),o.jsxs("button",{type:"button",className:"danger",disabled:e||n,onClick:r,children:[n?o.jsx(Gt,{className:"spin",size:14}):o.jsx(ln,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function fb(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 pb(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function mb(t){return t instanceof Error&&t.name==="AbortError"}function gb({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),C=h.useRef(e),k=h.useRef(i),D=h.useRef(a),T=h.useRef(c);C.current=e,k.current=i,D.current=a,T.current=c;const O=async _=>{b.current?.abort();const R=new AbortController;b.current=R;try{const S=await A(`/api/projects/${t}/comments?path=${encodeURIComponent(_)}`,{signal:R.signal});C.current===_&&d(S.comments)}catch(S){!mb(S)&&C.current===_&&d([])}finally{b.current===R&&(b.current=null)}};return h.useEffect(()=>{u(null)},[t,e]),h.useEffect(()=>(e?O(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 k.current())return;await A(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:e,content:g,...r})}),await O(e),p(!1),x(""),T.current()}catch(_){D.current(V(_))}},toggleComment:async _=>{try{await A(`/api/projects/${t}/comments/${_.id}`,{method:"PATCH",body:JSON.stringify({resolved:!_.resolved})}),await O(e)}catch(R){D.current(V(R))}},replyToComment:async(_,R)=>{try{return await A(`/api/projects/${t}/comments/${_.id}/replies`,{method:"POST",body:JSON.stringify({content:R})}),await O(e),!0}catch(S){return D.current(V(S)),!1}},editComment:async(_,R)=>{try{return await A(`/api/projects/${t}/comments/${_.id}`,{method:"PATCH",body:JSON.stringify({content:R})}),await O(e),!0}catch(S){return D.current(V(S)),!1}},deleteComment:async _=>{try{return await A(`/api/projects/${t}/comments/${_.id}`,{method:"DELETE"}),await O(e),u(R=>R?.id===_.id?null:R),!0}catch(R){return D.current(V(R)),!1}},editCommentReply:async(_,R,S)=>{try{return await A(`/api/projects/${t}/comments/${_.id}/replies/${R}`,{method:"PATCH",body:JSON.stringify({content:S})}),await O(e),!0}catch(M){return D.current(V(M)),!1}},deleteCommentReply:async(_,R)=>{try{return await A(`/api/projects/${t}/comments/${_.id}/replies/${R}`,{method:"DELETE"}),await O(e),!0}catch(S){return D.current(V(S)),!1}}}}function yb(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 wb(t,e,n,s){const[r]=h.useState(()=>new sb(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(""),[C,k]=h.useState(""),[D,T]=h.useState(!1),O=h.useRef(n),F=h.useRef(s);return O.current=n,F.current=s,h.useEffect(()=>{const q=ll(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(""),k(""),F.current()},P=({status:S})=>{a(S),S!=="connected"&&v()},X=S=>{l(S),S||v()},W=()=>{a("disconnected"),v()},_=()=>{const S=r.meta.get("filesEvent");yb(S)&&g(S);const M=r.meta.get("commentsRevision");typeof M=="string"&&b(M);const ue=r.meta.get("dictionaryRevision");typeof ue=="string"&&k(ue);const se=ll(r.meta.get("compileStates"));m(se[O.current]??null)};r.awareness.on("change",q),r.provider.on("status",P),r.provider.on("sync",X),r.provider.on("connection-close",W),r.provider.on("connection-error",W),r.meta.observe(_);const R=r.onDraftReady(()=>T(!0));return q(),_(),a(r.connected?"connected":"connecting"),l(r.synced),()=>{r.awareness.off("change",q),r.provider.off("status",P),r.provider.off("sync",X),r.provider.off("connection-close",W),r.provider.off("connection-error",W),r.meta.unobserve(_),R(),r.destroy()}},[r]),{collaboration:r,status:i,synced:c,activeSessions:d,compileState:u,setCompileState:m,filesEvent:p,commentsRevision:x,dictionaryRevision:C,localDraftReady:D,reconnect:()=>{a("connecting"),l(!1),f([]),m(null),r.reconnect()}}}function Kn(t){return t instanceof Error&&t.name==="AbortError"}function xb({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}=_e(),[g,x]=h.useState(""),[b,C]=h.useState(null),[k,D]=h.useState(""),[T,O]=h.useState(null),[F,E]=h.useState(null),[q,v]=h.useState([]),[P,X]=h.useState(null),[W,_]=h.useState(!1),[R,S]=h.useState(!1),[M,ue]=h.useState(()=>new Set),[se,be]=h.useState(""),Q=h.useRef(n),ee=h.useRef(null),ce=h.useRef(null),xe=h.useRef(new Map),ie=h.useRef(null),N=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 Ne=z=>{ie.current!==z&&(ie.current=z,B.current.onCompileSuccess())},He=async(z,Z)=>{Z||(ce.current?.abort(),ce.current=new AbortController,Z=ce.current.signal);try{const H=z?`?mainFile=${encodeURIComponent(z)}`:"",oe=await A(`/api/projects/${t}/compile/artifacts${H}`,{signal:Z});Q.current===z&&(v(oe.artifacts),X(null))}catch(H){!Kn(H)&&Q.current===z&&(v([]),X(null))}finally{ce.current?.signal===Z&&(ce.current=null)}};h.useEffect(()=>{ee.current?.abort();const z=new AbortController;if(ee.current=z,D(""),O(null),E(null),x(""),C(null),v([]),X(null),B.current.onPdfChanged(),!e||!n)return()=>z.abort();const Z=`?mainFile=${encodeURIComponent(n)}`,H=A(`/api/projects/${t}/compile/artifacts${Z}`,{signal:z.signal}).catch(oe=>{if(Kn(oe))throw oe;return{artifacts:[]}});return Promise.all([A(`/api/projects/${t}/compile/latest${Z}`,{signal:z.signal}),H,B.current.loadOutline(z.signal,n)]).then(([oe,yt])=>{z.signal.aborted||oe.mainFile!==Q.current||(v(yt.artifacts),D(oe.latestRun?.log??""),O(oe.latestRun?.diagnostics??null),E(oe.latestRun?.status==="succeeded"||oe.latestRun?.status==="failed"?oe.latestRun.status:null),oe.latestRun?.requestedBy&&(oe.latestRun.status==="queued"||oe.latestRun.status==="running")&&B.current.onSharedState({mainFile:n,runId:oe.latestRun.id,status:oe.latestRun.status,requestedBy:oe.latestRun.requestedBy,updatedAt:new Date().toISOString()}),oe.pdfUrl&&(x(oe.pdfUrl),C(oe.pdfCompiledAt),B.current.onPreviewTab("pdf")))}).catch(oe=>{!Kn(oe)&&Q.current===n&&B.current.onError(V(oe))}).finally(()=>{ee.current===z&&(ee.current=null)}),()=>z.abort()},[e?.id,t,n]),h.useEffect(()=>{!r||r.mainFile!==n||r.status!=="cleaned"||!r.cleanMode||(ee.current?.abort(),ce.current?.abort(),r.cleanMode==="artifacts"?(D(""),O(null),E(null),x(""),C(null),v([]),X(null),B.current.onPdfChanged(),B.current.onPreviewTab("pdf"),be(p("editor.cleanArtifactsComplete"))):be(p("editor.cleanCacheComplete")))},[r?.runId,r?.status,r?.cleanMode,r?.mainFile,n,p]),h.useEffect(()=>{if(!r||r.mainFile!==n||r.status!=="succeeded"&&r.status!=="failed")return;let z=!1;ee.current?.abort();const Z=new AbortController;return ee.current=Z,A(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:Z.signal}).then(H=>{z||H.mainFile!==Q.current||H.latestRun?.id!==r.runId||(D(H.latestRun.log),O(H.latestRun.diagnostics),E(r.status==="succeeded"?"succeeded":"failed"),r.status==="succeeded"&&H.pdfUrl?(B.current.onPdfChanged(),x(H.pdfUrl),C(H.pdfCompiledAt),B.current.onPreviewTab("pdf"),Ne(r.runId),He(n)):r.status==="failed"&&B.current.onPreviewTab(H.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(H=>{!Kn(H)&&!z&&B.current.onError(V(H))}),()=>{z=!0,Z.abort(),ee.current===Z&&(ee.current=null)}},[r?.runId,r?.status,r?.mainFile,n,t]);const tt=async()=>{if(!e||!n||e.permission==="read"||!s||xe.current.has(n)||r?.mainFile===n&&(r.status==="queued"||r.status==="running"))return;const z=n;ue(H=>new Set([...H,z])),B.current.onCompileStart(),be(""),D(""),O(null),E(null),B.current.onPreviewTab(g?"pdf":"log");const Z=new AbortController;xe.current.set(z,Z);try{if(!await B.current.save())return;const H=await A(`/api/projects/${t}/compile`,{method:"POST",signal:Z.signal,body:JSON.stringify({mainFile:z})});if(H.mainFile!==Q.current)return;D(H.log),O(H.diagnostics),E(H.ok?"succeeded":"failed"),H.skipped&&be(p("editor.upToDate")),H.pdfUrl?(B.current.onPdfChanged(),x(H.pdfUrl),C(H.pdfCompiledAt),B.current.onPreviewTab("pdf"),H.ok&&(H.skipped?B.current.onCompileSuccess():Ne(H.runId))):B.current.onPreviewTab(H.diagnostics.errors.length?"errors":"log")}catch(H){!Kn(H)&&Q.current===z&&B.current.onError(V(H))}finally{xe.current.get(z)===Z&&(xe.current.delete(z),ue(H=>{const oe=new Set(H);return oe.delete(z),oe}))}},nt=async z=>{if(!e||!n||e.permission==="read"||!s||R||xe.current.has(n)||r?.mainFile===n&&(r.status==="queued"||r.status==="running"))return;const Z=n;S(!0),ee.current?.abort(),ce.current?.abort();try{if((await A(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:Z,mode:z})})).mainFile!==Q.current)return;B.current.onSharedState(null),z==="artifacts"&&(D(""),O(null),E(null),x(""),C(null),v([]),X(null),B.current.onPdfChanged()),be(p(z==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(H){!Kn(H)&&Q.current===Z&&B.current.onError(V(H))}finally{S(!1)}};N.current=()=>{tt()},h.useEffect(()=>{if(!se)return;const z=window.setTimeout(()=>be(""),3e3);return()=>window.clearTimeout(z)},[se]),h.useEffect(()=>{const z=Z=>{!(Z.ctrlKey||Z.metaKey)||Z.key.toLocaleLowerCase()!=="s"||(Z.preventDefault(),Z.stopPropagation(),Z.repeat||N.current())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[]),h.useEffect(()=>()=>{ee.current?.abort(),ce.current?.abort();for(const z of xe.current.values())z.abort();xe.current.clear()},[]);const Ve=async z=>{if(z.viewable){_(!0);try{const Z=await A(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(z.path)}`);X(Z)}catch(Z){B.current.onError(V(Z))}finally{_(!1)}}};return{pdfUrl:g,pdfCompiledAt:b,compileLog:k,compileDiagnostics:T,compileOutcome:F,artifacts:q,artifactPreview:P,artifactLoading:W,editorNotice:se,localCompiling:M.has(n),cleaning:R,compile:tt,cleanCompile:nt,viewArtifact:Ve}}const hl=10*1024*1024,bb=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 fl(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 Gn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function vb(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!bb.has(e)}function Fo(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function pl(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":vb(t)?"text":"unsupported"}function Sb(t,e){return`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`}function Cb({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:a,onActiveFile:c,onActiveMainFile:l,onRootDocuments:d}){const{t:f}=_e(),[u,m]=h.useState([]),[p,g]=h.useState(!1),[x,b]=h.useState(""),[C,k]=h.useState(null),[D,T]=h.useState(!1),[O,F]=h.useState(!1),[E,q]=h.useState(""),[v,P]=h.useState(""),[X,W]=h.useState(""),[_,R]=h.useState(new Set),[S,M]=h.useState(null),[ue,se]=h.useState(""),[be,Q]=h.useState(null),[ee,ce]=h.useState(!1),[xe,ie]=h.useState(null),[N,B]=h.useState(!1),Ne=h.useRef(null),He=h.useRef(null),tt=async(U={})=>{Ne.current?.abort(),Ne.current=null;const te=U.signal?null:new AbortController;te&&(Ne.current=te);try{const ye=await A(`/api/projects/${t}/files`,{signal:U.signal??te?.signal});return(!U.isCurrent||U.isCurrent())&&m(ye.files),ye.files}catch(ye){if(!fl(ye))throw ye;return}finally{te&&Ne.current===te&&(Ne.current=null)}},nt=async()=>{if(!(!x.trim()||x.trim().endsWith("/"))){P("");try{await A(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:x,content:""})}),await tt(),c(x),R(U=>new Set([...U,...Fs(x)])),g(!1),b("")}catch(U){P(V(U))}}},Ve=async()=>{if(!E.trim())return;P("");const U=X?`${X}/${E.trim()}`:E.trim();try{const te=await A(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:U})});await tt(),R(ye=>new Set([...ye,...Fs(te.path),te.path])),W(te.path),F(!1),q("")}catch(te){P(V(te))}},z=async(U,te=new Set,ye=X)=>{if(!U.length)return;const st=e.maxUploadSizeMB??50;if(U.find(de=>de.size>st*1024*1024))return i(f("errors.fileTooLarge",{size:st}));const qe=ye,Ye=U.map(de=>qe?`${qe}/${de.name}`:de.name),wt=new Map;for(const de of Ye)wt.set(de,(wt.get(de)??0)+1);const lt=[...wt.entries()].filter(([,de])=>de>1).map(([de])=>de);if(lt.length)return i(f("errors.duplicateUploadNames",{files:lt.join(", ")}));const rt=new Set(u.map(de=>de.path)),dt=[...new Set(Ye.filter(de=>rt.has(de)&&!te.has(de)))];if(dt.length){ie({files:U,directory:qe,collisions:dt});return}ie(null),B(!0);try{const de=new URLSearchParams;qe&&de.set("directory",qe);let xt="";for(const[Xe,bt]of U.entries()){const pn=Ye[Xe];de.delete("overwrite"),te.has(pn)&&de.set("overwrite","1");const ve=de.toString()?`?${de.toString()}`:"",Ut=new FormData;Ut.append("file",bt);const ae=await fetch(`/api/projects/${t}/upload${ve}`,{method:"POST",body:Ut}),ut=await ae.json().catch(()=>({}));if(!ae.ok){if(ae.status===409&&!te.has(pn)&&ut.code==="FILE_EXISTS"){Xe>0&&await tt(),ie({files:U.slice(Xe),directory:qe,collisions:[typeof ut.path=="string"?ut.path:pn]});return}throw new Error(ae.status===409?f("errors.pathConflict"):Mo(ut,ae.status,"errors.upload"))}typeof ut.path=="string"&&Fo(ut.path)&&(xt=ut.path)}await tt(),xt&&c(xt)}catch(de){i(V(de))}finally{B(!1)}},Z=async U=>{await z(Array.from(U.target.files??[])),U.target.value=""},H=async U=>{He.current?.abort(),He.current=null,T(!1);const te=Sb(t,U.path);if((U.size??0)>hl){k({path:U.path,kind:"large",size:U.size??0,url:te});return}const ye=pl(U.path);if(ye!=="text"){k({path:U.path,kind:ye,size:U.size??0,url:te});return}k({path:U.path,kind:ye,size:U.size??0,url:te,content:""}),T(!0);const st=new AbortController;He.current=st;try{const le=await fetch(te,{signal:st.signal}),qe=await le.text();if(!le.ok)throw new Error(qe||f("errors.request",{status:le.status}));k(Ye=>Ye?.path===U.path?{...Ye,content:qe}:Ye)}catch(le){fl(le)||(k(null),i(V(le)))}finally{He.current===st&&(He.current=null,T(!1))}},oe=U=>{const te=pl(U.path);(U.size??0)>hl||te!=="text"||!Fo(U.path)?H(U):c(U.path)},yt=async()=>{if(S){P("");try{if(!await r())return;const U=await A(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:S.path,destinationDirectory:ue})}),te=le=>le===S.path?U.path:le.startsWith(`${S.path}/`)?`${U.path}${le.slice(S.path.length)}`:le;c(le=>te(le)),l(le=>te(le)),d(le=>new Set([...le].map(te))),W(le=>le&&te(le));const[ye,st]=await Promise.all([A(`/api/projects/${t}/files`),A(`/api/projects/${t}`)]);m(ye.files),a(st.project),R(le=>new Set([...le,...Fs(U.path),ue].filter(Boolean))),M(null),se("")}catch(U){P(V(U))}}},tn=async()=>{if(be){P("");try{if(s&&!await r())return;await A(`/api/projects/${t}/file?path=${encodeURIComponent(be.path)}`,{method:"DELETE"}),Q(null)}catch(U){P(V(U))}}};h.useEffect(()=>()=>{Ne.current?.abort(),He.current?.abort()},[]),h.useEffect(()=>{He.current?.abort(),He.current=null,T(!1)},[n]);const Mt=u.filter(U=>U.type==="directory"),$t=u.filter(U=>Fs(U.path).every(te=>_.has(te)));return{files:u,setFiles:m,loadFiles:tt,newFileOpen:p,setNewFileOpen:g,newFilePath:x,setNewFilePath:b,resourcePreview:C,setResourcePreview:k,resourcePreviewLoading:D,setResourcePreviewLoading:T,newFolderOpen:O,setNewFolderOpen:F,newFolderName:E,setNewFolderName:q,fileDialogError:v,setFileDialogError:P,selectedFolder:X,setSelectedFolder:W,expandedFolders:_,setExpandedFolders:R,moveEntry:S,setMoveEntry:M,moveDestination:ue,setMoveDestination:se,deleteEntry:be,setDeleteEntry:Q,fileDragActive:ee,setFileDragActive:ce,uploadConflict:xe,setUploadConflict:ie,uploadingFiles:N,directoryEntries:Mt,visibleEntries:$t,createFile:nt,createFolder:Ve,uploadFiles:z,upload:Z,openFile:oe,movePath:yt,removePath:tn}}function jb({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),C=h.useRef(0);x.current=n,b.current=e,h.useEffect(()=>{i([]),c(""),d(""),p(null)},[e,s]),h.useEffect(()=>{u(O=>r.length?Math.min(O,r.length-1):0)},[r]),h.useEffect(()=>{const O=++g.current;if(!t||!e){i([]),c(""),d(""),p(null);return}const F=n,E=e,q=window.setTimeout(()=>{Qt(async()=>{const{lintLatex:v}=await import("./spellCheck-BsMZuUSw.js");return{lintLatex:v}},__vite__mapDeps([2,1])).then(({lintLatex:v})=>{if(!(O!==g.current||x.current!==F||b.current!==E))return v(F,s).then(P=>{O!==g.current||x.current!==F||b.current!==E||(i(P),c(F),d(E),u(0),p(null))})}).catch(()=>{})},700);return()=>window.clearTimeout(q)},[t,e,n,s]);const k=l===e&&a===n,D=h.useMemo(()=>k?{total:r.length,unique:new Set(r.map(O=>`${O.kind}:${O.word.toLocaleLowerCase("en-US")}`)).size}:null,[k,r]);return{issues:k?r:[],jump:k?m:null,index:f,summary:D,jumpToIssue:O=>{if(!r.length)return;const F=Math.max(0,Math.min(O,r.length-1)),E=r[F];u(F),p({from:E.from,to:E.to,nonce:++C.current})}}}function ml(t){return t instanceof Error&&t.name==="AbortError"}function kb({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),C=h.useRef(i);g.current=n,x.current=s,b.current=r,C.current=i,h.useEffect(()=>(m.current?.abort(),m.current=null,c(null),d(null),u(null),()=>m.current?.abort()),[t,e]);const k=(F,E,q)=>{u({path:F,line:E,column:q,nonce:++p.current}),g.current!==F&&x.current(F)},D=async(F,E,q,v={})=>{m.current?.abort();const P=new AbortController;m.current=P;try{const X=await A(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(F)}&line=${E}&column=${q}`,{signal:P.signal});if(m.current!==P)return;c({...X,nonce:++p.current}),C.current()}catch(X){!ml(X)&&!v.silent&&b.current(V(X))}finally{m.current===P&&(m.current=null)}},T=async(F,E,q)=>{m.current?.abort();const v=new AbortController;m.current=v;try{const P=await A(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${F}&x=${E}&y=${q}`,{signal:v.signal});if(m.current!==v)return;k(P.path,P.line,P.column)}catch(P){ml(P)||b.current(V(P))}finally{m.current===v&&(m.current=null)}};return{pdfTarget:a,pdfViewport:l,sourceJump:f,setPdfViewport:d,clearPdfViewport:()=>d(null),jumpToSource:k,syncSourceToPdf:D,syncPdfToSource:T,syncVisiblePdfToSource:()=>{l&&T(l.page,l.x,l.y)}}}function Zu(t,e){return`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function gl(t,e){try{const n=window.localStorage.getItem(Zu(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function Eb(t,e){const[n,s]=h.useState(()=>gl(t,e));return h.useEffect(()=>{s(gl(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Zu(t,e),i)}catch{}}}}const Qu=()=>Qt(()=>import("./PdfPreview-CfolZ_vp.js"),__vite__mapDeps([3,1,4,5])),Db=h.lazy(()=>Qu().then(t=>({default:t.PdfPreview}))),Nb=h.lazy(()=>Qt(()=>import("./LatexEditor-CEtxGHGh.js"),__vite__mapDeps([6,1,7])).then(t=>({default:t.LatexEditor}))),Tb=h.lazy(()=>Qt(()=>import("./GitDialog-BNJvWeoG.js"),__vite__mapDeps([8,1,5])).then(t=>({default:t.GitDialog}))),Ob=h.lazy(()=>Qt(()=>import("./HistoryDialog-tBeFz_IG.js"),__vite__mapDeps([9,1,0])).then(t=>({default:t.HistoryDialog}))),Pb=h.lazy(()=>Qt(()=>import("./ProjectNavigationDialogs-CO6Pu3yg.js"),__vite__mapDeps([10,1])).then(t=>({default:t.ProjectSearchDialog}))),_b=h.lazy(()=>Qt(()=>import("./ProjectNavigationDialogs-CO6Pu3yg.js"),__vite__mapDeps([10,1])).then(t=>({default:t.QuickOpenDialog}))),Rb=h.lazy(()=>Qt(()=>import("./SystemMetricsDialog-DuOeZDPw.js"),__vite__mapDeps([11,1])).then(t=>({default:t.SystemMetricsDialog}))),Ze=8;function Zn(t){return t instanceof Error&&t.name==="AbortError"}function Lb(){const{t}=_e(),[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!==qi(m)){const x={texliteRoute:"project",projectId:m,fromDashboard:!1};window.history.replaceState(x,"",qi(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=qi(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(Qm(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 Io&&m.status,r(null)})},[]),s===void 0)return o.jsx("div",{className:"center-card",children:t("common.loading")});if(!s)return o.jsx(Fb,{site:e,onLogin:r});if(s.mustChangePassword)return o.jsx(Ab,{site:e,user:s,onChanged:m=>r(m)});if(i)return o.jsx(Ub,{site:e,user:s,projectId:i,onBack:f},i);const u=c?.userId===s.id?c:null;return o.jsx(Ib,{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 Pa(){const{t}=_e();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",Bh]})]}),o.jsx("span",{children:t("footer.credit")})]})}function Ab({site:t,user:e,onChanged:n}){const{t:s}=_e(),[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<Ze)return u(s("auth.passwordMinimum",{count:Ze}));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(Go,{}),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:Ze,autoComplete:"new-password",value:a,onChange:p=>c(p.target.value)}),o.jsx("small",{className:"field-hint",children:s("auth.passwordMinimum",{count:Ze})})]}),o.jsxs("label",{children:[s("auth.confirmPassword"),o.jsx("input",{type:"password",minLength:Ze,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(Pa,{})]})}function Fb({site:t,onLogin:e}){const{t:n}=_e(),[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(Go,{}),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(Pa,{})]})}function Ib({site:t,user:e,initialData:n,onDataChange:s,onUser:r,onOpenProject:i}){const{t:a}=_e(),[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),[C,k]=h.useState(!1),[D,T]=h.useState(""),[O,F]=h.useState(!1),[E,q]=h.useState(""),[v,P]=h.useState(!1),[X,W]=h.useState(""),[_,R]=h.useState(null),[S,M]=h.useState(""),ue=h.useRef(null),[se,be]=h.useState(!1),[Q,ee]=h.useState(""),[ce,xe]=h.useState(""),[ie,N]=h.useState(!1),[B,Ne]=h.useState(""),[He,tt]=h.useState("blue"),[nt,Ve]=h.useState(null),[z,Z]=h.useState(null),[H,oe]=h.useState(""),[yt,tn]=h.useState(null),[Mt,$t]=h.useState(""),[U,te]=h.useState(!1),[ye,st]=h.useState(null),[le,qe]=h.useState(null),[Ye,wt]=h.useState([]),[lt,rt]=h.useState(""),[dt,de]=h.useState(!1),[xt,Xe]=h.useState(""),[bt,pn]=h.useState(()=>localStorage.getItem("texlite-project-view")==="list"?"list":"grid"),[ve,Ut]=h.useState(()=>localStorage.getItem("texlite-project-sort")==="created"?"created":"updated"),[ae,ut]=h.useState(!1),[zt,Dt]=h.useState(""),[ke,We]=h.useState(1),[Vt,mn]=h.useState(""),_n=h.useRef(0),gn=h.useRef(null),Fe=(w,re,ne,Ce,Ee)=>`${w?"archived":"active"}|${re}|${ne}|${Ce}|${Ee}`,yn=Fe(ae,ke,Q,ce,ve),Te=(w,re,ne,Ce,Ee)=>{const Le=new URLSearchParams({page:String(re),pageSize:"20",sort:Ee});w&&Le.set("archived","1"),ne.trim()&&Le.set("search",ne.trim()),Ce&&Le.set("tag",Ce);const Ht=Fe(w,re,ne,Ce,Ee),Ln=++_n.current;gn.current?.abort();const An=new AbortController;return gn.current=An,Promise.all([A(`/api/projects?${Le.toString()}`,{signal:An.signal}),A("/api/tags",{signal:An.signal})]).then(([ht,fr])=>{Ln===_n.current&&(l(ht.projects),f(fr.tags),m(ht.pagination),We(ht.pagination.page),g(!0),mn(Ht))}).catch(ht=>{!Zn(ht)&&Ln===_n.current&&T(V(ht))}).finally(()=>{gn.current===An&&(gn.current=null)})};h.useEffect(()=>(Te(ae,ke,Q,ce,ve),()=>gn.current?.abort()),[ae,ke,Q,ce,ve]),h.useEffect(()=>{p&&!ae&&Vt===yn&&s(c,d,u)},[c,d,u,p,Vt,yn,ae]);const Ds=w=>{pn(w),localStorage.setItem("texlite-project-view",w)},Nt=w=>{Ut(w),We(1),localStorage.setItem("texlite-project-sort",w)},Ns=w=>{ut(w),We(1)},Se=w=>{xe(w),We(1)},lr=async()=>{if(E.trim())try{const{project:w}=await A("/api/projects",{method:"POST",body:JSON.stringify({name:E})});F(!1),q("");const re=ae||ke!==1?c:[w,...c].slice(0,u.pageSize),ne=ae?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(re),m(ne),ae||s(re,d,ne),i(w.id)}catch(w){T(V(w))}},dr=async()=>{if(!_)return;const w=t.maxUploadSizeMB??50;if(_.size>w*1024*1024)return M(a("errors.fileTooLarge",{size:w}));be(!0),M("");const re=new FormData;re.append("file",_);try{const ne=await fetch(`/api/projects/import?name=${encodeURIComponent(X.trim())}`,{method:"POST",body:re}),Ce=await ne.json();if(!ne.ok)throw new Error(Mo(Ce,ne.status,"errors.upload"));const Ee=Ce.project,Le=ae||ke!==1?c:[Ee,...c].slice(0,u.pageSize),Ht=ae?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(Le),m(Ht),ae||s(Le,d,Ht),P(!1),R(null),W(""),i(Ee.id)}catch(ne){M(V(ne))}finally{be(!1)}},Rn=w=>{if(w&&!w.name.toLocaleLowerCase().endsWith(".zip")){M(a("errors.zipOnly"));return}M(""),R(w),w&&!X&&W(w.name.replace(/\.zip$/i,""))},vi=async()=>{await A("/api/auth/logout",{method:"POST"}),r(null)},Si=async()=>{if(B.trim())try{const w=await A("/api/tags",{method:"POST",body:JSON.stringify({name:B,color:He})});f(re=>[...re,w.tag].sort((ne,Ce)=>ne.name.localeCompare(Ce.name))),N(!1),Ne(""),tt("blue")}catch(w){T(V(w))}},Ci=async w=>{if(!nt)return;const re=nt.tags.some(ne=>ne.id===w.id);try{const Ce=(await A(re?`/api/projects/${nt.id}/tags/${w.id}`:`/api/projects/${nt.id}/tags`,re?{method:"DELETE"}:{method:"POST",body:JSON.stringify({tagId:w.id})})).project;Ve(Ce),l(Ee=>Ee.map(Le=>Le.id===Ce.id?Ce:Le))}catch(ne){T(V(ne))}},Ts=async()=>{if(!(!z||!H.trim()))try{const w=await A(`/api/projects/${z.id}`,{method:"PATCH",body:JSON.stringify({name:H})});l(re=>re.map(ne=>ne.id===w.project.id?w.project:ne)),Z(null),oe("")}catch(w){T(V(w))}},Os=async()=>{if(!(!yt||!Mt.trim())){te(!0),T("");try{await A(`/api/projects/${yt.id}/duplicate`,{method:"POST",body:JSON.stringify({name:Mt})}),tn(null),$t(""),Te(ae,ke,Q,ce,ve)}catch(w){T(V(w))}finally{te(!1)}}},ur=async()=>{if(ye)try{await A(`/api/projects/${ye.id}`,{method:"DELETE"}),l(Ee=>Ee.filter(Le=>Le.id!==ye.id));const w=Math.max(0,u.total-1),re=Math.ceil(w/u.pageSize),ne=re===0?1:Math.min(ke,re),Ce={...u,page:ne,total:w,totalPages:re};m(Ce),st(null),ne!==ke?We(ne):Te(ae,ke,Q,ce,ve)}catch(w){T(V(w))}},wn=async w=>{qe(w),rt(""),wt([]),Xe(""),de(!0);try{const re=await A("/api/users");wt(re.users.filter(ne=>ne.id!==w.ownerId))}catch(re){Xe(V(re))}finally{de(!1)}},Ps=async()=>{if(!(!le||!lt)){de(!0),Xe("");try{await A(`/api/projects/${le.id}/owner`,{method:"PUT",body:JSON.stringify({userId:lt})}),qe(null),rt(""),Te(ae,ke,Q,ce,ve)}catch(w){Xe(V(w))}finally{de(!1)}}},ji=async w=>{const re=!ae;Dt(w.id),T("");try{await A(`/api/projects/${w.id}/archive`,{method:re?"PUT":"DELETE"});const ne=c.filter(Ln=>Ln.id!==w.id);l(ne);const Ce=Math.max(0,u.total-1),Ee=Math.ceil(Ce/u.pageSize),Le=Ee===0?1:Math.min(ke,Ee),Ht={...u,page:Le,total:Ce,totalPages:Ee};m(Ht),ae||s(ne,d,Ht),Le!==ke?We(Le):Te(ae,ke,Q,ce,ve)}catch(ne){T(V(ne))}finally{Dt("")}},hr=c,Bt=["red","orange","yellow","green","blue","purple","gray"],xn=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:()=>k(!0),children:[o.jsx(pm,{"aria-hidden":!0,size:14}),a("metrics.title")]}),o.jsxs("button",{className:"ghost",onClick:()=>b(!x),children:[x?o.jsx(ld,{"aria-hidden":!0,size:14}):o.jsx(Bs,{"aria-hidden":!0,size:14}),a(x?"users.back":"users.manage")]})]}),o.jsx(Go,{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:vi,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:()=>N(!0),children:[o.jsx(Ec,{"aria-hidden":!0,size:15}),a("tags.create")]}),e.canCreateProjects&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>{M(""),P(!0)},children:[o.jsx(Hr,{"aria-hidden":!0,size:15}),a("projects.upload")]}),o.jsxs("button",{className:"primary",onClick:()=>F(!0),children:[o.jsx(fd,{"aria-hidden":!0,size:15}),a("projects.new")]})]})]})]}),D&&o.jsx("p",{className:"error",children:D}),o.jsxs("div",{className:"project-toolbar",children:[o.jsx("input",{type:"search",placeholder:a("projects.search"),value:Q,onChange:w=>{ee(w.target.value),We(1)}}),o.jsxs("div",{className:"project-scope",role:"tablist","aria-label":a("projects.scope"),children:[o.jsxs("button",{className:ae?"":"active",onClick:()=>Ns(!1),role:"tab","aria-selected":!ae,children:[o.jsx(Vr,{size:14}),a("projects.active")]}),o.jsxs("button",{className:ae?"active":"",onClick:()=>Ns(!0),role:"tab","aria-selected":ae,children:[o.jsx(Sc,{size:14}),a("projects.archived")]})]}),o.jsxs("div",{className:"tag-filters",children:[o.jsx("button",{className:ce?"":"active",onClick:()=>Se(""),children:a("projects.allTags")}),d.map(w=>o.jsxs("button",{className:ce===w.id?"active":"",onClick:()=>Se(ce===w.id?"":w.id),children:[o.jsx(oo,{color:w.color}),w.name]},w.id))]}),o.jsxs("label",{className:"project-sort",children:[o.jsx(gm,{size:14}),o.jsx("span",{children:a("projects.sortBy")}),o.jsxs("select",{value:ve,onChange:w=>Nt(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:bt==="grid"?"active":"",onClick:()=>Ds("grid"),title:a("projects.grid"),children:"▦"}),o.jsx("button",{className:bt==="list"?"active":"",onClick:()=>Ds("list"),title:a("projects.list"),children:"☷"})]})]}),o.jsxs("div",{className:`project-grid ${bt==="list"?"list-view":""}`,children:[hr.map(w=>o.jsxs("article",{className:`project-card${w.ownerId===e.id?" owned-project":""}`,children:[bt==="grid"&&w.ownerId===e.id&&o.jsxs("button",{className:"project-transfer-action",title:a("projects.transferOwnership"),onClick:()=>{wn(w)},children:[o.jsx(Vi,{"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(re=>o.jsx("span",{className:`tag tag-${re.color}`,children:re.name},re.id))})]}),o.jsxs("dl",{className:"project-meta",children:[o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(ym,{"aria-hidden":!0,size:13}),a("projects.created")]}),o.jsx("dd",{children:o.jsx("time",{dateTime:w.createdAt,children:xn(w.createdAt)})})]}),o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(pd,{"aria-hidden":!0,size:13}),a("projects.modified")]}),o.jsxs("dd",{title:a("projects.modifiedByUser",{time:xn(w.updatedAt),user:w.lastModifiedDisplayName??w.lastModifiedUsername??a("projects.deletedUser")}),children:[o.jsx("time",{dateTime:w.updatedAt,children:xn(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:()=>Ve(w),children:[o.jsx(Ec,{"aria-hidden":!0,size:14}),a("tags.assign")]}),w.permission==="owner"&&o.jsxs("button",{onClick:()=>{Z(w),oe(w.name)},children:[o.jsx(vo,{"aria-hidden":!0,size:14}),a("projects.rename")]}),(e.role==="admin"||e.canCreateProjects)&&o.jsxs("button",{onClick:()=>{tn(w),$t(`${w.name} (1)`)},children:[o.jsx(Sm,{"aria-hidden":!0,size:14}),a("projects.duplicate")]}),o.jsxs("a",{href:`/api/projects/${w.id}/download`,download:!0,children:[o.jsx(Vs,{"aria-hidden":!0,size:14}),a("projects.download")]}),o.jsxs("button",{disabled:zt===w.id,onClick:()=>{ji(w)},children:[ae?o.jsx(mm,{"aria-hidden":!0,size:14}):o.jsx(Sc,{"aria-hidden":!0,size:14}),a(ae?"projects.unarchive":"projects.archive")]}),bt==="list"&&w.ownerId===e.id&&o.jsxs("button",{onClick:()=>{wn(w)},children:[o.jsx(Vi,{"aria-hidden":!0,size:14}),a("projects.transfer")]}),w.permission==="owner"&&o.jsxs("button",{className:"danger-text",onClick:()=>st(w),children:[o.jsx(ln,{"aria-hidden":!0,size:14}),a("common.delete")]})]})]},w.id)),hr.length===0&&(c.length===0?ae?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(Um,{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:()=>We(w=>Math.max(1,w-1)),title:a("projects.previousPage"),children:[o.jsx(hd,{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:()=>We(w=>Math.min(u.totalPages,w+1)),title:a("projects.nextPage"),children:[o.jsx(Jo,{size:15}),a("projects.nextPage")]})]}),o.jsx($e,{open:O,title:a("projects.new"),description:a("projects.newDescription"),onOpenChange:F,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>F(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{lr()},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"&&lr()}})]})}),o.jsx($e,{open:v,title:a("projects.upload"),description:a("projects.uploadDescription",{size:t.maxUploadSizeMB??50}),onOpenChange:w=>{P(w),w||M("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>{P(!1),M("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:!_||se,onClick:()=>{dr()},children:a(se?"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${_?" has-file":""}`,onDragOver:w=>{w.preventDefault(),w.dataTransfer.dropEffect="copy"},onDrop:w=>{w.preventDefault(),Rn(w.dataTransfer.files[0]??null)},children:[o.jsx("input",{ref:ue,className:"sr-only",type:"file",accept:".zip,application/zip",onChange:w=>Rn(w.target.files?.[0]??null)}),o.jsx(bo,{size:34}),o.jsxs("div",{className:"upload-picker-copy",children:[o.jsx("strong",{children:_?.name??a("projects.chooseZip")}),o.jsx("span",{children:_?a("projects.selectedFileSize",{size:eh(_.size)}):a("projects.dropZip")})]}),o.jsxs("button",{type:"button",onClick:()=>ue.current?.click(),children:[o.jsx(Hr,{size:15}),a("projects.browse")]}),_&&o.jsx("button",{className:"upload-clear",type:"button",title:a("projects.clearFile"),"aria-label":a("projects.clearFile"),onClick:()=>{Rn(null),ue.current&&(ue.current.value="")},children:o.jsx(Xo,{size:14})})]}),o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{value:X,onChange:w=>W(w.target.value)})]})]})}),o.jsx($e,{open:ie,title:a("tags.create"),description:a("tags.createDescription"),onOpenChange:N,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>N(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Si()},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:B,onChange:w=>Ne(w.target.value)})]}),o.jsxs("fieldset",{className:"color-picker",children:[o.jsx("legend",{children:a("tags.color")}),Bt.map(w=>o.jsxs("label",{className:He===w?"active":"",children:[o.jsx("input",{type:"radio",name:"dashboard-tag-color",checked:He===w,onChange:()=>tt(w)}),o.jsx(oo,{color:w}),a(`tags.${w}`)]},w))]})]})}),o.jsx($e,{open:!!nt,title:a("tags.assignTitle",{project:nt?.name??""}),description:a("tags.assignDescription"),onOpenChange:w=>{w||Ve(null)},footer:o.jsx("button",{onClick:()=>Ve(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:!!nt?.tags.some(re=>re.id===w.id),onChange:()=>{Ci(w)}}),o.jsx(oo,{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($e,{open:!!z,title:a("projects.renameTitle"),onOpenChange:w=>{w||Z(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Z(null),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Ts()},children:a("projects.rename")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:H,onChange:w=>oe(w.target.value),onKeyDown:w=>{w.key==="Enter"&&Ts()}})]})}),o.jsx($e,{open:!!yt,title:a("projects.duplicateTitle"),description:a("projects.duplicateDescription",{project:yt?.name??""}),onOpenChange:w=>{!w&&!U&&(tn(null),$t(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:U,onClick:()=>{tn(null),$t("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:U||!Mt.trim(),onClick:()=>{Os()},children:a(U?"projects.duplicating":"projects.duplicate")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:Mt,onChange:w=>$t(w.target.value),onKeyDown:w=>{w.key==="Enter"&&Os()}})]})}),o.jsx($e,{open:!!le,title:a("projects.transferOwnership"),description:a("projects.transferDescription",{project:le?.name??""}),onOpenChange:w=>{!w&&!dt&&(qe(null),rt(""),Xe(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:dt,onClick:()=>{qe(null),rt(""),Xe("")},children:a("common.cancel")}),o.jsxs("button",{className:"primary",disabled:dt||!lt,onClick:()=>{Ps()},children:[dt?o.jsx(Gt,{className:"spin",size:14}):o.jsx(Vi,{size:14}),a("projects.transfer")]})]}),children:o.jsxs("div",{className:"form-stack",children:[xt&&o.jsx("p",{className:"error dialog-error",children:xt}),o.jsxs("label",{className:"form-field",children:[a("projects.newOwner"),o.jsxs("select",{disabled:dt||Ye.length===0,value:lt,onChange:w=>rt(w.target.value),children:[o.jsx("option",{value:"",children:dt?a("common.loading"):Ye.length>0?a("projects.chooseNewOwner"):a("projects.noTransferUsers")}),Ye.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(us,{size:15}),a("projects.transferWarning")]})]})}),o.jsx(ds,{open:!!ye,title:a("projects.deleteTitle"),description:a("projects.deleteDescription",{project:ye?.name??""}),confirmLabel:a("common.delete"),danger:!0,onCancel:()=>st(null),onConfirm:()=>{ur()}})]}),C&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Rb,{open:!0,onOpenChange:k})}),o.jsx(Pa,{})]})}function oo({color:t}){return o.jsx("span",{className:`tag-dot tag-${t}`})}function Mb(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}=_e(),[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,C]=h.useState(!1),k=()=>A("/api/admin/users").then(({users:v})=>s(v)).catch(v=>i(V(v)));h.useEffect(()=>{k()},[]);const D=async()=>{if(l.password.length<Ze)return i(e("auth.passwordMinimum",{count:Ze}));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 k()}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 k()}catch(P){i(V(P))}},O=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({role:v.role==="admin"?"user":"admin"})}),await k()}catch(P){i(V(P))}},F=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({canCreateProjects:!v.canCreateProjects})}),await k()}catch(P){i(V(P))}},E=async()=>{if(!(!f||!m)){if(m.length<Ze)return i(e("auth.passwordMinimum",{count:Ze}));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),C(!1),await k()}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(Bs,{"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(gd,{"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:()=>O(v),children:v.role==="admin"?e("users.demote"):e("users.promote")}),o.jsx("button",{disabled:v.role==="admin",onClick:()=>F(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),C(!1)},children:e("common.delete")})]})]},v.id))})]})}),o.jsx($e,{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<Ze,onClick:()=>{D()},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:Ze,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:Mb()}),children:[o.jsx(Cm,{size:15}),e("users.randomPassword")]})]}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Ze})})]}),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($e,{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<Ze,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:Ze,autoComplete:"new-password",value:m,onChange:v=>p(v.target.value)}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Ze})})]})}),o.jsx($e,{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:()=>C(!1)})," ",e("users.transferProjects")]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",checked:b,onChange:()=>C(!0)})," ",e("users.deleteProjects")]})]})})]})}function Ub({site:t,user:e,projectId:n,onBack:s}){const{t:r}=_e(),[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(""),[C,k]=h.useState(new Set),[D,T]=h.useState(""),[O,F]=h.useState(""),[E,q]=h.useState(!1),[v,P]=h.useState("editor.saved"),[X,W]=h.useState(null),[_,R]=h.useState({line:1,column:1}),S=h.useRef(_),[M,ue]=h.useState("pdf"),[se,be]=h.useState("log"),Q=y=>{if(y==="pdf"){ue("pdf");return}be(y),ue("diagnostics")},{workspaceLayout:ee,setWorkspaceLayout:ce}=Eb(e.id,n),[xe,ie]=h.useState(""),[N,B]=h.useState(""),[Ne,He]=h.useState({selectedText:"",startOffset:0,endOffset:0}),tt=h.useRef({selectedText:"",startOffset:0,endOffset:0}),nt=y=>{tt.current=y,He(y)},[Ve,z]=h.useState(null),[Z,H]=h.useState(!1),[oe,yt]=h.useState(!1),[tn,Mt]=h.useState(!1),[$t,U]=h.useState(!1),[te,ye]=h.useState(null),[st,le]=h.useState(!1),[qe,Ye]=h.useState(!1),[wt,lt]=h.useState(!1),[rt,dt]=h.useState(()=>Nc(e.id,n)),de=h.useRef(null),xt=h.useRef(null),Xe=h.useRef(0),bt=h.useRef(0),pn=h.useRef(""),ve=h.useRef(""),Ut=h.useRef(""),ae=h.useRef(""),ut=h.useRef(0),zt=h.useRef(null),Dt=h.useRef(null),ke=h.useRef(null),We=h.useRef(null),Vt=h.useRef(!1),mn=h.useRef(null),_n=h.useRef(s);_n.current=s,Ut.current=x;const gn=(y,j)=>{const L={line:y,column:j};S.current=L,R(L)},{collaboration:Fe,status:yn,synced:Te,activeSessions:Ds,compileState:Nt,setCompileState:Ns,filesEvent:Se,commentsRevision:lr,dictionaryRevision:dr,localDraftReady:Rn,reconnect:vi}=wb(n,e,x,()=>P("editor.offlineDraft")),{pdfTarget:Si,pdfViewport:Ci,sourceJump:Ts,setPdfViewport:Os,clearPdfViewport:ur,jumpToSource:wn,syncSourceToPdf:Ps,syncPdfToSource:ji,syncVisiblePdfToSource:hr}=kb({projectId:n,mainFile:x,activeFile:p,onActiveFile:g,onError:ie,onShowPdf:()=>Q("pdf")}),Bt=jb({active:!!(i&&p&&Te&&rt.spellCheck),activeFile:p,content:D,dictionaryWords:c});h.useEffect(()=>{dt(Nc(e.id,n))},[e.id,n]);const xn=y=>{pn.current=y,T(y)};h.useEffect(()=>{ve.current=p,S.current={line:1,column:1},R({line:1,column:1}),nt({selectedText:"",startOffset:0,endOffset:0})},[p]),h.useEffect(()=>{if(!E)return;const y=j=>{j.preventDefault(),j.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[E]),h.useEffect(()=>{if(yn!=="disconnected")return;const y=new AbortController;return A(`/api/projects/${n}`,{signal:y.signal}).then(({project:j})=>{y.signal.aborted||(a(j),ie(""))}).catch(j=>{if(!Zn(j)){if(j instanceof Io&&[401,403,404].includes(j.status)){ie(V(j)),_n.current();return}ie(r("errors.collaborationUnavailable"))}}),()=>y.abort()},[yn,n,r]);const w=async(y={})=>{zt.current?.abort(),zt.current=null;const j=y.signal?null:new AbortController;j&&(zt.current=j);try{const L=await A(`/api/projects/${n}/completions`,{signal:y.signal??j?.signal});(!y.isCurrent||y.isCurrent())&&f(L.index)}catch(L){if(Zn(L))return;(!y.isCurrent||y.isCurrent())&&f(null)}finally{j&&zt.current===j&&(zt.current=null)}},re=async(y={},j=Ut.current)=>{Dt.current?.abort(),Dt.current=null;const L=y.signal?null:new AbortController;L&&(Dt.current=L);try{const J=j?`?mainFile=${encodeURIComponent(j)}`:"",he=await A(`/api/projects/${n}/outline${J}`,{signal:y.signal??L?.signal});(!y.isCurrent||y.isCurrent())&&m(he.outline)}catch(J){!Zn(J)&&(!y.isCurrent||y.isCurrent())&&m([])}finally{L&&Dt.current===L&&(Dt.current=null)}},ne=async(y={})=>{ke.current?.abort(),ke.current=null;const j=y.signal?null:new AbortController;j&&(ke.current=j);try{const L=await A(`/api/projects/${n}/dictionary`,{signal:y.signal??j?.signal});(!y.isCurrent||y.isCurrent())&&l(L.words)}catch(L){if(Zn(L))return;(!y.isCurrent||y.isCurrent())&&l([])}finally{j&&ke.current===j&&(ke.current=null)}};h.useEffect(()=>{let y=!1;const j=++ut.current,L=new AbortController,J=()=>!y&&ut.current===j;let he=!1;ae.current="",a(null),fr([]),m([]),g(""),b(""),k(new Set),T(""),F(""),Ns(null),ur(),f(null),l([]),Qu();const Be=A(`/api/projects/${n}`,{signal:L.signal}).then(Ke=>{J()&&(he=!0,a(Ke.project),g(Ke.project.mainFile),b(Ke.project.mainFile),k(new Set([Ke.project.mainFile])),Aa(new Set(Fs(Ke.project.mainFile))))}).catch(Ke=>{J()&&ie(V(Ke))}),fe=A(`/api/projects/${n}/files`,{signal:L.signal}).then(Ke=>{J()&&fr(Ke.files)}).catch(Ke=>{J()&&ie(V(Ke))});return Promise.allSettled([Be,fe]).then(()=>{!J()||!he||window.setTimeout(()=>{J()&&Promise.all([w({signal:L.signal,isCurrent:J}),ne({signal:L.signal,isCurrent:J})])},0)}),()=>{y=!0,L.abort(),zt.current?.abort(),zt.current=null,Dt.current?.abort(),Dt.current=null,ke.current?.abort(),ke.current=null,We.current?.abort(),We.current=null}},[n]),h.useEffect(()=>{dr&&ne()},[dr,n]),h.useEffect(()=>{i&&Fe.setPermission(i.permission)},[Fe,i?.permission]),h.useEffect(()=>{if(!Se)return;const y=Se.kind==="delete"&&!!Se.path&&Gn(Se.path,ve.current),j=Se.kind==="delete"&&!!Se.path&&Gn(Se.path,Ut.current);if(Se.kind==="move"&&Se.source&&Se.destination){const J=Se.source,he=Se.destination,Be=fe=>fe===J?he:fe.startsWith(`${J}/`)?`${he}${fe.slice(J.length)}`:fe;g(fe=>Be(fe)),b(fe=>Be(fe)),k(fe=>new Set([...fe].map(Be))),pr(fe=>fe&&Be(fe))}y&&(g(""),F(""),xn(""),B(r("editor.fileDeletedByCollaborator",{path:Se.path}))),Se.kind==="delete"&&Se.path&&(k(J=>new Set([...J].filter(he=>!Gn(Se.path,he)))),pr(J=>Gn(Se.path,J)?"":J),Ra(J=>J&&Gn(Se.path,J.path)?null:J)),We.current?.abort();const L=new AbortController;We.current=L,Promise.all([th({signal:L.signal}),A(`/api/projects/${n}`,{signal:L.signal})]).then(([J,he])=>{if(a(he.project),j&&b(he.project.mainFile),y&&J){const Be=J.find(fe=>fe.type==="file"&&fe.path===he.project.mainFile)??J.find(fe=>fe.type==="file"&&Fo(fe.path));g(Be?.path??"")}w({signal:L.signal}),re({signal:L.signal},j?he.project.mainFile:Ut.current)}).catch(J=>{Zn(J)}).finally(()=>{We.current===L&&(We.current=null)})},[Se?.revision]),h.useEffect(()=>{if(Fe.setActiveFile(p),!p)return;F(""),P("editor.loading");const y=Fe.getText(p),j=(L,J)=>{xn(y.toString()),F(p),J?.local&&i?.permission!=="read"?(Xe.current+=1,q(!0),P("editor.pending")):Xe.current<=bt.current&&P(X?"editor.savedAt":"editor.saved")};return y.observe(j),(Te||Rn)&&j(),()=>{y.unobserve(j)}},[p,Fe,Te,Rn,i?.permission]),h.useEffect(()=>{!p||O!==p||ae.current===p||(ae.current=p,!(!p.toLocaleLowerCase().endsWith(".tex")||!zb(D))&&(k(y=>new Set([...y,p])),b(p)))},[p,O,D]);const Ce=async()=>{if(!Te)throw new Error("Collaboration is not synchronized");const y=Xe.current,j=await Fe.flush();return bt.current=Math.max(bt.current,y),W(j.persistedAt),/\.tex$/i.test(ve.current)&&re(),Xe.current===y?(q(!1),P("editor.savedAt")):P("editor.pending"),j};h.useEffect(()=>{if(!E||!p)return;if(!Te){P("editor.offlineDraft");return}P("editor.pending");const y=window.setTimeout(()=>{P("editor.saving"),Ce().catch(()=>{P(Fe.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(y)},[D,E,p,Te]);const Ee=async()=>{if(!i||i.permission==="read"||!Te||!p)return!1;P("editor.saving");try{return await Ce(),w(),!0}catch{return P("editor.saveFailed"),ie(r("errors.collaborationUnavailable")),!1}},Le=async(y,j)=>(await A(`/api/projects/${n}/format`,{method:"POST",body:JSON.stringify({path:y,source:j})})).formatted,Ht=async()=>{if(!rt.formatOnCompile||!i||i.permission==="read"||!Te||!Hi(ve.current)||Vt.current)return;const y=ve.current,j=Fe.getText(y),L=j.toString();Vt.current=!0,lt(!0);try{const J=await Le(y,L),he=await Tc(L,J);if(ve.current!==y||j.toString()!==L)throw new Error(r("editor.formatSourceChanged"));he.length&&Fe.applyTextEdits(y,he)}catch(J){ie(r("editor.formatFailedContinue",{message:V(J)}))}finally{Vt.current=!1,lt(!1)}},Ln=async()=>(mn.current&&await mn.current,await Ht(),Ee()),An=async()=>{if(!i||i.permission==="read"||!Te||Vt.current||!Hi(ve.current))return;const y=tt.current;if(!y.selectedText.trim()){B(r("editor.formatSelectionRequired"));return}const j=ve.current,{startOffset:L,endOffset:J,selectedText:he}=y,Be=Fe.getText(j);if(Be.toString().slice(L,J)!==he){ie(r("editor.formatSelectionChanged"));return}Vt.current=!0,lt(!0);let fe=()=>{};const Ke=new Promise(Tt=>{fe=Tt});mn.current=Ke;try{const Tt=Km(he,await Le(j,he)),Xa=await Tc(he,Tt,L);if(ve.current!==j||Be.toString().slice(L,J)!==he){ie(r("editor.formatSelectionChanged"));return}Xa.length&&Fe.applyTextEdits(j,Xa),ie(""),B(r("editor.formatSelectionComplete"))}catch(Tt){ie(r("editor.formatFailed",{message:V(Tt)}))}finally{Vt.current=!1,lt(!1),fe(),mn.current===Ke&&(mn.current=null)}},{files:ht,setFiles:fr,loadFiles:th,newFileOpen:nh,setNewFileOpen:ki,newFilePath:sh,setNewFilePath:_a,resourcePreview:Oe,setResourcePreview:Ra,resourcePreviewLoading:rh,setResourcePreviewLoading:ih,newFolderOpen:oh,setNewFolderOpen:Ei,newFolderName:ah,setNewFolderName:La,fileDialogError:nn,setFileDialogError:Fn,selectedFolder:qt,setSelectedFolder:pr,expandedFolders:ch,setExpandedFolders:Aa,moveEntry:_s,setMoveEntry:mr,moveDestination:lh,setMoveDestination:Di,deleteEntry:In,setDeleteEntry:gr,fileDragActive:Fa,setFileDragActive:Ni,uploadConflict:Ti,setUploadConflict:Ia,uploadingFiles:yr,directoryEntries:dh,visibleEntries:uh,createFile:hh,createFolder:Ma,uploadFiles:$a,upload:fh,openFile:Ua,movePath:ph,removePath:mh}=Cb({projectId:n,site:t,activeFile:p,dirty:E,save:Ee,onError:ie,onProject:a,onActiveFile:g,onActiveMainFile:b,onRootDocuments:k}),{comments:Rs,focusComment:gh,setFocusComment:za,commentOpen:yh,setCommentOpen:Oi,commentText:wh,setCommentText:xh,addComment:bh,toggleComment:vh,replyToComment:Sh,editComment:Ch,deleteComment:jh,editCommentReply:kh,deleteCommentReply:Eh}=gb({projectId:n,activeFile:p,permission:i?.permission,revision:lr,selection:Ne,save:Ee,onError:ie,onAdded:()=>z("comments")}),{pdfUrl:bn,pdfCompiledAt:Mn,compileLog:wr,compileDiagnostics:xr,compileOutcome:br,artifacts:Pi,artifactPreview:Dh,artifactLoading:Nh,editorNotice:Va,localCompiling:_i,cleaning:Ba,compile:Th,cleanCompile:Oh,viewArtifact:Ph}=xb({projectId:n,project:i,mainFile:x,collaborationSynced:Te,sharedState:Nt,onSharedState:Ns,save:Ln,loadOutline:(y,j)=>re({signal:y},j),onPreviewTab:Q,onError:ie,onCompileStart:()=>{ie(""),B("")},onCompileSuccess:()=>{const y=ve.current;y&&Ps(y,S.current.line,S.current.column,{silent:!0})},onPdfChanged:ur});h.useEffect(()=>{const y=j=>{(j.ctrlKey||j.metaKey)&&(!j.shiftKey&&j.key.toLocaleLowerCase()==="p"?(j.preventDefault(),le(!0)):j.shiftKey&&j.key.toLocaleLowerCase()==="f"&&(j.preventDefault(),Ye(!0)))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[]);const _h=y=>{dt(y),Hm(e.id,n,y)},Ha=()=>{xt.current?.isCollapsed()?xt.current.expand():xt.current?.collapse()},qa=h.useMemo(()=>u.length?u:Vb(D).map(y=>({...y,path:p})),[u,D,p]),$n=h.useMemo(()=>Gm(wr,br),[wr,br]),Un=ee!=="pdf-only",Wa=ee!=="editor-only",vr=y=>{ce(y),y==="pdf-only"&&Q("pdf")},Ri=In?Ds.filter(y=>y.filePath&&Gn(In.path,y.filePath)):[];if(!i)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:xe||r("common.loading")}),xe&&o.jsx("button",{className:"primary",onClick:s,children:r("editor.backToProjects")})]});const vt=i.permission==="read"||!Te,Rh=(y,j)=>{if(vt)return;const L=ve.current;if(!L)return;if(Fe.getText(L).toString().slice(y.from,y.to)!==y.word){ie(r("editor.spellCheckSourceChanged"));return}try{Fe.applyTextEdits(L,[{from:y.from,to:y.to,replacement:j}])}catch(Be){ie(V(Be))}},Sr=Nt?.mainFile===x&&(Nt.status==="queued"||Nt.status==="running"),zn=_i||Sr||Ba,Ka=p?Fe.getText(p):null,Ga=Mn?new Date(Mn).toLocaleString(we.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Lh=x.split("/").at(-1)??x,Ah=$n.warnings.length+$n.errors.length+Pi.length,Ja=bn?`${bn}${bn.includes("?")?"&":"?"}download=1`:"",Ya=zn?Sr?Nt?.status==="queued"?r("editor.compileQueued"):r("editor.compilingBy",{name:Nt?.requestedBy.name??r("common.user")}):r("editor.compiling"):br==="failed"?bn&&Mn?r("editor.compileFailedRetained",{time:new Date(Mn).toLocaleString(we.resolvedLanguage)}):r("editor.compileFailedNoPdf"):"",Fh=v==="editor.savedAt"&&X?r("editor.savedAt",{time:new Date(X).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(ld,{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," · ",Fh]})]}),rt.vimMode&&o.jsxs("span",{className:"vim-status-badge",title:r("editor.vimOnHint"),children:[o.jsx(Nm,{size:14}),r("editor.vimOn")]}),o.jsx(ob,{sessions:Ds,status:yn}),yn==="disconnected"&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:r("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:vi,children:r("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[Un&&o.jsxs("button",{className:Z?"":"active",onClick:Ha,children:[Z?o.jsx(_m,{size:15}):o.jsx(kc,{size:15}),r("common.files")]}),o.jsx(ab,{value:ee,onChange:vr}),o.jsxs("button",{onClick:()=>U(!0),children:[o.jsx(pd,{size:15}),r("history.title")]}),o.jsxs("button",{onClick:()=>yt(!0),children:[o.jsx(Bs,{size:15}),r("projectSettings.share")]}),i.ownerId===e.id&&o.jsxs("button",{onClick:()=>Mt(!0),children:[o.jsx(Dm,{size:15}),"Git"]}),Un&&i.permission!=="read"&&Hi(p)&&o.jsxs("button",{title:Ne.selectedText.trim()?r("editor.formatSelection"):r("editor.formatSelectionHint"),onMouseDown:y=>y.preventDefault(),onClick:()=>{An()},disabled:vt||wt||!Te,children:[wt?o.jsx(Gt,{className:"spin",size:15}):o.jsx(cd,{size:15}),r(wt?"editor.formatting":"editor.formatSelection")]}),o.jsxs("button",{onClick:()=>Oi(!0),disabled:!p,children:[o.jsx(Om,{size:15}),r("editor.addComment")]}),o.jsxs("button",{className:Ve==="comments"?"active":"",onClick:()=>z(Ve==="comments"?null:"comments"),children:[o.jsx(Pm,{size:15}),r("common.comments")," ",Rs.filter(y=>!y.resolved).length||""]}),o.jsxs("button",{className:Ve==="settings"?"active":"",onClick:()=>z(Ve==="settings"?null:"settings"),children:[o.jsx(Lr,{size:15}),r("common.settings")]}),o.jsxs("button",{className:"compile",title:Sr?r("editor.compilingBy",{name:Nt?.requestedBy.name??""}):r("editor.compileShortcut"),onClick:Th,disabled:zn||wt||vt||!Te,children:[zn?o.jsx(Gt,{className:"spin",size:15}):o.jsx(Am,{size:15}),Sr?r("editor.compilingBy",{name:Nt?.requestedBy.name??""}):_i?r("editor.compiling"):r("editor.compile",{engine:i.engine})]})]})]}),Ya&&o.jsxs("div",{className:`compile-status-strip${br==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(Gt,{className:zn?"spin":"",size:14}),o.jsx("span",{children:Ya})]}),xe&&o.jsx("div",{className:"toast",onClick:()=>ie(""),children:xe}),N&&o.jsx("div",{className:"toast success",onClick:()=>B(""),children:N}),o.jsxs($h,{autoSaveId:"texlite-workspace-layout",direction:"horizontal",className:"work-grid",children:[Un&&o.jsx(Cr,{id:"files",order:1,ref:xt,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>H(!0),onExpand:()=>H(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${Fa?" drop-active":""}`,onDragEnter:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),!vt&&!yr&&Ni(!0))},onDragOver:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),y.dataTransfer.dropEffect=vt||yr?"none":"copy")},onDragLeave:y=>{y.currentTarget.contains(y.relatedTarget)||Ni(!1)},onDrop:y=>{y.preventDefault(),Ni(!1),!vt&&!yr&&$a(Array.from(y.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("span",{children:[o.jsx(Qn,{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:()=>le(!0),children:o.jsx(km,{size:15})}),o.jsx("button",{"aria-label":r("navigation.projectSearch"),title:`${r("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>Ye(!0),children:o.jsx(Mm,{size:15})}),!vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:yr,"aria-label":r("editor.uploadAttachment"),title:r("editor.uploadTo",{folder:qt||r("editor.projectRoot")}),onClick:()=>de.current?.click(),children:o.jsx(Hr,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFolder"),title:r("editor.newFolder"),onClick:()=>{La(""),Ei(!0)},children:o.jsx(fd,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFile"),title:r("editor.newFile"),onClick:()=>{_a(qt?`${qt}/`:""),ki(!0)},children:o.jsx(jm,{size:15})}),o.jsx("input",{ref:de,type:"file",multiple:!0,hidden:!0,onChange:y=>{fh(y)}})]}),o.jsx("button",{"aria-label":r("editor.collapseFiles"),title:r("editor.collapseFiles"),onClick:Ha,children:o.jsx(kc,{size:15})})]})]}),Fa&&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:qt||r("editor.projectRoot")})})]}),o.jsxs("div",{className:"folder-target",title:qt||r("editor.projectRoot"),children:[o.jsx(Vr,{size:13}),o.jsx("span",{children:qt||r("editor.projectRoot")})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${rt.fontSize}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${qt===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>pr(""),children:[o.jsx(Vr,{size:15}),o.jsx("span",{children:r("editor.projectRoot")})]})}),uh.map(y=>{const j=y.path.split("/").length-1,L=y.path.split("/").at(-1),J=ch.has(y.path),he=C.has(y.path),Be=x===y.path,fe=y.path!==i.mainFile&&!i.mainFile.startsWith(`${y.path}/`);return y.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${qt===y.path?" selected":""}`,style:{paddingLeft:`${j*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",title:y.path,onClick:()=>{pr(y.path),Aa(Ke=>{const Tt=new Set(Ke);return Tt.has(y.path)?Tt.delete(y.path):Tt.add(y.path),Tt})},children:[J?o.jsx(ud,{size:13}):o.jsx(Jo,{size:13}),o.jsx(Em,{size:14}),o.jsx("span",{children:L})]}),!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),Di("")},children:o.jsx(jc,{size:13})}),fe&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),Fn("")},children:o.jsx(ln,{size:13})})]})]},y.path):o.jsxs("div",{className:`file-entry${p===y.path?" active":""}${he?" root-document":""}${Be?" compile-target":""}`,style:{paddingLeft:`${j*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",title:Be?r("editor.currentMainDocument",{path:y.path}):he?r("editor.mainDocumentCandidate",{path:y.path}):y.path,onClick:()=>Ua(y),children:[he?o.jsx(dd,{size:13}):o.jsx(Qn,{size:13}),o.jsx("span",{children:L}),Be&&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),Di("")},children:o.jsx(jc,{size:13})}),fe&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),Fn("")},children:o.jsx(ln,{size:13})})]})]},y.path)})]})]}),o.jsxs("section",{className:"outline-panel",children:[o.jsx("div",{className:"panel-title",children:o.jsxs("span",{children:[o.jsx(Tm,{size:14}),r("common.outline")]})}),o.jsxs("div",{className:"outline",children:[qa.map((y,j)=>o.jsxs("button",{className:`outline-item${p===y.path&&_.line===y.line?" current":""}`,title:`${y.path}:${y.line}`,onClick:()=>{wn(y.path,y.line,1),Ps(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}-${j}`)),qa.length===0&&o.jsx("p",{className:"muted padded",children:r("editor.noOutline")})]})]})]})}),Un&&o.jsx(Li,{className:"resize-handle",children:o.jsx(Bi,{size:12})}),Un&&o.jsx(Cr,{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(Gt,{className:"spin",size:22}),o.jsx("span",{children:r("common.loading")})]}),children:o.jsx(Nb,{value:D,readOnly:vt,comments:Rs,focusComment:gh,preferences:rt,completionIndex:d,spellCheckIssues:Bt.issues,spellCheckJump:Bt.jump,jumpTo:O===p&&Ts?.path===p?Ts:null,searchRequest:0,collaboration:Ka?{text:Ka,awareness:Fe.awareness}:void 0,onChange:xn,onSelection:(y,j,L)=>nt({selectedText:y,startOffset:j,endOffset:L}),onCommentClick:y=>{const j=Rs.find(L=>L.id===y);j&&(za({...j}),z("comments"))},onSpellCheckReplace:Rh,onCursor:gn},p)}),Va&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:Va})]})}),Un&&Wa&&o.jsxs(Li,{className:"resize-handle sync-resize-handle",children:[o.jsx(Bi,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:y=>y.stopPropagation(),children:[o.jsx("button",{disabled:!Ci,title:r("editor.showInSource"),"aria-label":r("editor.showInSource"),onClick:hr,children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!p||!bn,title:r("editor.showInPdf"),"aria-label":r("editor.showInPdf"),onClick:()=>{Ps(p,_.line,_.column)},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),Wa&&o.jsx(Cr,{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":M==="pdf",className:`pdf-tab${M==="pdf"?" active":""}`,onClick:()=>Q("pdf"),title:Mn?r("editor.pdfCompiledAtFor",{file:x,time:new Date(Mn).toLocaleString(we.resolvedLanguage)}):r("editor.currentMainDocument",{path:x}),children:[o.jsx(Qn,{size:16}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",Lh,Ga&&o.jsx("small",{children:Ga})]})]}),o.jsxs("button",{role:"tab","aria-selected":M==="diagnostics",className:`diagnostics-tab${M==="diagnostics"?" active":""}`,onClick:()=>ue("diagnostics"),children:[o.jsx(So,{size:14}),r("editor.outputTabs"),o.jsx("span",{children:Ah})]})]}),Ja&&o.jsxs("a",{className:"pdf-download-top",href:Ja,download:!0,title:r("editor.downloadPdf"),"aria-label":r("editor.downloadPdf"),children:[o.jsx(Vs,{size:15}),o.jsx("span",{children:r("editor.downloadPdf")})]})]}),M==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":r("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":se==="log",className:se==="log"?"active":"",onClick:()=>Q("log"),children:[o.jsx(So,{size:13}),r("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":se==="warnings",className:se==="warnings"?"active":"",onClick:()=>Q("warnings"),children:[o.jsx(us,{size:13}),r("editor.warnings"),o.jsx("span",{children:$n.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":se==="errors",className:se==="errors"?"active":"",onClick:()=>Q("errors"),children:[o.jsx(Yo,{size:13}),r("editor.errors"),o.jsx("span",{children:$n.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":se==="artifacts",className:se==="artifacts"?"active":"",onClick:()=>Q("artifacts"),children:[o.jsx(md,{size:13}),r("editor.artifacts"),o.jsx("span",{children:Pi.length})]}),o.jsxs("button",{role:"tab","aria-selected":se==="clean",className:se==="clean"?"active":"",onClick:()=>Q("clean"),children:[o.jsx(xo,{size:13}),r("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${M} ${M==="diagnostics"?`preview-${se}`:""}`,children:[M==="pdf"&&(bn?o.jsx(h.Suspense,{fallback:o.jsx("div",{className:"preview-empty",children:o.jsx("span",{children:r("common.loading")})}),children:o.jsx(Db,{url:bn,target:Si,compiling:zn,onViewportLocation:(y,j,L)=>Os({page:y,x:j,y:L}),onDoubleClickLocation:(y,j,L)=>{Os({page:y,x:j,y:L}),ji(y,j,L)}})}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Qn,{size:28}),o.jsx("strong",{children:r("editor.preview")}),o.jsx("span",{children:r("editor.previewHint")})]})),M==="diagnostics"&&se==="log"&&o.jsx(io,{lines:wr?wr.split(`
|
|
12
|
+
${e}`),qu=(t,e,n)=>{const s=fn(e),r=Pe(),i=G(s),a=t.messageHandlers[i];return a?a(r,s,t,n,i):console.error("Unable to compute message"),r},Lo=(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,Oa(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Wu,ta(rg(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Wu=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=un();const s=qu(t,new Uint8Array(n.data),!0);na(s)>1&&e.send(me(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Lo(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=un(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Pe();if($(n,Sn),ii(n,t.doc),e.send(me(n)),t.awareness.getLocalState()!==null){const s=Pe();$(s,cs),je(s,as(t.awareness,[t.doc.clientID])),e.send(me(s))}},t.emit("status",[{status:"connecting"}])}},so=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Xn(t.bcChannel,e,t)};class Ux extends ea{constructor(e,n,s,{connect:r=!0,awareness:i=new Ax(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=cr.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=Pe();$(m,Sn),ii(m,s),this.ws.send(me(m))}},d)),this._bcSubscriber=(m,p)=>{if(p!==this){const g=qu(this,new Uint8Array(m),!1);na(g)>1&&Xn(this.bcChannel,me(g),this)}},this._updateHandler=(m,p)=>{if(p!==this){const g=Pe();$(g,Sn),Ox(g,m),so(this,me(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:m,updated:p,removed:g},x)=>{const b=m.concat(p).concat(g),C=Pe();$(C,cs),je(C,as(i,b)),so(this,me(C))},this._exitHandler=()=>{Oa(this.awareness,[s.clientID],"app closed")},hn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&il<un()-this.wsLastMessageReceived&&Lo(this,this.ws,null)},il/10),r&&this.connect()}get url(){const e=Ix(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(),hn&&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||(Dx(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Pe();$(e,Sn),ii(e,this.doc),Xn(this.bcChannel,me(e),this);const n=Pe();$(n,Sn),Vu(n,this.doc),Xn(this.bcChannel,me(n),this);const s=Pe();$(s,Hu),Xn(this.bcChannel,me(s),this);const r=Pe();$(r,cs),je(r,as(this.awareness,[this.doc.clientID])),Xn(this.bcChannel,me(r),this)}disconnectBc(){const e=Pe();$(e,cs),je(e,as(this.awareness,[this.doc.clientID],new Map)),so(this,me(e)),this.bcconnected&&(Nx(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Lo(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Wu(this),this.connectBc())}}const Pn=t=>ps((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),zx=(t,e)=>ps((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(kt(i.target.error)),r.onsuccess=i=>{const a=i.target.result;a.onversionchange=()=>{a.close()},n(a)}}),Vx=t=>Pn(indexedDB.deleteDatabase(t)),Bx=(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=>Xx(s,r))},Ku=(t,e)=>Pn(t.count(e)),Hx=(t,e)=>Pn(t.get(e)),Gu=(t,e)=>Pn(t.delete(e)),qx=(t,e,n)=>Pn(t.put(e,n)),Ao=(t,e)=>Pn(t.add(e)),Wx=(t,e,n)=>Pn(t.getAll(e,n)),Kx=(t,e,n)=>{let s=null;return Yx(t,e,r=>(s=r,!1),n).then(()=>s)},Gx=(t,e=null)=>Kx(t,e,"prev"),Jx=(t,e)=>ps((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()}}),Yx=(t,e,n,s="next")=>Jx(t.openKeyCursor(e,s),r=>n(r.key)),Xx=(t,e)=>t.objectStore(e),Zx=(t,e)=>IDBKeyRange.upperBound(t,e),Qx=(t,e)=>IDBKeyRange.lowerBound(t,e),ro="custom",Ju="updates",Yu=500,Xu=(t,e=()=>{},n=()=>{})=>{const[s]=As(t.db,[Ju]);return Wx(s,Qx(t._dbref,!1)).then(r=>{t._destroyed||(e(s),pe(t.doc,()=>{r.forEach(i=>cu(t.doc,i))},t,!1),n(s))}).then(()=>Gx(s).then(r=>{t._dbref=r+1})).then(()=>Ku(s).then(r=>{t._dbsize=r})).then(()=>s)},eb=(t,e=!0)=>Xu(t).then(n=>{(e||t._dbsize>=Yu)&&Ao(n,xa(t.doc)).then(()=>Gu(n,Zx(t._dbref,!0))).then(()=>Ku(n).then(s=>{t._dbsize=s}))});class tb extends wd{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=zx(e,s=>Bx(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=ps(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Xu(this,a=>Ao(a,xa(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,[Ju]);Ao(i,s),++this._dbsize>=Yu&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{eb(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(()=>{Vx(this.name)})}get(e){return this._db.then(n=>{const[s]=As(n,[ro],"readonly");return Hx(s,e)})}set(e,n){return this._db.then(s=>{const[r]=As(s,[ro]);return qx(r,n,e)})}del(e){return this._db.then(n=>{const[s]=As(n,[ro]);return Gu(s,e)})}}const ol=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],al=4,cl=5;function nb(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!["queued","running","succeeded","failed","cleaned"].includes(e.status??"")||e.status==="cleaned"&&e.cleanMode!=="cache"&&e.cleanMode!=="artifacts"||typeof e.updatedAt!="string"||!n||typeof n.id!="string"||typeof n.username!="string"||typeof n.name!="string"?null:e}function ll(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=nb(s);r&&r.mainFile===n&&(e[n]=r)}return e}class sb{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.persistence=new tb(`texlite:${n.id}:${e}`,this.doc),this.persistence.on("synced",()=>{this.localDraftReady=!0;for(const r of this.draftListeners)r()}),this.provider=new Ux(`${s}//${window.location.host}/api/collaboration`,e,this.doc,{disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness,this.provider.messageHandlers[al]=(r,i)=>{const a=Ct(i),c=this.flushRequests.get(a);if(!c)return;const l=G(i),d=Ct(i);window.clearTimeout(c.timer),this.flushRequests.delete(a),c.resolve({revision:l,persistedAt:d})},this.provider.messageHandlers[cl]=(r,i)=>{const a=Ct(i),c=this.epochStorageKey(),l=rb(c);if(this.epoch&&this.epoch!==a||l&&l!==a){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed")),this.persistence.clearData().then(()=>{dl(c,a),window.location.reload()});return}this.epoch=a,dl(c,a);const d=this.provider.ws;if(!d||d.readyState!==WebSocket.OPEN)return;const f=Pe();$(f,cl),Yt(f,a),d.send(me(f));const u=Pe();$(u,0),ii(u,this.doc),d.send(me(u));const m=Pe();$(m,1),je(m,as(this.awareness,[this.doc.clientID])),d.send(me(m))},this.provider.on("status",({status:r})=>{r==="disconnected"&&this.rejectFlushes(new Error("Collaboration connection closed"))}),this.updateLocalAwareness()}projectId;user;doc=new Tn;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=Pe();return $(s,al),Yt(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(me(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]=ol[Math.abs(this.doc.clientID)%ol.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 rb(t){try{return window.localStorage.getItem(t)}catch{return null}}function dl(t,e){try{window.localStorage.setItem(t,e)}catch{}}function ib(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function ob({sessions:t,status:e}){const{t:n}=_e(),[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:[ib(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 ab({value:t,onChange:e}){const{t:n}=_e(),[s,r]=h.useState(!1),i=h.useRef(null),a=[{value:"editor-pdf",icon:Cc},{value:"editor-only",icon:Rm},{value:"pdf-only",icon:Lm}];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(Cc,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(ud,{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(wm,{size:16})]},c.value)})]})]})}function cb({comment:t,currentUserId:e,onFocus:n,onToggle:s,onReply:r,onEdit:i,onDelete:a,onEditReply:c,onDeleteReply:l}){const{t:d}=_e(),[f,u]=h.useState(!1),[m,p]=h.useState(""),[g,x]=h.useState(!1),[b,C]=h.useState(t.content),[k,D]=h.useState(!1),[T,O]=h.useState(null),[F,E]=h.useState(""),[q,v]=h.useState(null),P=async S=>{S.preventDefault(),m.trim()&&await r(m)&&(p(""),u(!1))},X=async S=>{S.preventDefault(),b.trim()&&await i(b)&&x(!1)},W=async S=>{S.preventDefault(),!(!T||!F.trim())&&await c(T,F)&&O(null)},_=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:()=>{window.getSelection()?.toString()||n()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:t.authorDisplayName??_??d("editor.deletedUser")}),_&&o.jsxs("small",{children:["@",_]})]}),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",{className:"comment-selected-text",children:t.selectedText}),g?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:S=>{X(S)},onClick:S=>S.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:4,value:b,onChange:S=>C(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",{className:"comment-content",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:M=>{W(M)},onClick:M=>M.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:3,value:F,onChange:M=>E(M.target.value)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>O(null),children:d("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!F.trim(),children:[o.jsx(Br,{size:13}),d("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",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:M=>{M.stopPropagation(),O(S.id),E(S.content)},children:o.jsx(vo,{size:12})}),o.jsx("button",{className:"danger-text",title:d("editor.deleteReply"),"aria-label":d("editor.deleteReply"),onClick:M=>{M.stopPropagation(),v(S.id)},children:o.jsx(ln,{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(Im,{size:13}):o.jsx(vm,{size:13}),t.resolved?d("editor.reopen"):d("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:S=>{S.stopPropagation(),u(M=>!M)},children:[o.jsx(Fm,{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(),C(t.content),x(!0)},children:o.jsx(vo,{size:13})}),o.jsx("button",{className:"danger-text",title:d("editor.deleteComment"),"aria-label":d("editor.deleteComment"),onClick:S=>{S.stopPropagation(),D(!0)},children:o.jsx(ln,{size:13})})]})]}),f&&o.jsxs("form",{className:"comment-reply-form",onSubmit:S=>{P(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($m,{size:13}),d("editor.sendReply")]})]})]})]}),o.jsx(ds,{open:k,title:d("editor.deleteCommentTitle"),description:d("editor.deleteCommentDescription",{count:t.replies.length}),confirmLabel:d("common.delete"),danger:!0,onCancel:()=>D(!1),onConfirm:()=>{a().then(S=>{S&&D(!1)})}}),o.jsx(ds,{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 lb({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=_e(),[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(""),C=n.permission==="owner",k=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&&k()},[t,s]);const D=async()=>{if(d)try{await A(`/api/projects/${s}/members/${d}`,{method:"PUT",body:JSON.stringify({permission:u})}),f(""),m("read"),await k()}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 k()}catch(v){b(V(v))}},O=async()=>{if(p)try{await A(`/api/projects/${s}/members/${p.id}`,{method:"DELETE"}),g(null),await k()}catch(E){b(V(E))}},F=c.filter(E=>!i.some(q=>q.id===E.id));return o.jsxs(o.Fragment,{children:[o.jsx($e,{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(Bs,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),C&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:d,onChange:E=>f(E.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),F.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:()=>{D()},children:[o.jsx(gd,{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:!C,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")})]}),C&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(E),children:o.jsx(ln,{size:15})})]})]},E.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(Bs,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(ds,{open:!!p,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:p?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{O()}})]})}function db({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}=_e(),[g,x]=h.useState(t.engine),[b,C]=h.useState(""),[k,D]=h.useState(t.name),[T,O]=h.useState(t.mainFile),[F,E]=h.useState(""),[q,v]=h.useState(""),[P,X]=h.useState(""),[W,_]=h.useState("appearance"),[R,S]=h.useState(a),M=t.permission==="owner",ue=t.permission!=="read",se=t.permission!=="read";h.useEffect(()=>S(a),[a]),h.useEffect(()=>{if(!t.latexmkrc)return C("");A(`/api/projects/${e}/file?path=${encodeURIComponent(t.latexmkrc)}`).then(({content:N})=>C(N)).catch(N=>E(V(N)))},[t.latexmkrc]);const be=s.filter(N=>N.type==="file"&&/\.tex$/i.test(N.path)).map(N=>N.path),Q=[...new Set(t.mainFile.toLowerCase().endsWith(".tex")?[...be,t.mainFile]:be)].sort((N,B)=>N.localeCompare(B)),ee=async()=>{try{const N=b.trim()&&n.allowProjectLatexmkrc!==!1?".latexmkrc":null;N&&await A(`/api/projects/${e}/file`,{method:"PUT",body:JSON.stringify({path:N,content:b})});const B=await A(`/api/projects/${e}`,{method:"PATCH",body:JSON.stringify({name:k,mainFile:T,engine:g,latexmkrc:N})});m(B.project)}catch(N){E(V(N))}},ce=()=>c(R),xe=async()=>{const N=q.trim();if(N)try{const B=await A(`/api/projects/${e}/dictionary`,{method:"POST",body:JSON.stringify({word:N})});i(B.words),v(""),X("")}catch(B){X(V(B))}},ie=async N=>{try{const B=await A(`/api/projects/${e}/dictionary/${encodeURIComponent(N)}`,{method:"DELETE"});i(B.words),X("")}catch(B){X(V(B))}};return o.jsxs("div",{className:"settings padded",children:[F&&o.jsx("p",{className:"error",children:F}),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:()=>_("appearance"),children:[o.jsx(Dc,{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:()=>_("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(Dc,{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:N=>S({...R,font:N.target.value}),children:qr.map(N=>o.jsx("option",{value:N.id,children:p(N.labelKey)},N.id))})]}),o.jsxs("label",{children:[p("projectSettings.fontSize"),o.jsx("select",{value:R.fontSize,onChange:N=>S({...R,fontSize:Number(N.target.value)}),children:[12,13,14,15,16,18,20].map(N=>o.jsxs("option",{value:N,children:[N," px"]},N))})]}),o.jsxs("label",{children:[p("projectSettings.lineHeight"),o.jsxs("select",{value:R.lineHeight,onChange:N=>S({...R,lineHeight:Number(N.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:N=>S({...R,lineWrapping:N.target.checked})}),o.jsx(Vm,{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:N=>S({...R,spellCheck:N.target.checked})}),o.jsx("span",{children:p("projectSettings.spellCheck")})]}),o.jsxs("p",{className:"field-hint",children:[p("projectSettings.writingCheckDescription")," ",o.jsx("a",{href:"https://writewithharper.com/docs/harperjs/introduction",target:"_blank",rel:"noreferrer",children:"Harper.js"})]}),o.jsxs("label",{className:"editor-checkbox",children:[o.jsx("input",{type:"checkbox",checked:R.vimMode,onChange:N=>S({...R,vimMode:N.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:!ue,checked:R.formatOnCompile,onChange:N=>S({...R,formatOnCompile:N.target.checked})}),o.jsx(cd,{size:15}),o.jsx("span",{children:p("projectSettings.formatOnCompile")})]}),o.jsxs("p",{className:"field-hint",children:[p(ue?"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(zm,{size:14}),o.jsx("span",{children:l?p("projectSettings.writingIssues",{count:l,uniqueCount:d??0}):p("projectSettings.noWritingIssues")}),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(xm,{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(hd,{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(Jo,{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(bm,{size:14})})]})]}),o.jsxs("div",{className:"settings-section-title",children:[o.jsx(dd,{size:15}),o.jsx("strong",{children:p("projectSettings.dictionary")})]}),o.jsx("p",{className:"settings-description",children:p("projectSettings.dictionaryDescription")}),P&&o.jsx("p",{className:"error dictionary-error",children:P}),se&&o.jsxs("div",{className:"dictionary-add",children:[o.jsx("input",{value:q,placeholder:p("projectSettings.dictionaryPlaceholder"),onChange:N=>v(N.target.value),onKeyDown:N=>{N.key==="Enter"&&(N.preventDefault(),xe())}}),o.jsx("button",{type:"button",disabled:!q.trim(),onClick:()=>{xe()},children:p("projectSettings.addWord")})]}),o.jsxs("div",{className:"dictionary-words",children:[r.map(N=>o.jsxs("span",{className:"dictionary-word",children:[o.jsx("code",{children:N}),se&&o.jsx("button",{type:"button",title:p("common.delete"),"aria-label":`${p("common.delete")} ${N}`,onClick:()=>{ie(N)},children:o.jsx(Xo,{size:13})})]},N)),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:ce,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:!M,value:k,onChange:N=>D(N.target.value)})]}),o.jsxs("label",{children:[p("projectSettings.mainFile"),o.jsx("select",{disabled:!M||Q.length===0,value:T,onChange:N=>O(N.target.value),children:Q.map(N=>o.jsx("option",{value:N,children:N},N))})]}),o.jsxs("label",{children:[p("projectSettings.engine"),o.jsx("select",{disabled:!M,value:g,onChange:N=>x(N.target.value),children:(n.allowedEngines??["pdflatex","xelatex","lualatex"]).map(N=>o.jsx("option",{children:N},N))})]}),o.jsxs("label",{children:[p("projectSettings.latexmkrc"),o.jsx("textarea",{className:"latexmkrc-editor",rows:10,spellCheck:!1,disabled:!M||n.allowProjectLatexmkrc===!1,value:b,placeholder:p("projectSettings.latexmkrcPlaceholder"),onChange:N=>C(N.target.value)})]}),o.jsx("div",{className:"settings-actions",children:M&&o.jsxs("button",{className:"settings-save",onClick:()=>{ee()},children:[o.jsx(Br,{size:15}),p("projectSettings.saveCompiler")]})})]})]})}function ul({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=_e(),a=s==="error"?Yo:us;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((c,l)=>{const d=fb(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 io({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Yo:n==="warning"?us:So;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 ub({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:a}=_e(),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(Qn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:l.path}),o.jsx("small",{children:pb(l.size)})]})]}),o.jsx("a",{href:c(l.path),title:a("editor.downloadArtifact"),"aria-label":a("editor.downloadArtifact"),children:o.jsx(Vs,{size:14})})]},l.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(Gt,{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(Vs,{size:13}),a("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Qn,{size:24}),o.jsx("span",{children:a("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(md,{size:26}),o.jsx("span",{children:a("editor.noArtifacts")})]})}function hb({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=_e();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(us,{size:28}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanTitle")}),o.jsx("p",{children:i("editor.cleanDescription",{file:t})})]})]}),o.jsxs("div",{className:"compile-clean-actions",children:[o.jsxs("article",{children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(xo,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanCache")}),o.jsx("p",{children:i("editor.cleanCacheDescription")}),o.jsxs("button",{type:"button",disabled:e||n,onClick:s,children:[n?o.jsx(Gt,{className:"spin",size:14}):o.jsx(xo,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(ln,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanArtifacts")}),o.jsx("p",{children:i("editor.cleanArtifactsDescription")}),o.jsxs("button",{type:"button",className:"danger",disabled:e||n,onClick:r,children:[n?o.jsx(Gt,{className:"spin",size:14}):o.jsx(ln,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function fb(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 pb(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function mb(t){return t instanceof Error&&t.name==="AbortError"}function gb({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),C=h.useRef(e),k=h.useRef(i),D=h.useRef(a),T=h.useRef(c);C.current=e,k.current=i,D.current=a,T.current=c;const O=async _=>{b.current?.abort();const R=new AbortController;b.current=R;try{const S=await A(`/api/projects/${t}/comments?path=${encodeURIComponent(_)}`,{signal:R.signal});C.current===_&&d(S.comments)}catch(S){!mb(S)&&C.current===_&&d([])}finally{b.current===R&&(b.current=null)}};return h.useEffect(()=>{u(null)},[t,e]),h.useEffect(()=>(e?O(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 k.current())return;await A(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:e,content:g,...r})}),await O(e),p(!1),x(""),T.current()}catch(_){D.current(V(_))}},toggleComment:async _=>{try{await A(`/api/projects/${t}/comments/${_.id}`,{method:"PATCH",body:JSON.stringify({resolved:!_.resolved})}),await O(e)}catch(R){D.current(V(R))}},replyToComment:async(_,R)=>{try{return await A(`/api/projects/${t}/comments/${_.id}/replies`,{method:"POST",body:JSON.stringify({content:R})}),await O(e),!0}catch(S){return D.current(V(S)),!1}},editComment:async(_,R)=>{try{return await A(`/api/projects/${t}/comments/${_.id}`,{method:"PATCH",body:JSON.stringify({content:R})}),await O(e),!0}catch(S){return D.current(V(S)),!1}},deleteComment:async _=>{try{return await A(`/api/projects/${t}/comments/${_.id}`,{method:"DELETE"}),await O(e),u(R=>R?.id===_.id?null:R),!0}catch(R){return D.current(V(R)),!1}},editCommentReply:async(_,R,S)=>{try{return await A(`/api/projects/${t}/comments/${_.id}/replies/${R}`,{method:"PATCH",body:JSON.stringify({content:S})}),await O(e),!0}catch(M){return D.current(V(M)),!1}},deleteCommentReply:async(_,R)=>{try{return await A(`/api/projects/${t}/comments/${_.id}/replies/${R}`,{method:"DELETE"}),await O(e),!0}catch(S){return D.current(V(S)),!1}}}}function yb(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 wb(t,e,n,s){const[r]=h.useState(()=>new sb(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(""),[C,k]=h.useState(""),[D,T]=h.useState(!1),O=h.useRef(n),F=h.useRef(s);return O.current=n,F.current=s,h.useEffect(()=>{const q=ll(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(""),k(""),F.current()},P=({status:S})=>{a(S),S!=="connected"&&v()},X=S=>{l(S),S||v()},W=()=>{a("disconnected"),v()},_=()=>{const S=r.meta.get("filesEvent");yb(S)&&g(S);const M=r.meta.get("commentsRevision");typeof M=="string"&&b(M);const ue=r.meta.get("dictionaryRevision");typeof ue=="string"&&k(ue);const se=ll(r.meta.get("compileStates"));m(se[O.current]??null)};r.awareness.on("change",q),r.provider.on("status",P),r.provider.on("sync",X),r.provider.on("connection-close",W),r.provider.on("connection-error",W),r.meta.observe(_);const R=r.onDraftReady(()=>T(!0));return q(),_(),a(r.connected?"connected":"connecting"),l(r.synced),()=>{r.awareness.off("change",q),r.provider.off("status",P),r.provider.off("sync",X),r.provider.off("connection-close",W),r.provider.off("connection-error",W),r.meta.unobserve(_),R(),r.destroy()}},[r]),{collaboration:r,status:i,synced:c,activeSessions:d,compileState:u,setCompileState:m,filesEvent:p,commentsRevision:x,dictionaryRevision:C,localDraftReady:D,reconnect:()=>{a("connecting"),l(!1),f([]),m(null),r.reconnect()}}}function Kn(t){return t instanceof Error&&t.name==="AbortError"}function xb({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}=_e(),[g,x]=h.useState(""),[b,C]=h.useState(null),[k,D]=h.useState(""),[T,O]=h.useState(null),[F,E]=h.useState(null),[q,v]=h.useState([]),[P,X]=h.useState(null),[W,_]=h.useState(!1),[R,S]=h.useState(!1),[M,ue]=h.useState(()=>new Set),[se,be]=h.useState(""),Q=h.useRef(n),ee=h.useRef(null),ce=h.useRef(null),xe=h.useRef(new Map),ie=h.useRef(null),N=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 Ne=z=>{ie.current!==z&&(ie.current=z,B.current.onCompileSuccess())},He=async(z,Z)=>{Z||(ce.current?.abort(),ce.current=new AbortController,Z=ce.current.signal);try{const H=z?`?mainFile=${encodeURIComponent(z)}`:"",oe=await A(`/api/projects/${t}/compile/artifacts${H}`,{signal:Z});Q.current===z&&(v(oe.artifacts),X(null))}catch(H){!Kn(H)&&Q.current===z&&(v([]),X(null))}finally{ce.current?.signal===Z&&(ce.current=null)}};h.useEffect(()=>{ee.current?.abort();const z=new AbortController;if(ee.current=z,D(""),O(null),E(null),x(""),C(null),v([]),X(null),B.current.onPdfChanged(),!e||!n)return()=>z.abort();const Z=`?mainFile=${encodeURIComponent(n)}`,H=A(`/api/projects/${t}/compile/artifacts${Z}`,{signal:z.signal}).catch(oe=>{if(Kn(oe))throw oe;return{artifacts:[]}});return Promise.all([A(`/api/projects/${t}/compile/latest${Z}`,{signal:z.signal}),H,B.current.loadOutline(z.signal,n)]).then(([oe,yt])=>{z.signal.aborted||oe.mainFile!==Q.current||(v(yt.artifacts),D(oe.latestRun?.log??""),O(oe.latestRun?.diagnostics??null),E(oe.latestRun?.status==="succeeded"||oe.latestRun?.status==="failed"?oe.latestRun.status:null),oe.latestRun?.requestedBy&&(oe.latestRun.status==="queued"||oe.latestRun.status==="running")&&B.current.onSharedState({mainFile:n,runId:oe.latestRun.id,status:oe.latestRun.status,requestedBy:oe.latestRun.requestedBy,updatedAt:new Date().toISOString()}),oe.pdfUrl&&(x(oe.pdfUrl),C(oe.pdfCompiledAt),B.current.onPreviewTab("pdf")))}).catch(oe=>{!Kn(oe)&&Q.current===n&&B.current.onError(V(oe))}).finally(()=>{ee.current===z&&(ee.current=null)}),()=>z.abort()},[e?.id,t,n]),h.useEffect(()=>{!r||r.mainFile!==n||r.status!=="cleaned"||!r.cleanMode||(ee.current?.abort(),ce.current?.abort(),r.cleanMode==="artifacts"?(D(""),O(null),E(null),x(""),C(null),v([]),X(null),B.current.onPdfChanged(),B.current.onPreviewTab("pdf"),be(p("editor.cleanArtifactsComplete"))):be(p("editor.cleanCacheComplete")))},[r?.runId,r?.status,r?.cleanMode,r?.mainFile,n,p]),h.useEffect(()=>{if(!r||r.mainFile!==n||r.status!=="succeeded"&&r.status!=="failed")return;let z=!1;ee.current?.abort();const Z=new AbortController;return ee.current=Z,A(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:Z.signal}).then(H=>{z||H.mainFile!==Q.current||H.latestRun?.id!==r.runId||(D(H.latestRun.log),O(H.latestRun.diagnostics),E(r.status==="succeeded"?"succeeded":"failed"),r.status==="succeeded"&&H.pdfUrl?(B.current.onPdfChanged(),x(H.pdfUrl),C(H.pdfCompiledAt),B.current.onPreviewTab("pdf"),Ne(r.runId),He(n)):r.status==="failed"&&B.current.onPreviewTab(H.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(H=>{!Kn(H)&&!z&&B.current.onError(V(H))}),()=>{z=!0,Z.abort(),ee.current===Z&&(ee.current=null)}},[r?.runId,r?.status,r?.mainFile,n,t]);const tt=async()=>{if(!e||!n||e.permission==="read"||!s||xe.current.has(n)||r?.mainFile===n&&(r.status==="queued"||r.status==="running"))return;const z=n;ue(H=>new Set([...H,z])),B.current.onCompileStart(),be(""),D(""),O(null),E(null),B.current.onPreviewTab(g?"pdf":"log");const Z=new AbortController;xe.current.set(z,Z);try{if(!await B.current.save())return;const H=await A(`/api/projects/${t}/compile`,{method:"POST",signal:Z.signal,body:JSON.stringify({mainFile:z})});if(H.mainFile!==Q.current)return;D(H.log),O(H.diagnostics),E(H.ok?"succeeded":"failed"),H.skipped&&be(p("editor.upToDate")),H.pdfUrl?(B.current.onPdfChanged(),x(H.pdfUrl),C(H.pdfCompiledAt),B.current.onPreviewTab("pdf"),H.ok&&(H.skipped?B.current.onCompileSuccess():Ne(H.runId))):B.current.onPreviewTab(H.diagnostics.errors.length?"errors":"log")}catch(H){!Kn(H)&&Q.current===z&&B.current.onError(V(H))}finally{xe.current.get(z)===Z&&(xe.current.delete(z),ue(H=>{const oe=new Set(H);return oe.delete(z),oe}))}},nt=async z=>{if(!e||!n||e.permission==="read"||!s||R||xe.current.has(n)||r?.mainFile===n&&(r.status==="queued"||r.status==="running"))return;const Z=n;S(!0),ee.current?.abort(),ce.current?.abort();try{if((await A(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:Z,mode:z})})).mainFile!==Q.current)return;B.current.onSharedState(null),z==="artifacts"&&(D(""),O(null),E(null),x(""),C(null),v([]),X(null),B.current.onPdfChanged()),be(p(z==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(H){!Kn(H)&&Q.current===Z&&B.current.onError(V(H))}finally{S(!1)}};N.current=()=>{tt()},h.useEffect(()=>{if(!se)return;const z=window.setTimeout(()=>be(""),3e3);return()=>window.clearTimeout(z)},[se]),h.useEffect(()=>{const z=Z=>{!(Z.ctrlKey||Z.metaKey)||Z.key.toLocaleLowerCase()!=="s"||(Z.preventDefault(),Z.stopPropagation(),Z.repeat||N.current())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[]),h.useEffect(()=>()=>{ee.current?.abort(),ce.current?.abort();for(const z of xe.current.values())z.abort();xe.current.clear()},[]);const Ve=async z=>{if(z.viewable){_(!0);try{const Z=await A(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(z.path)}`);X(Z)}catch(Z){B.current.onError(V(Z))}finally{_(!1)}}};return{pdfUrl:g,pdfCompiledAt:b,compileLog:k,compileDiagnostics:T,compileOutcome:F,artifacts:q,artifactPreview:P,artifactLoading:W,editorNotice:se,localCompiling:M.has(n),cleaning:R,compile:tt,cleanCompile:nt,viewArtifact:Ve}}const hl=10*1024*1024,bb=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 fl(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 Gn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function vb(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!bb.has(e)}function Fo(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function pl(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":vb(t)?"text":"unsupported"}function Sb(t,e){return`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`}function Cb({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:a,onActiveFile:c,onActiveMainFile:l,onRootDocuments:d}){const{t:f}=_e(),[u,m]=h.useState([]),[p,g]=h.useState(!1),[x,b]=h.useState(""),[C,k]=h.useState(null),[D,T]=h.useState(!1),[O,F]=h.useState(!1),[E,q]=h.useState(""),[v,P]=h.useState(""),[X,W]=h.useState(""),[_,R]=h.useState(new Set),[S,M]=h.useState(null),[ue,se]=h.useState(""),[be,Q]=h.useState(null),[ee,ce]=h.useState(!1),[xe,ie]=h.useState(null),[N,B]=h.useState(!1),Ne=h.useRef(null),He=h.useRef(null),tt=async(U={})=>{Ne.current?.abort(),Ne.current=null;const te=U.signal?null:new AbortController;te&&(Ne.current=te);try{const ye=await A(`/api/projects/${t}/files`,{signal:U.signal??te?.signal});return(!U.isCurrent||U.isCurrent())&&m(ye.files),ye.files}catch(ye){if(!fl(ye))throw ye;return}finally{te&&Ne.current===te&&(Ne.current=null)}},nt=async()=>{if(!(!x.trim()||x.trim().endsWith("/"))){P("");try{await A(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:x,content:""})}),await tt(),c(x),R(U=>new Set([...U,...Fs(x)])),g(!1),b("")}catch(U){P(V(U))}}},Ve=async()=>{if(!E.trim())return;P("");const U=X?`${X}/${E.trim()}`:E.trim();try{const te=await A(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:U})});await tt(),R(ye=>new Set([...ye,...Fs(te.path),te.path])),W(te.path),F(!1),q("")}catch(te){P(V(te))}},z=async(U,te=new Set,ye=X)=>{if(!U.length)return;const st=e.maxUploadSizeMB??50;if(U.find(de=>de.size>st*1024*1024))return i(f("errors.fileTooLarge",{size:st}));const qe=ye,Ye=U.map(de=>qe?`${qe}/${de.name}`:de.name),wt=new Map;for(const de of Ye)wt.set(de,(wt.get(de)??0)+1);const lt=[...wt.entries()].filter(([,de])=>de>1).map(([de])=>de);if(lt.length)return i(f("errors.duplicateUploadNames",{files:lt.join(", ")}));const rt=new Set(u.map(de=>de.path)),dt=[...new Set(Ye.filter(de=>rt.has(de)&&!te.has(de)))];if(dt.length){ie({files:U,directory:qe,collisions:dt});return}ie(null),B(!0);try{const de=new URLSearchParams;qe&&de.set("directory",qe);let xt="";for(const[Xe,bt]of U.entries()){const pn=Ye[Xe];de.delete("overwrite"),te.has(pn)&&de.set("overwrite","1");const ve=de.toString()?`?${de.toString()}`:"",Ut=new FormData;Ut.append("file",bt);const ae=await fetch(`/api/projects/${t}/upload${ve}`,{method:"POST",body:Ut}),ut=await ae.json().catch(()=>({}));if(!ae.ok){if(ae.status===409&&!te.has(pn)&&ut.code==="FILE_EXISTS"){Xe>0&&await tt(),ie({files:U.slice(Xe),directory:qe,collisions:[typeof ut.path=="string"?ut.path:pn]});return}throw new Error(ae.status===409?f("errors.pathConflict"):Mo(ut,ae.status,"errors.upload"))}typeof ut.path=="string"&&Fo(ut.path)&&(xt=ut.path)}await tt(),xt&&c(xt)}catch(de){i(V(de))}finally{B(!1)}},Z=async U=>{await z(Array.from(U.target.files??[])),U.target.value=""},H=async U=>{He.current?.abort(),He.current=null,T(!1);const te=Sb(t,U.path);if((U.size??0)>hl){k({path:U.path,kind:"large",size:U.size??0,url:te});return}const ye=pl(U.path);if(ye!=="text"){k({path:U.path,kind:ye,size:U.size??0,url:te});return}k({path:U.path,kind:ye,size:U.size??0,url:te,content:""}),T(!0);const st=new AbortController;He.current=st;try{const le=await fetch(te,{signal:st.signal}),qe=await le.text();if(!le.ok)throw new Error(qe||f("errors.request",{status:le.status}));k(Ye=>Ye?.path===U.path?{...Ye,content:qe}:Ye)}catch(le){fl(le)||(k(null),i(V(le)))}finally{He.current===st&&(He.current=null,T(!1))}},oe=U=>{const te=pl(U.path);(U.size??0)>hl||te!=="text"||!Fo(U.path)?H(U):c(U.path)},yt=async()=>{if(S){P("");try{if(!await r())return;const U=await A(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:S.path,destinationDirectory:ue})}),te=le=>le===S.path?U.path:le.startsWith(`${S.path}/`)?`${U.path}${le.slice(S.path.length)}`:le;c(le=>te(le)),l(le=>te(le)),d(le=>new Set([...le].map(te))),W(le=>le&&te(le));const[ye,st]=await Promise.all([A(`/api/projects/${t}/files`),A(`/api/projects/${t}`)]);m(ye.files),a(st.project),R(le=>new Set([...le,...Fs(U.path),ue].filter(Boolean))),M(null),se("")}catch(U){P(V(U))}}},tn=async()=>{if(be){P("");try{if(s&&!await r())return;await A(`/api/projects/${t}/file?path=${encodeURIComponent(be.path)}`,{method:"DELETE"}),Q(null)}catch(U){P(V(U))}}};h.useEffect(()=>()=>{Ne.current?.abort(),He.current?.abort()},[]),h.useEffect(()=>{He.current?.abort(),He.current=null,T(!1)},[n]);const Mt=u.filter(U=>U.type==="directory"),$t=u.filter(U=>Fs(U.path).every(te=>_.has(te)));return{files:u,setFiles:m,loadFiles:tt,newFileOpen:p,setNewFileOpen:g,newFilePath:x,setNewFilePath:b,resourcePreview:C,setResourcePreview:k,resourcePreviewLoading:D,setResourcePreviewLoading:T,newFolderOpen:O,setNewFolderOpen:F,newFolderName:E,setNewFolderName:q,fileDialogError:v,setFileDialogError:P,selectedFolder:X,setSelectedFolder:W,expandedFolders:_,setExpandedFolders:R,moveEntry:S,setMoveEntry:M,moveDestination:ue,setMoveDestination:se,deleteEntry:be,setDeleteEntry:Q,fileDragActive:ee,setFileDragActive:ce,uploadConflict:xe,setUploadConflict:ie,uploadingFiles:N,directoryEntries:Mt,visibleEntries:$t,createFile:nt,createFolder:Ve,uploadFiles:z,upload:Z,openFile:oe,movePath:yt,removePath:tn}}function jb({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),C=h.useRef(0);x.current=n,b.current=e,h.useEffect(()=>{i([]),c(""),d(""),p(null)},[e,s]),h.useEffect(()=>{u(O=>r.length?Math.min(O,r.length-1):0)},[r]),h.useEffect(()=>{const O=++g.current;if(!t||!e){i([]),c(""),d(""),p(null);return}const F=n,E=e,q=window.setTimeout(()=>{Qt(async()=>{const{lintLatex:v}=await import("./spellCheck-C1kZMEs3.js");return{lintLatex:v}},__vite__mapDeps([2,1])).then(({lintLatex:v})=>{if(!(O!==g.current||x.current!==F||b.current!==E))return v(F,s).then(P=>{O!==g.current||x.current!==F||b.current!==E||(i(P),c(F),d(E),u(0),p(null))})}).catch(()=>{})},700);return()=>window.clearTimeout(q)},[t,e,n,s]);const k=l===e&&a===n,D=h.useMemo(()=>k?{total:r.length,unique:new Set(r.map(O=>`${O.kind}:${O.word.toLocaleLowerCase("en-US")}`)).size}:null,[k,r]);return{issues:k?r:[],jump:k?m:null,index:f,summary:D,jumpToIssue:O=>{if(!r.length)return;const F=Math.max(0,Math.min(O,r.length-1)),E=r[F];u(F),p({from:E.from,to:E.to,nonce:++C.current})}}}function ml(t){return t instanceof Error&&t.name==="AbortError"}function kb({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),C=h.useRef(i);g.current=n,x.current=s,b.current=r,C.current=i,h.useEffect(()=>(m.current?.abort(),m.current=null,c(null),d(null),u(null),()=>m.current?.abort()),[t,e]);const k=(F,E,q)=>{u({path:F,line:E,column:q,nonce:++p.current}),g.current!==F&&x.current(F)},D=async(F,E,q,v={})=>{m.current?.abort();const P=new AbortController;m.current=P;try{const X=await A(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(F)}&line=${E}&column=${q}`,{signal:P.signal});if(m.current!==P)return;c({...X,nonce:++p.current}),C.current()}catch(X){!ml(X)&&!v.silent&&b.current(V(X))}finally{m.current===P&&(m.current=null)}},T=async(F,E,q)=>{m.current?.abort();const v=new AbortController;m.current=v;try{const P=await A(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${F}&x=${E}&y=${q}`,{signal:v.signal});if(m.current!==v)return;k(P.path,P.line,P.column)}catch(P){ml(P)||b.current(V(P))}finally{m.current===v&&(m.current=null)}};return{pdfTarget:a,pdfViewport:l,sourceJump:f,setPdfViewport:d,clearPdfViewport:()=>d(null),jumpToSource:k,syncSourceToPdf:D,syncPdfToSource:T,syncVisiblePdfToSource:()=>{l&&T(l.page,l.x,l.y)}}}function Zu(t,e){return`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function gl(t,e){try{const n=window.localStorage.getItem(Zu(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function Eb(t,e){const[n,s]=h.useState(()=>gl(t,e));return h.useEffect(()=>{s(gl(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Zu(t,e),i)}catch{}}}}const Qu=()=>Qt(()=>import("./PdfPreview-BaOpY89K.js"),__vite__mapDeps([3,1,4,5])),Db=h.lazy(()=>Qu().then(t=>({default:t.PdfPreview}))),Nb=h.lazy(()=>Qt(()=>import("./LatexEditor-0ijwz3Ud.js"),__vite__mapDeps([6,1,7])).then(t=>({default:t.LatexEditor}))),Tb=h.lazy(()=>Qt(()=>import("./GitDialog-DPK1_Lf7.js"),__vite__mapDeps([8,1,5])).then(t=>({default:t.GitDialog}))),Ob=h.lazy(()=>Qt(()=>import("./HistoryDialog-wKZ0ECpn.js"),__vite__mapDeps([9,1,0])).then(t=>({default:t.HistoryDialog}))),Pb=h.lazy(()=>Qt(()=>import("./ProjectNavigationDialogs-CYY6XsGS.js"),__vite__mapDeps([10,1])).then(t=>({default:t.ProjectSearchDialog}))),_b=h.lazy(()=>Qt(()=>import("./ProjectNavigationDialogs-CYY6XsGS.js"),__vite__mapDeps([10,1])).then(t=>({default:t.QuickOpenDialog}))),Rb=h.lazy(()=>Qt(()=>import("./SystemMetricsDialog-D960tY84.js"),__vite__mapDeps([11,1])).then(t=>({default:t.SystemMetricsDialog}))),Ze=8;function Zn(t){return t instanceof Error&&t.name==="AbortError"}function Lb(){const{t}=_e(),[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!==qi(m)){const x={texliteRoute:"project",projectId:m,fromDashboard:!1};window.history.replaceState(x,"",qi(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=qi(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(Qm(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 Io&&m.status,r(null)})},[]),s===void 0)return o.jsx("div",{className:"center-card",children:t("common.loading")});if(!s)return o.jsx(Fb,{site:e,onLogin:r});if(s.mustChangePassword)return o.jsx(Ab,{site:e,user:s,onChanged:m=>r(m)});if(i)return o.jsx(Ub,{site:e,user:s,projectId:i,onBack:f},i);const u=c?.userId===s.id?c:null;return o.jsx(Ib,{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 Pa(){const{t}=_e();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",Bh]})]}),o.jsx("span",{children:t("footer.credit")})]})}function Ab({site:t,user:e,onChanged:n}){const{t:s}=_e(),[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<Ze)return u(s("auth.passwordMinimum",{count:Ze}));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(Go,{}),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:Ze,autoComplete:"new-password",value:a,onChange:p=>c(p.target.value)}),o.jsx("small",{className:"field-hint",children:s("auth.passwordMinimum",{count:Ze})})]}),o.jsxs("label",{children:[s("auth.confirmPassword"),o.jsx("input",{type:"password",minLength:Ze,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(Pa,{})]})}function Fb({site:t,onLogin:e}){const{t:n}=_e(),[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(Go,{}),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(Pa,{})]})}function Ib({site:t,user:e,initialData:n,onDataChange:s,onUser:r,onOpenProject:i}){const{t:a}=_e(),[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),[C,k]=h.useState(!1),[D,T]=h.useState(""),[O,F]=h.useState(!1),[E,q]=h.useState(""),[v,P]=h.useState(!1),[X,W]=h.useState(""),[_,R]=h.useState(null),[S,M]=h.useState(""),ue=h.useRef(null),[se,be]=h.useState(!1),[Q,ee]=h.useState(""),[ce,xe]=h.useState(""),[ie,N]=h.useState(!1),[B,Ne]=h.useState(""),[He,tt]=h.useState("blue"),[nt,Ve]=h.useState(null),[z,Z]=h.useState(null),[H,oe]=h.useState(""),[yt,tn]=h.useState(null),[Mt,$t]=h.useState(""),[U,te]=h.useState(!1),[ye,st]=h.useState(null),[le,qe]=h.useState(null),[Ye,wt]=h.useState([]),[lt,rt]=h.useState(""),[dt,de]=h.useState(!1),[xt,Xe]=h.useState(""),[bt,pn]=h.useState(()=>localStorage.getItem("texlite-project-view")==="list"?"list":"grid"),[ve,Ut]=h.useState(()=>localStorage.getItem("texlite-project-sort")==="created"?"created":"updated"),[ae,ut]=h.useState(!1),[zt,Dt]=h.useState(""),[ke,We]=h.useState(1),[Vt,mn]=h.useState(""),_n=h.useRef(0),gn=h.useRef(null),Fe=(w,re,ne,Ce,Ee)=>`${w?"archived":"active"}|${re}|${ne}|${Ce}|${Ee}`,yn=Fe(ae,ke,Q,ce,ve),Te=(w,re,ne,Ce,Ee)=>{const Le=new URLSearchParams({page:String(re),pageSize:"20",sort:Ee});w&&Le.set("archived","1"),ne.trim()&&Le.set("search",ne.trim()),Ce&&Le.set("tag",Ce);const Ht=Fe(w,re,ne,Ce,Ee),Ln=++_n.current;gn.current?.abort();const An=new AbortController;return gn.current=An,Promise.all([A(`/api/projects?${Le.toString()}`,{signal:An.signal}),A("/api/tags",{signal:An.signal})]).then(([ht,fr])=>{Ln===_n.current&&(l(ht.projects),f(fr.tags),m(ht.pagination),We(ht.pagination.page),g(!0),mn(Ht))}).catch(ht=>{!Zn(ht)&&Ln===_n.current&&T(V(ht))}).finally(()=>{gn.current===An&&(gn.current=null)})};h.useEffect(()=>(Te(ae,ke,Q,ce,ve),()=>gn.current?.abort()),[ae,ke,Q,ce,ve]),h.useEffect(()=>{p&&!ae&&Vt===yn&&s(c,d,u)},[c,d,u,p,Vt,yn,ae]);const Ds=w=>{pn(w),localStorage.setItem("texlite-project-view",w)},Nt=w=>{Ut(w),We(1),localStorage.setItem("texlite-project-sort",w)},Ns=w=>{ut(w),We(1)},Se=w=>{xe(w),We(1)},lr=async()=>{if(E.trim())try{const{project:w}=await A("/api/projects",{method:"POST",body:JSON.stringify({name:E})});F(!1),q("");const re=ae||ke!==1?c:[w,...c].slice(0,u.pageSize),ne=ae?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(re),m(ne),ae||s(re,d,ne),i(w.id)}catch(w){T(V(w))}},dr=async()=>{if(!_)return;const w=t.maxUploadSizeMB??50;if(_.size>w*1024*1024)return M(a("errors.fileTooLarge",{size:w}));be(!0),M("");const re=new FormData;re.append("file",_);try{const ne=await fetch(`/api/projects/import?name=${encodeURIComponent(X.trim())}`,{method:"POST",body:re}),Ce=await ne.json();if(!ne.ok)throw new Error(Mo(Ce,ne.status,"errors.upload"));const Ee=Ce.project,Le=ae||ke!==1?c:[Ee,...c].slice(0,u.pageSize),Ht=ae?u:{...u,total:u.total+1,totalPages:Math.ceil((u.total+1)/u.pageSize)};l(Le),m(Ht),ae||s(Le,d,Ht),P(!1),R(null),W(""),i(Ee.id)}catch(ne){M(V(ne))}finally{be(!1)}},Rn=w=>{if(w&&!w.name.toLocaleLowerCase().endsWith(".zip")){M(a("errors.zipOnly"));return}M(""),R(w),w&&!X&&W(w.name.replace(/\.zip$/i,""))},vi=async()=>{await A("/api/auth/logout",{method:"POST"}),r(null)},Si=async()=>{if(B.trim())try{const w=await A("/api/tags",{method:"POST",body:JSON.stringify({name:B,color:He})});f(re=>[...re,w.tag].sort((ne,Ce)=>ne.name.localeCompare(Ce.name))),N(!1),Ne(""),tt("blue")}catch(w){T(V(w))}},Ci=async w=>{if(!nt)return;const re=nt.tags.some(ne=>ne.id===w.id);try{const Ce=(await A(re?`/api/projects/${nt.id}/tags/${w.id}`:`/api/projects/${nt.id}/tags`,re?{method:"DELETE"}:{method:"POST",body:JSON.stringify({tagId:w.id})})).project;Ve(Ce),l(Ee=>Ee.map(Le=>Le.id===Ce.id?Ce:Le))}catch(ne){T(V(ne))}},Ts=async()=>{if(!(!z||!H.trim()))try{const w=await A(`/api/projects/${z.id}`,{method:"PATCH",body:JSON.stringify({name:H})});l(re=>re.map(ne=>ne.id===w.project.id?w.project:ne)),Z(null),oe("")}catch(w){T(V(w))}},Os=async()=>{if(!(!yt||!Mt.trim())){te(!0),T("");try{await A(`/api/projects/${yt.id}/duplicate`,{method:"POST",body:JSON.stringify({name:Mt})}),tn(null),$t(""),Te(ae,ke,Q,ce,ve)}catch(w){T(V(w))}finally{te(!1)}}},ur=async()=>{if(ye)try{await A(`/api/projects/${ye.id}`,{method:"DELETE"}),l(Ee=>Ee.filter(Le=>Le.id!==ye.id));const w=Math.max(0,u.total-1),re=Math.ceil(w/u.pageSize),ne=re===0?1:Math.min(ke,re),Ce={...u,page:ne,total:w,totalPages:re};m(Ce),st(null),ne!==ke?We(ne):Te(ae,ke,Q,ce,ve)}catch(w){T(V(w))}},wn=async w=>{qe(w),rt(""),wt([]),Xe(""),de(!0);try{const re=await A("/api/users");wt(re.users.filter(ne=>ne.id!==w.ownerId))}catch(re){Xe(V(re))}finally{de(!1)}},Ps=async()=>{if(!(!le||!lt)){de(!0),Xe("");try{await A(`/api/projects/${le.id}/owner`,{method:"PUT",body:JSON.stringify({userId:lt})}),qe(null),rt(""),Te(ae,ke,Q,ce,ve)}catch(w){Xe(V(w))}finally{de(!1)}}},ji=async w=>{const re=!ae;Dt(w.id),T("");try{await A(`/api/projects/${w.id}/archive`,{method:re?"PUT":"DELETE"});const ne=c.filter(Ln=>Ln.id!==w.id);l(ne);const Ce=Math.max(0,u.total-1),Ee=Math.ceil(Ce/u.pageSize),Le=Ee===0?1:Math.min(ke,Ee),Ht={...u,page:Le,total:Ce,totalPages:Ee};m(Ht),ae||s(ne,d,Ht),Le!==ke?We(Le):Te(ae,ke,Q,ce,ve)}catch(ne){T(V(ne))}finally{Dt("")}},hr=c,Bt=["red","orange","yellow","green","blue","purple","gray"],xn=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:()=>k(!0),children:[o.jsx(pm,{"aria-hidden":!0,size:14}),a("metrics.title")]}),o.jsxs("button",{className:"ghost",onClick:()=>b(!x),children:[x?o.jsx(ld,{"aria-hidden":!0,size:14}):o.jsx(Bs,{"aria-hidden":!0,size:14}),a(x?"users.back":"users.manage")]})]}),o.jsx(Go,{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:vi,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:()=>N(!0),children:[o.jsx(Ec,{"aria-hidden":!0,size:15}),a("tags.create")]}),e.canCreateProjects&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>{M(""),P(!0)},children:[o.jsx(Hr,{"aria-hidden":!0,size:15}),a("projects.upload")]}),o.jsxs("button",{className:"primary",onClick:()=>F(!0),children:[o.jsx(fd,{"aria-hidden":!0,size:15}),a("projects.new")]})]})]})]}),D&&o.jsx("p",{className:"error",children:D}),o.jsxs("div",{className:"project-toolbar",children:[o.jsx("input",{type:"search",placeholder:a("projects.search"),value:Q,onChange:w=>{ee(w.target.value),We(1)}}),o.jsxs("div",{className:"project-scope",role:"tablist","aria-label":a("projects.scope"),children:[o.jsxs("button",{className:ae?"":"active",onClick:()=>Ns(!1),role:"tab","aria-selected":!ae,children:[o.jsx(Vr,{size:14}),a("projects.active")]}),o.jsxs("button",{className:ae?"active":"",onClick:()=>Ns(!0),role:"tab","aria-selected":ae,children:[o.jsx(Sc,{size:14}),a("projects.archived")]})]}),o.jsxs("div",{className:"tag-filters",children:[o.jsx("button",{className:ce?"":"active",onClick:()=>Se(""),children:a("projects.allTags")}),d.map(w=>o.jsxs("button",{className:ce===w.id?"active":"",onClick:()=>Se(ce===w.id?"":w.id),children:[o.jsx(oo,{color:w.color}),w.name]},w.id))]}),o.jsxs("label",{className:"project-sort",children:[o.jsx(gm,{size:14}),o.jsx("span",{children:a("projects.sortBy")}),o.jsxs("select",{value:ve,onChange:w=>Nt(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:bt==="grid"?"active":"",onClick:()=>Ds("grid"),title:a("projects.grid"),children:"▦"}),o.jsx("button",{className:bt==="list"?"active":"",onClick:()=>Ds("list"),title:a("projects.list"),children:"☷"})]})]}),o.jsxs("div",{className:`project-grid ${bt==="list"?"list-view":""}`,children:[hr.map(w=>o.jsxs("article",{className:`project-card${w.ownerId===e.id?" owned-project":""}`,children:[bt==="grid"&&w.ownerId===e.id&&o.jsxs("button",{className:"project-transfer-action",title:a("projects.transferOwnership"),onClick:()=>{wn(w)},children:[o.jsx(Vi,{"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(re=>o.jsx("span",{className:`tag tag-${re.color}`,children:re.name},re.id))})]}),o.jsxs("dl",{className:"project-meta",children:[o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(ym,{"aria-hidden":!0,size:13}),a("projects.created")]}),o.jsx("dd",{children:o.jsx("time",{dateTime:w.createdAt,children:xn(w.createdAt)})})]}),o.jsxs("div",{children:[o.jsxs("dt",{children:[o.jsx(pd,{"aria-hidden":!0,size:13}),a("projects.modified")]}),o.jsxs("dd",{title:a("projects.modifiedByUser",{time:xn(w.updatedAt),user:w.lastModifiedDisplayName??w.lastModifiedUsername??a("projects.deletedUser")}),children:[o.jsx("time",{dateTime:w.updatedAt,children:xn(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:()=>Ve(w),children:[o.jsx(Ec,{"aria-hidden":!0,size:14}),a("tags.assign")]}),w.permission==="owner"&&o.jsxs("button",{onClick:()=>{Z(w),oe(w.name)},children:[o.jsx(vo,{"aria-hidden":!0,size:14}),a("projects.rename")]}),(e.role==="admin"||e.canCreateProjects)&&o.jsxs("button",{onClick:()=>{tn(w),$t(`${w.name} (1)`)},children:[o.jsx(Sm,{"aria-hidden":!0,size:14}),a("projects.duplicate")]}),o.jsxs("a",{href:`/api/projects/${w.id}/download`,download:!0,children:[o.jsx(Vs,{"aria-hidden":!0,size:14}),a("projects.download")]}),o.jsxs("button",{disabled:zt===w.id,onClick:()=>{ji(w)},children:[ae?o.jsx(mm,{"aria-hidden":!0,size:14}):o.jsx(Sc,{"aria-hidden":!0,size:14}),a(ae?"projects.unarchive":"projects.archive")]}),bt==="list"&&w.ownerId===e.id&&o.jsxs("button",{onClick:()=>{wn(w)},children:[o.jsx(Vi,{"aria-hidden":!0,size:14}),a("projects.transfer")]}),w.permission==="owner"&&o.jsxs("button",{className:"danger-text",onClick:()=>st(w),children:[o.jsx(ln,{"aria-hidden":!0,size:14}),a("common.delete")]})]})]},w.id)),hr.length===0&&(c.length===0?ae?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(Um,{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:()=>We(w=>Math.max(1,w-1)),title:a("projects.previousPage"),children:[o.jsx(hd,{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:()=>We(w=>Math.min(u.totalPages,w+1)),title:a("projects.nextPage"),children:[o.jsx(Jo,{size:15}),a("projects.nextPage")]})]}),o.jsx($e,{open:O,title:a("projects.new"),description:a("projects.newDescription"),onOpenChange:F,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>F(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{lr()},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"&&lr()}})]})}),o.jsx($e,{open:v,title:a("projects.upload"),description:a("projects.uploadDescription",{size:t.maxUploadSizeMB??50}),onOpenChange:w=>{P(w),w||M("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>{P(!1),M("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:!_||se,onClick:()=>{dr()},children:a(se?"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${_?" has-file":""}`,onDragOver:w=>{w.preventDefault(),w.dataTransfer.dropEffect="copy"},onDrop:w=>{w.preventDefault(),Rn(w.dataTransfer.files[0]??null)},children:[o.jsx("input",{ref:ue,className:"sr-only",type:"file",accept:".zip,application/zip",onChange:w=>Rn(w.target.files?.[0]??null)}),o.jsx(bo,{size:34}),o.jsxs("div",{className:"upload-picker-copy",children:[o.jsx("strong",{children:_?.name??a("projects.chooseZip")}),o.jsx("span",{children:_?a("projects.selectedFileSize",{size:eh(_.size)}):a("projects.dropZip")})]}),o.jsxs("button",{type:"button",onClick:()=>ue.current?.click(),children:[o.jsx(Hr,{size:15}),a("projects.browse")]}),_&&o.jsx("button",{className:"upload-clear",type:"button",title:a("projects.clearFile"),"aria-label":a("projects.clearFile"),onClick:()=>{Rn(null),ue.current&&(ue.current.value="")},children:o.jsx(Xo,{size:14})})]}),o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{value:X,onChange:w=>W(w.target.value)})]})]})}),o.jsx($e,{open:ie,title:a("tags.create"),description:a("tags.createDescription"),onOpenChange:N,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>N(!1),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Si()},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:B,onChange:w=>Ne(w.target.value)})]}),o.jsxs("fieldset",{className:"color-picker",children:[o.jsx("legend",{children:a("tags.color")}),Bt.map(w=>o.jsxs("label",{className:He===w?"active":"",children:[o.jsx("input",{type:"radio",name:"dashboard-tag-color",checked:He===w,onChange:()=>tt(w)}),o.jsx(oo,{color:w}),a(`tags.${w}`)]},w))]})]})}),o.jsx($e,{open:!!nt,title:a("tags.assignTitle",{project:nt?.name??""}),description:a("tags.assignDescription"),onOpenChange:w=>{w||Ve(null)},footer:o.jsx("button",{onClick:()=>Ve(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:!!nt?.tags.some(re=>re.id===w.id),onChange:()=>{Ci(w)}}),o.jsx(oo,{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($e,{open:!!z,title:a("projects.renameTitle"),onOpenChange:w=>{w||Z(null)},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Z(null),children:a("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Ts()},children:a("projects.rename")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:H,onChange:w=>oe(w.target.value),onKeyDown:w=>{w.key==="Enter"&&Ts()}})]})}),o.jsx($e,{open:!!yt,title:a("projects.duplicateTitle"),description:a("projects.duplicateDescription",{project:yt?.name??""}),onOpenChange:w=>{!w&&!U&&(tn(null),$t(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:U,onClick:()=>{tn(null),$t("")},children:a("common.cancel")}),o.jsx("button",{className:"primary",disabled:U||!Mt.trim(),onClick:()=>{Os()},children:a(U?"projects.duplicating":"projects.duplicate")})]}),children:o.jsxs("label",{className:"form-field",children:[a("projects.name"),o.jsx("input",{autoFocus:!0,value:Mt,onChange:w=>$t(w.target.value),onKeyDown:w=>{w.key==="Enter"&&Os()}})]})}),o.jsx($e,{open:!!le,title:a("projects.transferOwnership"),description:a("projects.transferDescription",{project:le?.name??""}),onOpenChange:w=>{!w&&!dt&&(qe(null),rt(""),Xe(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:dt,onClick:()=>{qe(null),rt(""),Xe("")},children:a("common.cancel")}),o.jsxs("button",{className:"primary",disabled:dt||!lt,onClick:()=>{Ps()},children:[dt?o.jsx(Gt,{className:"spin",size:14}):o.jsx(Vi,{size:14}),a("projects.transfer")]})]}),children:o.jsxs("div",{className:"form-stack",children:[xt&&o.jsx("p",{className:"error dialog-error",children:xt}),o.jsxs("label",{className:"form-field",children:[a("projects.newOwner"),o.jsxs("select",{disabled:dt||Ye.length===0,value:lt,onChange:w=>rt(w.target.value),children:[o.jsx("option",{value:"",children:dt?a("common.loading"):Ye.length>0?a("projects.chooseNewOwner"):a("projects.noTransferUsers")}),Ye.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(us,{size:15}),a("projects.transferWarning")]})]})}),o.jsx(ds,{open:!!ye,title:a("projects.deleteTitle"),description:a("projects.deleteDescription",{project:ye?.name??""}),confirmLabel:a("common.delete"),danger:!0,onCancel:()=>st(null),onConfirm:()=>{ur()}})]}),C&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Rb,{open:!0,onOpenChange:k})}),o.jsx(Pa,{})]})}function oo({color:t}){return o.jsx("span",{className:`tag-dot tag-${t}`})}function Mb(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}=_e(),[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,C]=h.useState(!1),k=()=>A("/api/admin/users").then(({users:v})=>s(v)).catch(v=>i(V(v)));h.useEffect(()=>{k()},[]);const D=async()=>{if(l.password.length<Ze)return i(e("auth.passwordMinimum",{count:Ze}));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 k()}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 k()}catch(P){i(V(P))}},O=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({role:v.role==="admin"?"user":"admin"})}),await k()}catch(P){i(V(P))}},F=async v=>{try{await A(`/api/admin/users/${v.id}`,{method:"PATCH",body:JSON.stringify({canCreateProjects:!v.canCreateProjects})}),await k()}catch(P){i(V(P))}},E=async()=>{if(!(!f||!m)){if(m.length<Ze)return i(e("auth.passwordMinimum",{count:Ze}));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),C(!1),await k()}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(Bs,{"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(gd,{"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:()=>O(v),children:v.role==="admin"?e("users.demote"):e("users.promote")}),o.jsx("button",{disabled:v.role==="admin",onClick:()=>F(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),C(!1)},children:e("common.delete")})]})]},v.id))})]})}),o.jsx($e,{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<Ze,onClick:()=>{D()},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:Ze,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:Mb()}),children:[o.jsx(Cm,{size:15}),e("users.randomPassword")]})]}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Ze})})]}),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($e,{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<Ze,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:Ze,autoComplete:"new-password",value:m,onChange:v=>p(v.target.value)}),o.jsx("small",{className:"field-hint",children:e("auth.passwordMinimum",{count:Ze})})]})}),o.jsx($e,{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:()=>C(!1)})," ",e("users.transferProjects")]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",checked:b,onChange:()=>C(!0)})," ",e("users.deleteProjects")]})]})})]})}function Ub({site:t,user:e,projectId:n,onBack:s}){const{t:r}=_e(),[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(""),[C,k]=h.useState(new Set),[D,T]=h.useState(""),[O,F]=h.useState(""),[E,q]=h.useState(!1),[v,P]=h.useState("editor.saved"),[X,W]=h.useState(null),[_,R]=h.useState({line:1,column:1}),S=h.useRef(_),[M,ue]=h.useState("pdf"),[se,be]=h.useState("log"),Q=y=>{if(y==="pdf"){ue("pdf");return}be(y),ue("diagnostics")},{workspaceLayout:ee,setWorkspaceLayout:ce}=Eb(e.id,n),[xe,ie]=h.useState(""),[N,B]=h.useState(""),[Ne,He]=h.useState({selectedText:"",startOffset:0,endOffset:0}),tt=h.useRef({selectedText:"",startOffset:0,endOffset:0}),nt=y=>{tt.current=y,He(y)},[Ve,z]=h.useState(null),[Z,H]=h.useState(!1),[oe,yt]=h.useState(!1),[tn,Mt]=h.useState(!1),[$t,U]=h.useState(!1),[te,ye]=h.useState(null),[st,le]=h.useState(!1),[qe,Ye]=h.useState(!1),[wt,lt]=h.useState(!1),[rt,dt]=h.useState(()=>Nc(e.id,n)),de=h.useRef(null),xt=h.useRef(null),Xe=h.useRef(0),bt=h.useRef(0),pn=h.useRef(""),ve=h.useRef(""),Ut=h.useRef(""),ae=h.useRef(""),ut=h.useRef(0),zt=h.useRef(null),Dt=h.useRef(null),ke=h.useRef(null),We=h.useRef(null),Vt=h.useRef(!1),mn=h.useRef(null),_n=h.useRef(s);_n.current=s,Ut.current=x;const gn=(y,j)=>{const L={line:y,column:j};S.current=L,R(L)},{collaboration:Fe,status:yn,synced:Te,activeSessions:Ds,compileState:Nt,setCompileState:Ns,filesEvent:Se,commentsRevision:lr,dictionaryRevision:dr,localDraftReady:Rn,reconnect:vi}=wb(n,e,x,()=>P("editor.offlineDraft")),{pdfTarget:Si,pdfViewport:Ci,sourceJump:Ts,setPdfViewport:Os,clearPdfViewport:ur,jumpToSource:wn,syncSourceToPdf:Ps,syncPdfToSource:ji,syncVisiblePdfToSource:hr}=kb({projectId:n,mainFile:x,activeFile:p,onActiveFile:g,onError:ie,onShowPdf:()=>Q("pdf")}),Bt=jb({active:!!(i&&p&&Te&&rt.spellCheck),activeFile:p,content:D,dictionaryWords:c});h.useEffect(()=>{dt(Nc(e.id,n))},[e.id,n]);const xn=y=>{pn.current=y,T(y)};h.useEffect(()=>{ve.current=p,S.current={line:1,column:1},R({line:1,column:1}),nt({selectedText:"",startOffset:0,endOffset:0})},[p]),h.useEffect(()=>{if(!E)return;const y=j=>{j.preventDefault(),j.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[E]),h.useEffect(()=>{if(yn!=="disconnected")return;const y=new AbortController;return A(`/api/projects/${n}`,{signal:y.signal}).then(({project:j})=>{y.signal.aborted||(a(j),ie(""))}).catch(j=>{if(!Zn(j)){if(j instanceof Io&&[401,403,404].includes(j.status)){ie(V(j)),_n.current();return}ie(r("errors.collaborationUnavailable"))}}),()=>y.abort()},[yn,n,r]);const w=async(y={})=>{zt.current?.abort(),zt.current=null;const j=y.signal?null:new AbortController;j&&(zt.current=j);try{const L=await A(`/api/projects/${n}/completions`,{signal:y.signal??j?.signal});(!y.isCurrent||y.isCurrent())&&f(L.index)}catch(L){if(Zn(L))return;(!y.isCurrent||y.isCurrent())&&f(null)}finally{j&&zt.current===j&&(zt.current=null)}},re=async(y={},j=Ut.current)=>{Dt.current?.abort(),Dt.current=null;const L=y.signal?null:new AbortController;L&&(Dt.current=L);try{const J=j?`?mainFile=${encodeURIComponent(j)}`:"",he=await A(`/api/projects/${n}/outline${J}`,{signal:y.signal??L?.signal});(!y.isCurrent||y.isCurrent())&&m(he.outline)}catch(J){!Zn(J)&&(!y.isCurrent||y.isCurrent())&&m([])}finally{L&&Dt.current===L&&(Dt.current=null)}},ne=async(y={})=>{ke.current?.abort(),ke.current=null;const j=y.signal?null:new AbortController;j&&(ke.current=j);try{const L=await A(`/api/projects/${n}/dictionary`,{signal:y.signal??j?.signal});(!y.isCurrent||y.isCurrent())&&l(L.words)}catch(L){if(Zn(L))return;(!y.isCurrent||y.isCurrent())&&l([])}finally{j&&ke.current===j&&(ke.current=null)}};h.useEffect(()=>{let y=!1;const j=++ut.current,L=new AbortController,J=()=>!y&&ut.current===j;let he=!1;ae.current="",a(null),fr([]),m([]),g(""),b(""),k(new Set),T(""),F(""),Ns(null),ur(),f(null),l([]),Qu();const Be=A(`/api/projects/${n}`,{signal:L.signal}).then(Ke=>{J()&&(he=!0,a(Ke.project),g(Ke.project.mainFile),b(Ke.project.mainFile),k(new Set([Ke.project.mainFile])),Aa(new Set(Fs(Ke.project.mainFile))))}).catch(Ke=>{J()&&ie(V(Ke))}),fe=A(`/api/projects/${n}/files`,{signal:L.signal}).then(Ke=>{J()&&fr(Ke.files)}).catch(Ke=>{J()&&ie(V(Ke))});return Promise.allSettled([Be,fe]).then(()=>{!J()||!he||window.setTimeout(()=>{J()&&Promise.all([w({signal:L.signal,isCurrent:J}),ne({signal:L.signal,isCurrent:J})])},0)}),()=>{y=!0,L.abort(),zt.current?.abort(),zt.current=null,Dt.current?.abort(),Dt.current=null,ke.current?.abort(),ke.current=null,We.current?.abort(),We.current=null}},[n]),h.useEffect(()=>{dr&&ne()},[dr,n]),h.useEffect(()=>{i&&Fe.setPermission(i.permission)},[Fe,i?.permission]),h.useEffect(()=>{if(!Se)return;const y=Se.kind==="delete"&&!!Se.path&&Gn(Se.path,ve.current),j=Se.kind==="delete"&&!!Se.path&&Gn(Se.path,Ut.current);if(Se.kind==="move"&&Se.source&&Se.destination){const J=Se.source,he=Se.destination,Be=fe=>fe===J?he:fe.startsWith(`${J}/`)?`${he}${fe.slice(J.length)}`:fe;g(fe=>Be(fe)),b(fe=>Be(fe)),k(fe=>new Set([...fe].map(Be))),pr(fe=>fe&&Be(fe))}y&&(g(""),F(""),xn(""),B(r("editor.fileDeletedByCollaborator",{path:Se.path}))),Se.kind==="delete"&&Se.path&&(k(J=>new Set([...J].filter(he=>!Gn(Se.path,he)))),pr(J=>Gn(Se.path,J)?"":J),Ra(J=>J&&Gn(Se.path,J.path)?null:J)),We.current?.abort();const L=new AbortController;We.current=L,Promise.all([th({signal:L.signal}),A(`/api/projects/${n}`,{signal:L.signal})]).then(([J,he])=>{if(a(he.project),j&&b(he.project.mainFile),y&&J){const Be=J.find(fe=>fe.type==="file"&&fe.path===he.project.mainFile)??J.find(fe=>fe.type==="file"&&Fo(fe.path));g(Be?.path??"")}w({signal:L.signal}),re({signal:L.signal},j?he.project.mainFile:Ut.current)}).catch(J=>{Zn(J)}).finally(()=>{We.current===L&&(We.current=null)})},[Se?.revision]),h.useEffect(()=>{if(Fe.setActiveFile(p),!p)return;F(""),P("editor.loading");const y=Fe.getText(p),j=(L,J)=>{xn(y.toString()),F(p),J?.local&&i?.permission!=="read"?(Xe.current+=1,q(!0),P("editor.pending")):Xe.current<=bt.current&&P(X?"editor.savedAt":"editor.saved")};return y.observe(j),(Te||Rn)&&j(),()=>{y.unobserve(j)}},[p,Fe,Te,Rn,i?.permission]),h.useEffect(()=>{!p||O!==p||ae.current===p||(ae.current=p,!(!p.toLocaleLowerCase().endsWith(".tex")||!zb(D))&&(k(y=>new Set([...y,p])),b(p)))},[p,O,D]);const Ce=async()=>{if(!Te)throw new Error("Collaboration is not synchronized");const y=Xe.current,j=await Fe.flush();return bt.current=Math.max(bt.current,y),W(j.persistedAt),/\.tex$/i.test(ve.current)&&re(),Xe.current===y?(q(!1),P("editor.savedAt")):P("editor.pending"),j};h.useEffect(()=>{if(!E||!p)return;if(!Te){P("editor.offlineDraft");return}P("editor.pending");const y=window.setTimeout(()=>{P("editor.saving"),Ce().catch(()=>{P(Fe.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(y)},[D,E,p,Te]);const Ee=async()=>{if(!i||i.permission==="read"||!Te||!p)return!1;P("editor.saving");try{return await Ce(),w(),!0}catch{return P("editor.saveFailed"),ie(r("errors.collaborationUnavailable")),!1}},Le=async(y,j)=>(await A(`/api/projects/${n}/format`,{method:"POST",body:JSON.stringify({path:y,source:j})})).formatted,Ht=async()=>{if(!rt.formatOnCompile||!i||i.permission==="read"||!Te||!Hi(ve.current)||Vt.current)return;const y=ve.current,j=Fe.getText(y),L=j.toString();Vt.current=!0,lt(!0);try{const J=await Le(y,L),he=await Tc(L,J);if(ve.current!==y||j.toString()!==L)throw new Error(r("editor.formatSourceChanged"));he.length&&Fe.applyTextEdits(y,he)}catch(J){ie(r("editor.formatFailedContinue",{message:V(J)}))}finally{Vt.current=!1,lt(!1)}},Ln=async()=>(mn.current&&await mn.current,await Ht(),Ee()),An=async()=>{if(!i||i.permission==="read"||!Te||Vt.current||!Hi(ve.current))return;const y=tt.current;if(!y.selectedText.trim()){B(r("editor.formatSelectionRequired"));return}const j=ve.current,{startOffset:L,endOffset:J,selectedText:he}=y,Be=Fe.getText(j);if(Be.toString().slice(L,J)!==he){ie(r("editor.formatSelectionChanged"));return}Vt.current=!0,lt(!0);let fe=()=>{};const Ke=new Promise(Tt=>{fe=Tt});mn.current=Ke;try{const Tt=Km(he,await Le(j,he)),Xa=await Tc(he,Tt,L);if(ve.current!==j||Be.toString().slice(L,J)!==he){ie(r("editor.formatSelectionChanged"));return}Xa.length&&Fe.applyTextEdits(j,Xa),ie(""),B(r("editor.formatSelectionComplete"))}catch(Tt){ie(r("editor.formatFailed",{message:V(Tt)}))}finally{Vt.current=!1,lt(!1),fe(),mn.current===Ke&&(mn.current=null)}},{files:ht,setFiles:fr,loadFiles:th,newFileOpen:nh,setNewFileOpen:ki,newFilePath:sh,setNewFilePath:_a,resourcePreview:Oe,setResourcePreview:Ra,resourcePreviewLoading:rh,setResourcePreviewLoading:ih,newFolderOpen:oh,setNewFolderOpen:Ei,newFolderName:ah,setNewFolderName:La,fileDialogError:nn,setFileDialogError:Fn,selectedFolder:qt,setSelectedFolder:pr,expandedFolders:ch,setExpandedFolders:Aa,moveEntry:_s,setMoveEntry:mr,moveDestination:lh,setMoveDestination:Di,deleteEntry:In,setDeleteEntry:gr,fileDragActive:Fa,setFileDragActive:Ni,uploadConflict:Ti,setUploadConflict:Ia,uploadingFiles:yr,directoryEntries:dh,visibleEntries:uh,createFile:hh,createFolder:Ma,uploadFiles:$a,upload:fh,openFile:Ua,movePath:ph,removePath:mh}=Cb({projectId:n,site:t,activeFile:p,dirty:E,save:Ee,onError:ie,onProject:a,onActiveFile:g,onActiveMainFile:b,onRootDocuments:k}),{comments:Rs,focusComment:gh,setFocusComment:za,commentOpen:yh,setCommentOpen:Oi,commentText:wh,setCommentText:xh,addComment:bh,toggleComment:vh,replyToComment:Sh,editComment:Ch,deleteComment:jh,editCommentReply:kh,deleteCommentReply:Eh}=gb({projectId:n,activeFile:p,permission:i?.permission,revision:lr,selection:Ne,save:Ee,onError:ie,onAdded:()=>z("comments")}),{pdfUrl:bn,pdfCompiledAt:Mn,compileLog:wr,compileDiagnostics:xr,compileOutcome:br,artifacts:Pi,artifactPreview:Dh,artifactLoading:Nh,editorNotice:Va,localCompiling:_i,cleaning:Ba,compile:Th,cleanCompile:Oh,viewArtifact:Ph}=xb({projectId:n,project:i,mainFile:x,collaborationSynced:Te,sharedState:Nt,onSharedState:Ns,save:Ln,loadOutline:(y,j)=>re({signal:y},j),onPreviewTab:Q,onError:ie,onCompileStart:()=>{ie(""),B("")},onCompileSuccess:()=>{const y=ve.current;y&&Ps(y,S.current.line,S.current.column,{silent:!0})},onPdfChanged:ur});h.useEffect(()=>{const y=j=>{(j.ctrlKey||j.metaKey)&&(!j.shiftKey&&j.key.toLocaleLowerCase()==="p"?(j.preventDefault(),le(!0)):j.shiftKey&&j.key.toLocaleLowerCase()==="f"&&(j.preventDefault(),Ye(!0)))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[]);const _h=y=>{dt(y),Hm(e.id,n,y)},Ha=()=>{xt.current?.isCollapsed()?xt.current.expand():xt.current?.collapse()},qa=h.useMemo(()=>u.length?u:Vb(D).map(y=>({...y,path:p})),[u,D,p]),$n=h.useMemo(()=>Gm(wr,br),[wr,br]),Un=ee!=="pdf-only",Wa=ee!=="editor-only",vr=y=>{ce(y),y==="pdf-only"&&Q("pdf")},Ri=In?Ds.filter(y=>y.filePath&&Gn(In.path,y.filePath)):[];if(!i)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:xe||r("common.loading")}),xe&&o.jsx("button",{className:"primary",onClick:s,children:r("editor.backToProjects")})]});const vt=i.permission==="read"||!Te,Rh=(y,j)=>{if(vt)return;const L=ve.current;if(!L)return;if(Fe.getText(L).toString().slice(y.from,y.to)!==y.word){ie(r("editor.spellCheckSourceChanged"));return}try{Fe.applyTextEdits(L,[{from:y.from,to:y.to,replacement:j}])}catch(Be){ie(V(Be))}},Sr=Nt?.mainFile===x&&(Nt.status==="queued"||Nt.status==="running"),zn=_i||Sr||Ba,Ka=p?Fe.getText(p):null,Ga=Mn?new Date(Mn).toLocaleString(we.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Lh=x.split("/").at(-1)??x,Ah=$n.warnings.length+$n.errors.length+Pi.length,Ja=bn?`${bn}${bn.includes("?")?"&":"?"}download=1`:"",Ya=zn?Sr?Nt?.status==="queued"?r("editor.compileQueued"):r("editor.compilingBy",{name:Nt?.requestedBy.name??r("common.user")}):r("editor.compiling"):br==="failed"?bn&&Mn?r("editor.compileFailedRetained",{time:new Date(Mn).toLocaleString(we.resolvedLanguage)}):r("editor.compileFailedNoPdf"):"",Fh=v==="editor.savedAt"&&X?r("editor.savedAt",{time:new Date(X).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(ld,{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," · ",Fh]})]}),rt.vimMode&&o.jsxs("span",{className:"vim-status-badge",title:r("editor.vimOnHint"),children:[o.jsx(Nm,{size:14}),r("editor.vimOn")]}),o.jsx(ob,{sessions:Ds,status:yn}),yn==="disconnected"&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:r("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:vi,children:r("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[Un&&o.jsxs("button",{className:Z?"":"active",onClick:Ha,children:[Z?o.jsx(_m,{size:15}):o.jsx(kc,{size:15}),r("common.files")]}),o.jsx(ab,{value:ee,onChange:vr}),o.jsxs("button",{onClick:()=>U(!0),children:[o.jsx(pd,{size:15}),r("history.title")]}),o.jsxs("button",{onClick:()=>yt(!0),children:[o.jsx(Bs,{size:15}),r("projectSettings.share")]}),i.ownerId===e.id&&o.jsxs("button",{onClick:()=>Mt(!0),children:[o.jsx(Dm,{size:15}),"Git"]}),Un&&i.permission!=="read"&&Hi(p)&&o.jsxs("button",{title:Ne.selectedText.trim()?r("editor.formatSelection"):r("editor.formatSelectionHint"),onMouseDown:y=>y.preventDefault(),onClick:()=>{An()},disabled:vt||wt||!Te,children:[wt?o.jsx(Gt,{className:"spin",size:15}):o.jsx(cd,{size:15}),r(wt?"editor.formatting":"editor.formatSelection")]}),o.jsxs("button",{onClick:()=>Oi(!0),disabled:!p,children:[o.jsx(Om,{size:15}),r("editor.addComment")]}),o.jsxs("button",{className:Ve==="comments"?"active":"",onClick:()=>z(Ve==="comments"?null:"comments"),children:[o.jsx(Pm,{size:15}),r("common.comments")," ",Rs.filter(y=>!y.resolved).length||""]}),o.jsxs("button",{className:Ve==="settings"?"active":"",onClick:()=>z(Ve==="settings"?null:"settings"),children:[o.jsx(Lr,{size:15}),r("common.settings")]}),o.jsxs("button",{className:"compile",title:Sr?r("editor.compilingBy",{name:Nt?.requestedBy.name??""}):r("editor.compileShortcut"),onClick:Th,disabled:zn||wt||vt||!Te,children:[zn?o.jsx(Gt,{className:"spin",size:15}):o.jsx(Am,{size:15}),Sr?r("editor.compilingBy",{name:Nt?.requestedBy.name??""}):_i?r("editor.compiling"):r("editor.compile",{engine:i.engine})]})]})]}),Ya&&o.jsxs("div",{className:`compile-status-strip${br==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(Gt,{className:zn?"spin":"",size:14}),o.jsx("span",{children:Ya})]}),xe&&o.jsx("div",{className:"toast",onClick:()=>ie(""),children:xe}),N&&o.jsx("div",{className:"toast success",onClick:()=>B(""),children:N}),o.jsxs($h,{autoSaveId:"texlite-workspace-layout",direction:"horizontal",className:"work-grid",children:[Un&&o.jsx(Cr,{id:"files",order:1,ref:xt,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>H(!0),onExpand:()=>H(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${Fa?" drop-active":""}`,onDragEnter:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),!vt&&!yr&&Ni(!0))},onDragOver:y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),y.dataTransfer.dropEffect=vt||yr?"none":"copy")},onDragLeave:y=>{y.currentTarget.contains(y.relatedTarget)||Ni(!1)},onDrop:y=>{y.preventDefault(),Ni(!1),!vt&&!yr&&$a(Array.from(y.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("span",{children:[o.jsx(Qn,{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:()=>le(!0),children:o.jsx(km,{size:15})}),o.jsx("button",{"aria-label":r("navigation.projectSearch"),title:`${r("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>Ye(!0),children:o.jsx(Mm,{size:15})}),!vt&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:yr,"aria-label":r("editor.uploadAttachment"),title:r("editor.uploadTo",{folder:qt||r("editor.projectRoot")}),onClick:()=>de.current?.click(),children:o.jsx(Hr,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFolder"),title:r("editor.newFolder"),onClick:()=>{La(""),Ei(!0)},children:o.jsx(fd,{size:15})}),o.jsx("button",{"aria-label":r("editor.newFile"),title:r("editor.newFile"),onClick:()=>{_a(qt?`${qt}/`:""),ki(!0)},children:o.jsx(jm,{size:15})}),o.jsx("input",{ref:de,type:"file",multiple:!0,hidden:!0,onChange:y=>{fh(y)}})]}),o.jsx("button",{"aria-label":r("editor.collapseFiles"),title:r("editor.collapseFiles"),onClick:Ha,children:o.jsx(kc,{size:15})})]})]}),Fa&&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:qt||r("editor.projectRoot")})})]}),o.jsxs("div",{className:"folder-target",title:qt||r("editor.projectRoot"),children:[o.jsx(Vr,{size:13}),o.jsx("span",{children:qt||r("editor.projectRoot")})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${rt.fontSize}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${qt===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>pr(""),children:[o.jsx(Vr,{size:15}),o.jsx("span",{children:r("editor.projectRoot")})]})}),uh.map(y=>{const j=y.path.split("/").length-1,L=y.path.split("/").at(-1),J=ch.has(y.path),he=C.has(y.path),Be=x===y.path,fe=y.path!==i.mainFile&&!i.mainFile.startsWith(`${y.path}/`);return y.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${qt===y.path?" selected":""}`,style:{paddingLeft:`${j*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",title:y.path,onClick:()=>{pr(y.path),Aa(Ke=>{const Tt=new Set(Ke);return Tt.has(y.path)?Tt.delete(y.path):Tt.add(y.path),Tt})},children:[J?o.jsx(ud,{size:13}):o.jsx(Jo,{size:13}),o.jsx(Em,{size:14}),o.jsx("span",{children:L})]}),!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),Di("")},children:o.jsx(jc,{size:13})}),fe&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),Fn("")},children:o.jsx(ln,{size:13})})]})]},y.path):o.jsxs("div",{className:`file-entry${p===y.path?" active":""}${he?" root-document":""}${Be?" compile-target":""}`,style:{paddingLeft:`${j*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",title:Be?r("editor.currentMainDocument",{path:y.path}):he?r("editor.mainDocumentCandidate",{path:y.path}):y.path,onClick:()=>Ua(y),children:[he?o.jsx(dd,{size:13}):o.jsx(Qn,{size:13}),o.jsx("span",{children:L}),Be&&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),Di("")},children:o.jsx(jc,{size:13})}),fe&&o.jsx("button",{className:"file-entry-action danger-text",title:r("editor.deletePath"),"aria-label":r("editor.deletePath"),onClick:()=>{gr(y),Fn("")},children:o.jsx(ln,{size:13})})]})]},y.path)})]})]}),o.jsxs("section",{className:"outline-panel",children:[o.jsx("div",{className:"panel-title",children:o.jsxs("span",{children:[o.jsx(Tm,{size:14}),r("common.outline")]})}),o.jsxs("div",{className:"outline",children:[qa.map((y,j)=>o.jsxs("button",{className:`outline-item${p===y.path&&_.line===y.line?" current":""}`,title:`${y.path}:${y.line}`,onClick:()=>{wn(y.path,y.line,1),Ps(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}-${j}`)),qa.length===0&&o.jsx("p",{className:"muted padded",children:r("editor.noOutline")})]})]})]})}),Un&&o.jsx(Li,{className:"resize-handle",children:o.jsx(Bi,{size:12})}),Un&&o.jsx(Cr,{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(Gt,{className:"spin",size:22}),o.jsx("span",{children:r("common.loading")})]}),children:o.jsx(Nb,{value:D,readOnly:vt,comments:Rs,focusComment:gh,preferences:rt,completionIndex:d,spellCheckIssues:Bt.issues,spellCheckJump:Bt.jump,jumpTo:O===p&&Ts?.path===p?Ts:null,searchRequest:0,collaboration:Ka?{text:Ka,awareness:Fe.awareness}:void 0,onChange:xn,onSelection:(y,j,L)=>nt({selectedText:y,startOffset:j,endOffset:L}),onCommentClick:y=>{const j=Rs.find(L=>L.id===y);j&&(za({...j}),z("comments"))},onSpellCheckReplace:Rh,onCursor:gn},p)}),Va&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:Va})]})}),Un&&Wa&&o.jsxs(Li,{className:"resize-handle sync-resize-handle",children:[o.jsx(Bi,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:y=>y.stopPropagation(),children:[o.jsx("button",{disabled:!Ci,title:r("editor.showInSource"),"aria-label":r("editor.showInSource"),onClick:hr,children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!p||!bn,title:r("editor.showInPdf"),"aria-label":r("editor.showInPdf"),onClick:()=>{Ps(p,_.line,_.column)},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),Wa&&o.jsx(Cr,{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":M==="pdf",className:`pdf-tab${M==="pdf"?" active":""}`,onClick:()=>Q("pdf"),title:Mn?r("editor.pdfCompiledAtFor",{file:x,time:new Date(Mn).toLocaleString(we.resolvedLanguage)}):r("editor.currentMainDocument",{path:x}),children:[o.jsx(Qn,{size:16}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",Lh,Ga&&o.jsx("small",{children:Ga})]})]}),o.jsxs("button",{role:"tab","aria-selected":M==="diagnostics",className:`diagnostics-tab${M==="diagnostics"?" active":""}`,onClick:()=>ue("diagnostics"),children:[o.jsx(So,{size:14}),r("editor.outputTabs"),o.jsx("span",{children:Ah})]})]}),Ja&&o.jsxs("a",{className:"pdf-download-top",href:Ja,download:!0,title:r("editor.downloadPdf"),"aria-label":r("editor.downloadPdf"),children:[o.jsx(Vs,{size:15}),o.jsx("span",{children:r("editor.downloadPdf")})]})]}),M==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":r("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":se==="log",className:se==="log"?"active":"",onClick:()=>Q("log"),children:[o.jsx(So,{size:13}),r("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":se==="warnings",className:se==="warnings"?"active":"",onClick:()=>Q("warnings"),children:[o.jsx(us,{size:13}),r("editor.warnings"),o.jsx("span",{children:$n.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":se==="errors",className:se==="errors"?"active":"",onClick:()=>Q("errors"),children:[o.jsx(Yo,{size:13}),r("editor.errors"),o.jsx("span",{children:$n.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":se==="artifacts",className:se==="artifacts"?"active":"",onClick:()=>Q("artifacts"),children:[o.jsx(md,{size:13}),r("editor.artifacts"),o.jsx("span",{children:Pi.length})]}),o.jsxs("button",{role:"tab","aria-selected":se==="clean",className:se==="clean"?"active":"",onClick:()=>Q("clean"),children:[o.jsx(xo,{size:13}),r("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${M} ${M==="diagnostics"?`preview-${se}`:""}`,children:[M==="pdf"&&(bn?o.jsx(h.Suspense,{fallback:o.jsx("div",{className:"preview-empty",children:o.jsx("span",{children:r("common.loading")})}),children:o.jsx(Db,{url:bn,target:Si,compiling:zn,onViewportLocation:(y,j,L)=>Os({page:y,x:j,y:L}),onDoubleClickLocation:(y,j,L)=>{Os({page:y,x:j,y:L}),ji(y,j,L)}})}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Qn,{size:28}),o.jsx("strong",{children:r("editor.preview")}),o.jsx("span",{children:r("editor.previewHint")})]})),M==="diagnostics"&&se==="log"&&o.jsx(io,{lines:wr?wr.split(`
|
|
14
14
|
`):[],empty:r(_i?"editor.compiling":"editor.noLog")}),M==="diagnostics"&&se==="warnings"&&(xr?o.jsx(ul,{tone:"warning",diagnostics:xr.warnings,files:ht,empty:r("editor.noWarnings"),onJump:(y,j,L)=>{ee==="pdf-only"&&vr("editor-pdf"),wn(y,j,L)}}):o.jsx(io,{tone:"warning",lines:$n.warnings,empty:r("editor.noWarnings")})),M==="diagnostics"&&se==="errors"&&(xr?o.jsx(ul,{tone:"error",diagnostics:xr.errors,files:ht,empty:r("editor.noErrors"),onJump:(y,j,L)=>{ee==="pdf-only"&&vr("editor-pdf"),wn(y,j,L)}}):o.jsx(io,{tone:"error",lines:$n.errors,empty:r("editor.noErrors")})),M==="diagnostics"&&se==="artifacts"&&o.jsx(ub,{projectId:n,mainFile:x,artifacts:Pi,preview:Dh,loading:Nh,onView:y=>{Ph(y)}}),M==="diagnostics"&&se==="clean"&&o.jsx(hb,{mainFile:x,disabled:vt||!Te||zn,cleaning:Ba,onCleanCache:()=>ye("cache"),onCleanArtifacts:()=>ye("artifacts")})]})]})}),Ve&&o.jsxs(o.Fragment,{children:[o.jsx(Li,{className:"resize-handle",children:o.jsx(Bi,{size:12})}),o.jsx(Cr,{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(Ve==="comments"?"editor.sourceComments":"editor.projectSettings")}),o.jsx("button",{"aria-label":r("common.close"),onClick:()=>z(null),children:o.jsx(Xo,{size:17})})]}),Ve==="comments"&&o.jsxs("div",{className:"comments",children:[Rs.map(y=>o.jsx(cb,{comment:y,currentUserId:e.id,onFocus:()=>za({...y}),onToggle:()=>{vh(y)},onReply:j=>Sh(y,j),onEdit:j=>Ch(y,j),onDelete:()=>jh(y),onEditReply:(j,L)=>kh(y,j,L),onDeleteReply:j=>Eh(y,j)},y.id)),Rs.length===0&&o.jsx("p",{className:"muted padded",children:r("editor.noComments")})]}),Ve==="settings"&&o.jsx(db,{project:i,projectId:n,site:t,files:ht,dictionaryWords:c,onDictionaryChange:l,editorPreferences:rt,onEditorPreferences:_h,spellCheckCount:Bt.summary?.total??null,spellCheckUniqueCount:Bt.summary?.unique??null,spellCheckIndex:Bt.summary?Bt.index:-1,onSpellCheckNavigate:Bt.jumpToIssue,onProject:a})]})})]})]}),o.jsxs($e,{open:!!Oe,extraWide:Oe?.kind==="image"||Oe?.kind==="pdf"||Oe?.kind==="text",title:Oe?.path??"",description:Oe?.kind==="large"?r("editor.resourceTooLarge",{size:eh(Oe.size),limit:"10 MB"}):r(`editor.resourcePreview.${Oe?.kind??"text"}`),onOpenChange:y=>{y||(Ra(null),ih(!1))},footer:Oe&&o.jsxs("a",{className:"primary resource-download",href:`${Oe.url}&download=1`,download:!0,children:[o.jsx(Vs,{size:14}),r("editor.downloadResource")]}),children:[Oe?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(bo,{size:34}),o.jsx("strong",{children:r("editor.resourceTooLargeTitle")}),o.jsx("span",{children:r("editor.resourceTooLargeDescription")})]}),Oe?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(bo,{size:34}),o.jsx("strong",{children:r("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:r("editor.resourceUnsupportedDescription")})]}),Oe?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:Oe.url,alt:Oe.path})}),Oe?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:Oe.url,title:Oe.path}),Oe?.kind==="text"&&(rh?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Gt,{className:"spin",size:24}),o.jsx("span",{children:r("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:Oe.content}))]}),o.jsx(ds,{open:!!Ti,title:r("editor.uploadOverwriteTitle"),description:r("editor.uploadOverwriteDescription",{files:Ti?.collisions.join(", ")??""}),confirmLabel:r("editor.uploadOverwrite"),danger:!0,onCancel:()=>Ia(null),onConfirm:()=>{const y=Ti;Ia(null),y&&$a(y.files,new Set(y.collisions),y.directory)}}),o.jsx(ds,{open:!!te,title:r(te==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:r(te==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:r("editor.cleanConfirm"),danger:te==="artifacts",onCancel:()=>ye(null),onConfirm:()=>{const y=te;ye(null),y&&Oh(y)}}),o.jsx($e,{open:nh,title:r("editor.newFile"),description:r("editor.newFileDescription"),onOpenChange:y=>{ki(y),y||Fn("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ki(!1),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{hh()},children:r("common.create")})]}),children:o.jsxs(o.Fragment,{children:[nn&&o.jsx("p",{className:"error dialog-error",children:nn}),o.jsxs("label",{className:"form-field",children:[r("editor.filePath"),o.jsx("input",{autoFocus:!0,value:sh,onChange:y=>_a(y.target.value)})]})]})}),o.jsx($e,{open:oh,title:r("editor.newFolder"),description:r("editor.folderDestination",{folder:qt||r("editor.projectRoot")}),onOpenChange:y=>{Ei(y),y||Fn("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Ei(!1),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Ma()},children:r("common.create")})]}),children:o.jsxs(o.Fragment,{children:[nn&&o.jsx("p",{className:"error dialog-error",children:nn}),o.jsxs("label",{className:"form-field",children:[r("editor.folderName"),o.jsx("input",{autoFocus:!0,value:ah,onChange:y=>La(y.target.value),onKeyDown:y=>{y.key==="Enter"&&Ma()}})]})]})}),o.jsx($e,{open:!!_s,title:r("editor.moveTitle",{name:_s?.path.split("/").at(-1)??""}),description:r("editor.moveDescription"),onOpenChange:y=>{y||(mr(null),Fn(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>mr(null),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ph()},children:r("editor.move")})]}),children:o.jsxs(o.Fragment,{children:[nn&&o.jsx("p",{className:"error dialog-error",children:nn}),o.jsxs("label",{className:"form-field",children:[r("editor.destinationFolder"),o.jsxs("select",{value:lh,onChange:y=>Di(y.target.value),children:[o.jsx("option",{value:"",children:r("editor.projectRoot")}),dh.filter(y=>_s?.type!=="directory"||y.path!==_s.path&&!y.path.startsWith(`${_s.path}/`)).map(y=>o.jsx("option",{value:y.path,children:y.path},y.path))]})]})]})}),o.jsx($e,{open:!!In,title:r("editor.deletePathTitle",{name:In?.path.split("/").at(-1)??""}),description:Ri.length?r("editor.deletePathActiveDescription",{path:In?.path??"",users:[...new Set(Ri.map(y=>y.name))].join(", ")}):r("editor.deletePathDescription",{path:In?.path??""}),onOpenChange:y=>{y||(gr(null),Fn(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>gr(null),children:r("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{mh()},children:r("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[nn&&o.jsx("p",{className:"error dialog-error",children:nn}),Ri.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(us,{size:15}),r("editor.deletePathWillClose")]})]})}),o.jsxs($e,{open:yh,title:r("editor.addComment"),description:Ne.selectedText?r("editor.commentDescription",{count:Ne.endOffset-Ne.startOffset}):r("editor.pointComment"),onOpenChange:Oi,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Oi(!1),children:r("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{bh()},children:r("editor.addComment")})]}),children:[o.jsxs("label",{className:"form-field",children:[r("editor.commentContent"),o.jsx("textarea",{autoFocus:!0,rows:5,value:wh,onChange:y=>xh(y.target.value)})]}),Ne.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:Ne.selectedText})]}),o.jsx(lb,{open:oe,onOpenChange:yt,project:i,projectId:n}),st&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(_b,{open:!0,files:ht,onOpenChange:le,onOpenFile:y=>{const j=ht.find(L=>L.path===y);j&&Ua(j)}})}),qe&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Pb,{open:!0,project:i,onOpenChange:Ye,onJump:(y,j,L)=>{ee==="pdf-only"&&vr("editor-pdf"),wn(y,j,L)}})}),$t&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Ob,{open:!0,onOpenChange:U,project:i,onBeforeMutation:i.permission==="read"?async()=>!0:Ee})}),i.ownerId===e.id&&tn&&o.jsx(h.Suspense,{fallback:null,children:o.jsx(Tb,{open:!0,onOpenChange:Mt,project:i,onBeforeMutation:Ee})})]})}function zb(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 eh(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Vb(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
|