@jant/core 0.5.3 → 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.
@@ -1,4 +1,4 @@
1
- import{a as e,n as t,o as n,t as r}from"./chunks/url-pLre2DM_.js";import{_ as i,a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./client-CJQYvkEx.js";var x={maxWidth:1920,maxHeight:1920,quality:.85,mimeType:`image/webp`};function S(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function C(e,t,n,r){if(e<=n&&t<=r)return{width:e,height:t};let i=Math.min(n/e,r/t);return{width:Math.round(e*i),height:Math.round(t*i)}}async function ee(e,t,n){let r=await new Promise((r,i)=>{e.toBlob(e=>e?r(e):i(Error(`Failed to create blob`)),t,n)});return t!==`image/png`&&r.type===`image/png`?new Promise((t,r)=>{e.toBlob(e=>e?t(e):r(Error(`Failed to create blob`)),`image/jpeg`,n)}):r}async function te(e,t={}){let n={...x,...t},r=await S(e),{width:i,height:a}=C(r.width,r.height,n.maxWidth,n.maxHeight),o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),{blob:await ee(o,n.mimeType,n.quality),width:i,height:a}}async function ne(e,t={}){let{blob:n,width:r,height:i}=await te(e,t),a={"image/webp":`webp`,"image/jpeg":`jpg`,"image/png":`png`}[n.type]??`png`,o=`${e.name.replace(/\.[^.]+$/,``)}.${a}`;return{file:new File([n],o,{type:n.type}),width:r,height:i}}var re={process:te,processToFile:ne},ie={ICO_16:16,ICO_32:32,APPLE_TOUCH:512};function ae(e){let t=e.length*16,n=6+t,r=new ArrayBuffer(6+t),i=new DataView(r);i.setUint16(0,0,!0),i.setUint16(2,1,!0),i.setUint16(4,e.length,!0);let a=[];for(let t=0;t<e.length;t++){let r=e[t],o=6+t*16;i.setUint8(o+0,r.size<256?r.size:0),i.setUint8(o+1,r.size<256?r.size:0),i.setUint8(o+2,0),i.setUint8(o+3,0),i.setUint16(o+4,1,!0),i.setUint16(o+6,32,!0),i.setUint32(o+8,r.png.byteLength,!0),i.setUint32(o+12,n,!0),n+=r.png.byteLength,a.push(r.png)}return new Blob([r,...a],{type:`image/x-icon`})}function oe(e){return typeof e==`object`&&!!e}function w(e,t){if(!oe(e))return;let n=e[t];return typeof n==`string`?n:void 0}function se(e,t){if(!oe(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}function ce(e,t){if(!oe(e))return;let n=e[t];return typeof n==`number`?n:void 0}async function le(e){let t=await e.json();return oe(t)?t:{}}var ue=180;function de(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function fe(e,t){let n=document.createElement(`canvas`);n.width=t,n.height=t;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let i=Math.max(t/e.width,t/e.height),a=t/i,o=t/i,s=(e.width-a)/2,c=(e.height-o)/2;return r.drawImage(e,s,c,a,o,0,0,t,t),new Promise((e,t)=>{n.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}function pe(e,t){return e.type===`image/png`&&t.width===t.height&&t.width>=ue&&t.height>=ue}async function me(e,t){let n=e.closest(`form`)?.querySelector(`label`),r=n?.textContent??``;try{n&&(n.textContent=e.dataset.textProcessing||`Processing...`);let r=await de(t),a=t,o=t.name;if(t.type!==`image/svg+xml`){let e=await fe(r,512);a=new File([e],t.name.replace(/\.[^.]+$/,`.png`),{type:`image/png`}),o=a.name}let s=pe(t,r)?Promise.resolve(t):fe(r,ie.APPLE_TOUCH),[c,l,u]=await Promise.all([fe(r,16),fe(r,32),s]),[d,f]=await Promise.all([c.arrayBuffer(),l.arrayBuffer()]),p=ae([{size:16,png:d},{size:32,png:f}]);n&&(n.textContent=e.dataset.textUploading||`Uploading...`);let m=new FormData;m.append(`file`,a,o),m.append(`favicon`,p,`favicon.ico`),m.append(`appleTouch`,u,`apple-touch-icon.png`);let h=await fetch(i(`/settings/avatar`),{method:`POST`,headers:{Accept:`application/json`},body:m});if(!h.ok){let t=e.dataset.textError||`Upload failed. Please try again.`;try{let e=await le(h);t=w(e,`error`)??w(e,`message`)??t}catch{}throw Error(t)}let g=await le(h),_=w(g,`status`),v=w(g,`url`);if(_===`redirect`&&v){window.location.href=v;return}window.location.href=i(`/settings/avatar?saved`)}catch(t){n&&(n.textContent=r),d(t instanceof Error&&t.message?t.message:e.dataset.textError||`Upload failed. Please try again.`,`error`)}e.value=``}function he(){document.addEventListener(`change`,e=>{let t=e.target.closest(`[data-avatar-upload]`);t?.files?.[0]&&(e.stopPropagation(),me(t,t.files[0]))})}he();var ge=`default`,_e=class extends c{static properties={_open:{state:!0},_title:{state:!0},_message:{state:!0},_confirmLabel:{state:!0},_cancelLabel:{state:!0},_tone:{state:!0}};#e=[];#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=ge}disconnectedCallback(){super.disconnectedCallback();let e=this.#t;this.#t=null,e?.resolve(!1);for(let e of this.#e.splice(0))e.resolve(!1)}async confirm(e){return await new Promise(t=>{this.#e.push({...e,tone:e.tone??ge,resolve:t}),this.#t||this.#n()})}async#n(){if(this.#t||this.#e.length===0)return;let e=this.#e.shift();if(!e)return;this.#t=e,this._title=e.title??``,this._message=e.message,this._confirmLabel=e.confirmLabel,this._cancelLabel=e.cancelLabel,this._tone=e.tone??ge,this._open=!0,await this.updateComplete;let t=this.querySelector(`.confirm-dialog`);t&&(t.open||t.showModal(),t.querySelector(`.confirm-dialog-panel`)?.focus())}#r(e){let t=this.#t;if(!t)return;this.#t=null;let n=this.querySelector(`.confirm-dialog`);n?.open&&n.close(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=ge,t.resolve(e),queueMicrotask(()=>void this.#n())}#i=e=>{e.preventDefault(),this.#r(!1)};#a=e=>{e.target===e.currentTarget&&this.#r(!1)};#o=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.#r(!1);return}let t=e.target,n=t instanceof HTMLButtonElement||t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLAnchorElement;e.key===`Enter`&&!e.defaultPrevented&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!n&&(e.preventDefault(),this.#r(!0))};#s(){if(this._title)return{title:this._title,message:this._message};let e=this._message.match(/^(.+?[??])\s+(.+)$/u);return e?{title:e[1],message:e[2]}:{title:this._message,message:``}}render(){if(!this._open)return g;let{title:e,message:t}=this.#s(),n=this._tone===`danger`?`btn-destructive`:`btn`;return u`
1
+ import{a as e,n as t,o as n,t as r}from"./chunks/url-pLre2DM_.js";import{_ as i,a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./client-CtAgWT8i.js";var x={maxWidth:1920,maxHeight:1920,quality:.85,mimeType:`image/webp`};function S(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function C(e,t,n,r){if(e<=n&&t<=r)return{width:e,height:t};let i=Math.min(n/e,r/t);return{width:Math.round(e*i),height:Math.round(t*i)}}async function ee(e,t,n){let r=await new Promise((r,i)=>{e.toBlob(e=>e?r(e):i(Error(`Failed to create blob`)),t,n)});return t!==`image/png`&&r.type===`image/png`?new Promise((t,r)=>{e.toBlob(e=>e?t(e):r(Error(`Failed to create blob`)),`image/jpeg`,n)}):r}async function te(e,t={}){let n={...x,...t},r=await S(e),{width:i,height:a}=C(r.width,r.height,n.maxWidth,n.maxHeight),o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),{blob:await ee(o,n.mimeType,n.quality),width:i,height:a}}async function ne(e,t={}){let{blob:n,width:r,height:i}=await te(e,t),a={"image/webp":`webp`,"image/jpeg":`jpg`,"image/png":`png`}[n.type]??`png`,o=`${e.name.replace(/\.[^.]+$/,``)}.${a}`;return{file:new File([n],o,{type:n.type}),width:r,height:i}}var re={process:te,processToFile:ne},ie={ICO_16:16,ICO_32:32,APPLE_TOUCH:512};function ae(e){let t=e.length*16,n=6+t,r=new ArrayBuffer(6+t),i=new DataView(r);i.setUint16(0,0,!0),i.setUint16(2,1,!0),i.setUint16(4,e.length,!0);let a=[];for(let t=0;t<e.length;t++){let r=e[t],o=6+t*16;i.setUint8(o+0,r.size<256?r.size:0),i.setUint8(o+1,r.size<256?r.size:0),i.setUint8(o+2,0),i.setUint8(o+3,0),i.setUint16(o+4,1,!0),i.setUint16(o+6,32,!0),i.setUint32(o+8,r.png.byteLength,!0),i.setUint32(o+12,n,!0),n+=r.png.byteLength,a.push(r.png)}return new Blob([r,...a],{type:`image/x-icon`})}function oe(e){return typeof e==`object`&&!!e}function w(e,t){if(!oe(e))return;let n=e[t];return typeof n==`string`?n:void 0}function se(e,t){if(!oe(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}function ce(e,t){if(!oe(e))return;let n=e[t];return typeof n==`number`?n:void 0}async function le(e){let t=await e.json();return oe(t)?t:{}}var ue=180;function de(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function fe(e,t){let n=document.createElement(`canvas`);n.width=t,n.height=t;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let i=Math.max(t/e.width,t/e.height),a=t/i,o=t/i,s=(e.width-a)/2,c=(e.height-o)/2;return r.drawImage(e,s,c,a,o,0,0,t,t),new Promise((e,t)=>{n.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}function pe(e,t){return e.type===`image/png`&&t.width===t.height&&t.width>=ue&&t.height>=ue}async function me(e,t){let n=e.closest(`form`)?.querySelector(`label`),r=n?.textContent??``;try{n&&(n.textContent=e.dataset.textProcessing||`Processing...`);let r=await de(t),a=t,o=t.name;if(t.type!==`image/svg+xml`){let e=await fe(r,512);a=new File([e],t.name.replace(/\.[^.]+$/,`.png`),{type:`image/png`}),o=a.name}let s=pe(t,r)?Promise.resolve(t):fe(r,ie.APPLE_TOUCH),[c,l,u]=await Promise.all([fe(r,16),fe(r,32),s]),[d,f]=await Promise.all([c.arrayBuffer(),l.arrayBuffer()]),p=ae([{size:16,png:d},{size:32,png:f}]);n&&(n.textContent=e.dataset.textUploading||`Uploading...`);let m=new FormData;m.append(`file`,a,o),m.append(`favicon`,p,`favicon.ico`),m.append(`appleTouch`,u,`apple-touch-icon.png`);let h=await fetch(i(`/settings/avatar`),{method:`POST`,headers:{Accept:`application/json`},body:m});if(!h.ok){let t=e.dataset.textError||`Upload failed. Please try again.`;try{let e=await le(h);t=w(e,`error`)??w(e,`message`)??t}catch{}throw Error(t)}let g=await le(h),_=w(g,`status`),v=w(g,`url`);if(_===`redirect`&&v){window.location.href=v;return}window.location.href=i(`/settings/avatar?saved`)}catch(t){n&&(n.textContent=r),d(t instanceof Error&&t.message?t.message:e.dataset.textError||`Upload failed. Please try again.`,`error`)}e.value=``}function he(){document.addEventListener(`change`,e=>{let t=e.target.closest(`[data-avatar-upload]`);t?.files?.[0]&&(e.stopPropagation(),me(t,t.files[0]))})}he();var ge=`default`,_e=class extends c{static properties={_open:{state:!0},_title:{state:!0},_message:{state:!0},_confirmLabel:{state:!0},_cancelLabel:{state:!0},_tone:{state:!0}};#e=[];#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=ge}disconnectedCallback(){super.disconnectedCallback();let e=this.#t;this.#t=null,e?.resolve(!1);for(let e of this.#e.splice(0))e.resolve(!1)}async confirm(e){return await new Promise(t=>{this.#e.push({...e,tone:e.tone??ge,resolve:t}),this.#t||this.#n()})}async#n(){if(this.#t||this.#e.length===0)return;let e=this.#e.shift();if(!e)return;this.#t=e,this._title=e.title??``,this._message=e.message,this._confirmLabel=e.confirmLabel,this._cancelLabel=e.cancelLabel,this._tone=e.tone??ge,this._open=!0,await this.updateComplete;let t=this.querySelector(`.confirm-dialog`);t&&(t.open||t.showModal(),t.querySelector(`.confirm-dialog-panel`)?.focus())}#r(e){let t=this.#t;if(!t)return;this.#t=null;let n=this.querySelector(`.confirm-dialog`);n?.open&&n.close(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=ge,t.resolve(e),queueMicrotask(()=>void this.#n())}#i=e=>{e.preventDefault(),this.#r(!1)};#a=e=>{e.target===e.currentTarget&&this.#r(!1)};#o=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.#r(!1);return}let t=e.target,n=t instanceof HTMLButtonElement||t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLAnchorElement;e.key===`Enter`&&!e.defaultPrevented&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!n&&(e.preventDefault(),this.#r(!0))};#s(){if(this._title)return{title:this._title,message:this._message};let e=this._message.match(/^(.+?[??])\s+(.+)$/u);return e?{title:e[1],message:e[2]}:{title:this._message,message:``}}render(){if(!this._open)return g;let{title:e,message:t}=this.#s(),n=this._tone===`danger`?`btn-destructive`:`btn`;return u`
2
2
  <dialog
3
3
  class="dialog confirm-dialog"
4
4
  @cancel=${this.#i}
@@ -295,7 +295,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
295
295
  </section>`}).join(``);YS.innerHTML=`<div class="tiptap-slash-menu-scroll">
296
296
  ${n}
297
297
  </div>
298
- ${cC(oC())}`,YS.querySelectorAll(`.tiptap-slash-item`).forEach(e=>{e.addEventListener(`mousedown`,n=>{n.preventDefault(),t(parseInt(e.dataset.index??`0`,10))}),e.addEventListener(`mouseenter`,()=>{XS=parseInt(e.dataset.index??`0`,10),aC()})});let r=nC();r&&(r.scrollTop=0)}function dC(){tC&&=(document.removeEventListener(`mousedown`,tC,!0),null),YS?.remove(),YS=null,XS=0,ZS=[],QS=null,$S=null,eC=null}function fC(e,t){if(!YS)return;YS.style.maxHeight=``;let n=ES(null),r=t?ES(t):n,i=DS({anchorRect:{left:e.left,right:e.left,top:e.top,bottom:e.bottom},containerRect:n,floatingWidth:YS.offsetWidth,floatingHeight:YS.offsetHeight,preferredPlacement:`bottom`,fallbackPlacement:`top`,align:`start`,gap:6});YS.style.left=`${i.left-r.left}px`,YS.style.top=`${i.top-r.top}px`,YS.style.maxHeight=i.maxHeight===null?``:`${i.maxHeight}px`}function pC(){tC=e=>{if(!(!YS||YS.contains(e.target))&&$S&&eC){let{state:e,view:t}=$S;t.dispatch(e.tr.delete(eC.from,eC.to))}},document.addEventListener(`mousedown`,tC,!0)}var mC=new Or(`jantSlashTyping`);function hC(){return new A({key:mC,state:{init:()=>({docChanged:!1}),apply:e=>({docChanged:e.docChanged})}})}function gC({state:e,range:t}){let n=e.doc.resolve(t.to),r=n.parent,i=t.to-n.start();if(i>=r.content.size)return!0;let a=r.textBetween(i,i+1,` `,` `);return a?/\s/.test(a):!0}function _C({state:e,range:t,isActive:n}){return gC({state:e,range:t})?n?!0:mC.getState(e)?.docChanged??!1:!1}var vC=N.create({name:`slashCommands`,addOptions(){return{suggestion:{char:`/`,startOfLine:!1,allow:_C,items:({query:e,editor:t})=>{let n=JS(t),r=Wx(e);return r?n.map((e,t)=>({item:e,index:t,rank:Ux([e.label,e.description,...e.keywords],r)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):n},render:()=>{function e(e){let t=e.options.element;return t instanceof globalThis.Element?t:null}return{onStart:t=>{YS=rC(),XS=0,QS=t.command,$S=t.editor,eC=t.range,uC(t.items,e=>t.command({index:e})),document.dispatchEvent(new CustomEvent(`jant:slash-command-discovered`,{bubbles:!0}));let n=e(t.editor)?.closest(`dialog`)??null;(n??document.body).appendChild(YS);let r=t.clientRect?.();r&&fC(r,n),pC()},onUpdate:t=>{QS=t.command,eC=t.range,uC(t.items,e=>t.command({index:e}));let n=t.clientRect?.();n&&fC(n,e(t.editor)?.closest(`dialog`)??null)},onKeyDown:e=>{let{event:t,view:n,range:r}=e;return t.key===`ArrowDown`?(t.preventDefault(),ZS.length===0?!0:(XS=(XS+1)%ZS.length,aC(),!0)):t.key===`ArrowUp`?(t.preventDefault(),ZS.length===0?!0:(XS=(XS-1+ZS.length)%ZS.length,aC(),!0)):t.key===`Enter`?(t.preventDefault(),ZS.length===0||QS?.({index:XS}),!0):t.key===`Escape`?(t.stopPropagation(),t.preventDefault(),n.dispatch(n.state.tr.delete(r.from,r.to)),!0):!1},onExit:()=>{dC()}}},command:({editor:e,range:t,props:n})=>{let r=ZS[n.index];r&&r.command(e,t)}}}},addProseMirrorPlugins(){return[hC(),CS({editor:this.editor,...this.options.suggestion})]}}),yC=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~`.split(``),bC=(e,t)=>{var n=``;for(let r=1;r<=t;r++){let i=Math.floor(e)/83**(t-r)%83;n+=yC[Math.floor(i)]}return n},xC=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4},SC=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(t*12.92*255+.5):Math.trunc((1.055*t**.4166666666666667-.055)*255+.5)},CC=e=>e<0?-1:1,wC=(e,t)=>CC(e)*Math.abs(e)**+t,TC=class extends Error{constructor(e){super(e),this.name=`ValidationError`,this.message=e}},EC=4,DC=(e,t,n,r)=>{let i=0,a=0,o=0,s=t*EC;for(let c=0;c<t;c++){let t=EC*c;for(let l=0;l<n;l++){let n=t+l*s,u=r(c,l);i+=u*xC(e[n]),a+=u*xC(e[n+1]),o+=u*xC(e[n+2])}}let c=1/(t*n);return[i*c,a*c,o*c]},OC=e=>{let t=SC(e[0]),n=SC(e[1]),r=SC(e[2]);return(t<<16)+(n<<8)+r},kC=(e,t)=>{let n=Math.floor(Math.max(0,Math.min(18,Math.floor(wC(e[0]/t,.5)*9+9.5)))),r=Math.floor(Math.max(0,Math.min(18,Math.floor(wC(e[1]/t,.5)*9+9.5)))),i=Math.floor(Math.max(0,Math.min(18,Math.floor(wC(e[2]/t,.5)*9+9.5))));return n*19*19+r*19+i},AC=(e,t,n,r,i)=>{if(r<1||r>9||i<1||i>9)throw new TC(`BlurHash must have between 1 and 9 components`);if(t*n*4!==e.length)throw new TC(`Width and height must match the pixels array`);let a=[];for(let o=0;o<i;o++)for(let i=0;i<r;i++){let r=i==0&&o==0?1:2,s=DC(e,t,n,(e,a)=>r*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*o*a/n));a.push(s)}let o=a[0],s=a.slice(1),c=``,l=r-1+(i-1)*9;c+=bC(l,1);let u;if(s.length>0){let e=Math.max(...s.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(e*166-.5))));u=(t+1)/166,c+=bC(t,1)}else u=1,c+=bC(0,1);return c+=bC(OC(o),4),s.forEach(e=>{c+=bC(kC(e,u),2)}),c};async function jC(e){let t=await FC(e),{width:n,height:r}=t,i=Math.min(32/n,32/r,1),a=Math.max(Math.round(n*i),1),o=Math.max(Math.round(r*i),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);return c.drawImage(t,0,0,a,o),{width:n,height:r,blurhash:AC(c.getImageData(0,0,a,o).data,a,o,4,3)}}async function MC(e){let t=URL.createObjectURL(e);try{let e=document.createElement(`video`);e.muted=!0,e.preload=`auto`;let{width:n,height:r,duration:i}=await new Promise((n,r)=>{e.onloadedmetadata=()=>n({width:e.videoWidth,height:e.videoHeight,duration:e.duration}),e.onerror=()=>r(Error(`Failed to load video metadata`)),e.src=t}),a,o;try{let t=Math.min(i*.1,3),s=await Promise.race([IC(e,n,r,t),LC(8e3)]);a=s.blurhash,o=s.poster}catch{}return{width:n,height:r,blurhash:a,poster:o}}finally{URL.revokeObjectURL(t)}}async function NC(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function PC(e){try{if(e.type.startsWith(`image/`))return await jC(e);if(e.type.startsWith(`video/`)){let t=await MC(e);return{width:t.width,height:t.height,blurhash:t.blurhash,poster:t.poster}}if(e.type.startsWith(`audio/`))return{waveform:await NC(e)}}catch{}return{}}function FC(e){return new Promise((t,n)=>{let r=new Image,i=URL.createObjectURL(e);r.onload=()=>{URL.revokeObjectURL(i),t(r)},r.onerror=()=>{URL.revokeObjectURL(i),n(Error(`Failed to load image`))},r.src=i})}function IC(e,t,n,r){return new Promise((i,a)=>{e.currentTime=r,e.onseeked=()=>{try{let r=Math.min(32/t,32/n,1),a=Math.max(Math.round(t*r),1),o=Math.max(Math.round(n*r),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);c.drawImage(e,0,0,a,o);let l=AC(c.getImageData(0,0,a,o).data,a,o,4,3),u=Math.min(640/t,1),d=Math.round(t*u),f=Math.round(n*u),p=document.createElement(`canvas`);p.width=d,p.height=f;let m=p.getContext(`2d`);if(!m){i({blurhash:l});return}m.drawImage(e,0,0,d,f),p.toBlob(e=>{i({blurhash:l,poster:e??void 0})},`image/webp`,.8)}catch(e){a(e)}},e.onerror=()=>a(Error(`Video seek failed`))})}function LC(e){return new Promise((t,n)=>setTimeout(()=>n(Error(`Timeout`)),e))}function RC(e){if(!oe(e))return null;let t=w(e,`kind`),n=w(e,`method`),r=w(e,`url`);if(!t||n!==`PUT`||!r)return null;if(t===`relay`)return{kind:t,method:`PUT`,url:r};if(t===`multipartRelay`){let n=ce(e,`partSize`);return n?{kind:t,method:`PUT`,url:r,partSize:n}:null}if(t===`put`){let n=ce(e,`expiresAt`),i=e.headers;if(!n||!oe(i))return null;let a={};for(let[e,t]of Object.entries(i))typeof t==`string`&&(a[e]=t);return{kind:t,method:`PUT`,url:r,headers:a,expiresAt:n}}return null}function zC(e,t,n,r){return new Promise((i,a)=>{let o=new globalThis.XMLHttpRequest;o.open(`PUT`,e);for(let[e,t]of Object.entries(n))o.setRequestHeader(e,t);o.upload.addEventListener(`progress`,e=>{e.lengthComputable&&r&&r(e.loaded/e.total)}),o.addEventListener(`load`,()=>{i({status:o.status,ok:o.status>=200&&o.status<300,text:o.responseText})}),o.addEventListener(`error`,()=>a(Error(`Network error`))),o.addEventListener(`abort`,()=>a(Error(`Upload aborted`))),o.send(t)})}function BC(e){try{let t=JSON.parse(e);return oe(t)?t:null}catch{return null}}async function VC(e){let t=await fetch(i(`/api/uploads/init`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({filename:e.name,contentType:e.type||`application/octet-stream`,size:e.size})});if(!t.ok){let e=await le(t);throw Error(w(e,`error`)??`Failed to start upload`)}let n=await le(t),r=w(n,`id`),a=RC(n.transport);if(!r||!a)throw Error(`Failed to start upload`);return{id:r,transport:a}}async function HC(e,t){if(!(await fetch(i(`/api/uploads/${e}/poster`),{method:`PUT`,headers:{"Content-Type":t.type||`image/webp`},body:t})).ok)throw Error(`Failed to upload poster`)}async function UC(e){await fetch(i(`/api/uploads/${e}/abort`),{method:`POST`}).catch(()=>{})}async function WC(e,t){let n=await fetch(i(`/api/uploads/${e}/complete`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await le(n);throw Error(w(e,`error`)??`Failed to complete upload`)}let r=await le(n),a=w(r,`id`),o=w(r,`filename`),s=w(r,`url`),c=w(r,`mimeType`),l=ce(r,`size`);if(!a||!o||!s||!c||l===void 0)throw Error(`Failed to complete upload`);return{id:a,filename:o,url:s,mimeType:c,size:l}}async function GC(e,t,n,r){let a=Math.ceil(n.size/t.partSize),o=[],s=0;for(let e=0;e<a;e+=1){let a=e*t.partSize,c=Math.min(a+t.partSize,n.size),l=e+1,u=n.slice(a,c),d=c-a,f=await zC(i(`${t.url}?partNumber=${l}`),u,{},e=>{r?.((s+d*e)/n.size)});if(!f.ok)throw Error(`Failed to upload part ${l}`);let p=BC(f.text),m=p?ce(p,`partNumber`):null,h=p?w(p,`etag`):null;if(!m||!h)throw Error(`Failed to upload part ${l}`);o.push({partNumber:m,etag:h}),s+=d,r?.(s/n.size)}return o}async function KC(e,t,n){let{id:r,transport:a}=await VC(e);try{if(a.kind===`put`){if(!(await zC(a.url,e,a.headers,n)).ok)throw Error(`Upload failed`);n?.(1)}else if(a.kind===`relay`){let t=await zC(i(a.url),e,{"Content-Type":e.type},n);if(!t.ok){let e=BC(t.text);throw Error((e&&w(e,`error`))??`Upload failed`)}n?.(1)}let o=a.kind===`multipartRelay`?await GC(r,a,e,n):void 0;return t.poster&&await HC(r,t.poster),WC(r,{...t,parts:o})}catch(e){throw await UC(r),e}}async function qC(e){let{file:t,width:n,height:r}=await re.processToFile(e),i;try{i=(await jC(t)).blurhash}catch{}let a=await KC(t,{width:n,height:r,blurhash:i});return{url:a.url,id:a.id}}var JC=new Map,YC=new Map;function XC(e,t,n){if(e.isDestroyed)return;let{doc:r}=e.state,i=!1;r.descendants((r,a)=>{i||r.type.name!==`image`||r.attrs.src!==t||(e.chain().command(({tr:e})=>(e.setNodeMarkup(a,void 0,{...r.attrs,src:n}),!0)).run(),i=!0)})}function ZC(e,t){if(e.isDestroyed)return;let{doc:n}=e.state;n.descendants((n,r)=>{n.type.name===`image`&&n.attrs.src===t&&e.chain().command(({tr:e})=>(e.delete(r,r+n.nodeSize),!0)).run()})}async function QC(e,t,n=qC){let r=URL.createObjectURL(t);e.chain().focus().setImage({src:r}).run();let i=n(t).then(e=>e.url);JC.set(r,i);try{XC(e,r,await i)}catch{ZC(e,r)}finally{JC.delete(r)&&URL.revokeObjectURL(r)}}function $C(e){let t=[],{doc:n}=e.state;return n.descendants(n=>{if(n.type.name!==`image`)return;let r=n.attrs.src;if(!r?.startsWith(`blob:`))return;let i=JC.get(r);if(!i)return;JC.delete(r),YC.set(r,i);let a=i.then(t=>XC(e,r,t),()=>ZC(e,r)).finally(()=>{YC.delete(r),URL.revokeObjectURL(r)});t.push(a)}),t}async function ew(e){if(!e)return e;let t=new Map;if(tw(e,t),t.size===0)return e;let n=new Map;return await Promise.allSettled(Array.from(t.entries()).map(async([e,t])=>{let r=await t;n.set(e,r)})),nw(e,n)}function tw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=JC.get(e.attrs.src)??YC.get(e.attrs.src);n&&t.set(e.attrs.src,n)}if(e.content)for(let n of e.content)tw(n,t)}function nw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=t.get(e.attrs.src);return n?{...e,attrs:{...e.attrs,src:n}}:{type:`__removed__`}}if(!e.content)return e;let n=e.content.map(e=>nw(e,t)).filter(e=>e.type!==`__removed__`);return n===e.content?e:{...e,content:n}}var rw=new Or(`pasteMedia`);function iw(e){return`${e.name}:${e.type}:${e.size}:${e.lastModified}`}function aw(e){if(!e)return[];let t=Array.from(e.items??[]).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null),n=t.length>0?t:Array.from(e.files??[]),r=new Set;return n.filter(e=>{let t=iw(e);return r.has(t)?!1:(r.add(t),!0)})}var ow=N.create({name:`pasteMedia`,addOptions(){return{shouldInsertInline:void 0,onPasteFiles:void 0}},addProseMirrorPlugins(){let e=this;return[new A({key:rw,props:{handlePaste(t,n){let r=aw(n.clipboardData);if(r.length===0)return!1;let i=r.filter(t=>e.options.shouldInsertInline?.(t)===!0),a=r.filter(e=>!i.includes(e));if(i.length===0&&(a.length===0||e.options.onPasteFiles===void 0))return!1;n.preventDefault();for(let t of i){let n=e.options.uploadInlineImage;if(n){n(t);continue}QC(e.editor,t)}return a.length>0&&e.options.onPasteFiles!==void 0&&e.options.onPasteFiles(a),!0}}})]}}),sw=`(pointer: coarse)`;function cw(e){return e===`compose`&&(globalThis.matchMedia?.(sw).matches??!1)}function lw(e,t){let n=t.dom.closest(`jant-compose-editor`),r=t.dom.closest(`jant-compose-dialog, .compose-fullscreen, .compose-attached-panel`)??t.dom.closest(`dialog`),i=16,a=n?.querySelector(`.compose-tools-row`)??r?.querySelector(`.compose-tools-row`),o=r?.querySelector(`.compose-action-row`),s=n?.querySelector(`.compose-attachments-dock`);a&&(i+=a.getBoundingClientRect().height),o&&(i+=o.getBoundingClientRect().height),s&&(i+=s.getBoundingClientRect().height),e.style.setProperty(`--tiptap-docked-offset`,`${i}px`)}var uw=new Or(`linkToolbar`),dw=`hidden`,fw=!1;function pw(){return dw===`input`&&fw}var mw=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/></svg>`;function hw(e){let{selection:t}=e;if(!t.empty)return null;let n=t.$from,r=e.schema.marks.link;if(!r)return null;let i=n.marks().find(e=>e.type===r);if(!i)return null;let a=n.parent,o=n.start(),s=0,c=0,l=!1,u=0;for(let e=0;e<a.childCount;e++){let t=a.child(e),n=o+u,d=n+t.nodeSize;if(t.marks.some(e=>e.type===r&&e.attrs.href===i.attrs.href))l||=(s=n,!0),c=d;else if(l)break;u+=t.nodeSize}return l?{from:s,to:c,href:i.attrs.href}:null}var gw=N.create({name:`linkToolbar`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=null,i=null,a=0,o=0,s=!1,c=!1,l=null;function u(){n=document.createElement(`div`),n.className=`tiptap-link-input`,n.dataset.editorFloatingUi=`true`,n.style.display=`none`;let t=document.createElement(`div`);t.className=`tiptap-link-input-fields`,i=document.createElement(`input`),i.type=`text`,i.className=`tiptap-link-input-text`,i.placeholder=`Link text`,r=document.createElement(`input`),r.type=`url`,r.className=`tiptap-link-input-field`,r.placeholder=`https:// (empty to unlink)`,t.appendChild(i),t.appendChild(r);let a=document.createElement(`button`);a.type=`button`,a.className=`tiptap-link-input-confirm`,a.innerHTML=mw,a.title=`Apply link`,n.appendChild(t),n.appendChild(a);let o=t=>{t.key===`Enter`?(t.preventDefault(),t.stopPropagation(),h()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),c=!0,p(),e.commands.focus())};i.addEventListener(`keydown`,o),r.addEventListener(`keydown`,o);let s=()=>{fw=!0},l=()=>{requestAnimationFrame(()=>{let e=document.activeElement;(!n||!n.contains(e))&&(fw=!1)})};i.addEventListener(`focus`,s),r.addEventListener(`focus`,s),i.addEventListener(`blur`,l),r.addEventListener(`blur`,l),a.addEventListener(`mousedown`,e=>{e.preventDefault(),h()}),n.addEventListener(`mousedown`,e=>{e.stopPropagation()})}function d(e,n,r,i){let a=cw(t);if(e.classList.toggle(`tiptap-link-input-docked`,a),e.style.display=`flex`,a){lw(e,n),e.style.removeProperty(`left`),e.style.removeProperty(`top`);return}let o=n.dom.closest(`dialog`),s=n.coordsAtPos(r),c=n.coordsAtPos(i),l=e.getBoundingClientRect(),u=DS({anchorRect:{left:s.left,right:c.right,top:Math.min(s.top,c.top),bottom:Math.max(s.bottom,c.bottom)},containerRect:ES(o),floatingWidth:l.width,floatingHeight:l.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});e.style.left=`${u.left}px`,e.style.top=`${u.top}px`}function f(e,t){if(!(!n||!r||!i)){if(t.from!==void 0&&t.to!==void 0?(a=t.from,o=t.to):(a=e.state.selection.from,o=e.state.selection.to),dw=`input`,r.value=t.href,i.value=t.text??e.state.doc.textBetween(a,o,``),d(n,e,a,o),t.focus){let e=i.value.length>0?r:i;requestAnimationFrame(()=>{e.focus(),e.select()})}m(),l=e=>{n&&!n.contains(e.target)&&(c=!0,p())},setTimeout(()=>{l&&document.addEventListener(`mousedown`,l,!0)},0)}}function p(){n&&(n.style.display=`none`),dw=`hidden`,fw=!1,m()}function m(){l&&=(document.removeEventListener(`mousedown`,l,!0),null)}function h(){if(!r||!i)return;let t=r.value.trim(),n=e.state.doc.textBetween(a,o,``),c=i.value,l=c.length>0?c:t;if(p(),!t){e.chain().focus().setTextSelection({from:a,to:o}).unsetLink().setTextSelection(o).run(),s=!0;return}let u=l!==n,d=a+l.length;u?e.chain().focus().command(({tr:e})=>(e.insertText(l,a,o),!0)).setTextSelection({from:a,to:d}).setLink({href:t}).setTextSelection(d).run():e.chain().focus().setTextSelection({from:a,to:o}).setLink({href:t}).setTextSelection(o).run(),s=!0}return[new A({key:uw,view(e){u();let t=e.dom.closest(`dialog`);n&&(t??document.body).appendChild(n);let r=()=>{c=!1,s=!0,f(e,{href:``,focus:!0})};e.dom.addEventListener(`tiptap:open-link-input`,r);let i=e=>{e.key===`Escape`&&dw===`input`&&(e.preventDefault(),e.stopPropagation(),c=!0,p())};return e.dom.addEventListener(`keydown`,i),{update(e){if(s){s=!1;return}let t=hw(e.state);if(dw===`input`&&fw){n&&d(n,e,a,o);return}if(t){if(c)return;f(e,{href:t.href,from:t.from,to:t.to,focus:!1})}else c=!1,dw===`input`&&p()},destroy(){e.dom.removeEventListener(`tiptap:open-link-input`,r),e.dom.removeEventListener(`keydown`,i),m(),n?.remove(),n=null,dw=`hidden`,fw=!1}}}})]}}),_w=new Or(`bubbleMenu`),vw={bold:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 12h9a4 4 0 0 1 0 8H6V4h8a4 4 0 0 1 0 8"/></svg>`,italic:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>`,h1:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17 12l3-2v10"/></svg>`,h2:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>`,blockquote:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,clear:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m16 22-1-4"/><path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1"/><path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z"/><path d="m8 22 1-4"/></svg>`};function yw(e,t){return t===`compose`?[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)},{key:`clear`,icon:vw.clear,title:`Clear formatting`,action:()=>{let{to:t}=e.state.selection;e.chain().focus().unsetAllMarks().clearNodes().setTextSelection(t).run()},isActive:()=>!1}]:[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`h1`,icon:vw.h1,title:`Heading 1`,action:()=>e.chain().focus().toggleHeading({level:1}).run(),isActive:()=>e.isActive(`heading`,{level:1})},{key:`h2`,icon:vw.h2,title:`Heading 2`,action:()=>e.chain().focus().toggleHeading({level:2}).run(),isActive:()=>e.isActive(`heading`,{level:2})},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`blockquote`,icon:vw.blockquote,title:`Quote`,action:()=>e.chain().focus().toggleBlockquote().run(),isActive:()=>e.isActive(`blockquote`)},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)}]}var bw=N.create({name:`bubbleMenu`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=[],i=new Map;function a(){n=document.createElement(`div`),n.className=`tiptap-bubble-menu`,n.dataset.editorFloatingUi=`true`,n.style.position=`fixed`,n.style.display=`none`,r=yw(e,t);for(let t of r){if(t.key===`sep`){let e=document.createElement(`span`);e.className=`tiptap-bubble-sep`,n.appendChild(e);continue}let r=document.createElement(`button`);r.type=`button`,r.innerHTML=t.icon,r.title=t.title,r.className=`tiptap-bubble-btn`,r.addEventListener(`mousedown`,n=>{n.preventDefault(),t.action(e.view)}),n.appendChild(r),i.set(t.key,r)}}function o(e){if(!n)return;let r=cw(t);if(n.classList.toggle(`tiptap-bubble-menu-docked`,r),n.style.display=`flex`,r){lw(n,e),n.style.removeProperty(`left`),n.style.removeProperty(`top`),c();return}let{from:i,to:a}=e.state.selection,o=e.coordsAtPos(i),s=e.coordsAtPos(a),l=e.dom.closest(`dialog`),u=n.getBoundingClientRect(),d=DS({anchorRect:{left:o.left,right:s.right,top:Math.min(o.top,s.top),bottom:Math.max(o.bottom,s.bottom)},containerRect:ES(l),floatingWidth:u.width,floatingHeight:u.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});n.style.left=`${d.left}px`,n.style.top=`${d.top}px`,c()}function s(){n&&(n.style.display=`none`)}function c(){for(let t of r){if(t.key===`sep`)continue;let n=i.get(t.key);n&&n.classList.toggle(`is-active`,t.isActive(e.view))}}function l(e){let{state:t}=e,{selection:n}=t,{empty:r}=n;return!(r||!n.$from.parent.isTextblock||pw())}return[new A({key:_w,view(e){a();let t=e.dom.closest(`dialog`)??document.body;n&&t.appendChild(n);function r(t){let r=t.target;if(!r||e.dom.contains(r)||r.closest(`[data-editor-floating-ui]`)||n?.contains(r))return;let{state:i}=e,a=i.selection.from;e.dispatch(i.tr.setSelection(D.near(i.doc.resolve(a)))),e.dom.blur()}return t.addEventListener(`mousedown`,r),{update(e){l(e)?o(e):s()},destroy(){t.removeEventListener(`mousedown`,r),n?.remove(),n=null}}}})]}}),xw=new Set([`bold`,`italic`,`strike`,`code`,`underline`]);function Sw(e){return e.filter(e=>xw.has(e.type.name))}var Cw=N.create({name:`exitableMarks`,addKeyboardShortcuts(){return{ArrowRight:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;if(!t.empty||n.pos!==n.end())return!1;let r=Sw(n.marks());if(!r.length)return!1;let{tr:i}=e.state;for(let e of r)i.removeStoredMark(e);return e.view.dispatch(i),!0},Enter:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;return!t.empty||n.parent.textContent.length>0||!Sw(e.state.storedMarks??n.marks()).length||requestAnimationFrame(()=>{let{tr:t}=e.state;t.setStoredMarks([]),e.view.dispatch(t)}),!1}}}}),ww=` `,Tw=N.create({name:`tabIndent`,addKeyboardShortcuts(){return{Tab:({editor:e})=>{if(e.isActive(`listItem`))return e.commands.sinkListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a)return n(t.tr.insertText(ww,i)),!0;let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
298
+ ${cC(oC())}`,YS.querySelectorAll(`.tiptap-slash-item`).forEach(e=>{e.addEventListener(`mousedown`,n=>{n.preventDefault(),t(parseInt(e.dataset.index??`0`,10))}),e.addEventListener(`mouseenter`,()=>{XS=parseInt(e.dataset.index??`0`,10),aC()})});let r=nC();r&&(r.scrollTop=0)}function dC(){tC&&=(document.removeEventListener(`mousedown`,tC,!0),null),YS?.remove(),YS=null,XS=0,ZS=[],QS=null,$S=null,eC=null}function fC(e,t){if(!YS)return;YS.style.maxHeight=``;let n=ES(null),r=t?ES(t):n,i=DS({anchorRect:{left:e.left,right:e.left,top:e.top,bottom:e.bottom},containerRect:n,floatingWidth:YS.offsetWidth,floatingHeight:YS.offsetHeight,preferredPlacement:`bottom`,fallbackPlacement:`top`,align:`start`,gap:6});YS.style.left=`${i.left-r.left}px`,YS.style.top=`${i.top-r.top}px`,YS.style.maxHeight=i.maxHeight===null?``:`${i.maxHeight}px`}function pC(){tC=e=>{if(!(!YS||YS.contains(e.target))&&$S&&eC){let{state:e,view:t}=$S;t.dispatch(e.tr.delete(eC.from,eC.to))}},document.addEventListener(`mousedown`,tC,!0)}var mC=new Or(`jantSlashTyping`);function hC(){return new A({key:mC,state:{init:()=>({docChanged:!1}),apply:e=>({docChanged:e.docChanged})}})}function gC({state:e,range:t}){let n=e.doc.resolve(t.to),r=n.parent,i=t.to-n.start();if(i>=r.content.size)return!0;let a=r.textBetween(i,i+1,` `,` `);return a?/\s/.test(a):!0}function _C({state:e,range:t,isActive:n}){return gC({state:e,range:t})?n?!0:mC.getState(e)?.docChanged??!1:!1}var vC=N.create({name:`slashCommands`,addOptions(){return{suggestion:{char:`/`,startOfLine:!1,allow:_C,items:({query:e,editor:t})=>{let n=JS(t),r=Wx(e);return r?n.map((e,t)=>({item:e,index:t,rank:Ux([e.label,e.description,...e.keywords],r)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):n},render:()=>{function e(e){let t=e.options.element;return t instanceof globalThis.Element?t:null}return{onStart:t=>{YS=rC(),XS=0,QS=t.command,$S=t.editor,eC=t.range,uC(t.items,e=>t.command({index:e})),document.dispatchEvent(new CustomEvent(`jant:slash-command-discovered`,{bubbles:!0}));let n=e(t.editor)?.closest(`dialog`)??null;(n??document.body).appendChild(YS);let r=t.clientRect?.();r&&fC(r,n),pC()},onUpdate:t=>{QS=t.command,eC=t.range,uC(t.items,e=>t.command({index:e}));let n=t.clientRect?.();n&&fC(n,e(t.editor)?.closest(`dialog`)??null)},onKeyDown:e=>{let{event:t,view:n,range:r}=e;return t.key===`ArrowDown`?(t.preventDefault(),ZS.length===0?!0:(XS=(XS+1)%ZS.length,aC(),!0)):t.key===`ArrowUp`?(t.preventDefault(),ZS.length===0?!0:(XS=(XS-1+ZS.length)%ZS.length,aC(),!0)):t.key===`Enter`?(t.preventDefault(),ZS.length===0||QS?.({index:XS}),!0):t.key===`Escape`?(t.stopPropagation(),t.preventDefault(),n.dispatch(n.state.tr.delete(r.from,r.to)),!0):!1},onExit:()=>{dC()}}},command:({editor:e,range:t,props:n})=>{let r=ZS[n.index];r&&r.command(e,t)}}}},addProseMirrorPlugins(){return[hC(),CS({editor:this.editor,...this.options.suggestion})]}}),yC=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~`.split(``),bC=(e,t)=>{var n=``;for(let r=1;r<=t;r++){let i=Math.floor(e)/83**(t-r)%83;n+=yC[Math.floor(i)]}return n},xC=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4},SC=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(t*12.92*255+.5):Math.trunc((1.055*t**.4166666666666667-.055)*255+.5)},CC=e=>e<0?-1:1,wC=(e,t)=>CC(e)*Math.abs(e)**+t,TC=class extends Error{constructor(e){super(e),this.name=`ValidationError`,this.message=e}},EC=4,DC=(e,t,n,r)=>{let i=0,a=0,o=0,s=t*EC;for(let c=0;c<t;c++){let t=EC*c;for(let l=0;l<n;l++){let n=t+l*s,u=r(c,l);i+=u*xC(e[n]),a+=u*xC(e[n+1]),o+=u*xC(e[n+2])}}let c=1/(t*n);return[i*c,a*c,o*c]},OC=e=>{let t=SC(e[0]),n=SC(e[1]),r=SC(e[2]);return(t<<16)+(n<<8)+r},kC=(e,t)=>{let n=Math.floor(Math.max(0,Math.min(18,Math.floor(wC(e[0]/t,.5)*9+9.5)))),r=Math.floor(Math.max(0,Math.min(18,Math.floor(wC(e[1]/t,.5)*9+9.5)))),i=Math.floor(Math.max(0,Math.min(18,Math.floor(wC(e[2]/t,.5)*9+9.5))));return n*19*19+r*19+i},AC=(e,t,n,r,i)=>{if(r<1||r>9||i<1||i>9)throw new TC(`BlurHash must have between 1 and 9 components`);if(t*n*4!==e.length)throw new TC(`Width and height must match the pixels array`);let a=[];for(let o=0;o<i;o++)for(let i=0;i<r;i++){let r=i==0&&o==0?1:2,s=DC(e,t,n,(e,a)=>r*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*o*a/n));a.push(s)}let o=a[0],s=a.slice(1),c=``,l=r-1+(i-1)*9;c+=bC(l,1);let u;if(s.length>0){let e=Math.max(...s.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(e*166-.5))));u=(t+1)/166,c+=bC(t,1)}else u=1,c+=bC(0,1);return c+=bC(OC(o),4),s.forEach(e=>{c+=bC(kC(e,u),2)}),c};async function jC(e){let t=await FC(e),{width:n,height:r}=t,i=Math.min(32/n,32/r,1),a=Math.max(Math.round(n*i),1),o=Math.max(Math.round(r*i),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);return c.drawImage(t,0,0,a,o),{width:n,height:r,blurhash:AC(c.getImageData(0,0,a,o).data,a,o,4,3)}}async function MC(e){let t=URL.createObjectURL(e);try{let e=document.createElement(`video`);e.muted=!0,e.preload=`auto`;let{width:n,height:r,duration:i}=await new Promise((n,r)=>{e.onloadedmetadata=()=>n({width:e.videoWidth,height:e.videoHeight,duration:e.duration}),e.onerror=()=>r(Error(`Failed to load video metadata`)),e.src=t}),a,o;try{let t=Math.min(i*.1,3),s=await Promise.race([IC(e,n,r,t),LC(8e3)]);a=s.blurhash,o=s.poster}catch{}return{width:n,height:r,blurhash:a,poster:o}}finally{URL.revokeObjectURL(t)}}async function NC(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function PC(e){try{if(e.type.startsWith(`image/`))return await jC(e);if(e.type.startsWith(`video/`)){let t=await MC(e);return{width:t.width,height:t.height,blurhash:t.blurhash,poster:t.poster}}if(e.type.startsWith(`audio/`))return{waveform:await NC(e)}}catch{}return{}}function FC(e){return new Promise((t,n)=>{let r=new Image,i=URL.createObjectURL(e);r.onload=()=>{URL.revokeObjectURL(i),t(r)},r.onerror=()=>{URL.revokeObjectURL(i),n(Error(`Failed to load image`))},r.src=i})}function IC(e,t,n,r){return new Promise((i,a)=>{e.currentTime=r,e.onseeked=()=>{try{let r=Math.min(32/t,32/n,1),a=Math.max(Math.round(t*r),1),o=Math.max(Math.round(n*r),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);c.drawImage(e,0,0,a,o);let l=AC(c.getImageData(0,0,a,o).data,a,o,4,3),u=Math.min(640/t,1),d=Math.round(t*u),f=Math.round(n*u),p=document.createElement(`canvas`);p.width=d,p.height=f;let m=p.getContext(`2d`);if(!m){i({blurhash:l});return}m.drawImage(e,0,0,d,f),p.toBlob(e=>{i({blurhash:l,poster:e??void 0})},`image/webp`,.8)}catch(e){a(e)}},e.onerror=()=>a(Error(`Video seek failed`))})}function LC(e){return new Promise((t,n)=>setTimeout(()=>n(Error(`Timeout`)),e))}function RC(e){if(!oe(e))return null;let t=w(e,`kind`),n=w(e,`method`),r=w(e,`url`);if(!t||n!==`PUT`||!r)return null;if(t===`relay`)return{kind:t,method:`PUT`,url:r};if(t===`multipartRelay`){let n=ce(e,`partSize`);return n?{kind:t,method:`PUT`,url:r,partSize:n}:null}if(t===`put`){let n=ce(e,`expiresAt`),i=e.headers;if(!n||!oe(i))return null;let a={};for(let[e,t]of Object.entries(i))typeof t==`string`&&(a[e]=t);return{kind:t,method:`PUT`,url:r,headers:a,expiresAt:n}}return null}function zC(e,t,n,r){return new Promise((i,a)=>{let o=new globalThis.XMLHttpRequest;o.open(`PUT`,e);for(let[e,t]of Object.entries(n))o.setRequestHeader(e,t);o.upload.addEventListener(`progress`,e=>{e.lengthComputable&&r&&r(e.loaded/e.total)}),o.addEventListener(`load`,()=>{i({status:o.status,ok:o.status>=200&&o.status<300,text:o.responseText})}),o.addEventListener(`error`,()=>a(Error(`Network error`))),o.addEventListener(`abort`,()=>a(Error(`Upload aborted`))),o.send(t)})}function BC(e){try{let t=JSON.parse(e);return oe(t)?t:null}catch{return null}}async function VC(e){let t=await fetch(i(`/api/uploads/init`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({filename:e.name,contentType:e.type||`application/octet-stream`,size:e.size})});if(!t.ok){let e=await le(t);throw Error(w(e,`error`)??`Failed to start upload`)}let n=await le(t),r=w(n,`id`),a=RC(n.transport);if(!r||!a)throw Error(`Failed to start upload`);return{id:r,transport:a}}async function HC(e,t){if(!(await fetch(i(`/api/uploads/${e}/poster`),{method:`PUT`,headers:{"Content-Type":t.type||`image/webp`},body:t})).ok)throw Error(`Failed to upload poster`)}async function UC(e){await fetch(i(`/api/uploads/${e}/abort`),{method:`POST`}).catch(()=>{})}async function WC(e,t){let n=await fetch(i(`/api/uploads/${e}/complete`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await le(n);throw Error(w(e,`error`)??`Failed to complete upload`)}let r=await le(n),a=w(r,`id`),o=w(r,`filename`),s=w(r,`url`),c=w(r,`mimeType`),l=ce(r,`size`);if(!a||!o||!s||!c||l===void 0)throw Error(`Failed to complete upload`);return{id:a,filename:o,url:s,mimeType:c,size:l}}async function GC(e,t,n,r){let a=Math.ceil(n.size/t.partSize),o=[],s=0;for(let e=0;e<a;e+=1){let a=e*t.partSize,c=Math.min(a+t.partSize,n.size),l=e+1,u=n.slice(a,c),d=c-a,f=await zC(i(`${t.url}?partNumber=${l}`),u,{},e=>{r?.((s+d*e)/n.size)});if(!f.ok)throw Error(`Failed to upload part ${l}`);let p=BC(f.text),m=p?ce(p,`partNumber`):null,h=p?w(p,`etag`):null;if(!m||!h)throw Error(`Failed to upload part ${l}`);o.push({partNumber:m,etag:h}),s+=d,r?.(s/n.size)}return o}async function KC(e,t,n){let{id:r,transport:a}=await VC(e);try{if(a.kind===`put`){if(!(await zC(a.url,e,a.headers,n)).ok)throw Error(`Upload failed`);n?.(1)}else if(a.kind===`relay`){let t=await zC(i(a.url),e,{"Content-Type":e.type},n);if(!t.ok){let e=BC(t.text);throw Error((e&&w(e,`error`))??`Upload failed`)}n?.(1)}let o=a.kind===`multipartRelay`?await GC(r,a,e,n):void 0;return t.poster&&await HC(r,t.poster),WC(r,{...t,parts:o})}catch(e){throw await UC(r),e}}async function qC(e){let{file:t,width:n,height:r}=await re.processToFile(e),i;try{i=(await jC(t)).blurhash}catch{}let a=await KC(t,{width:n,height:r,blurhash:i});return{url:a.url,id:a.id}}var JC=new Map,YC=new Map;function XC(e,t,n){if(e.isDestroyed)return;let{doc:r}=e.state,i=!1;r.descendants((r,a)=>{i||r.type.name!==`image`||r.attrs.src!==t||(e.chain().command(({tr:e})=>(e.setNodeMarkup(a,void 0,{...r.attrs,src:n}),!0)).run(),i=!0)})}function ZC(e,t){if(e.isDestroyed)return;let{doc:n}=e.state;n.descendants((n,r)=>{n.type.name===`image`&&n.attrs.src===t&&e.chain().command(({tr:e})=>(e.delete(r,r+n.nodeSize),!0)).run()})}async function QC(e,t,n=qC){let r=URL.createObjectURL(t);e.chain().focus().setImage({src:r}).run();let i=n(t).then(e=>e.url);JC.set(r,i);try{XC(e,r,await i)}catch{ZC(e,r)}finally{JC.delete(r)&&URL.revokeObjectURL(r)}}function $C(e){let t=[],{doc:n}=e.state;return n.descendants(n=>{if(n.type.name!==`image`)return;let r=n.attrs.src;if(!r?.startsWith(`blob:`))return;let i=JC.get(r);if(!i)return;JC.delete(r),YC.set(r,i);let a=i.then(t=>XC(e,r,t),()=>ZC(e,r)).finally(()=>{YC.delete(r),URL.revokeObjectURL(r)});t.push(a)}),t}async function ew(e){if(!e)return e;let t=new Map;if(tw(e,t),t.size===0)return e;let n=new Map;return await Promise.allSettled(Array.from(t.entries()).map(async([e,t])=>{let r=await t;n.set(e,r)})),nw(e,n)}function tw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=JC.get(e.attrs.src)??YC.get(e.attrs.src);n&&t.set(e.attrs.src,n)}if(e.content)for(let n of e.content)tw(n,t)}function nw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=t.get(e.attrs.src);return n?{...e,attrs:{...e.attrs,src:n}}:{type:`__removed__`}}if(!e.content)return e;let n=e.content.map(e=>nw(e,t)).filter(e=>e.type!==`__removed__`);return n===e.content?e:{...e,content:n}}var rw=new Or(`pasteMedia`);function iw(e){return`${e.name}:${e.type}:${e.size}:${e.lastModified}`}function aw(e){if(!e)return[];let t=Array.from(e.items??[]).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null),n=t.length>0?t:Array.from(e.files??[]),r=new Set;return n.filter(e=>{let t=iw(e);return r.has(t)?!1:(r.add(t),!0)})}var ow=N.create({name:`pasteMedia`,addOptions(){return{shouldInsertInline:void 0,onPasteFiles:void 0}},addProseMirrorPlugins(){let e=this,t=t=>{let n=t.filter(t=>e.options.shouldInsertInline?.(t)===!0),r=t.filter(e=>!n.includes(e));if(n.length===0&&(r.length===0||e.options.onPasteFiles===void 0))return!1;for(let t of n){let n=e.options.uploadInlineImage;if(n){n(t);continue}QC(e.editor,t)}return r.length>0&&e.options.onPasteFiles!==void 0&&e.options.onPasteFiles(r),!0};return[new A({key:rw,props:{handlePaste(e,n){let r=aw(n.clipboardData);return r.length===0||!t(r)?!1:(n.preventDefault(),!0)},handleDrop(e,n){let r=aw(n.dataTransfer);return r.length===0||!t(r)?!1:(n.preventDefault(),!0)}}})]}}),sw=`(pointer: coarse)`;function cw(e){return e===`compose`&&(globalThis.matchMedia?.(sw).matches??!1)}function lw(e,t){let n=t.dom.closest(`jant-compose-editor`),r=t.dom.closest(`jant-compose-dialog, .compose-fullscreen, .compose-attached-panel`)??t.dom.closest(`dialog`),i=16,a=n?.querySelector(`.compose-tools-row`)??r?.querySelector(`.compose-tools-row`),o=r?.querySelector(`.compose-action-row`),s=n?.querySelector(`.compose-attachments-dock`);a&&(i+=a.getBoundingClientRect().height),o&&(i+=o.getBoundingClientRect().height),s&&(i+=s.getBoundingClientRect().height),e.style.setProperty(`--tiptap-docked-offset`,`${i}px`)}var uw=new Or(`linkToolbar`),dw=`hidden`,fw=!1;function pw(){return dw===`input`&&fw}var mw=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/></svg>`;function hw(e){let{selection:t}=e;if(!t.empty)return null;let n=t.$from,r=e.schema.marks.link;if(!r)return null;let i=n.marks().find(e=>e.type===r);if(!i)return null;let a=n.parent,o=n.start(),s=0,c=0,l=!1,u=0;for(let e=0;e<a.childCount;e++){let t=a.child(e),n=o+u,d=n+t.nodeSize;if(t.marks.some(e=>e.type===r&&e.attrs.href===i.attrs.href))l||=(s=n,!0),c=d;else if(l)break;u+=t.nodeSize}return l?{from:s,to:c,href:i.attrs.href}:null}var gw=N.create({name:`linkToolbar`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=null,i=null,a=0,o=0,s=!1,c=!1,l=null;function u(){n=document.createElement(`div`),n.className=`tiptap-link-input`,n.dataset.editorFloatingUi=`true`,n.style.display=`none`;let t=document.createElement(`div`);t.className=`tiptap-link-input-fields`,i=document.createElement(`input`),i.type=`text`,i.className=`tiptap-link-input-text`,i.placeholder=`Link text`,r=document.createElement(`input`),r.type=`url`,r.className=`tiptap-link-input-field`,r.placeholder=`https:// (empty to unlink)`,t.appendChild(i),t.appendChild(r);let a=document.createElement(`button`);a.type=`button`,a.className=`tiptap-link-input-confirm`,a.innerHTML=mw,a.title=`Apply link`,n.appendChild(t),n.appendChild(a);let o=t=>{t.key===`Enter`?(t.preventDefault(),t.stopPropagation(),h()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),c=!0,p(),e.commands.focus())};i.addEventListener(`keydown`,o),r.addEventListener(`keydown`,o);let s=()=>{fw=!0},l=()=>{requestAnimationFrame(()=>{let e=document.activeElement;(!n||!n.contains(e))&&(fw=!1)})};i.addEventListener(`focus`,s),r.addEventListener(`focus`,s),i.addEventListener(`blur`,l),r.addEventListener(`blur`,l),a.addEventListener(`mousedown`,e=>{e.preventDefault(),h()}),n.addEventListener(`mousedown`,e=>{e.stopPropagation()})}function d(e,n,r,i){let a=cw(t);if(e.classList.toggle(`tiptap-link-input-docked`,a),e.style.display=`flex`,a){lw(e,n),e.style.removeProperty(`left`),e.style.removeProperty(`top`);return}let o=n.dom.closest(`dialog`),s=n.coordsAtPos(r),c=n.coordsAtPos(i),l=e.getBoundingClientRect(),u=DS({anchorRect:{left:s.left,right:c.right,top:Math.min(s.top,c.top),bottom:Math.max(s.bottom,c.bottom)},containerRect:ES(o),floatingWidth:l.width,floatingHeight:l.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});e.style.left=`${u.left}px`,e.style.top=`${u.top}px`}function f(e,t){if(!(!n||!r||!i)){if(t.from!==void 0&&t.to!==void 0?(a=t.from,o=t.to):(a=e.state.selection.from,o=e.state.selection.to),dw=`input`,r.value=t.href,i.value=t.text??e.state.doc.textBetween(a,o,``),d(n,e,a,o),t.focus){let e=i.value.length>0?r:i;requestAnimationFrame(()=>{e.focus(),e.select()})}m(),l=e=>{n&&!n.contains(e.target)&&(c=!0,p())},setTimeout(()=>{l&&document.addEventListener(`mousedown`,l,!0)},0)}}function p(){n&&(n.style.display=`none`),dw=`hidden`,fw=!1,m()}function m(){l&&=(document.removeEventListener(`mousedown`,l,!0),null)}function h(){if(!r||!i)return;let t=r.value.trim(),n=e.state.doc.textBetween(a,o,``),c=i.value,l=c.length>0?c:t;if(p(),!t){e.chain().focus().setTextSelection({from:a,to:o}).unsetLink().setTextSelection(o).run(),s=!0;return}let u=l!==n,d=a+l.length;u?e.chain().focus().command(({tr:e})=>(e.insertText(l,a,o),!0)).setTextSelection({from:a,to:d}).setLink({href:t}).setTextSelection(d).run():e.chain().focus().setTextSelection({from:a,to:o}).setLink({href:t}).setTextSelection(o).run(),s=!0}return[new A({key:uw,view(e){u();let t=e.dom.closest(`dialog`);n&&(t??document.body).appendChild(n);let r=()=>{c=!1,s=!0,f(e,{href:``,focus:!0})};e.dom.addEventListener(`tiptap:open-link-input`,r);let i=e=>{e.key===`Escape`&&dw===`input`&&(e.preventDefault(),e.stopPropagation(),c=!0,p())};return e.dom.addEventListener(`keydown`,i),{update(e){if(s){s=!1;return}let t=hw(e.state);if(dw===`input`&&fw){n&&d(n,e,a,o);return}if(t){if(c)return;f(e,{href:t.href,from:t.from,to:t.to,focus:!1})}else c=!1,dw===`input`&&p()},destroy(){e.dom.removeEventListener(`tiptap:open-link-input`,r),e.dom.removeEventListener(`keydown`,i),m(),n?.remove(),n=null,dw=`hidden`,fw=!1}}}})]}}),_w=new Or(`bubbleMenu`),vw={bold:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 12h9a4 4 0 0 1 0 8H6V4h8a4 4 0 0 1 0 8"/></svg>`,italic:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>`,h1:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17 12l3-2v10"/></svg>`,h2:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>`,blockquote:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,clear:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m16 22-1-4"/><path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1"/><path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z"/><path d="m8 22 1-4"/></svg>`};function yw(e,t){return t===`compose`?[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)},{key:`clear`,icon:vw.clear,title:`Clear formatting`,action:()=>{let{to:t}=e.state.selection;e.chain().focus().unsetAllMarks().clearNodes().setTextSelection(t).run()},isActive:()=>!1}]:[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`h1`,icon:vw.h1,title:`Heading 1`,action:()=>e.chain().focus().toggleHeading({level:1}).run(),isActive:()=>e.isActive(`heading`,{level:1})},{key:`h2`,icon:vw.h2,title:`Heading 2`,action:()=>e.chain().focus().toggleHeading({level:2}).run(),isActive:()=>e.isActive(`heading`,{level:2})},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`blockquote`,icon:vw.blockquote,title:`Quote`,action:()=>e.chain().focus().toggleBlockquote().run(),isActive:()=>e.isActive(`blockquote`)},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)}]}var bw=N.create({name:`bubbleMenu`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=[],i=new Map;function a(){n=document.createElement(`div`),n.className=`tiptap-bubble-menu`,n.dataset.editorFloatingUi=`true`,n.style.position=`fixed`,n.style.display=`none`,r=yw(e,t);for(let t of r){if(t.key===`sep`){let e=document.createElement(`span`);e.className=`tiptap-bubble-sep`,n.appendChild(e);continue}let r=document.createElement(`button`);r.type=`button`,r.innerHTML=t.icon,r.title=t.title,r.className=`tiptap-bubble-btn`,r.addEventListener(`mousedown`,n=>{n.preventDefault(),t.action(e.view)}),n.appendChild(r),i.set(t.key,r)}}function o(e){if(!n)return;let r=cw(t);if(n.classList.toggle(`tiptap-bubble-menu-docked`,r),n.style.display=`flex`,r){lw(n,e),n.style.removeProperty(`left`),n.style.removeProperty(`top`),c();return}let{from:i,to:a}=e.state.selection,o=e.coordsAtPos(i),s=e.coordsAtPos(a),l=e.dom.closest(`dialog`),u=n.getBoundingClientRect(),d=DS({anchorRect:{left:o.left,right:s.right,top:Math.min(o.top,s.top),bottom:Math.max(o.bottom,s.bottom)},containerRect:ES(l),floatingWidth:u.width,floatingHeight:u.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});n.style.left=`${d.left}px`,n.style.top=`${d.top}px`,c()}function s(){n&&(n.style.display=`none`)}function c(){for(let t of r){if(t.key===`sep`)continue;let n=i.get(t.key);n&&n.classList.toggle(`is-active`,t.isActive(e.view))}}function l(e){let{state:t}=e,{selection:n}=t,{empty:r}=n;return!(r||!n.$from.parent.isTextblock||pw())}return[new A({key:_w,view(e){a();let t=e.dom.closest(`dialog`)??document.body;n&&t.appendChild(n);function r(t){let r=t.target;if(!r||e.dom.contains(r)||r.closest(`[data-editor-floating-ui]`)||n?.contains(r))return;let{state:i}=e,a=i.selection.from;e.dispatch(i.tr.setSelection(D.near(i.doc.resolve(a)))),e.dom.blur()}return t.addEventListener(`mousedown`,r),{update(e){l(e)?o(e):s()},destroy(){t.removeEventListener(`mousedown`,r),n?.remove(),n=null}}}})]}}),xw=new Set([`bold`,`italic`,`strike`,`code`,`underline`]);function Sw(e){return e.filter(e=>xw.has(e.type.name))}var Cw=N.create({name:`exitableMarks`,addKeyboardShortcuts(){return{ArrowRight:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;if(!t.empty||n.pos!==n.end())return!1;let r=Sw(n.marks());if(!r.length)return!1;let{tr:i}=e.state;for(let e of r)i.removeStoredMark(e);return e.view.dispatch(i),!0},Enter:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;return!t.empty||n.parent.textContent.length>0||!Sw(e.state.storedMarks??n.marks()).length||requestAnimationFrame(()=>{let{tr:t}=e.state;t.setStoredMarks([]),e.view.dispatch(t)}),!1}}}}),ww=` `,Tw=N.create({name:`tabIndent`,addKeyboardShortcuts(){return{Tab:({editor:e})=>{if(e.isActive(`listItem`))return e.commands.sinkListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a)return n(t.tr.insertText(ww,i)),!0;let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
299
299
  `,u-1)+1;f.push(p);let m=p;for(;;){let e=l.indexOf(`
300
300
  `,m);if(e===-1||e>=d)break;f.push(e+1),m=e+1}let h=t.tr,g=0;for(let e of f)h=h.insertText(ww,c+e+g),g+=2;let _=i+2,v=a+g;return h.setSelection(O.create(h.doc,_,v)),n(h),!0}return!1},"Shift-Tab":({editor:e})=>{if(e.isActive(`listItem`))return e.commands.liftListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a){let e=i-c,r=l.lastIndexOf(`
301
301
  `,e-1)+1,a=l.slice(r),o=a.startsWith(ww)?2:a.startsWith(` `)?1:0;return o===0||n(t.tr.delete(c+r,c+r+o)),!0}let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
@@ -1457,7 +1457,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1457
1457
  >
1458
1458
  ${Ce(EO)}
1459
1459
  </svg>
1460
- </span>`}function tk(e,t){let n=e.state.doc.content.size,r=Math.max(1,Math.min(t.from,n));return{from:r,to:Math.max(r,Math.min(t.to,n))}}var nk=class e extends c{static properties={format:{type:String},labels:{type:Object},uploadMaxFileSize:{type:Number},threadItem:{type:Boolean,attribute:`thread-item`},removable:{type:Boolean},slashCommandDiscovered:{type:Boolean},_title:{state:!0},_bodyJson:{state:!0},_url:{state:!0},_quoteText:{state:!0},_quoteAuthor:{state:!0},_rating:{state:!0},_showTitle:{state:!0},_showRating:{state:!0},_attachedTexts:{state:!0},_attachments:{state:!0},_attachmentOrder:{state:!0},_failedAttachmentPreviews:{state:!0},_showAltPanel:{state:!0},_altPanelIndex:{state:!0},_showEmojiPicker:{state:!0},_showUrlValidation:{state:!0},_showLinkTitleValidation:{state:!0}};_editor=null;_fileInput=null;_lastFocusedField=null;_lastEditorSelection=null;_emojiPickerEl=null;_emojiContainer=null;_urlStatusId=`compose-url-status-${FT()}`;_onDocClickBound=this._onDocumentClick.bind(this);_scrollBufferApplied=!1;_filePickerCleanup=null;_suppressAttachedTextOpenUntil=0;#e=0;#t=new Set;#n=null;#r=null;createRenderRoot(){return this}constructor(){super(),this.format=`note`,this.labels={},this.uploadMaxFileSize=500,this.threadItem=!1,this.removable=!1,this.slashCommandDiscovered=!1,this._title=``,this._bodyJson=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[],this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showEmojiPicker=!1,this._showUrlValidation=!1,this._showLinkTitleValidation=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered)}disconnectedCallback(){super.disconnectedCallback(),this.#i(),this._editor?.destroy(),this._editor=null,this.#n?.destroy(),this.#n=null,document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),document.removeEventListener(`click`,this._onDocClickBound),WO(this),this._emojiContainer?.remove(),this._emojiPickerEl=null,this._filePickerCleanup?.(),this._filePickerCleanup=null}_onSlashCommandDiscovered=()=>{qO()};_onSlashImage=()=>{document.querySelector(`.compose-fullscreen-dialog[open]`)||this._editor&&this._triggerSlashImagePicker()};_slashImageInput=null;_triggerSlashImagePicker(){this._slashImageInput||(this._slashImageInput=document.createElement(`input`),this._slashImageInput.type=`file`,this._slashImageInput.accept=`image/*`,this._slashImageInput.style.display=`none`,this._slashImageInput.addEventListener(`change`,()=>{let e=this._slashImageInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._slashImageInput&&(this._slashImageInput.value=``)}),document.body.appendChild(this._slashImageInput)),this._trackFilePickerSession(this._slashImageInput),this._slashImageInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=this.#e,r=QC(t,e).finally(()=>{n===this.#e&&this.#t.delete(r)});return this.#t.add(r),r}hasPendingInlineImageUploads(){return this.#t.size>0}async waitForPendingInlineImageUploads(){let e=this.#e;for(;e===this.#e&&this.#t.size>0;)await Promise.allSettled(Array.from(this.#t))}#i(){this.#e+=1,this.#t.clear()}adoptPendingUploads(){if(!this._editor)return;let e=this.#e,t=$C(this._editor);for(let n of t){let t=n.finally(()=>{e===this.#e&&this.#t.delete(t)});this.#t.add(t)}}_dispatchFilePickerEvent(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_trackFilePickerSession(e){this._filePickerCleanup?.();let t=!1,n=e=>{t||(t=!0,o(),this._dispatchFilePickerEvent(`jant:file-picker-close`,{cancelled:e}))},r=()=>n(!1),i=()=>n(!0),a=()=>{globalThis.setTimeout(()=>{n(!(e.files&&e.files.length>0))},0)},o=()=>{e.removeEventListener(`change`,r),e.removeEventListener(`cancel`,i),window.removeEventListener(`focus`,a),this._filePickerCleanup===o&&(this._filePickerCleanup=null)};this._filePickerCleanup=o,e.addEventListener(`change`,r,{once:!0}),e.addEventListener(`cancel`,i,{once:!0}),window.addEventListener(`focus`,a,{once:!0}),this._dispatchFilePickerEvent(`jant:file-picker-open`)}_isEmptyDoc(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0||e.content.every(e=>e.type===`hardBreak`)))}_normalizeDocJson(e){return e?this._isEmptyDoc(e)?null:e:null}getNormalizedBodyJson(){return this._normalizeDocJson(this._bodyJson)}getEffectiveAttachedTexts(){return this._attachedTexts.flatMap(e=>{let t=this._normalizeDocJson(e.bodyJson);return t?[{...e,bodyJson:t,originalBodyJson:this._normalizeDocJson(e.originalBodyJson??null)}]:[]})}getEffectiveAttachmentOrder(){let e=new Set(this.getEffectiveAttachedTexts().map(e=>e.clientId)),t=new Set(this._attachments.map(e=>e.clientId));return this._attachmentOrder.filter(n=>t.has(n)||e.has(n))}_getEffectiveRating(){return this._showRating?this._rating:0}getData(){let e=this.getNormalizedBodyJson(),t=this.getEffectiveAttachedTexts(),n=this.getEffectiveAttachmentOrder(),r=e?JSON.stringify(e):``,i={rating:this._getEffectiveRating(),attachedTexts:t,attachments:this._attachments,attachmentOrder:n};switch(this.format){case`link`:return{...i,title:this._title,body:r,url:this._url,quoteText:``,quoteAuthor:``};case`quote`:return{...i,title:``,body:r,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor};default:return{...i,title:this._showTitle?this._title:``,body:r,url:``,quoteText:``,quoteAuthor:``}}}reset(){this.#i(),this._title=``,this._bodyJson=null,this._editor?.commands.clearContent(),this._lastEditorSelection=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[];for(let e of this._attachments)URL.revokeObjectURL(e.previewUrl),e.posterUrl&&URL.revokeObjectURL(e.posterUrl);this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.closeEmojiPicker()}updateAttachmentStatus(e,t,n,r){this._attachments=this._attachments.map(i=>i.clientId===e?{...i,status:t,mediaId:n,error:r}:i)}updateAttachmentPreview(e,t){this._setAttachmentPreviewFailure(e,!1),this._attachments=this._attachments.map(n=>n.clientId===e?(URL.revokeObjectURL(n.previewUrl),n.posterUrl&&URL.revokeObjectURL(n.posterUrl),{...n,file:t,previewUrl:URL.createObjectURL(t),posterUrl:null}):n)}updateAttachmentPoster(e,t){let n=URL.createObjectURL(t);this._attachments=this._attachments.map(t=>t.clientId===e?{...t,posterUrl:n}:t)}updateAttachmentProgress(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?{...n,progress:t}:n)}focusInput(e){if(this.format===`link`){this.focusUrlInput(e);return}if(this.format===`quote`){this._focusTextControl(this.querySelector(`.compose-quote-text`),e);return}if(e){this._editor?.commands.focus(e);return}this._editor?.commands.focus()}focusSelection(e){if(this.format!==`note`||!this._editor){this.focusInput();return}let t=e??this.getEditorSelection();if(!t){this.focusInput();return}let n=tk(this._editor,t);this._lastEditorSelection=n,this._editor.chain().focus().setTextSelection(n).run()}focusUrlInput(e){this._focusTextControl(this.querySelector(`.compose-url-input`),e)}focusLinkTitleInput(e){this._focusTextControl(this.querySelector(`.compose-link-title`),e)}getUrlValidationMessage(){return this.format===`note`?null:this._url.trim()?r(this._url)?null:this.labels.urlInvalid:this.format===`link`?this.labels.linkUrlRequired:null}getLinkTitleValidationMessage(){return this.format===`link`?this._title.trim()?null:this.labels.linkTitleRequired:null}_getInlineUrlValidationMessage(){return this.format===`link`&&!this._url.trim()?null:this.getUrlValidationMessage()}_getInlineLinkTitleValidationMessage(){return this.format!==`link`||!this._title.trim()?null:this.getLinkTitleValidationMessage()}revealUrlValidation(){return this._showUrlValidation=!0,this.getUrlValidationMessage()}revealLinkTitleValidation(){return this._showLinkTitleValidation=!0,this.getLinkTitleValidationMessage()}getEditorSelection(){return this._readEditorSelection()??this._lastEditorSelection}isEmojiPickerOpen(){return this._showEmojiPicker}_readEditorSelection(){if(!this._editor)return null;let{from:e,to:t}=this._editor.state.selection;return{from:e,to:t}}_focusTextControl(e,t){if(!e||(e.focus(),!t))return;let n=t===`end`?e.value.length:0;e.setSelectionRange(n,n)}_initEditor(){let e=this.querySelector(`.compose-tiptap-body`);if(!e||this._editor)return;this.dataset.slashCommandDiscovered=this.slashCommandDiscovered?`true`:`false`,this._editor=MT({element:e,placeholder:this.format===`note`?this.labels.bodyPlaceholder:this.labels.thoughtsPlaceholder,content:this._bodyJson,toolbarMode:`compose`,onUpdate:e=>{this._bodyJson=e,this._ensureScrollBuffer(),WO(this)},onFocus:()=>{this._lastFocusedField=null,this._editor?.isEmpty&&KO(this)},onSelectionUpdate:e=>{this._lastEditorSelection=e},pasteMedia:{shouldInsertInline:e=>this._shouldPasteInlineImage(e),uploadInlineImage:e=>this._uploadAndInsertImage(e),onPasteFiles:e=>{this.addFiles(e)}}}),this._lastEditorSelection=this._readEditorSelection(),this._scrollBufferApplied=!1;let t=this._editor.view.dom;if(!this.closest(`.compose-page-shell`)){let e=t.lastElementChild,n=e?e.offsetTop+e.offsetHeight:0,r=this.format===`note`?120:60;t.style.minHeight=`${n+r}px`}}_ensureScrollBuffer(){if(this._scrollBufferApplied)return;let e=this._editor?.view?.dom;if(!e)return;let t=this.querySelector(`.compose-body`);t&&t.scrollHeight>t.clientHeight+20&&(e.style.paddingBottom=`40px`,this._scrollBufferApplied=!0)}_destroyEditor(){this.#i(),this._editor?.destroy(),this._editor=null}static _CONTENT_PROPS=new Set([`_title`,`_bodyJson`,`_url`,`_quoteText`,`_quoteAuthor`,`_rating`,`_showTitle`,`_showRating`,`_attachedTexts`,`_attachmentOrder`]);updated(t){super.updated(t),this._editor||this._initEditor(),t.has(`format`)&&t.get(`format`)!==void 0&&(this._showUrlValidation&&=!1,this._showLinkTitleValidation&&=!1,this._destroyEditor(),this.updateComplete.then(()=>this._initEditor())),(t.has(`_attachmentOrder`)||t.has(`_attachments`)||t.has(`_attachedTexts`))&&(t.has(`_attachments`)&&this._syncFailedAttachmentPreviews(),this._attachmentOrder.length>1?this.#a():(this.#n?.destroy(),this.#n=null));for(let n of t.keys())if(e._CONTENT_PROPS.has(n)){this.dispatchEvent(new Event(`jant:compose-content-changed`,{bubbles:!0}));break}}getEditorState(){return{json:this._editor?.getJSON()??this._bodyJson,title:this._title,showTitle:this._showTitle,selection:this.getEditorSelection()}}populate(e){if(e.title&&(this._title=e.title),e.url&&(this._url=e.url),e.quoteText&&(this._quoteText=e.quoteText),e.quoteAuthor&&(this._quoteAuthor=e.quoteAuthor),e.rating&&e.rating>0&&(this._rating=e.rating,this._showRating=!0),e.showTitle===void 0?e.title&&e.format===`note`&&(this._showTitle=!0):this._showTitle=e.showTitle,e.showRating!==void 0&&(this._showRating=e.showRating),this._failedAttachmentPreviews=[],e.bodyJson)try{let t=JSON.parse(e.bodyJson);this._bodyJson=t,this._editor&&this._editor.commands.setContent(t)}catch{}if(e.media?.length){let t=e.media.map(e=>({clientId:FT(),file:new File([],e.originalName??`existing`,{type:e.mimeType}),previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,status:`done`,progress:null,mediaId:e.id,alt:e.alt??``,error:null,summary:e.summary??null,chars:e.chars??null}));this._attachments=t,this._attachmentOrder=t.map(e=>e.clientId)}if(e.textAttachments?.length){let t=e.textAttachments.map(e=>{let t=null;try{t=JSON.parse(e.bodyJson)}catch{}return{clientId:e.clientId??FT(),bodyJson:t,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:t}});this._attachedTexts=t,this._attachmentOrder=[...this._attachmentOrder,...t.map(e=>e.clientId)]}if(e.attachmentOrder?.length){let t=e.attachmentOrder.map(e=>this._attachments.find(t=>t.mediaId===e||t.clientId===e)?.clientId||this._attachedTexts.find(t=>t.mediaId===e||t.clientId===e)?.clientId).filter(e=>e!==void 0),n=this._attachmentOrder.filter(e=>!t.includes(e));this._attachmentOrder=[...t,...n]}this._showUrlValidation=!1,this._showLinkTitleValidation=!1}setEditorState(e,t,n,r){this._bodyJson=e,this._title=t,this.format===`note`&&(this._showTitle=n||t.length>0),this._editor&&this._editor.commands.setContent(e??{type:`doc`,content:[{type:`paragraph`}]}),this._lastEditorSelection=r??this._readEditorSelection()}static SUMMARY_LENGTH=100;_computeSummary(t){let n=t.replace(/\s+/g,` `).trim();return n.length<=e.SUMMARY_LENGTH?n:n.slice(0,e.SUMMARY_LENGTH)+`…`}_openAttachedText(){let e={clientId:FT(),bodyJson:null,bodyHtml:``,summary:``};this._attachedTexts=[...this._attachedTexts,e],this._attachmentOrder=[...this._attachmentOrder,e.clientId];let t=this._attachedTexts.length-1;this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:t}}))}_moveAttachment(e,t){let n=this._attachmentOrder.indexOf(e),r=n+t;if(n===-1||r<0||r>=this._attachmentOrder.length)return;let i=[...this._attachmentOrder],[a]=i.splice(n,1);a&&(i.splice(r,0,a),this._attachmentOrder=i,this.#o(e))}_handleAttachmentKeydown(e,t,n){if(t.key===`ArrowLeft`||t.key===`ArrowUp`){t.preventDefault(),this._moveAttachment(e,-1);return}if(t.key===`ArrowRight`||t.key===`ArrowDown`){t.preventDefault(),this._moveAttachment(e,1);return}n&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n())}#a(){let e=this.querySelector(`[data-attachment-list]`);!e||this.#n||this._attachmentOrder.length<=1||(this.#n=H.create(e,{...yO,chosenClass:`compose-attachment-chosen`,direction:`horizontal`,dragClass:`compose-attachment-drag`,filter:`button, a, input, textarea, select, option, [contenteditable='true']`,ghostClass:`compose-attachment-ghost`,handle:`[data-attachment-sortable]`,preventOnFilter:!1,scroll:e,onChoose:()=>{CO(e,!0)},onStart:e=>{this.#r=xO(e)},onUnchoose:()=>{CO(e,!1)},onEnd:t=>{let n=bO(e,`[data-attachment-id]`,`attachmentId`);if(SO(e,t,this.#r),this.#r=null,CO(e,!1),this.#n?.destroy(),this.#n=null,n.length===this._attachmentOrder.length){this._attachmentOrder=n;let{movedId:e}=wO(n,t.newIndex);e&&(this._suppressAttachedTextOpenUntil=Date.now()+250,this.#o(e))}}}))}#o(e){this.updateComplete.then(()=>{this.querySelector(`[data-attachment-id="${e}"]`)?.scrollIntoView({behavior:`smooth`,block:`nearest`,inline:`nearest`})})}_maybeEditAttachedText(e){Date.now()<this._suppressAttachedTextOpenUntil||this._editAttachedText(e)}_editAttachedText(e){this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:e}}))}_removeAttachedText(e){let t=this._attachedTexts[e];this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}updateAttachedText(e,t,n){let r=this._normalizeDocJson(t),i=this._extractPlainText(r);this._attachedTexts=this._attachedTexts.map((t,a)=>a===e?{...t,bodyJson:r,bodyHtml:r?n??``:``,summary:this._computeSummary(i)}:t)}closeAttachedPanel(e){let t=this._attachedTexts[e];t&&(t.mediaId||this._hasAttachedTextContent(t.bodyJson)||(this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)))}_hasAttachedTextContent(e){let t=this._normalizeDocJson(e);return t?this._extractPlainText(t).trim().length>0:!1}_extractPlainText(e){if(!e)return``;let t=``,n=e=>{e.text&&(t+=e.text),e.content&&e.content.forEach(n)};return n(e),t}_onInput(e,t){let n=t.target;this[e]=n.value,n.tagName===`TEXTAREA`&&this._autoResize(n)}_autoResize(e){e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`}_setRating(e){this._rating=this._rating===e?0:e}_shouldPasteInlineImage(e){return!e.type.startsWith(`image/`)||this.format===`note`&&!this._showTitle?!1:this._title.trim().length>0}_openFilePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`*/*`,this._fileInput.multiple=!0,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>this._handleFilesSelected()),this.appendChild(this._fileInput)),this._fileInput.value=``,this._trackFilePickerSession(this._fileInput),this._fileInput.click()}_handleFilesSelected(){let e=this._fileInput?.files;!e||e.length===0||this.addFiles(e)}addFiles(e){let t=Array.from(e);if(t.length===0)return;let n=[],r=[];for(let e of t){let t=lS(e,{maxFileSizeMB:this.uploadMaxFileSize});if(t){d(t,`error`);continue}let i=FT(),a=URL.createObjectURL(e);n.push({clientId:i,file:e,previewUrl:a,posterUrl:null,status:`pending`,progress:null,mediaId:null,alt:``,error:null,summary:null,chars:null}),r.push({file:e,clientId:i})}if(n.length!==0){this._attachments=[...this._attachments,...n],this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)];for(let e of n)sS(e.file.type)===`text`&&e.file.text().then(t=>{let n=this._computeSummary(t),r=t.length;this._attachments=this._attachments.map(t=>t.clientId===e.clientId?{...t,summary:n,chars:r}:t)});this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:r}}))}}removeAttachment(e){let t=this._attachments.findIndex(t=>t.clientId===e);t!==-1&&this._removeAttachment(t)}_removeAttachment(e){let t=this._attachments[e];t&&(this._setAttachmentPreviewFailure(t.clientId,!1),URL.revokeObjectURL(t.previewUrl),t.posterUrl&&URL.revokeObjectURL(t.posterUrl),this.dispatchEvent(new CustomEvent(`jant:attachment-removed`,{bubbles:!0,detail:{clientId:t.clientId,mediaId:t.mediaId}}))),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)),this._attachments=this._attachments.filter((t,n)=>n!==e),this._showAltPanel&&this._altPanelIndex===e?(this._showAltPanel=!1,this.dispatchEvent(new CustomEvent(`jant:alt-panel-close`,{bubbles:!0}))):this._showAltPanel&&this._altPanelIndex>e&&--this._altPanelIndex}_retryAllFailed(){let e=this._attachments.filter(e=>e.status===`error`);e.length!==0&&(this._attachments=this._attachments.map(e=>e.status===`error`?{...e,status:`pending`,progress:null,error:null}:e),this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:e.map(e=>({file:e.file,clientId:e.clientId}))}})))}_openAltPanel(e){this._altPanelIndex=e,this._showAltPanel=!0,this.dispatchEvent(new CustomEvent(`jant:alt-panel-open`,{bubbles:!0,detail:{index:e}}))}updateAlt(e,t){this._attachments=this._attachments.map((n,r)=>r===e?{...n,alt:t}:n)}_onFieldFocus(e){this._lastFocusedField=e.target}_toggleEmojiPicker(){this._showEmojiPicker?this.closeEmojiPicker():(this._showEmojiPicker=!0,this._mountEmojiPicker(),globalThis.setTimeout(()=>{document.addEventListener(`click`,this._onDocClickBound)},0))}closeEmojiPicker(e){if(!this._showEmojiPicker){e?.restoreFocus&&this._restoreEmojiFocus();return}this._showEmojiPicker=!1,this._emojiContainer?.remove(),this._emojiPickerEl=null,document.removeEventListener(`click`,this._onDocClickBound),e?.restoreFocus&&this._restoreEmojiFocus()}_restoreEmojiFocus(){let e=this._lastFocusedField;if(e&&this.contains(e)&&!e.disabled){e.focus();return}this.focusSelection()}_onDocumentClick(e){let t=e.target;this.querySelector(`.compose-emoji-btn`)?.contains(t)||this._emojiContainer?.contains(t)||this.closeEmojiPicker()}async _mountEmojiPicker(){let e=this.closest(`dialog`);if(this._emojiContainer||(this._emojiContainer=document.createElement(`div`),this._emojiContainer.className=`compose-emoji-picker`),(e??document.body).appendChild(this._emojiContainer),!this._emojiPickerEl){let[{default:e},{Picker:t}]=await Promise.all([ZO(()=>import(`./chunks/native-DpcrFAPh.js`),[]),ZO(()=>import(`./chunks/module-DcsAZQZ_.js`),[])]);if(!this._showEmojiPicker)return;this._emojiPickerEl=new t({data:e,onEmojiSelect:e=>{this._insertEmoji(e.native),this.closeEmojiPicker()},theme:`auto`,previewPosition:`none`,skinTonePosition:`none`})}this._emojiContainer.innerHTML=``,this._emojiContainer.appendChild(this._emojiPickerEl);let t=this.querySelector(`.compose-emoji-btn`);if(t&&e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=n.left-r.left,a=n.top-r.top,o=i+n.width/2-352/2;o=Math.max(-r.left+8,Math.min(o,r.width-8));let s=a-435-8;r.top+s<8&&(s=a+n.height+8),this._emojiContainer.style.left=`${o}px`,this._emojiContainer.style.top=`${s}px`}}_insertEmoji(e){let t=this._lastFocusedField;if(!t){this._editor&&this._editor.chain().focus().insertContent(e).run();return}let n=t.selectionStart??t.value.length,r=t.selectionEnd??n,i=t.value.slice(0,n),a=t.value.slice(r);t.value=i+e+a,t.dispatchEvent(new Event(`input`,{bubbles:!0}));let o=n+e.length;globalThis.requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(o,o)})}_getCategory(e){return sS(e.file.type)}_formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}_formatChars(e){return e<1e3?`${e} chars`:e<1e6?`${parseFloat((e/1e3).toFixed(1))}k chars`:`${parseFloat((e/1e6).toFixed(1))}M chars`}_renderFileIcon(e,t){let n;return n=e===`application/pdf`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`:e===`text/markdown`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`:e===`text/csv`?`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`:sS(e)===`archive`?`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`:e===`text/html; charset=utf-8`?`<line x1="16" y1="11" x2="8" y2="11"/><line x1="16" y1="14" x2="8" y2="14"/><line x1="12" y1="17" x2="8" y2="17"/>`:`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`,u`<svg
1460
+ </span>`}function tk(e,t){let n=e.state.doc.content.size,r=Math.max(1,Math.min(t.from,n));return{from:r,to:Math.max(r,Math.min(t.to,n))}}var nk=class e extends c{static properties={format:{type:String},labels:{type:Object},uploadMaxFileSize:{type:Number},threadItem:{type:Boolean,attribute:`thread-item`},removable:{type:Boolean},slashCommandDiscovered:{type:Boolean},_title:{state:!0},_bodyJson:{state:!0},_url:{state:!0},_quoteText:{state:!0},_quoteAuthor:{state:!0},_rating:{state:!0},_showTitle:{state:!0},_showRating:{state:!0},_attachedTexts:{state:!0},_attachments:{state:!0},_attachmentOrder:{state:!0},_failedAttachmentPreviews:{state:!0},_showAltPanel:{state:!0},_altPanelIndex:{state:!0},_showEmojiPicker:{state:!0},_showUrlValidation:{state:!0},_showLinkTitleValidation:{state:!0}};_editor=null;_fileInput=null;_lastFocusedField=null;_lastEditorSelection=null;_emojiPickerEl=null;_emojiContainer=null;_urlStatusId=`compose-url-status-${FT()}`;_onDocClickBound=this._onDocumentClick.bind(this);_scrollBufferApplied=!1;_filePickerCleanup=null;_suppressAttachedTextOpenUntil=0;#e=0;#t=new Set;#n=null;#r=null;createRenderRoot(){return this}constructor(){super(),this.format=`note`,this.labels={},this.uploadMaxFileSize=500,this.threadItem=!1,this.removable=!1,this.slashCommandDiscovered=!1,this._title=``,this._bodyJson=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[],this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showEmojiPicker=!1,this._showUrlValidation=!1,this._showLinkTitleValidation=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),this.addEventListener(`dragenter`,this._onDragEnter),this.addEventListener(`dragover`,this._onDragOver,!0),this.addEventListener(`dragleave`,this._onDragLeave),this.addEventListener(`drop`,this._onDrop)}disconnectedCallback(){super.disconnectedCallback(),this.#o(),this._editor?.destroy(),this._editor=null,this.#n?.destroy(),this.#n=null,document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),document.removeEventListener(`click`,this._onDocClickBound),this.removeEventListener(`dragenter`,this._onDragEnter),this.removeEventListener(`dragover`,this._onDragOver,!0),this.removeEventListener(`dragleave`,this._onDragLeave),this.removeEventListener(`drop`,this._onDrop),WO(this),this._emojiContainer?.remove(),this._emojiPickerEl=null,this._filePickerCleanup?.(),this._filePickerCleanup=null}#i=0;#a(e){let t=e.dataTransfer?.types;return t?Array.from(t).includes(`Files`):!1}_onDragEnter=e=>{this.#a(e)&&(this.#i+=1,this.classList.add(`compose-editor-dragover`))};_onDragOver=e=>{this.#a(e)&&(e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`))};_onDragLeave=e=>{this.#a(e)&&(this.#i=Math.max(0,this.#i-1),this.#i===0&&this.classList.remove(`compose-editor-dragover`))};_onDrop=e=>{if(this.#i=0,this.classList.remove(`compose-editor-dragover`),e.defaultPrevented)return;let t=aw(e.dataTransfer);if(t.length===0)return;e.preventDefault();let n=[],r=[];for(let e of t)this._editor&&this._shouldPasteInlineImage(e)?n.push(e):r.push(e);for(let e of n)this._uploadAndInsertImage(e);r.length>0&&this.addFiles(r)};_onSlashCommandDiscovered=()=>{qO()};_onSlashImage=()=>{document.querySelector(`.compose-fullscreen-dialog[open]`)||this._editor&&this._triggerSlashImagePicker()};_slashImageInput=null;_triggerSlashImagePicker(){this._slashImageInput||(this._slashImageInput=document.createElement(`input`),this._slashImageInput.type=`file`,this._slashImageInput.accept=`image/*`,this._slashImageInput.style.display=`none`,this._slashImageInput.addEventListener(`change`,()=>{let e=this._slashImageInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._slashImageInput&&(this._slashImageInput.value=``)}),document.body.appendChild(this._slashImageInput)),this._trackFilePickerSession(this._slashImageInput),this._slashImageInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=this.#e,r=QC(t,e).finally(()=>{n===this.#e&&this.#t.delete(r)});return this.#t.add(r),r}hasPendingInlineImageUploads(){return this.#t.size>0}async waitForPendingInlineImageUploads(){let e=this.#e;for(;e===this.#e&&this.#t.size>0;)await Promise.allSettled(Array.from(this.#t))}#o(){this.#e+=1,this.#t.clear()}adoptPendingUploads(){if(!this._editor)return;let e=this.#e,t=$C(this._editor);for(let n of t){let t=n.finally(()=>{e===this.#e&&this.#t.delete(t)});this.#t.add(t)}}_dispatchFilePickerEvent(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_trackFilePickerSession(e){this._filePickerCleanup?.();let t=!1,n=e=>{t||(t=!0,o(),this._dispatchFilePickerEvent(`jant:file-picker-close`,{cancelled:e}))},r=()=>n(!1),i=()=>n(!0),a=()=>{globalThis.setTimeout(()=>{n(!(e.files&&e.files.length>0))},0)},o=()=>{e.removeEventListener(`change`,r),e.removeEventListener(`cancel`,i),window.removeEventListener(`focus`,a),this._filePickerCleanup===o&&(this._filePickerCleanup=null)};this._filePickerCleanup=o,e.addEventListener(`change`,r,{once:!0}),e.addEventListener(`cancel`,i,{once:!0}),window.addEventListener(`focus`,a,{once:!0}),this._dispatchFilePickerEvent(`jant:file-picker-open`)}_isEmptyDoc(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0||e.content.every(e=>e.type===`hardBreak`)))}_normalizeDocJson(e){return e?this._isEmptyDoc(e)?null:e:null}getNormalizedBodyJson(){return this._normalizeDocJson(this._bodyJson)}getEffectiveAttachedTexts(){return this._attachedTexts.flatMap(e=>{let t=this._normalizeDocJson(e.bodyJson);return t?[{...e,bodyJson:t,originalBodyJson:this._normalizeDocJson(e.originalBodyJson??null)}]:[]})}getEffectiveAttachmentOrder(){let e=new Set(this.getEffectiveAttachedTexts().map(e=>e.clientId)),t=new Set(this._attachments.map(e=>e.clientId));return this._attachmentOrder.filter(n=>t.has(n)||e.has(n))}_getEffectiveRating(){return this._showRating?this._rating:0}getData(){let e=this.getNormalizedBodyJson(),t=this.getEffectiveAttachedTexts(),n=this.getEffectiveAttachmentOrder(),r=e?JSON.stringify(e):``,i={rating:this._getEffectiveRating(),attachedTexts:t,attachments:this._attachments,attachmentOrder:n};switch(this.format){case`link`:return{...i,title:this._title,body:r,url:this._url,quoteText:``,quoteAuthor:``};case`quote`:return{...i,title:``,body:r,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor};default:return{...i,title:this._showTitle?this._title:``,body:r,url:``,quoteText:``,quoteAuthor:``}}}reset(){this.#o(),this._title=``,this._bodyJson=null,this._editor?.commands.clearContent(),this._lastEditorSelection=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[];for(let e of this._attachments)URL.revokeObjectURL(e.previewUrl),e.posterUrl&&URL.revokeObjectURL(e.posterUrl);this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.closeEmojiPicker()}updateAttachmentStatus(e,t,n,r){this._attachments=this._attachments.map(i=>i.clientId===e?{...i,status:t,mediaId:n,error:r}:i)}updateAttachmentPreview(e,t){this._setAttachmentPreviewFailure(e,!1),this._attachments=this._attachments.map(n=>n.clientId===e?(URL.revokeObjectURL(n.previewUrl),n.posterUrl&&URL.revokeObjectURL(n.posterUrl),{...n,file:t,previewUrl:URL.createObjectURL(t),posterUrl:null}):n)}updateAttachmentPoster(e,t){let n=URL.createObjectURL(t);this._attachments=this._attachments.map(t=>t.clientId===e?{...t,posterUrl:n}:t)}updateAttachmentProgress(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?{...n,progress:t}:n)}focusInput(e){if(this.format===`link`){this.focusUrlInput(e);return}if(this.format===`quote`){this._focusTextControl(this.querySelector(`.compose-quote-text`),e);return}if(e){this._editor?.commands.focus(e);return}this._editor?.commands.focus()}focusSelection(e){if(this.format!==`note`||!this._editor){this.focusInput();return}let t=e??this.getEditorSelection();if(!t){this.focusInput();return}let n=tk(this._editor,t);this._lastEditorSelection=n,this._editor.chain().focus().setTextSelection(n).run()}focusUrlInput(e){this._focusTextControl(this.querySelector(`.compose-url-input`),e)}focusLinkTitleInput(e){this._focusTextControl(this.querySelector(`.compose-link-title`),e)}getUrlValidationMessage(){return this.format===`note`?null:this._url.trim()?r(this._url)?null:this.labels.urlInvalid:this.format===`link`?this.labels.linkUrlRequired:null}getLinkTitleValidationMessage(){return this.format===`link`?this._title.trim()?null:this.labels.linkTitleRequired:null}_getInlineUrlValidationMessage(){return this.format===`link`&&!this._url.trim()?null:this.getUrlValidationMessage()}_getInlineLinkTitleValidationMessage(){return this.format!==`link`||!this._title.trim()?null:this.getLinkTitleValidationMessage()}revealUrlValidation(){return this._showUrlValidation=!0,this.getUrlValidationMessage()}revealLinkTitleValidation(){return this._showLinkTitleValidation=!0,this.getLinkTitleValidationMessage()}getEditorSelection(){return this._readEditorSelection()??this._lastEditorSelection}isEmojiPickerOpen(){return this._showEmojiPicker}_readEditorSelection(){if(!this._editor)return null;let{from:e,to:t}=this._editor.state.selection;return{from:e,to:t}}_focusTextControl(e,t){if(!e||(e.focus(),!t))return;let n=t===`end`?e.value.length:0;e.setSelectionRange(n,n)}_initEditor(){let e=this.querySelector(`.compose-tiptap-body`);if(!e||this._editor)return;this.dataset.slashCommandDiscovered=this.slashCommandDiscovered?`true`:`false`,this._editor=MT({element:e,placeholder:this.format===`note`?this.labels.bodyPlaceholder:this.labels.thoughtsPlaceholder,content:this._bodyJson,toolbarMode:`compose`,onUpdate:e=>{this._bodyJson=e,this._ensureScrollBuffer(),WO(this)},onFocus:()=>{this._lastFocusedField=null,this._editor?.isEmpty&&KO(this)},onSelectionUpdate:e=>{this._lastEditorSelection=e},pasteMedia:{shouldInsertInline:e=>this._shouldPasteInlineImage(e),uploadInlineImage:e=>this._uploadAndInsertImage(e),onPasteFiles:e=>{this.addFiles(e)}}}),this._lastEditorSelection=this._readEditorSelection(),this._scrollBufferApplied=!1;let t=this._editor.view.dom;if(!this.closest(`.compose-page-shell`)){let e=t.lastElementChild,n=e?e.offsetTop+e.offsetHeight:0,r=this.format===`note`?120:60;t.style.minHeight=`${n+r}px`}}_ensureScrollBuffer(){if(this._scrollBufferApplied)return;let e=this._editor?.view?.dom;if(!e)return;let t=this.querySelector(`.compose-body`);t&&t.scrollHeight>t.clientHeight+20&&(e.style.paddingBottom=`40px`,this._scrollBufferApplied=!0)}_destroyEditor(){this.#o(),this._editor?.destroy(),this._editor=null}static _CONTENT_PROPS=new Set([`_title`,`_bodyJson`,`_url`,`_quoteText`,`_quoteAuthor`,`_rating`,`_showTitle`,`_showRating`,`_attachedTexts`,`_attachmentOrder`]);updated(t){super.updated(t),this._editor||this._initEditor(),t.has(`format`)&&t.get(`format`)!==void 0&&(this._showUrlValidation&&=!1,this._showLinkTitleValidation&&=!1,this._destroyEditor(),this.updateComplete.then(()=>this._initEditor())),(t.has(`_attachmentOrder`)||t.has(`_attachments`)||t.has(`_attachedTexts`))&&(t.has(`_attachments`)&&this._syncFailedAttachmentPreviews(),this._attachmentOrder.length>1?this.#s():(this.#n?.destroy(),this.#n=null));for(let n of t.keys())if(e._CONTENT_PROPS.has(n)){this.dispatchEvent(new Event(`jant:compose-content-changed`,{bubbles:!0}));break}}getEditorState(){return{json:this._editor?.getJSON()??this._bodyJson,title:this._title,showTitle:this._showTitle,selection:this.getEditorSelection()}}populate(e){if(e.title&&(this._title=e.title),e.url&&(this._url=e.url),e.quoteText&&(this._quoteText=e.quoteText),e.quoteAuthor&&(this._quoteAuthor=e.quoteAuthor),e.rating&&e.rating>0&&(this._rating=e.rating,this._showRating=!0),e.showTitle===void 0?e.title&&e.format===`note`&&(this._showTitle=!0):this._showTitle=e.showTitle,e.showRating!==void 0&&(this._showRating=e.showRating),this._failedAttachmentPreviews=[],e.bodyJson)try{let t=JSON.parse(e.bodyJson);this._bodyJson=t,this._editor&&this._editor.commands.setContent(t)}catch{}if(e.media?.length){let t=e.media.map(e=>({clientId:FT(),file:new File([],e.originalName??`existing`,{type:e.mimeType}),previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,status:`done`,progress:null,mediaId:e.id,alt:e.alt??``,error:null,summary:e.summary??null,chars:e.chars??null}));this._attachments=t,this._attachmentOrder=t.map(e=>e.clientId)}if(e.textAttachments?.length){let t=e.textAttachments.map(e=>{let t=null;try{t=JSON.parse(e.bodyJson)}catch{}return{clientId:e.clientId??FT(),bodyJson:t,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:t}});this._attachedTexts=t,this._attachmentOrder=[...this._attachmentOrder,...t.map(e=>e.clientId)]}if(e.attachmentOrder?.length){let t=e.attachmentOrder.map(e=>this._attachments.find(t=>t.mediaId===e||t.clientId===e)?.clientId||this._attachedTexts.find(t=>t.mediaId===e||t.clientId===e)?.clientId).filter(e=>e!==void 0),n=this._attachmentOrder.filter(e=>!t.includes(e));this._attachmentOrder=[...t,...n]}this._showUrlValidation=!1,this._showLinkTitleValidation=!1}setEditorState(e,t,n,r){this._bodyJson=e,this._title=t,this.format===`note`&&(this._showTitle=n||t.length>0),this._editor&&this._editor.commands.setContent(e??{type:`doc`,content:[{type:`paragraph`}]}),this._lastEditorSelection=r??this._readEditorSelection()}static SUMMARY_LENGTH=100;_computeSummary(t){let n=t.replace(/\s+/g,` `).trim();return n.length<=e.SUMMARY_LENGTH?n:n.slice(0,e.SUMMARY_LENGTH)+`…`}_openAttachedText(){let e={clientId:FT(),bodyJson:null,bodyHtml:``,summary:``};this._attachedTexts=[...this._attachedTexts,e],this._attachmentOrder=[...this._attachmentOrder,e.clientId];let t=this._attachedTexts.length-1;this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:t}}))}_moveAttachment(e,t){let n=this._attachmentOrder.indexOf(e),r=n+t;if(n===-1||r<0||r>=this._attachmentOrder.length)return;let i=[...this._attachmentOrder],[a]=i.splice(n,1);a&&(i.splice(r,0,a),this._attachmentOrder=i,this.#c(e))}_handleAttachmentKeydown(e,t,n){if(t.key===`ArrowLeft`||t.key===`ArrowUp`){t.preventDefault(),this._moveAttachment(e,-1);return}if(t.key===`ArrowRight`||t.key===`ArrowDown`){t.preventDefault(),this._moveAttachment(e,1);return}n&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n())}#s(){let e=this.querySelector(`[data-attachment-list]`);!e||this.#n||this._attachmentOrder.length<=1||(this.#n=H.create(e,{...yO,chosenClass:`compose-attachment-chosen`,direction:`horizontal`,dragClass:`compose-attachment-drag`,filter:`button, a, input, textarea, select, option, [contenteditable='true']`,ghostClass:`compose-attachment-ghost`,handle:`[data-attachment-sortable]`,preventOnFilter:!1,scroll:e,onChoose:()=>{CO(e,!0)},onStart:e=>{this.#r=xO(e)},onUnchoose:()=>{CO(e,!1)},onEnd:t=>{let n=bO(e,`[data-attachment-id]`,`attachmentId`);if(SO(e,t,this.#r),this.#r=null,CO(e,!1),this.#n?.destroy(),this.#n=null,n.length===this._attachmentOrder.length){this._attachmentOrder=n;let{movedId:e}=wO(n,t.newIndex);e&&(this._suppressAttachedTextOpenUntil=Date.now()+250,this.#c(e))}}}))}#c(e){this.updateComplete.then(()=>{this.querySelector(`[data-attachment-id="${e}"]`)?.scrollIntoView({behavior:`smooth`,block:`nearest`,inline:`nearest`})})}_maybeEditAttachedText(e){Date.now()<this._suppressAttachedTextOpenUntil||this._editAttachedText(e)}_editAttachedText(e){this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:e}}))}_removeAttachedText(e){let t=this._attachedTexts[e];this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}updateAttachedText(e,t,n){let r=this._normalizeDocJson(t),i=this._extractPlainText(r);this._attachedTexts=this._attachedTexts.map((t,a)=>a===e?{...t,bodyJson:r,bodyHtml:r?n??``:``,summary:this._computeSummary(i)}:t)}closeAttachedPanel(e){let t=this._attachedTexts[e];t&&(t.mediaId||this._hasAttachedTextContent(t.bodyJson)||(this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)))}_hasAttachedTextContent(e){let t=this._normalizeDocJson(e);return t?this._extractPlainText(t).trim().length>0:!1}_extractPlainText(e){if(!e)return``;let t=``,n=e=>{e.text&&(t+=e.text),e.content&&e.content.forEach(n)};return n(e),t}_onInput(e,t){let n=t.target;this[e]=n.value,n.tagName===`TEXTAREA`&&this._autoResize(n)}_autoResize(e){e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`}_setRating(e){this._rating=this._rating===e?0:e}_shouldPasteInlineImage(e){return!e.type.startsWith(`image/`)||this.format===`note`&&!this._showTitle?!1:this._title.trim().length>0}_openFilePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`*/*`,this._fileInput.multiple=!0,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>this._handleFilesSelected()),this.appendChild(this._fileInput)),this._fileInput.value=``,this._trackFilePickerSession(this._fileInput),this._fileInput.click()}_handleFilesSelected(){let e=this._fileInput?.files;!e||e.length===0||this.addFiles(e)}addFiles(e){let t=Array.from(e);if(t.length===0)return;let n=[],r=[];for(let e of t){let t=lS(e,{maxFileSizeMB:this.uploadMaxFileSize});if(t){d(t,`error`);continue}let i=FT(),a=URL.createObjectURL(e);n.push({clientId:i,file:e,previewUrl:a,posterUrl:null,status:`pending`,progress:null,mediaId:null,alt:``,error:null,summary:null,chars:null}),r.push({file:e,clientId:i})}if(n.length!==0){this._attachments=[...this._attachments,...n],this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)];for(let e of n)sS(e.file.type)===`text`&&e.file.text().then(t=>{let n=this._computeSummary(t),r=t.length;this._attachments=this._attachments.map(t=>t.clientId===e.clientId?{...t,summary:n,chars:r}:t)});this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:r}}))}}removeAttachment(e){let t=this._attachments.findIndex(t=>t.clientId===e);t!==-1&&this._removeAttachment(t)}_removeAttachment(e){let t=this._attachments[e];t&&(this._setAttachmentPreviewFailure(t.clientId,!1),URL.revokeObjectURL(t.previewUrl),t.posterUrl&&URL.revokeObjectURL(t.posterUrl),this.dispatchEvent(new CustomEvent(`jant:attachment-removed`,{bubbles:!0,detail:{clientId:t.clientId,mediaId:t.mediaId}}))),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)),this._attachments=this._attachments.filter((t,n)=>n!==e),this._showAltPanel&&this._altPanelIndex===e?(this._showAltPanel=!1,this.dispatchEvent(new CustomEvent(`jant:alt-panel-close`,{bubbles:!0}))):this._showAltPanel&&this._altPanelIndex>e&&--this._altPanelIndex}_retryAllFailed(){let e=this._attachments.filter(e=>e.status===`error`);e.length!==0&&(this._attachments=this._attachments.map(e=>e.status===`error`?{...e,status:`pending`,progress:null,error:null}:e),this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:e.map(e=>({file:e.file,clientId:e.clientId}))}})))}_openAltPanel(e){this._altPanelIndex=e,this._showAltPanel=!0,this.dispatchEvent(new CustomEvent(`jant:alt-panel-open`,{bubbles:!0,detail:{index:e}}))}updateAlt(e,t){this._attachments=this._attachments.map((n,r)=>r===e?{...n,alt:t}:n)}_onFieldFocus(e){this._lastFocusedField=e.target}_toggleEmojiPicker(){this._showEmojiPicker?this.closeEmojiPicker():(this._showEmojiPicker=!0,this._mountEmojiPicker(),globalThis.setTimeout(()=>{document.addEventListener(`click`,this._onDocClickBound)},0))}closeEmojiPicker(e){if(!this._showEmojiPicker){e?.restoreFocus&&this._restoreEmojiFocus();return}this._showEmojiPicker=!1,this._emojiContainer?.remove(),this._emojiPickerEl=null,document.removeEventListener(`click`,this._onDocClickBound),e?.restoreFocus&&this._restoreEmojiFocus()}_restoreEmojiFocus(){let e=this._lastFocusedField;if(e&&this.contains(e)&&!e.disabled){e.focus();return}this.focusSelection()}_onDocumentClick(e){let t=e.target;this.querySelector(`.compose-emoji-btn`)?.contains(t)||this._emojiContainer?.contains(t)||this.closeEmojiPicker()}async _mountEmojiPicker(){let e=this.closest(`dialog`);if(this._emojiContainer||(this._emojiContainer=document.createElement(`div`),this._emojiContainer.className=`compose-emoji-picker`),(e??document.body).appendChild(this._emojiContainer),!this._emojiPickerEl){let[{default:e},{Picker:t}]=await Promise.all([ZO(()=>import(`./chunks/native-DpcrFAPh.js`),[]),ZO(()=>import(`./chunks/module-DcsAZQZ_.js`),[])]);if(!this._showEmojiPicker)return;this._emojiPickerEl=new t({data:e,onEmojiSelect:e=>{this._insertEmoji(e.native),this.closeEmojiPicker()},theme:`auto`,previewPosition:`none`,skinTonePosition:`none`})}this._emojiContainer.innerHTML=``,this._emojiContainer.appendChild(this._emojiPickerEl);let t=this.querySelector(`.compose-emoji-btn`);if(t&&e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=n.left-r.left,a=n.top-r.top,o=i+n.width/2-352/2;o=Math.max(-r.left+8,Math.min(o,r.width-8));let s=a-435-8;r.top+s<8&&(s=a+n.height+8),this._emojiContainer.style.left=`${o}px`,this._emojiContainer.style.top=`${s}px`}}_insertEmoji(e){let t=this._lastFocusedField;if(!t){this._editor&&this._editor.chain().focus().insertContent(e).run();return}let n=t.selectionStart??t.value.length,r=t.selectionEnd??n,i=t.value.slice(0,n),a=t.value.slice(r);t.value=i+e+a,t.dispatchEvent(new Event(`input`,{bubbles:!0}));let o=n+e.length;globalThis.requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(o,o)})}_getCategory(e){return sS(e.file.type)}_formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}_formatChars(e){return e<1e3?`${e} chars`:e<1e6?`${parseFloat((e/1e3).toFixed(1))}k chars`:`${parseFloat((e/1e6).toFixed(1))}M chars`}_renderFileIcon(e,t){let n;return n=e===`application/pdf`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`:e===`text/markdown`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`:e===`text/csv`?`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`:sS(e)===`archive`?`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`:e===`text/html; charset=utf-8`?`<line x1="16" y1="11" x2="8" y2="11"/><line x1="16" y1="14" x2="8" y2="14"/><line x1="12" y1="17" x2="8" y2="17"/>`:`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`,u`<svg
1461
1461
  width="${t}"
1462
1462
  height="${t}"
1463
1463
  viewBox="0 0 24 24"
@@ -2191,7 +2191,7 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
2191
2191
  The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),t.includes(`flac`)&&e.push(`
2192
2192
  The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
2193
2193
  Check the discardedTracks field for more info.`)}return e}async execute(){if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
2194
- `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(e=>e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new lR;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=ak(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&yM(l,s,c);let[u,d]=l?[l.width,l.height]:[s,c],f=u,p=d,m=f/p,h=e=>Math.ceil(e/2)*2;t.width!==void 0&&t.height===void 0?(f=h(t.width),p=h(Math.round(f/m))):t.width===void 0&&t.height!==void 0?(p=h(t.height),f=h(Math.round(p*m))):t.width!==void 0&&t.height!==void 0&&(f=h(t.width),p=h(t.height));let g=await e.getFirstTimestamp(),_=this.output.format.getSupportedVideoCodecs(),v=!!t.forceTranscode||g<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!_.includes(n)||t.codec&&t.codec!==n||f!==u||p!==d||i!==0&&!o||!!l,y=t.alpha??`discard`;if(v){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}t.codec&&(_=_.filter(e=>e===t.codec));let n=t.bitrate??zL,s=await UL(_,{width:t.process&&t.processedWidth?t.processedWidth:f,height:t.process&&t.processedHeight?t.processedHeight:p,bitrate:n});if(!s){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}let c={codec:s,bitrate:n,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:y,hardwareAcceleration:t.hardwareAcceleration},m=new YL(c);r=m;let h=f!==u||p!==d||i!==0&&(!o||t.process!==void 0)||!!l||e.squarePixelWidth!==e.codedWidth||e.squarePixelHeight!==e.codedHeight;if(!h){let t=new rR({format:new AL,target:new SL}),n=new YL(c);t.addVideoTrack(n),await t.start();let r=await new VM(e).getSample(g);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),h=!0,t.cancel()}else await t.cancel()}h?this._trackPromises.push((async()=>{await this._started;let n=new HM(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new gM(o,{timestamp:s+n/r,duration:1/r});await this._registerVideoSample(e,t,m,i),i.close()}};for await(let{canvas:i,timestamp:a,duration:u}of n){if(this._canceled)return;let n=Math.max(a-this._startTimestamp,0);if(c=n+u,r!==void 0){let e=Math.floor(n*r)/r;if(o!==null)if(e<=s){o=i,s=e;continue}else await l(e);n=e}let d=new gM(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(U(c!==null),U(r!==void 0),await l(Math.floor(c*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let n=new VM(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{U(i),U(r!==void 0);let o=Math.round((n-a)*r);for(let n=1;n<o;n++)i.setTimestamp(a+n/r),i.setDuration(1/r),await this._registerVideoSample(e,t,m,i);i.close()};for await(let c of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){c.close(),i?.close();return}let n=Math.max(c.timestamp-this._startTimestamp,0);if(o=n+c.duration,r!==void 0){let e=Math.floor(n*r)/r;if(i!==null)if(e<=a){i.close(),i=c,a=e;continue}else await s(e);n=e,c.setDuration(1/r)}c.setTimestamp(n),await this._registerVideoSample(e,t,m,c),r===void 0?c.close():(i=c,a=n)}i&&(U(o!==null),U(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new KL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new FM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:Gk(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),i=e.map(e=>e instanceof gM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new gM(e):new gM(e,{timestamp:r.timestamp,duration:r.duration}))}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}async _processAudioTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp(),s=t.numberOfChannels??i,c=t.sampleRate??a,l=s!==i||c!==a||o<this._startTimestamp||o>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,u=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!l&&u.includes(n)&&(!t.codec||t.codec===n)&&!t.process){let t=new ZL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new FM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}let n=null;t.codec&&(u=u.filter(e=>e===t.codec));let i=t.bitrate??zL,a=await HL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>CA.includes(e))&&u.some(e=>CA.includes(e))&&(s!==oR||c!==sR)){let e=(await HL(u,{numberOfChannels:oR,sampleRate:sR,bitrate:i})).find(e=>CA.includes(e));e&&(l=!0,n=e,s=oR,c=sR)}else n=a[0]??null;if(n===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}if(l)r=this._resampleAudio(e,t,n,s,c,i);else{let a=new $L({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new GM(e);for await(let r of n.samples(void 0,this._endTimestamp)){if(this._canceled){r.close();return}r.setTimestamp(r.timestamp-this._startTimestamp),await this._registerAudioSample(e,t,a,r),r.close()}a.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:Gk(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),!e.every(e=>e instanceof TM))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);i=e}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}_resampleAudio(e,t,n,r,i,a){let o=new $L({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new fR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new GM(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=zk(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},lR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},uR=5,dR=class{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<uR&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){return this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0)),t-this.computeMinAndMaybeResolve()>=uR}wait(e){let{promise:t,resolve:n}=Ok();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},fR=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){U(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+a,this.endTime-this.startTime),s=Math.floor(i*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;U(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new TM({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};function pR(){return typeof AudioEncoder<`u`}async function mR(e,t){let n=new eF({source:new XP(e),formats:JP}),r=new xL,i=new rR({format:new AL({fastStart:`in-memory`}),target:r});try{let a=await cR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:zL}});t&&(a.onProgress=t),await a.execute();let o=r.buffer;if(!o)throw Error(`Audio processing produced no output`);let s=e.name.replace(/\.[^.]+$/,``);return{file:new File([o],`${s}.m4a`,{type:`audio/mp4`})}}finally{n.dispose()}}var hR={isSupported:pR,processToFile:mR},gR=1920,_R=1080,vR=640,yR=32;function bR(){return typeof VideoEncoder<`u`}async function xR(e){let t=new eF({source:new XP(e),formats:JP});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=s(a),c=Math.min(a*.1,3),l=await new HM(e).getCanvas(c);if(!l)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=l.canvas,d=u.width,f=u.height,p=Math.min(vR/d,1),m=Math.round(d*p),h=Math.round(f*p),g=document.createElement(`canvas`);g.width=m,g.height=h;let _=g.getContext(`2d`);if(!_)return{sourceWidth:n,sourceHeight:r};_.drawImage(u,0,0,m,h);let v=await new Promise(e=>{g.toBlob(t=>e(t??void 0),`image/webp`,.8)}),y=Math.min(yR/d,yR/f,1),b=Math.max(Math.round(d*y),1),x=Math.max(Math.round(f*y),1),S=document.createElement(`canvas`);S.width=b,S.height=x;let C=S.getContext(`2d`);return C?(C.drawImage(u,0,0,b,x),{poster:v,blurhash:AC(C.getImageData(0,0,b,x).data,b,x,4,3),sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o}):{poster:v,sourceWidth:n,sourceHeight:r}}catch{return{}}finally{t.dispose()}}async function SR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await xR(e),c=i||gR,l=a||_R;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(gR/e,_R/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new eF({source:new XP(e),formats:JP}),d=new xL,f=new rR({format:new AL({fastStart:`in-memory`}),target:d});try{let i=await cR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:zL},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ER(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&(TR(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ER(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var CR=[65536,0,0,0,65536,0,0,0,1073741824];function wR(e,t,n,r){let i=t;for(;i+8<=n;){let t=e.getUint32(i),a=String.fromCharCode(e.getUint8(i+4),e.getUint8(i+5),e.getUint8(i+6),e.getUint8(i+7));if(t===0&&(t=n-i),t<8||i+t>n)break;r(i,t,a),(a===`moov`||a===`trak`||a===`mdia`||a===`edts`)&&wR(e,i+8,i+t,r),i+=t}}function TR(e){let t=new DataView(e);wR(t,0,e.byteLength,(n,r,i)=>{if(i!==`tkhd`)return;let a=n+8,o=a+(t.getUint8(a)===0?40:52);if(o+36>e.byteLength)return;let s=!0;for(let e=0;e<9;e++)if(t.getInt32(o+e*4)!==CR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,CR[e])})}function ER(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=document.createElement(`video`);i.preload=`metadata`,i.onloadedmetadata=()=>{URL.revokeObjectURL(r),t({width:i.videoWidth,height:i.videoHeight})},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(`Failed to probe transcoded video dimensions`))},i.src=r})}var DR={isSupported:bR,processToFile:SR};function OR(){return document.querySelector(`jant-compose-dialog`)}function kR(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function AR(e=document){if(e===document){let e=document.querySelector(`[data-page='post'] article[data-post]:hover`);if(e)return e}return e.querySelector(`[data-post-current] article[data-post]`)||e.querySelector(`[data-post-view] article[data-post]`)||(e===document?document.querySelector(`article[data-post]:hover`):null)}function jR(e){let t=e.closest(`[data-post-view]`)?.dataset.postViewId;if(t)return{kind:`post-view`,id:t};let n=e.closest(`[data-timeline-item]`),r=n?.dataset.threadRootId??e.dataset.threadRootId??e.dataset.postId;if(n&&r)return{kind:`timeline-item`,id:r};let i=e.dataset.postId;return i?{kind:`post-card`,id:i}:null}function MR(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}async function NR(e){await OR()?.openNew(e)}async function PR(e){let t=e.dataset.postId;if(!t)return;let n=OR();if(!n)return;let r=e.dataset.threadRootId??t;await n.openReply(t,MR(e),r,jR(e)??void 0)}function FR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function IR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function LR(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function RR(e){try{let t=document.querySelector(`[data-timeline-item][data-thread-root-id="${e}"]`)?.querySelector(`[data-timeline-item-content]`);if(!t)return!1;let n=await LR(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,!0):!1}catch{return!1}}async function zR(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await LR(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);return r?(r.outerHTML=n,!0):!1}catch{return!1}}async function BR(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await LR(`/_/post-view/${encodeURIComponent(e)}`);return n?(t.outerHTML=n,!0):!1}catch{return!1}}async function VR(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?RR(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?BR(e.replyRefreshId):zR(e.replyRefreshId)}var HR=new Map,UR=new Set,WR=new Map,GR=null;function KR(){if(!GR)return;let{clientIds:e,baseMsg:t}=GR;if(e.length===0)return;let n=0,r=0;for(let t of e){let e=WR.get(t)??0;n+=Math.min(1,Math.max(0,e)),e>=1&&(r+=1)}let i=e.length,o=Math.floor(n/i*100),s=Math.min(r+1,i);a(`compose-deferred`,i===1?`${t} ${o}%`:`${t} ${o}% ${s}/${i}`)}var qR=new Map;function JR(e){return new Promise(t=>{let n=setTimeout(()=>{a(),t(null)},3e3),r=URL.createObjectURL(e),i=document.createElement(`video`);i.muted=!0,i.playsInline=!0,i.preload=`auto`;function a(){clearTimeout(n),i.removeAttribute(`src`),i.load(),URL.revokeObjectURL(r)}i.onloadeddata=()=>{try{let e=i.videoWidth,n=i.videoHeight;if(!e||!n){a(),t(null);return}let r=Math.min(640/e,1),o=Math.round(e*r),s=Math.round(n*r),c=document.createElement(`canvas`);c.width=o,c.height=s;let l=c.getContext(`2d`);if(!l){a(),t(null);return}l.drawImage(i,0,0,o,s),c.toBlob(e=>{a(),t(e)},`image/webp`,.6)}catch{a(),t(null)}},i.onerror=()=>{a(),t(null)},i.src=r})}async function YR(e,t,n){let r=e.type,i=e.name;try{let a,o,s,c,l,u,f;if(r.startsWith(`video/`)){if(!DR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;JR(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let r=await DR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});a=r.file,e=null,o=r.width,s=r.height,c=r.durationSeconds,l=r.blurhash,f=r.poster,f&&n?.updateAttachmentPoster(t,f)}else if(r.startsWith(`audio/`)){if(!hR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{u=await NC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),a=(await hR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file,e=null}else if(r.startsWith(`image/`)||/\.heic$/i.test(i)||/\.heif$/i.test(i)){let r=e;try{let{isHeic:c,heicTo:l}=await ZO(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await c(r)){n?.updateAttachmentStatus(t,`processing`,null,null);let e=await l({blob:r,type:`image/jpeg`,quality:.92});r=new File([e],i.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,r)}let u=await re.processToFile(r);a=u.file,o=u.width,s=u.height,e=null,r=null}catch{return n?.removeAttachment(t),d(`Image format not supported.`,`error`),null}}else a=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!r.startsWith(`video/`)){let e=await PC(a);o??=e.width,s??=e.height,l??=e.blurhash,u??=e.waveform,!f&&e.poster&&(f=e.poster,n?.updateAttachmentPoster(t,f))}let p,m;if(sS(r)===`text`)try{let e=await a.text(),t=e.replace(/\s+/g,` `).trim();m=e.length,p=t.length<=100?t:t.slice(0,100)+`…`}catch{}WR.set(t,0),KR();let h=await KC(a,{width:o,height:s,durationSeconds:c,blurhash:l,waveform:u,poster:f,summary:p,chars:m},e=>{n?.updateAttachmentProgress(t,e),WR.set(t,e),KR()});return WR.set(t,1),KR(),n?.updateAttachmentStatus(t,`done`,h.id,null),qR.set(t,h.id),h.id}catch(e){WR.delete(t),KR();let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),n||d(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;qR.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):UR.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=FR(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=YR(e,r,n).then(e=>UR.has(r)?(UR.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);HR.set(r,t),t.finally(()=>HR.delete(r))}}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-reply-trigger]`);if(!t)return;let n=t.closest(`article[data-post]`);n&&PR(n)});function XR(e,t){let n=e.format===`quote`,r=e.format===`link`,i=!!e.editPostId,a=e=>e||void 0,o=e=>e||null;return{format:e.format,title:n?void 0:i?o(e.title):a(e.title),body:i?o(e.body):a(e.body),url:r?i?o(e.url):a(e.url):i?null:void 0,sourceName:n?i?o(e.quoteAuthor):a(e.quoteAuthor):void 0,sourceUrl:n?i?o(e.url):a(e.url):void 0,quoteText:n?i?o(e.quoteText):a(e.quoteText):i?null:void 0,slug:e.slug||void 0,status:e.status,publishedAt:e.status===`published`?e.publishedAt:void 0,visibility:e.visibility||void 0,rating:i?e.rating>0?e.rating:null:e.rating||void 0,collectionIds:e.collectionIds,attachments:t.length>0?t:void 0,replyToId:e.replyToId||void 0,quietReply:e.quietReply||void 0}}function ZR(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function QR(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??qR.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!ZR(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:jT(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=IR(t.target)??document.querySelector(`jant-compose-dialog`),a=!!r?.pageMode,o=r?.labels,s=o?.uploading??`Uploading...`,c=n.threadPosts?n.threadPosts.some(e=>e.body.includes(`"blob:`)):n.body.includes(`"blob:`),l=n.pendingAttachments.length>0||c,u=o?.published??`Published!`,f=o?.view??`View`;l&&(_(`compose-deferred`,s),n.pendingAttachments.length>0&&(GR={clientIds:n.pendingAttachments.map(e=>e.clientId),baseMsg:s},KR()));let p=(e,t=`success`)=>{if(GR){for(let e of GR.clientIds)WR.delete(e);GR=null}l?m(`compose-deferred`,e,t):d(e,t)},h=()=>{!a||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},g=()=>{!a||!r||(r.loading=!1)},v=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||a)){if(te&&n.editPostId){if(typeof r.openEdit!=`function`)return;await r.openEdit(n.editPostId);return}if(n.replyToId){if(typeof r.openReply!=`function`)return;await r.openReply(n.replyToId,void 0,n.replyThreadRootId,n.replyRefreshKind&&n.replyRefreshId?{kind:n.replyRefreshKind,id:n.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:n.format});return}typeof r.openNew==`function`&&await r.openNew({restoreDraft:!0})}},x=async e=>{g(),await b(),p(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{y(e,`success`,t)},ee=()=>!a||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||i(`/`)),!0),te=!!n.editPostId,ne=!!(n.threadPosts&&n.threadPosts.length>=2),re=null;try{let e=n.pendingAttachments.map(e=>e.clientId),t=e.map(e=>HR.get(e)??Promise.resolve(null)),s=await Promise.all(t);if(s.filter((t,n)=>t===null&&!qR.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let l=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=s[t];n&&r&&l.set(n,r)}if(ne&&n.threadPosts){let e=n.threadPosts,t=re?`draft`:n.status,i=(await Promise.all(e.map(async e=>{let n=e.body;if(n.includes(`"blob:`))try{let e=await ew(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>XR(e,QR(e,l))),s={posts:i};te&&n.editPostId&&(s.replaceThreadId=n.editPostId);let c=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(s)});if(!c.ok){if(n.status===`published`&&!re){let e={posts:i.map(e=>({...e,status:`draft`}))};if((await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)})).ok){re=`server`,v();let e=o?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||h(),p(e);return}}await x(w(await le(c),`error`)??`Something went wrong`);return}if(re===`upload`){v();let e=o?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),h(),p(e);return}let d=await le(c),m=w(d,`status`),g=w(d,`permalink`),_=w(d,`toast`);m===`published`?(v(),a?(await S(),h(),p(u)):(C(u,g?{label:f,href:g}:void 0),globalThis.location.reload())):(v(),await S(),ee()||h(),p(_??`Draft saved.`),$R(r,`draft`));return}let d=QR(n,l);if(c)try{let e=await ew(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let m=te?`/api/posts/${n.editPostId}`:`/compose`,g=te?`PUT`:`POST`,_=XR({...n,status:re?`draft`:n.status},d),y=await fetch(m,{method:g,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!y.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(m,{method:g,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,v();let e=await le(t),n=o?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||h(),p(n);let r=w(e,`toast`);r&&p(r);return}}await x(w(await le(y),`error`)??`Something went wrong`);return}if(te){v();let e=await le(y),t=n.editPostId??``,r=w(e,`slug`),o=r?i(`/${r}`):null;if(a)o&&o!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(o)):t&&await BR(t)?p(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`)){if(o&&o!==globalThis.location.pathname){C(`Post updated.`),globalThis.location.assign(o);return}await BR(t)?p(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else{let e=document.querySelector(`article[data-post-id="${t}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await RR(e):await zR(t))?p(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){v();let e=o?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),h(),p(e);return}let b=await le(y),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(v(),a)await S(),h(),p(u);else if(n.replyToId){if(await S(),!await VR(n)){C(u,ae?{label:f,href:ae}:void 0),globalThis.location.reload();return}p(u)}else C(u,ae?{label:f,href:ae}:void 0),globalThis.location.reload();return}else v(),await S(),ee()||h(),p(oe??`Draft saved.`),$R(r,`draft`)}catch{await x(`Something went wrong`)}});function $R(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var ez=`.compose-prompt`,tz=`.compose-prompt-trigger`,nz=`jant.composeOpenShortcutDiscovery`,rz=`/api/settings/discovery/compose-open-shortcut`,iz=350,az=1800,oz=3,sz=`compose-prompt-discovery-visible`,cz=!1,lz=null,uz=null,dz=null;function fz(){try{return globalThis.localStorage!==void 0}catch{return!1}}function pz(){if(!fz())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(nz);if(!e)return{shownCount:0,completed:!1};try{let t=JSON.parse(e);return{shownCount:typeof t.shownCount==`number`&&t.shownCount>=0?t.shownCount:0,completed:t.completed===!0}}catch{return globalThis.localStorage.removeItem(nz),{shownCount:0,completed:!1}}}function mz(e){if(fz())try{globalThis.localStorage.setItem(nz,JSON.stringify(e))}catch{}}function hz(){lz!==null&&(clearTimeout(lz),lz=null)}function gz(){uz!==null&&(clearTimeout(uz),uz=null)}function _z(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function vz(e){return pz().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function yz(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(sz)),document.querySelectorAll(ez).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(sz)})}function bz(){let e=pz();e.completed||cz||e.shownCount>=oz||(cz=!0,mz({...e,shownCount:e.shownCount+1}))}function xz(e){return!_z()||vz(e)?!1:pz().shownCount<oz||cz}function Sz(e){hz(),gz(),e?e.classList.remove(sz):dz&&dz.classList.remove(sz),(!e||e===dz)&&(dz=null)}function Cz(e){xz(e)&&(Sz(dz),dz=e,e.classList.add(sz),bz(),uz=setTimeout(()=>{Sz(e)},az))}function wz(e){xz(e)&&(e.classList.contains(sz)||(hz(),lz=setTimeout(()=>{Cz(e)},iz)))}function Tz(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(tz);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{wz(e)}),t.addEventListener(`pointerleave`,()=>{Sz(e)}),t.addEventListener(`focusin`,()=>{wz(e)}),t.addEventListener(`focusout`,()=>{Sz(e)}))}function Ez(e=document){e.querySelectorAll(ez).forEach(e=>Tz(e))}function Dz(){let e=pz();e.completed||mz({shownCount:Math.max(e.shownCount,oz),completed:!0}),yz(dz),Sz(dz),typeof globalThis.fetch==`function`&&globalThis.fetch(rz,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Ez()}):Ez(),document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{});var Oz=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function kz(e){return e instanceof globalThis.Element&&e.closest(Oz)!==null}function Az(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!OR()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return kz(e.target)||t!==e.target&&kz(t)}async function jz(e,t,n){try{if(!(await fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:t})})).ok)throw Error();t?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`),d(t?`Added to Featured.`:`Removed from Featured.`)}catch{d(`Could not update post. Try again.`,`error`)}}document.addEventListener(`keydown`,e=>{let t=e.key.toLowerCase();if(t!==`n`&&t!==`l`&&t!==`q`&&t!==`r`&&t!==`e`&&t!==`c`&&t!==`f`||Az(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),Dz();let n=kR(),r=t===`l`?`link`:t===`q`?`quote`:void 0;NR({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=AR();if(n){if(t===`r`){e.preventDefault(),PR(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=OR();r&&r.openEdit(t);return}if(t===`c`){e.preventDefault();let t=document.querySelector(`jant-post-menu`);t&&t.openCollectionsForPost(n);return}if(t===`f`){let t=n.dataset.postId;if(!t)return;e.preventDefault(),jz(t,!n.hasAttribute(`data-post-featured`),n);return}}});var Mz=[`en`,`zh-Hans`,`zh-Hant`];function Nz(e){return typeof e==`string`&&Mz.includes(e)}function Pz(e){let t=e.trim();if(!t)return`en`;let n;try{n=new Intl.Locale(t)}catch{return`en`}if(Nz(n.baseName))return n.baseName;if(n.language===`zh`){let e=n.region;return n.script===`Hant`||e===`TW`||e===`HK`||e===`MO`?`zh-Hant`:`zh-Hans`}return`en`}var Fz={en:1,"zh-Hans":1,"zh-Hant":1},Iz=`en.zh-Hans.zh-Hant.ja.ko.es.fr.de.it.pt.ru.ar.hi.bn.ur.tr.vi.th.id.fa.he.nl.pl.sv.da.no.fi.cs.hu.el.ro.uk.en-GB.en-US.fr-CA.pt-BR.es-MX.zh-CN.zh-TW.zh-HK`.split(`.`),Lz=null;function Rz(e){let t=e,n=e;try{let n=new Intl.DisplayNames([e],{type:`language`}).of(e);typeof n==`string`&&n.length>0&&(t=n)}catch{}try{let t=new Intl.DisplayNames([`en`],{type:`language`}).of(e);typeof t==`string`&&t.length>0&&(n=t)}catch{}return{tag:e,native:t,english:n,coverage:zz(e)}}function zz(e){let t=Pz(e);if(t===`en`){let t;try{t=new Intl.Locale(e).language}catch{return 0}if(t!==`en`)return 0}return Fz[t]}function Bz(){return Lz||(Lz=Iz.map(Rz),Lz)}function Vz(e){let t=e.trim();return Bz().find(e=>e.tag===t)||Rz(t)}var Hz=class extends c{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},demoMode:{type:Boolean,attribute:`demo-mode`},mainFeedUrl:{type:String,attribute:`main-feed-url`},latestFeedUrl:{type:String,attribute:`latest-feed-url`},featuredFeedUrl:{type:String,attribute:`featured-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_localeOpen:{state:!0},_localeQuery:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/feed/latest`,this.featuredFeedUrl=`/feed/featured`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._localeOpen=!1,this._localeQuery=``,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onLocalePickerDocumentClick),document.addEventListener(`keydown`,this._onLocalePickerKeydown)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this._onLocalePickerDocumentClick),document.removeEventListener(`keydown`,this._onLocalePickerKeydown),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=PT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=NT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`3rem`)}_initFooterEditor(){let e=this.querySelector(`[data-settings-footer-editor]`);if(!e||this._footerEditor)return;this._footerEditor=PT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=NT(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_filteredLocaleEntries(){let e=Bz(),t=this._localeQuery.trim().toLowerCase();return t?e.filter(e=>e.tag.toLowerCase().includes(t)||e.native.toLowerCase().includes(t)||e.english.toLowerCase().includes(t)):e}_toggleLocalePicker=()=>{this._localeOpen=!this._localeOpen,this._localeOpen?this.updateComplete.then(()=>{this.querySelector(`[data-locale-search]`)?.focus()}):this._localeQuery=``};_selectLocale(e){this._siteLanguage=e,this._localeOpen=!1,this._localeQuery=``,this._syncLocaleDirty()}_onLocalePickerDocumentClick=e=>{if(!this._localeOpen)return;let t=e.target,n=this.querySelector(`[data-locale-picker]`);n&&t&&!n.contains(t)&&(this._localeOpen=!1)};_onLocalePickerKeydown=e=>{e.key===`Escape`&&this._localeOpen&&(this._localeOpen=!1,this._localeQuery=``)};_renderLanguagePicker(){let e=Vz(this._siteLanguage||`en`),t=this._filteredLocaleEntries(),n=this.labels.siteLanguageSearchPlaceholder||`Search…`,r=this.labels.siteLanguageNoMatches||`No matches.`;return u`
2194
+ `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(e=>e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new lR;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=ak(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&yM(l,s,c);let[u,d]=l?[l.width,l.height]:[s,c],f=u,p=d,m=f/p,h=e=>Math.ceil(e/2)*2;t.width!==void 0&&t.height===void 0?(f=h(t.width),p=h(Math.round(f/m))):t.width===void 0&&t.height!==void 0?(p=h(t.height),f=h(Math.round(p*m))):t.width!==void 0&&t.height!==void 0&&(f=h(t.width),p=h(t.height));let g=await e.getFirstTimestamp(),_=this.output.format.getSupportedVideoCodecs(),v=!!t.forceTranscode||g<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!_.includes(n)||t.codec&&t.codec!==n||f!==u||p!==d||i!==0&&!o||!!l,y=t.alpha??`discard`;if(v){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}t.codec&&(_=_.filter(e=>e===t.codec));let n=t.bitrate??zL,s=await UL(_,{width:t.process&&t.processedWidth?t.processedWidth:f,height:t.process&&t.processedHeight?t.processedHeight:p,bitrate:n});if(!s){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}let c={codec:s,bitrate:n,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:y,hardwareAcceleration:t.hardwareAcceleration},m=new YL(c);r=m;let h=f!==u||p!==d||i!==0&&(!o||t.process!==void 0)||!!l||e.squarePixelWidth!==e.codedWidth||e.squarePixelHeight!==e.codedHeight;if(!h){let t=new rR({format:new AL,target:new SL}),n=new YL(c);t.addVideoTrack(n),await t.start();let r=await new VM(e).getSample(g);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),h=!0,t.cancel()}else await t.cancel()}h?this._trackPromises.push((async()=>{await this._started;let n=new HM(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new gM(o,{timestamp:s+n/r,duration:1/r});await this._registerVideoSample(e,t,m,i),i.close()}};for await(let{canvas:i,timestamp:a,duration:u}of n){if(this._canceled)return;let n=Math.max(a-this._startTimestamp,0);if(c=n+u,r!==void 0){let e=Math.floor(n*r)/r;if(o!==null)if(e<=s){o=i,s=e;continue}else await l(e);n=e}let d=new gM(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(U(c!==null),U(r!==void 0),await l(Math.floor(c*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let n=new VM(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{U(i),U(r!==void 0);let o=Math.round((n-a)*r);for(let n=1;n<o;n++)i.setTimestamp(a+n/r),i.setDuration(1/r),await this._registerVideoSample(e,t,m,i);i.close()};for await(let c of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){c.close(),i?.close();return}let n=Math.max(c.timestamp-this._startTimestamp,0);if(o=n+c.duration,r!==void 0){let e=Math.floor(n*r)/r;if(i!==null)if(e<=a){i.close(),i=c,a=e;continue}else await s(e);n=e,c.setDuration(1/r)}c.setTimestamp(n),await this._registerVideoSample(e,t,m,c),r===void 0?c.close():(i=c,a=n)}i&&(U(o!==null),U(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new KL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new FM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:Gk(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),i=e.map(e=>e instanceof gM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new gM(e):new gM(e,{timestamp:r.timestamp,duration:r.duration}))}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}async _processAudioTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp(),s=t.numberOfChannels??i,c=t.sampleRate??a,l=s!==i||c!==a||o<this._startTimestamp||o>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,u=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!l&&u.includes(n)&&(!t.codec||t.codec===n)&&!t.process){let t=new ZL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new FM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}let n=null;t.codec&&(u=u.filter(e=>e===t.codec));let i=t.bitrate??zL,a=await HL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>CA.includes(e))&&u.some(e=>CA.includes(e))&&(s!==oR||c!==sR)){let e=(await HL(u,{numberOfChannels:oR,sampleRate:sR,bitrate:i})).find(e=>CA.includes(e));e&&(l=!0,n=e,s=oR,c=sR)}else n=a[0]??null;if(n===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}if(l)r=this._resampleAudio(e,t,n,s,c,i);else{let a=new $L({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new GM(e);for await(let r of n.samples(void 0,this._endTimestamp)){if(this._canceled){r.close();return}r.setTimestamp(r.timestamp-this._startTimestamp),await this._registerAudioSample(e,t,a,r),r.close()}a.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:Gk(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),!e.every(e=>e instanceof TM))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);i=e}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}_resampleAudio(e,t,n,r,i,a){let o=new $L({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new fR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new GM(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=zk(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},lR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},uR=5,dR=class{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<uR&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){return this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0)),t-this.computeMinAndMaybeResolve()>=uR}wait(e){let{promise:t,resolve:n}=Ok();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},fR=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){U(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+a,this.endTime-this.startTime),s=Math.floor(i*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;U(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new TM({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};function pR(){return typeof AudioEncoder<`u`}async function mR(e,t){let n=new eF({source:new XP(e),formats:JP}),r=new xL,i=new rR({format:new AL({fastStart:`in-memory`}),target:r});try{let a=await cR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:zL}});t&&(a.onProgress=t),await a.execute();let o=r.buffer;if(!o)throw Error(`Audio processing produced no output`);let s=e.name.replace(/\.[^.]+$/,``);return{file:new File([o],`${s}.m4a`,{type:`audio/mp4`})}}finally{n.dispose()}}var hR={isSupported:pR,processToFile:mR},gR=new Set([`moov`,`trak`]);function _R(e){return 12+(e===1?32:20)+8+2}function vR(e){let t=new DataView(e),n=(e,r)=>{let i=e;for(;i+8<=r;){let e=t.getUint32(i),a=String.fromCharCode(t.getUint8(i+4),t.getUint8(i+5),t.getUint8(i+6),t.getUint8(i+7));if(e===0&&(e=r-i),e<8||i+e>r)break;if(a===`tkhd`){let n=t.getUint8(i+8),r=i+_R(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else gR.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var yR=1920,bR=1080,xR=640,SR=32;function CR(){return typeof VideoEncoder<`u`}async function wR(e){let t=new eF({source:new XP(e),formats:JP});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=s(a),c=Math.min(a*.1,3),l=await new HM(e).getCanvas(c);if(!l)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=l.canvas,d=u.width,f=u.height,p=Math.min(xR/d,1),m=Math.round(d*p),h=Math.round(f*p),g=document.createElement(`canvas`);g.width=m,g.height=h;let _=g.getContext(`2d`);if(!_)return{sourceWidth:n,sourceHeight:r};_.drawImage(u,0,0,m,h);let v=await new Promise(e=>{g.toBlob(t=>e(t??void 0),`image/webp`,.8)}),y=Math.min(SR/d,SR/f,1),b=Math.max(Math.round(d*y),1),x=Math.max(Math.round(f*y),1),S=document.createElement(`canvas`);S.width=b,S.height=x;let C=S.getContext(`2d`);return C?(C.drawImage(u,0,0,b,x),{poster:v,blurhash:AC(C.getImageData(0,0,b,x).data,b,x,4,3),sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o}):{poster:v,sourceWidth:n,sourceHeight:r}}catch{return{}}finally{t.dispose()}}async function TR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await wR(e),c=i||yR,l=a||bR;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(yR/e,bR/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new eF({source:new XP(e),formats:JP}),d=new xL,f=new rR({format:new AL({fastStart:`in-memory`}),target:d});try{let i=await cR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:zL},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);vR(a);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await kR(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&(OR(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await kR(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var ER=[65536,0,0,0,65536,0,0,0,1073741824];function DR(e,t,n,r){let i=t;for(;i+8<=n;){let t=e.getUint32(i),a=String.fromCharCode(e.getUint8(i+4),e.getUint8(i+5),e.getUint8(i+6),e.getUint8(i+7));if(t===0&&(t=n-i),t<8||i+t>n)break;r(i,t,a),(a===`moov`||a===`trak`||a===`mdia`||a===`edts`)&&DR(e,i+8,i+t,r),i+=t}}function OR(e){let t=new DataView(e);DR(t,0,e.byteLength,(n,r,i)=>{if(i!==`tkhd`)return;let a=n+8,o=a+(t.getUint8(a)===0?40:52);if(o+36>e.byteLength)return;let s=!0;for(let e=0;e<9;e++)if(t.getInt32(o+e*4)!==ER[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,ER[e])})}function kR(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=document.createElement(`video`);i.preload=`metadata`,i.onloadedmetadata=()=>{URL.revokeObjectURL(r),t({width:i.videoWidth,height:i.videoHeight})},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(`Failed to probe transcoded video dimensions`))},i.src=r})}var AR={isSupported:CR,processToFile:TR};function jR(){return document.querySelector(`jant-compose-dialog`)}function MR(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function NR(e=document){if(e===document){let e=document.querySelector(`[data-page='post'] article[data-post]:hover`);if(e)return e}return e.querySelector(`[data-post-current] article[data-post]`)||e.querySelector(`[data-post-view] article[data-post]`)||(e===document?document.querySelector(`article[data-post]:hover`):null)}function PR(e){let t=e.closest(`[data-post-view]`)?.dataset.postViewId;if(t)return{kind:`post-view`,id:t};let n=e.closest(`[data-timeline-item]`),r=n?.dataset.threadRootId??e.dataset.threadRootId??e.dataset.postId;if(n&&r)return{kind:`timeline-item`,id:r};let i=e.dataset.postId;return i?{kind:`post-card`,id:i}:null}function FR(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}async function IR(e){await jR()?.openNew(e)}async function LR(e){let t=e.dataset.postId;if(!t)return;let n=jR();if(!n)return;let r=e.dataset.threadRootId??t;await n.openReply(t,FR(e),r,PR(e)??void 0)}function RR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function zR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function BR(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function VR(e){try{let t=document.querySelector(`[data-timeline-item][data-thread-root-id="${e}"]`)?.querySelector(`[data-timeline-item-content]`);if(!t)return!1;let n=await BR(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,!0):!1}catch{return!1}}async function HR(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await BR(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);return r?(r.outerHTML=n,!0):!1}catch{return!1}}async function UR(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await BR(`/_/post-view/${encodeURIComponent(e)}`);return n?(t.outerHTML=n,!0):!1}catch{return!1}}async function WR(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?VR(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?UR(e.replyRefreshId):HR(e.replyRefreshId)}var GR=new Map,KR=new Set,qR=new Map,JR=null;function YR(){if(!JR)return;let{clientIds:e,baseMsg:t}=JR;if(e.length===0)return;let n=0,r=0;for(let t of e){let e=qR.get(t)??0;n+=Math.min(1,Math.max(0,e)),e>=1&&(r+=1)}let i=e.length,o=Math.floor(n/i*100),s=Math.min(r+1,i);a(`compose-deferred`,i===1?`${t} ${o}%`:`${t} ${o}% ${s}/${i}`)}var XR=new Map;function ZR(e){return new Promise(t=>{let n=setTimeout(()=>{a(),t(null)},3e3),r=URL.createObjectURL(e),i=document.createElement(`video`);i.muted=!0,i.playsInline=!0,i.preload=`auto`;function a(){clearTimeout(n),i.removeAttribute(`src`),i.load(),URL.revokeObjectURL(r)}i.onloadeddata=()=>{try{let e=i.videoWidth,n=i.videoHeight;if(!e||!n){a(),t(null);return}let r=Math.min(640/e,1),o=Math.round(e*r),s=Math.round(n*r),c=document.createElement(`canvas`);c.width=o,c.height=s;let l=c.getContext(`2d`);if(!l){a(),t(null);return}l.drawImage(i,0,0,o,s),c.toBlob(e=>{a(),t(e)},`image/webp`,.6)}catch{a(),t(null)}},i.onerror=()=>{a(),t(null)},i.src=r})}async function QR(e,t,n){let r=e.type,i=e.name;try{let a,o,s,c,l,u,f;if(r.startsWith(`video/`)){if(!AR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;ZR(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let r=await AR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});a=r.file,e=null,o=r.width,s=r.height,c=r.durationSeconds,l=r.blurhash,f=r.poster,f&&n?.updateAttachmentPoster(t,f)}else if(r.startsWith(`audio/`)){if(!hR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{u=await NC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),a=(await hR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file,e=null}else if(r.startsWith(`image/`)||/\.heic$/i.test(i)||/\.heif$/i.test(i)){let r=e;try{let{isHeic:c,heicTo:l}=await ZO(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await c(r)){n?.updateAttachmentStatus(t,`processing`,null,null);let e=await l({blob:r,type:`image/jpeg`,quality:.92});r=new File([e],i.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,r)}let u=await re.processToFile(r);a=u.file,o=u.width,s=u.height,e=null,r=null}catch{return n?.removeAttachment(t),d(`Image format not supported.`,`error`),null}}else a=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!r.startsWith(`video/`)){let e=await PC(a);o??=e.width,s??=e.height,l??=e.blurhash,u??=e.waveform,!f&&e.poster&&(f=e.poster,n?.updateAttachmentPoster(t,f))}let p,m;if(sS(r)===`text`)try{let e=await a.text(),t=e.replace(/\s+/g,` `).trim();m=e.length,p=t.length<=100?t:t.slice(0,100)+`…`}catch{}qR.set(t,0),YR();let h=await KC(a,{width:o,height:s,durationSeconds:c,blurhash:l,waveform:u,poster:f,summary:p,chars:m},e=>{n?.updateAttachmentProgress(t,e),qR.set(t,e),YR()});return qR.set(t,1),YR(),n?.updateAttachmentStatus(t,`done`,h.id,null),XR.set(t,h.id),h.id}catch(e){qR.delete(t),YR();let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),n||d(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;XR.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):KR.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=RR(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=QR(e,r,n).then(e=>KR.has(r)?(KR.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);GR.set(r,t),t.finally(()=>GR.delete(r))}}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-reply-trigger]`);if(!t)return;let n=t.closest(`article[data-post]`);n&&LR(n)});function $R(e,t){let n=e.format===`quote`,r=e.format===`link`,i=!!e.editPostId,a=e=>e||void 0,o=e=>e||null;return{format:e.format,title:n?void 0:i?o(e.title):a(e.title),body:i?o(e.body):a(e.body),url:r?i?o(e.url):a(e.url):i?null:void 0,sourceName:n?i?o(e.quoteAuthor):a(e.quoteAuthor):void 0,sourceUrl:n?i?o(e.url):a(e.url):void 0,quoteText:n?i?o(e.quoteText):a(e.quoteText):i?null:void 0,slug:e.slug||void 0,status:e.status,publishedAt:e.status===`published`?e.publishedAt:void 0,visibility:e.visibility||void 0,rating:i?e.rating>0?e.rating:null:e.rating||void 0,collectionIds:e.collectionIds,attachments:t.length>0?t:void 0,replyToId:e.replyToId||void 0,quietReply:e.quietReply||void 0}}function ez(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function tz(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??XR.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!ez(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:jT(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=zR(t.target)??document.querySelector(`jant-compose-dialog`),a=!!r?.pageMode,o=r?.labels,s=o?.uploading??`Uploading...`,c=n.threadPosts?n.threadPosts.some(e=>e.body.includes(`"blob:`)):n.body.includes(`"blob:`),l=n.pendingAttachments.length>0||c,u=o?.published??`Published!`,f=o?.view??`View`;l&&(_(`compose-deferred`,s),n.pendingAttachments.length>0&&(JR={clientIds:n.pendingAttachments.map(e=>e.clientId),baseMsg:s},YR()));let p=(e,t=`success`)=>{if(JR){for(let e of JR.clientIds)qR.delete(e);JR=null}l?m(`compose-deferred`,e,t):d(e,t)},h=()=>{!a||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},g=()=>{!a||!r||(r.loading=!1)},v=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||a)){if(te&&n.editPostId){if(typeof r.openEdit!=`function`)return;await r.openEdit(n.editPostId);return}if(n.replyToId){if(typeof r.openReply!=`function`)return;await r.openReply(n.replyToId,void 0,n.replyThreadRootId,n.replyRefreshKind&&n.replyRefreshId?{kind:n.replyRefreshKind,id:n.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:n.format});return}typeof r.openNew==`function`&&await r.openNew({restoreDraft:!0})}},x=async e=>{g(),await b(),p(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{y(e,`success`,t)},ee=()=>!a||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||i(`/`)),!0),te=!!n.editPostId,ne=!!(n.threadPosts&&n.threadPosts.length>=2),re=null;try{let e=n.pendingAttachments.map(e=>e.clientId),t=e.map(e=>GR.get(e)??Promise.resolve(null)),s=await Promise.all(t);if(s.filter((t,n)=>t===null&&!XR.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let l=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=s[t];n&&r&&l.set(n,r)}if(ne&&n.threadPosts){let e=n.threadPosts,t=re?`draft`:n.status,i=(await Promise.all(e.map(async e=>{let n=e.body;if(n.includes(`"blob:`))try{let e=await ew(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>$R(e,tz(e,l))),s={posts:i};te&&n.editPostId&&(s.replaceThreadId=n.editPostId);let c=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(s)});if(!c.ok){if(n.status===`published`&&!re){let e={posts:i.map(e=>({...e,status:`draft`}))};if((await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)})).ok){re=`server`,v();let e=o?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||h(),p(e);return}}await x(w(await le(c),`error`)??`Something went wrong`);return}if(re===`upload`){v();let e=o?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),h(),p(e);return}let d=await le(c),m=w(d,`status`),g=w(d,`permalink`),_=w(d,`toast`);m===`published`?(v(),a?(await S(),h(),p(u)):(C(u,g?{label:f,href:g}:void 0),globalThis.location.reload())):(v(),await S(),ee()||h(),p(_??`Draft saved.`),nz(r,`draft`));return}let d=tz(n,l);if(c)try{let e=await ew(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let m=te?`/api/posts/${n.editPostId}`:`/compose`,g=te?`PUT`:`POST`,_=$R({...n,status:re?`draft`:n.status},d),y=await fetch(m,{method:g,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!y.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(m,{method:g,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,v();let e=await le(t),n=o?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||h(),p(n);let r=w(e,`toast`);r&&p(r);return}}await x(w(await le(y),`error`)??`Something went wrong`);return}if(te){v();let e=await le(y),t=n.editPostId??``,r=w(e,`slug`),o=r?i(`/${r}`):null;if(a)o&&o!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(o)):t&&await UR(t)?p(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`)){if(o&&o!==globalThis.location.pathname){C(`Post updated.`),globalThis.location.assign(o);return}await UR(t)?p(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else{let e=document.querySelector(`article[data-post-id="${t}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await VR(e):await HR(t))?p(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){v();let e=o?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),h(),p(e);return}let b=await le(y),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(v(),a)await S(),h(),p(u);else if(n.replyToId){if(await S(),!await WR(n)){C(u,ae?{label:f,href:ae}:void 0),globalThis.location.reload();return}p(u)}else C(u,ae?{label:f,href:ae}:void 0),globalThis.location.reload();return}else v(),await S(),ee()||h(),p(oe??`Draft saved.`),nz(r,`draft`)}catch{await x(`Something went wrong`)}});function nz(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var rz=`.compose-prompt`,iz=`.compose-prompt-trigger`,az=`jant.composeOpenShortcutDiscovery`,oz=`/api/settings/discovery/compose-open-shortcut`,sz=350,cz=1800,lz=3,uz=`compose-prompt-discovery-visible`,dz=!1,fz=null,pz=null,mz=null;function hz(){try{return globalThis.localStorage!==void 0}catch{return!1}}function gz(){if(!hz())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(az);if(!e)return{shownCount:0,completed:!1};try{let t=JSON.parse(e);return{shownCount:typeof t.shownCount==`number`&&t.shownCount>=0?t.shownCount:0,completed:t.completed===!0}}catch{return globalThis.localStorage.removeItem(az),{shownCount:0,completed:!1}}}function _z(e){if(hz())try{globalThis.localStorage.setItem(az,JSON.stringify(e))}catch{}}function vz(){fz!==null&&(clearTimeout(fz),fz=null)}function yz(){pz!==null&&(clearTimeout(pz),pz=null)}function bz(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function xz(e){return gz().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function Sz(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(uz)),document.querySelectorAll(rz).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(uz)})}function Cz(){let e=gz();e.completed||dz||e.shownCount>=lz||(dz=!0,_z({...e,shownCount:e.shownCount+1}))}function wz(e){return!bz()||xz(e)?!1:gz().shownCount<lz||dz}function Tz(e){vz(),yz(),e?e.classList.remove(uz):mz&&mz.classList.remove(uz),(!e||e===mz)&&(mz=null)}function Ez(e){wz(e)&&(Tz(mz),mz=e,e.classList.add(uz),Cz(),pz=setTimeout(()=>{Tz(e)},cz))}function Dz(e){wz(e)&&(e.classList.contains(uz)||(vz(),fz=setTimeout(()=>{Ez(e)},sz)))}function Oz(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(iz);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{Dz(e)}),t.addEventListener(`pointerleave`,()=>{Tz(e)}),t.addEventListener(`focusin`,()=>{Dz(e)}),t.addEventListener(`focusout`,()=>{Tz(e)}))}function kz(e=document){e.querySelectorAll(rz).forEach(e=>Oz(e))}function Az(){let e=gz();e.completed||_z({shownCount:Math.max(e.shownCount,lz),completed:!0}),Sz(mz),Tz(mz),typeof globalThis.fetch==`function`&&globalThis.fetch(oz,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{kz()}):kz(),document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{});var jz=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function Mz(e){return e instanceof globalThis.Element&&e.closest(jz)!==null}function Nz(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!jR()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return Mz(e.target)||t!==e.target&&Mz(t)}async function Pz(e,t,n){try{if(!(await fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:t})})).ok)throw Error();t?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`),d(t?`Added to Featured.`:`Removed from Featured.`)}catch{d(`Could not update post. Try again.`,`error`)}}document.addEventListener(`keydown`,e=>{let t=e.key.toLowerCase();if(t!==`n`&&t!==`l`&&t!==`q`&&t!==`r`&&t!==`e`&&t!==`c`&&t!==`f`||Nz(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),Az();let n=MR(),r=t===`l`?`link`:t===`q`?`quote`:void 0;IR({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=NR();if(n){if(t===`r`){e.preventDefault(),LR(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=jR();r&&r.openEdit(t);return}if(t===`c`){e.preventDefault();let t=document.querySelector(`jant-post-menu`);t&&t.openCollectionsForPost(n);return}if(t===`f`){let t=n.dataset.postId;if(!t)return;e.preventDefault(),Pz(t,!n.hasAttribute(`data-post-featured`),n);return}}});var Fz=[`en`,`zh-Hans`,`zh-Hant`];function Iz(e){return typeof e==`string`&&Fz.includes(e)}function Lz(e){let t=e.trim();if(!t)return`en`;let n;try{n=new Intl.Locale(t)}catch{return`en`}if(Iz(n.baseName))return n.baseName;if(n.language===`zh`){let e=n.region;return n.script===`Hant`||e===`TW`||e===`HK`||e===`MO`?`zh-Hant`:`zh-Hans`}return`en`}var Rz={en:1,"zh-Hans":1,"zh-Hant":1},zz=`en.zh-Hans.zh-Hant.ja.ko.es.fr.de.it.pt.ru.ar.hi.bn.ur.tr.vi.th.id.fa.he.nl.pl.sv.da.no.fi.cs.hu.el.ro.uk.en-GB.en-US.fr-CA.pt-BR.es-MX.zh-CN.zh-TW.zh-HK`.split(`.`),Bz=null;function Vz(e){let t=e,n=e;try{let n=new Intl.DisplayNames([e],{type:`language`}).of(e);typeof n==`string`&&n.length>0&&(t=n)}catch{}try{let t=new Intl.DisplayNames([`en`],{type:`language`}).of(e);typeof t==`string`&&t.length>0&&(n=t)}catch{}return{tag:e,native:t,english:n,coverage:Hz(e)}}function Hz(e){let t=Lz(e);if(t===`en`){let t;try{t=new Intl.Locale(e).language}catch{return 0}if(t!==`en`)return 0}return Rz[t]}function Uz(){return Bz||(Bz=zz.map(Vz),Bz)}function Wz(e){let t=e.trim();return Uz().find(e=>e.tag===t)||Vz(t)}var Gz=class extends c{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},demoMode:{type:Boolean,attribute:`demo-mode`},mainFeedUrl:{type:String,attribute:`main-feed-url`},latestFeedUrl:{type:String,attribute:`latest-feed-url`},featuredFeedUrl:{type:String,attribute:`featured-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_localeOpen:{state:!0},_localeQuery:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/feed/latest`,this.featuredFeedUrl=`/feed/featured`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._localeOpen=!1,this._localeQuery=``,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onLocalePickerDocumentClick),document.addEventListener(`keydown`,this._onLocalePickerKeydown)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this._onLocalePickerDocumentClick),document.removeEventListener(`keydown`,this._onLocalePickerKeydown),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=PT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=NT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`3rem`)}_initFooterEditor(){let e=this.querySelector(`[data-settings-footer-editor]`);if(!e||this._footerEditor)return;this._footerEditor=PT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=NT(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_filteredLocaleEntries(){let e=Uz(),t=this._localeQuery.trim().toLowerCase();return t?e.filter(e=>e.tag.toLowerCase().includes(t)||e.native.toLowerCase().includes(t)||e.english.toLowerCase().includes(t)):e}_toggleLocalePicker=()=>{this._localeOpen=!this._localeOpen,this._localeOpen?this.updateComplete.then(()=>{this.querySelector(`[data-locale-search]`)?.focus()}):this._localeQuery=``};_selectLocale(e){this._siteLanguage=e,this._localeOpen=!1,this._localeQuery=``,this._syncLocaleDirty()}_onLocalePickerDocumentClick=e=>{if(!this._localeOpen)return;let t=e.target,n=this.querySelector(`[data-locale-picker]`);n&&t&&!n.contains(t)&&(this._localeOpen=!1)};_onLocalePickerKeydown=e=>{e.key===`Escape`&&this._localeOpen&&(this._localeOpen=!1,this._localeQuery=``)};_renderLanguagePicker(){let e=Wz(this._siteLanguage||`en`),t=this._filteredLocaleEntries(),n=this.labels.siteLanguageSearchPlaceholder||`Search…`,r=this.labels.siteLanguageNoMatches||`No matches.`;return u`
2195
2195
  <div class="relative" data-locale-picker>
2196
2196
  <button
2197
2197
  type="button"
@@ -2494,7 +2494,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2494
2494
  <div class="flex flex-col">
2495
2495
  ${this._renderGeneralForm()} ${this._renderSearchForm()}
2496
2496
  </div>
2497
- `}};customElements.define(`jant-settings-general`,Hz);var Uz=class extends c{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}removeError(){this._removeLoading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}async _removeAvatar(){await be({message:this.labels.confirmRemoveAvatar,confirmLabel:this.labels.remove,cancelLabel:this.labels.cancel,tone:`danger`})&&(this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}}))))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?u`
2497
+ `}};customElements.define(`jant-settings-general`,Gz);var Kz=class extends c{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}removeError(){this._removeLoading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}async _removeAvatar(){await be({message:this.labels.confirmRemoveAvatar,confirmLabel:this.labels.remove,cancelLabel:this.labels.cancel,tone:`danger`})&&(this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}}))))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?u`
2498
2498
  <div class=${e}>
2499
2499
  <img
2500
2500
  src=${this.avatarUrl}
@@ -2602,7 +2602,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2602
2602
  </div>
2603
2603
  </div>
2604
2604
  </div>
2605
- `}};customElements.define(`jant-settings-avatar`,Uz);function Wz(e){let t=w(e,`siteName`),n=w(e,`siteDescription`),r=w(e,`siteLanguage`),i=w(e,`cjkSerifFont`),a=w(e,`mainRssFeed`),o=w(e,`timeZone`),s=w(e,`siteFooter`),c=se(e,`showJantBrandingOnHome`),l=se(e,`noindex`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,cjkSerifFont:i,mainRssFeed:a,timeZone:o,siteFooter:s,showJantBrandingOnHome:c,noindex:l}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),a=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n)});if(!e.ok)throw Error(`HTTP ${e.status}`);let o=await le(e),s=w(o,`status`),c=w(o,`url`),l=w(o,`toast`);if(s===`redirect`&&c){window.location.href=c;return}l&&d(l),r===`avatar-display`?a?.saved():i?.sectionSaved(r)}catch{d(`Failed to save. Please try again.`,`error`),r===`avatar-display`?a?.saveError():i?.sectionError(r)}}),document.addEventListener(`jant:avatar-remove`,async e=>{let{endpoint:t}=e.detail,n=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await le(e),r=w(n,`status`),i=w(n,`url`);if(r===`redirect`&&i){window.location.href=i;return}}catch{d(`Failed to remove avatar. Please try again.`,`error`),n?.removeError()}});function Gz(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=Wz(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,Gz):queueMicrotask(Gz);var Kz=300,qz=1,Jz=class extends c{static properties={labels:{type:Object},apiBase:{type:String,attribute:`api-base`},connectUrl:{type:String,attribute:`connect-url`},installUrl:{type:String,attribute:`install-url`},cancelUrl:{type:String,attribute:`cancel-url`},createRepoNameHint:{type:String,attribute:`create-repo-name-hint`},_installations:{state:!0},_selectedOwner:{state:!0},_ownerOpen:{state:!0},_repos:{state:!0},_totalCount:{state:!0},_hasMore:{state:!0},_nextPage:{state:!0},_reposMode:{state:!0},_repoOpen:{state:!0},_repoSearch:{state:!0},_loadingRepos:{state:!0},_selectedRepo:{state:!0},_classification:{state:!0},_classifying:{state:!0},_confirmText:{state:!0},_connecting:{state:!0},_error:{state:!0}};#e=null;#t=0;#n=!1;#r=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.apiBase=``,this.connectUrl=``,this.installUrl=``,this.cancelUrl=``,this.createRepoNameHint=``,this._installations=[],this._selectedOwner=null,this._ownerOpen=!1,this._repos=[],this._totalCount=0,this._hasMore=!1,this._nextPage=null,this._reposMode=`list`,this._repoOpen=!1,this._repoSearch=``,this._loadingRepos=!1,this._selectedRepo=null,this._classification=null,this._classifying=!1,this._confirmText=``,this._connecting=!1,this._error=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#m),document.addEventListener(`keydown`,this.#h),window.addEventListener(`focus`,this.#g),this.#i()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#m),document.removeEventListener(`keydown`,this.#h),window.removeEventListener(`focus`,this.#g),this.#e&&clearTimeout(this.#e)}async#i(){try{let e=await fetch(`${this.apiBase}/installations`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._installations=t.installations;let n=t.installations.length===1?t.installations[0]:null;n&&this.#u(n)}catch(e){this._error=e instanceof Error?e.message:String(e)}}async#a(e,t={}){let n=++this.#t;this._loadingRepos=!0;try{let r=new URLSearchParams({installationId:e});t.q&&r.set(`q`,t.q);let i=await fetch(`${this.apiBase}/repos?${r.toString()}`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(n!==this.#t)return;if(i.status===410){this._installations=this._installations.filter(t=>t.installationId!==e),this._selectedOwner=null,this._repos=[];return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let a=await i.json();this._repos=a.repos,this._totalCount=a.totalCount,this._hasMore=a.hasMore,this._nextPage=a.nextPage,this._reposMode=a.mode}catch(e){n===this.#t&&(this._error=e instanceof Error?e.message:String(e))}finally{n===this.#t&&(this._loadingRepos=!1)}}async#o(e,t){this._classifying=!0,this._classification=null,this._confirmText=``;try{let n=await fetch(`${this.apiBase}/classify`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:e,repo:t})}),r=await n.json();if(!n.ok||!r.classification)throw Error(r.error??`HTTP ${n.status}`);this._classification=r.classification}catch(e){this._error=e instanceof Error?e.message:String(e)}finally{this._classifying=!1}}async#s(){if(!(!this._selectedOwner||!this._selectedRepo||!this._classification)){this._connecting=!0,this._error=null;try{let e=this._classification.kind===`foreign`||this._classification.kind===`owned-by-other-site`,t=await fetch(this.connectUrl,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:this._selectedOwner.installationId,repo:this._selectedRepo.fullName,confirmForeign:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw Error(n.error??`HTTP ${t.status}`);window.location.href=n.redirect??this.cancelUrl}catch(e){this._error=e instanceof Error?e.message:String(e),this._connecting=!1}}}#c(){let e=this._selectedOwner;if(!e)return;let t=this.createRepoNameHint||``,n=new URL(`https://github.com/new`);t&&n.searchParams.set(`name`,t),n.searchParams.set(`owner`,e.account.login),n.searchParams.set(`visibility`,`private`),this.#n=!0,this.#r=t||null,window.open(n.toString(),`_blank`,`noopener,noreferrer`),this._repoOpen=!1}#l(){if(!this._selectedOwner)return;let e=this._repoSearch.trim();this.#a(this._selectedOwner.installationId,e?{q:e}:{})}#u(e){if(this._selectedOwner?.installationId===e.installationId){this._ownerOpen=!1;return}this._selectedOwner=e,this._ownerOpen=!1,this._selectedRepo=null,this._classification=null,this._confirmText=``,this._repoSearch=``,this.#a(e.installationId)}#d(e){this._selectedRepo=e,this._repoOpen=!1,this._repoSearch=``,this._selectedOwner&&this.#o(this._selectedOwner.installationId,e.fullName)}#f(e){let t=e.target.value;if(this._repoSearch=t,this.#e&&clearTimeout(this.#e),!this._selectedOwner)return;let n=t.trim();if(n.length<qz){this._reposMode===`search`&&this.#a(this._selectedOwner.installationId);return}this.#e=setTimeout(()=>{this._selectedOwner&&this.#a(this._selectedOwner.installationId,{q:n})},Kz)}#p(){let e=this._repoSearch.trim().toLowerCase();return!e||this._reposMode===`search`?this._repos:this._repos.filter(t=>t.name.toLowerCase().includes(e)||t.fullName.toLowerCase().includes(e))}#m=e=>{if(!this._ownerOpen&&!this._repoOpen)return;let t=e.target,n=this.querySelector(`.repo-picker-owner`),r=this.querySelector(`.repo-picker-repo`);n&&!n.contains(t)&&(this._ownerOpen=!1),r&&!r.contains(t)&&(this._repoOpen=!1)};#h=e=>{e.key===`Escape`&&(this._ownerOpen||this._repoOpen)&&(this._ownerOpen=!1,this._repoOpen=!1)};#g=()=>{if(!this.#n)return;let e=this._selectedOwner;if(!e){this.#n=!1;return}let t=this.#r;this.#n=!1,this.#r=null,(async()=>{if(this._repoSearch=``,await this.#a(e.installationId),t){let e=this._repos.find(e=>e.name===t);e&&this.#d(e)}})()};#_(){this._ownerOpen=!this._ownerOpen,this._repoOpen=!1}#v(){this._selectedOwner&&(this._repoOpen=!this._repoOpen,this._ownerOpen=!1,this._repoOpen&&queueMicrotask(()=>{this.querySelector(`.repo-picker-repo-search`)?.focus()}))}render(){return u`
2605
+ `}};customElements.define(`jant-settings-avatar`,Kz);function qz(e){let t=w(e,`siteName`),n=w(e,`siteDescription`),r=w(e,`siteLanguage`),i=w(e,`cjkSerifFont`),a=w(e,`mainRssFeed`),o=w(e,`timeZone`),s=w(e,`siteFooter`),c=se(e,`showJantBrandingOnHome`),l=se(e,`noindex`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,cjkSerifFont:i,mainRssFeed:a,timeZone:o,siteFooter:s,showJantBrandingOnHome:c,noindex:l}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),a=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n)});if(!e.ok)throw Error(`HTTP ${e.status}`);let o=await le(e),s=w(o,`status`),c=w(o,`url`),l=w(o,`toast`);if(s===`redirect`&&c){window.location.href=c;return}l&&d(l),r===`avatar-display`?a?.saved():i?.sectionSaved(r)}catch{d(`Failed to save. Please try again.`,`error`),r===`avatar-display`?a?.saveError():i?.sectionError(r)}}),document.addEventListener(`jant:avatar-remove`,async e=>{let{endpoint:t}=e.detail,n=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await le(e),r=w(n,`status`),i=w(n,`url`);if(r===`redirect`&&i){window.location.href=i;return}}catch{d(`Failed to remove avatar. Please try again.`,`error`),n?.removeError()}});function Jz(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=qz(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,Jz):queueMicrotask(Jz);var Yz=300,Xz=1,Zz=class extends c{static properties={labels:{type:Object},apiBase:{type:String,attribute:`api-base`},connectUrl:{type:String,attribute:`connect-url`},installUrl:{type:String,attribute:`install-url`},cancelUrl:{type:String,attribute:`cancel-url`},createRepoNameHint:{type:String,attribute:`create-repo-name-hint`},_installations:{state:!0},_selectedOwner:{state:!0},_ownerOpen:{state:!0},_repos:{state:!0},_totalCount:{state:!0},_hasMore:{state:!0},_nextPage:{state:!0},_reposMode:{state:!0},_repoOpen:{state:!0},_repoSearch:{state:!0},_loadingRepos:{state:!0},_selectedRepo:{state:!0},_classification:{state:!0},_classifying:{state:!0},_confirmText:{state:!0},_connecting:{state:!0},_error:{state:!0}};#e=null;#t=0;#n=!1;#r=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.apiBase=``,this.connectUrl=``,this.installUrl=``,this.cancelUrl=``,this.createRepoNameHint=``,this._installations=[],this._selectedOwner=null,this._ownerOpen=!1,this._repos=[],this._totalCount=0,this._hasMore=!1,this._nextPage=null,this._reposMode=`list`,this._repoOpen=!1,this._repoSearch=``,this._loadingRepos=!1,this._selectedRepo=null,this._classification=null,this._classifying=!1,this._confirmText=``,this._connecting=!1,this._error=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#m),document.addEventListener(`keydown`,this.#h),window.addEventListener(`focus`,this.#g),this.#i()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#m),document.removeEventListener(`keydown`,this.#h),window.removeEventListener(`focus`,this.#g),this.#e&&clearTimeout(this.#e)}async#i(){try{let e=await fetch(`${this.apiBase}/installations`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._installations=t.installations;let n=t.installations.length===1?t.installations[0]:null;n&&this.#u(n)}catch(e){this._error=e instanceof Error?e.message:String(e)}}async#a(e,t={}){let n=++this.#t;this._loadingRepos=!0;try{let r=new URLSearchParams({installationId:e});t.q&&r.set(`q`,t.q);let i=await fetch(`${this.apiBase}/repos?${r.toString()}`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(n!==this.#t)return;if(i.status===410){this._installations=this._installations.filter(t=>t.installationId!==e),this._selectedOwner=null,this._repos=[];return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let a=await i.json();this._repos=a.repos,this._totalCount=a.totalCount,this._hasMore=a.hasMore,this._nextPage=a.nextPage,this._reposMode=a.mode}catch(e){n===this.#t&&(this._error=e instanceof Error?e.message:String(e))}finally{n===this.#t&&(this._loadingRepos=!1)}}async#o(e,t){this._classifying=!0,this._classification=null,this._confirmText=``;try{let n=await fetch(`${this.apiBase}/classify`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:e,repo:t})}),r=await n.json();if(!n.ok||!r.classification)throw Error(r.error??`HTTP ${n.status}`);this._classification=r.classification}catch(e){this._error=e instanceof Error?e.message:String(e)}finally{this._classifying=!1}}async#s(){if(!(!this._selectedOwner||!this._selectedRepo||!this._classification)){this._connecting=!0,this._error=null;try{let e=this._classification.kind===`foreign`||this._classification.kind===`owned-by-other-site`,t=await fetch(this.connectUrl,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:this._selectedOwner.installationId,repo:this._selectedRepo.fullName,confirmForeign:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw Error(n.error??`HTTP ${t.status}`);window.location.href=n.redirect??this.cancelUrl}catch(e){this._error=e instanceof Error?e.message:String(e),this._connecting=!1}}}#c(){let e=this._selectedOwner;if(!e)return;let t=this.createRepoNameHint||``,n=new URL(`https://github.com/new`);t&&n.searchParams.set(`name`,t),n.searchParams.set(`owner`,e.account.login),n.searchParams.set(`visibility`,`private`),this.#n=!0,this.#r=t||null,window.open(n.toString(),`_blank`,`noopener,noreferrer`),this._repoOpen=!1}#l(){if(!this._selectedOwner)return;let e=this._repoSearch.trim();this.#a(this._selectedOwner.installationId,e?{q:e}:{})}#u(e){if(this._selectedOwner?.installationId===e.installationId){this._ownerOpen=!1;return}this._selectedOwner=e,this._ownerOpen=!1,this._selectedRepo=null,this._classification=null,this._confirmText=``,this._repoSearch=``,this.#a(e.installationId)}#d(e){this._selectedRepo=e,this._repoOpen=!1,this._repoSearch=``,this._selectedOwner&&this.#o(this._selectedOwner.installationId,e.fullName)}#f(e){let t=e.target.value;if(this._repoSearch=t,this.#e&&clearTimeout(this.#e),!this._selectedOwner)return;let n=t.trim();if(n.length<Xz){this._reposMode===`search`&&this.#a(this._selectedOwner.installationId);return}this.#e=setTimeout(()=>{this._selectedOwner&&this.#a(this._selectedOwner.installationId,{q:n})},Yz)}#p(){let e=this._repoSearch.trim().toLowerCase();return!e||this._reposMode===`search`?this._repos:this._repos.filter(t=>t.name.toLowerCase().includes(e)||t.fullName.toLowerCase().includes(e))}#m=e=>{if(!this._ownerOpen&&!this._repoOpen)return;let t=e.target,n=this.querySelector(`.repo-picker-owner`),r=this.querySelector(`.repo-picker-repo`);n&&!n.contains(t)&&(this._ownerOpen=!1),r&&!r.contains(t)&&(this._repoOpen=!1)};#h=e=>{e.key===`Escape`&&(this._ownerOpen||this._repoOpen)&&(this._ownerOpen=!1,this._repoOpen=!1)};#g=()=>{if(!this.#n)return;let e=this._selectedOwner;if(!e){this.#n=!1;return}let t=this.#r;this.#n=!1,this.#r=null,(async()=>{if(this._repoSearch=``,await this.#a(e.installationId),t){let e=this._repos.find(e=>e.name===t);e&&this.#d(e)}})()};#_(){this._ownerOpen=!this._ownerOpen,this._repoOpen=!1}#v(){this._selectedOwner&&(this._repoOpen=!this._repoOpen,this._ownerOpen=!1,this._repoOpen&&queueMicrotask(()=>{this.querySelector(`.repo-picker-repo-search`)?.focus()}))}render(){return u`
2606
2606
  <div class="flex flex-col gap-6 max-w-lg">
2607
2607
  <div>
2608
2608
  <h2 class="text-lg font-medium mb-1">${this.labels.pageTitle}</h2>
@@ -2813,7 +2813,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2813
2813
  </button>
2814
2814
  <a href=${this.cancelUrl} class="btn-ghost">${this.labels.cancel}</a>
2815
2815
  </div>
2816
- `}};customElements.define(`jant-repo-picker`,Jz);var Yz=`/collections`;function Xz(e){return e.includes(`+`)}function Zz(){return Yz}function Qz(e){return`/${e}`}function $z(e){return Xz(e)?`${Yz}/${e}`:Qz(e)}function eB(e){return`${Yz}/${e}/edit`}var tB,nB;function rB(){return tB?Promise.resolve(tB):(nB||=ZO(()=>import(`./chunks/url-pLre2DM_.js`).then(e=>e.i).then(e=>(tB=e.slugify,e.slugify)),[]),nB)}async function iB(e){return(await rB())(e)}var aB=class extends c{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;_descEditor=null;#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),this.#f(e))},this.addEventListener(`keydown`,this.#t)}disconnectedCallback(){this.#t&&=(this.removeEventListener(`keydown`,this.#t),null),super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null}update(e){(!this.#e||e.has(`initial`))&&this.#n(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#n(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`,this.variant!==`quick`&&this.updateComplete.then(()=>this.#r()))}#r(){let e=this.querySelector(`[data-collection-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=PT({element:e,placeholder:this.isEdit?void 0:this.labels.descriptionPlaceholder,content:this._description||void 0,onUpdate:e=>{this._description=e}}),this._description=NT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`5rem`)}async#i(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=gS(await iB(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#a(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#o(){let e=_S(this._slug,{maxLength:200});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#s(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#c(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#l(){let e=i(Qz(this._slug.trim()||`example`)),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}#u(){let e=this.#o();return e?u`<p
2816
+ `}};customElements.define(`jant-repo-picker`,Zz);var Qz=`/collections`;function $z(e){return e.includes(`+`)}function eB(){return Qz}function tB(e){return`/${e}`}function nB(e){return $z(e)?`${Qz}/${e}`:tB(e)}function rB(e){return`${Qz}/${e}/edit`}var iB,aB;function oB(){return iB?Promise.resolve(iB):(aB||=ZO(()=>import(`./chunks/url-pLre2DM_.js`).then(e=>e.i).then(e=>(iB=e.slugify,e.slugify)),[]),aB)}async function sB(e){return(await oB())(e)}var cB=class extends c{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;_descEditor=null;#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),this.#f(e))},this.addEventListener(`keydown`,this.#t)}disconnectedCallback(){this.#t&&=(this.removeEventListener(`keydown`,this.#t),null),super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null}update(e){(!this.#e||e.has(`initial`))&&this.#n(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#n(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`,this.variant!==`quick`&&this.updateComplete.then(()=>this.#r()))}#r(){let e=this.querySelector(`[data-collection-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=PT({element:e,placeholder:this.isEdit?void 0:this.labels.descriptionPlaceholder,content:this._description||void 0,onUpdate:e=>{this._description=e}}),this._description=NT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`5rem`)}async#i(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=gS(await sB(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#a(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#o(){let e=_S(this._slug,{maxLength:200});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#s(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#c(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#l(){let e=i(tB(this._slug.trim()||`example`)),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}#u(){let e=this.#o();return e?u`<p
2817
2817
  class="text-xs text-destructive mt-1"
2818
2818
  data-collection-slug-error
2819
2819
  >
@@ -2870,7 +2870,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2870
2870
  </button>
2871
2871
  </div>
2872
2872
  </div>
2873
- `}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=gS(await iB(t),200),this._slug=n,this._suggestedSlug=n),!n||this.#o()){this.variant===`quick`&&!this._showSlugEditor&&this.#s(),this.updateComplete.then(()=>{this.querySelector(`[data-collection-slug-input]`)?.focus()});return}let r={endpoint:this.action,isEdit:this.isEdit,data:{title:t,slug:n,description:this.variant===`quick`?void 0:this._description.trim()||void 0,sortOrder:this.variant===`quick`?void 0:this._sortOrder||void 0}};this.dispatchEvent(new CustomEvent(`jant:collection-submit`,{bubbles:!0,detail:r}))}render(){let e=this.variant===`quick`;return u`
2873
+ `}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=gS(await sB(t),200),this._slug=n,this._suggestedSlug=n),!n||this.#o()){this.variant===`quick`&&!this._showSlugEditor&&this.#s(),this.updateComplete.then(()=>{this.querySelector(`[data-collection-slug-input]`)?.focus()});return}let r={endpoint:this.action,isEdit:this.isEdit,data:{title:t,slug:n,description:this.variant===`quick`?void 0:this._description.trim()||void 0,sortOrder:this.variant===`quick`?void 0:this._sortOrder||void 0}};this.dispatchEvent(new CustomEvent(`jant:collection-submit`,{bubbles:!0,detail:r}))}render(){let e=this.variant===`quick`;return u`
2874
2874
  <form
2875
2875
  class=${e?`flex flex-col gap-4`:`collection-editor-form`}
2876
2876
  @submit=${e=>void this.#f(e)}
@@ -2985,20 +2985,20 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2985
2985
  </div>
2986
2986
  `}
2987
2987
  </form>
2988
- `}};customElements.define(`jant-collection-form`,aB);function oB(e,t){let n=e[t];if(!n||n.type!==`divider`||!n.label)return null;let r=[];for(let n=t+1;n<e.length;n+=1){let t=e[n];if(!t||t.type===`divider`)break;let i=t.collection?.slug;i&&r.push(i)}return r.length<2?null:{slugExpression:r.join(`+`),collectionCount:r.length}}function sB(e){return typeof e==`string`?e:``}function cB(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function lB(e){let n=sx(t(e.src));if(!n)return``;let r=` sandbox="${sx(e.sandbox)}"`,i=e.allow?` allow="${sx(e.allow)}"`:``;return`<iframe src="${n}"${` title="${sx(e.providerName)} embed"`}${r}${i} loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`}function uB(e){let t=e.orientation===`portrait`?`portrait`:e.orientation===`square`?`square`:e.orientation===`auto`?`auto`:`landscape`,n=[];e.heightPx&&e.heightPx>0&&n.push(`--tiptap-embed-height:${Math.round(e.heightPx)}px`);let r=n.length>0?` style="${sx(n.join(`;`))}"`:``;return` data-orientation="${sx(t)}"${r}`}function dB(e,n){let r=lB(e);if(!r)return``;let i=sx(t(e.url||e.src)),a=sx(e.providerName),o=i?`<a class="tiptap-embed-fallback" href="${i}" target="_blank" rel="noopener noreferrer">${a} →</a>`:``,s=sx(e.provider),c=n?.trim()?`<figcaption>${sx(n.trim())}</figcaption>`:``;return`<figure class="tiptap-embed-figure" data-provider="${s}"${uB(e)}><div class="tiptap-embed-frame">${r}</div>`+o+c+`</figure>`}function fB(e){let n=e??{},r=sB(n.url),i=sB(n.src),a=null;if(i){let e=t(i);e&&(a={provider:sB(n.provider)||`iframe`,providerName:sB(n.providerName)||`Embed`,src:e,url:r||e,orientation:sB(n.orientation)||`landscape`,heightPx:cB(n.heightPx)??void 0,sandbox:sB(n.sandbox)||`allow-scripts allow-same-origin allow-popups`,allow:sB(n.allow)||void 0,cspFrameSrc:[],cspScriptSrc:[]})}if(!a&&r&&(a=RS(r)),!a){if(!r)return``;let e=sx(t(r));return e?`<p class="tiptap-embed-fallback"><a href="${e}" target="_blank" rel="noopener noreferrer">${e}</a></p>`:``}return dB(a,sB(n.caption))}function pB(e,t){let n=e?.[t];return typeof n==`string`?n:``}function mB(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function hB(e){switch(e.type){case`text`:return sx(e.text??``);case`hardBreak`:return`
2989
- `;default:return(e.content??[]).map(hB).join(``)}}function gB(e,t,n){let r=mB(t.attrs,`colspan`),i=mB(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function _B(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var vB=null;function yB(e,t){let n=Qb(pB(e.attrs,`label`)),r=nx(n),i=vB?.get(n),a=i?_B(t.renderChildren(i.content)):``;return`<label for="sn-${sx(r)}" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-${sx(r)}" class="margin-toggle"/><span class="sidenote">${a}</span>`}var bB={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=sx(t(pB(n.attrs,`href`))),i=pB(n.attrs,`target`);return`<a href="${r}"${i?` target="${sx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},xB={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=Qb(pB(e.attrs,`label`));t&&r.set(t,e)}vB=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{vB=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(mB(e.attrs,`level`)??1,1),6);return`<h${n}>${t.renderChildren(e.content)}</h${n}>`},text:(e,t)=>t.renderText(e.text??``,e.marks),bulletList:(e,t)=>`<ul>${t.renderChildren(e.content)}</ul>`,orderedList:(e,t)=>{let n=mB(e.attrs,`start`);return`<ol${n!==null&&n!==1?` start="${n}"`:``}>${t.renderChildren(e.content)}</ol>`},listItem:(e,t)=>`<li>${t.renderChildren(e.content)}</li>`,blockquote:(e,t)=>`<blockquote>${t.renderChildren(e.content)}</blockquote>`,codeBlock:e=>{let t=pB(e.attrs,`language`);return`<pre><code${t?` class="language-${sx(t)}"`:``}>${hB(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>gB(`td`,e,t),tableHeader:(e,t)=>gB(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>ux(e.attrs??{}),embed:e=>fB(e.attrs),htmlBlock:e=>{let t=pB(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>yB(e,t),footnoteDefinition:()=>``};function SB(e,t=[]){let n=sx(e);for(let e of t){let t=bB[e.type];t&&(n=t(n,e))}return n}function CB(e=[]){return e.map(TB).join(``)}function wB(e,t){return e.content?t.renderChildren(e.content):``}function TB(e){return(xB[e.type]??wB)(e,EB)}var EB={renderChildren:CB,renderNode:TB,renderText:SB};function DB(e){return e.type===`doc`?TB(ax(e)):``}function OB(e){return e.trim()?DB(Bx(e)):``}function kB(){return Math.floor(Date.now()/1e3)}function AB(e){return new Date(e*1e3).toISOString()}function jB(e,t=`UTC`){let n=kB()-e;if(n<60)return`1m`;let r=Math.floor(n/60);if(r<60)return`${r}m`;let i=Math.floor(n/3600);if(i<24)return`${i}h`;let a=Math.floor(n/86400);return a<=7?`${a}d`:new Date(e*1e3).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,timeZone:t})}function MB(e,t=`UTC`){let n=jB(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var NB=class extends c{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#b();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#y();break;case`divider`:this.#C();break;case`link`:this.#w();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#p()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(){return this._items.filter(e=>e.type===`collection`&&e.collection).length}#d(){let e=this.#u();return`${e} ${e===1?this.labels.collectionSingular:this.labels.collectionPlural}`}#f(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#p(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#m(e){return this.#r?.querySelector(e)??null}#h(){let e=this.#m(`[data-collections-count]`);e&&(e.textContent=this.#d(),e.hidden=!1);let t=this.#m(`[data-collections-action="done"]`);t&&(t.hidden=!this._reorderMode);let n=this.#m(`[data-collections-reorder-actions]`);n&&(n.hidden=!this._reorderMode);let r=this.#m(`[data-collections-toolbar]`);r&&(r.hidden=this._reorderMode);let i=this.#m(`[data-collections-hint]`);i&&(i.hidden=!this._reorderMode);let a=this.#m(`[data-collections-more-menu]`);a&&(a.hidden=!this._showMoreMenu||this._reorderMode);let o=this.#m(`[data-collections-action="toggle-menu"]`);o&&o.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#g(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#_(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#g(t)}catch{}}#v(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...yO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{CO(e,!0)},onStart:e=>{this.#n=xO(e)},onUnchoose:()=>{CO(e,!1)},onEnd:t=>{let n=bO(e,`[data-directory-item]`,`directoryItem`);SO(e,t,this.#n),this.#n=null,CO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:a}=wO(n,t.newIndex);if(!r)return;let o=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>o.get(e)).filter(e=>e!==void 0),fetch(`/api/collections/directory-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:a??null})}).then(e=>{e.ok?d(this.labels.orderSaved):d(this.labels.saveFailed,`error`)})}}))}#y(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#b(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#p(),this.#h(),this._reorderMode&&this.#v(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#x()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#S()}#x(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=PT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=NT(this.#i.getJSON()))}#S(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=PT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=NT(this.#a.getJSON()))}async#C(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#_(),this._editingDividerId=t.id}catch{d(this.labels.saveFailed,`error`)}}#w(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#T(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){d(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=this._newLinkDescription.trim()||null,r=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,description:n})});if(!r.ok)throw Error(`HTTP ${r.status}`);this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,d(this.labels.linkCreated),await this.#_()}catch{d(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#E(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{d(this.labels.saveFailed,`error`)}}async#D(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{d(this.labels.saveFailed,`error`),await this.#_()}}async#O(e){if(await be({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);d(this.labels.deleted),await this.#_()}catch{d(this.labels.saveFailed,`error`)}}}#k(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#A(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){d(this.labels.labelAndUrlRequired,`error`);return}try{let r=this._editLinkDescription.trim()||null,i=await fetch(`/api/collections/directory-items/${e.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,url:n,description:r})});if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();this._items=this._items.map(r=>r.id===e.id?{...r,label:a.label??t,url:a.url??n,description:a.description??null}:r),this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,d(this.labels.linkSaved)}catch{d(this.labels.saveFailed,`error`),await this.#_()}}async#j(e){if(await be({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,d(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{d(this.labels.saveFailed,`error`)}}}#M(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#N(e,t){let n=e.collection;if(!n)return g;let r=u`
2988
+ `}};customElements.define(`jant-collection-form`,cB);function lB(e,t){let n=e[t];if(!n||n.type!==`divider`||!n.label)return null;let r=[];for(let n=t+1;n<e.length;n+=1){let t=e[n];if(!t||t.type===`divider`)break;let i=t.collection?.slug;i&&r.push(i)}return r.length<2?null:{slugExpression:r.join(`+`),collectionCount:r.length}}function uB(e){return typeof e==`string`?e:``}function dB(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function fB(e){let n=sx(t(e.src));if(!n)return``;let r=` sandbox="${sx(e.sandbox)}"`,i=e.allow?` allow="${sx(e.allow)}"`:``;return`<iframe src="${n}"${` title="${sx(e.providerName)} embed"`}${r}${i} loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`}function pB(e){let t=e.orientation===`portrait`?`portrait`:e.orientation===`square`?`square`:e.orientation===`auto`?`auto`:`landscape`,n=[];e.heightPx&&e.heightPx>0&&n.push(`--tiptap-embed-height:${Math.round(e.heightPx)}px`);let r=n.length>0?` style="${sx(n.join(`;`))}"`:``;return` data-orientation="${sx(t)}"${r}`}function mB(e,n){let r=fB(e);if(!r)return``;let i=sx(t(e.url||e.src)),a=sx(e.providerName),o=i?`<a class="tiptap-embed-fallback" href="${i}" target="_blank" rel="noopener noreferrer">${a} →</a>`:``,s=sx(e.provider),c=n?.trim()?`<figcaption>${sx(n.trim())}</figcaption>`:``;return`<figure class="tiptap-embed-figure" data-provider="${s}"${pB(e)}><div class="tiptap-embed-frame">${r}</div>`+o+c+`</figure>`}function hB(e){let n=e??{},r=uB(n.url),i=uB(n.src),a=null;if(i){let e=t(i);e&&(a={provider:uB(n.provider)||`iframe`,providerName:uB(n.providerName)||`Embed`,src:e,url:r||e,orientation:uB(n.orientation)||`landscape`,heightPx:dB(n.heightPx)??void 0,sandbox:uB(n.sandbox)||`allow-scripts allow-same-origin allow-popups`,allow:uB(n.allow)||void 0,cspFrameSrc:[],cspScriptSrc:[]})}if(!a&&r&&(a=RS(r)),!a){if(!r)return``;let e=sx(t(r));return e?`<p class="tiptap-embed-fallback"><a href="${e}" target="_blank" rel="noopener noreferrer">${e}</a></p>`:``}return mB(a,uB(n.caption))}function gB(e,t){let n=e?.[t];return typeof n==`string`?n:``}function _B(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function vB(e){switch(e.type){case`text`:return sx(e.text??``);case`hardBreak`:return`
2989
+ `;default:return(e.content??[]).map(vB).join(``)}}function yB(e,t,n){let r=_B(t.attrs,`colspan`),i=_B(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function bB(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var xB=null;function SB(e,t){let n=Qb(gB(e.attrs,`label`)),r=nx(n),i=xB?.get(n),a=i?bB(t.renderChildren(i.content)):``;return`<label for="sn-${sx(r)}" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-${sx(r)}" class="margin-toggle"/><span class="sidenote">${a}</span>`}var CB={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=sx(t(gB(n.attrs,`href`))),i=gB(n.attrs,`target`);return`<a href="${r}"${i?` target="${sx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},wB={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=Qb(gB(e.attrs,`label`));t&&r.set(t,e)}xB=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{xB=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(_B(e.attrs,`level`)??1,1),6);return`<h${n}>${t.renderChildren(e.content)}</h${n}>`},text:(e,t)=>t.renderText(e.text??``,e.marks),bulletList:(e,t)=>`<ul>${t.renderChildren(e.content)}</ul>`,orderedList:(e,t)=>{let n=_B(e.attrs,`start`);return`<ol${n!==null&&n!==1?` start="${n}"`:``}>${t.renderChildren(e.content)}</ol>`},listItem:(e,t)=>`<li>${t.renderChildren(e.content)}</li>`,blockquote:(e,t)=>`<blockquote>${t.renderChildren(e.content)}</blockquote>`,codeBlock:e=>{let t=gB(e.attrs,`language`);return`<pre><code${t?` class="language-${sx(t)}"`:``}>${vB(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>yB(`td`,e,t),tableHeader:(e,t)=>yB(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>ux(e.attrs??{}),embed:e=>hB(e.attrs),htmlBlock:e=>{let t=gB(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>SB(e,t),footnoteDefinition:()=>``};function TB(e,t=[]){let n=sx(e);for(let e of t){let t=CB[e.type];t&&(n=t(n,e))}return n}function EB(e=[]){return e.map(OB).join(``)}function DB(e,t){return e.content?t.renderChildren(e.content):``}function OB(e){return(wB[e.type]??DB)(e,kB)}var kB={renderChildren:EB,renderNode:OB,renderText:TB};function AB(e){return e.type===`doc`?OB(ax(e)):``}function jB(e){return e.trim()?AB(Bx(e)):``}function MB(){return Math.floor(Date.now()/1e3)}function NB(e){return new Date(e*1e3).toISOString()}function PB(e,t=`UTC`){let n=MB()-e;if(n<60)return`1m`;let r=Math.floor(n/60);if(r<60)return`${r}m`;let i=Math.floor(n/3600);if(i<24)return`${i}h`;let a=Math.floor(n/86400);return a<=7?`${a}d`:new Date(e*1e3).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,timeZone:t})}function FB(e,t=`UTC`){let n=PB(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var IB=class extends c{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#b();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#y();break;case`divider`:this.#C();break;case`link`:this.#w();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#p()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(){return this._items.filter(e=>e.type===`collection`&&e.collection).length}#d(){let e=this.#u();return`${e} ${e===1?this.labels.collectionSingular:this.labels.collectionPlural}`}#f(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#p(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#m(e){return this.#r?.querySelector(e)??null}#h(){let e=this.#m(`[data-collections-count]`);e&&(e.textContent=this.#d(),e.hidden=!1);let t=this.#m(`[data-collections-action="done"]`);t&&(t.hidden=!this._reorderMode);let n=this.#m(`[data-collections-reorder-actions]`);n&&(n.hidden=!this._reorderMode);let r=this.#m(`[data-collections-toolbar]`);r&&(r.hidden=this._reorderMode);let i=this.#m(`[data-collections-hint]`);i&&(i.hidden=!this._reorderMode);let a=this.#m(`[data-collections-more-menu]`);a&&(a.hidden=!this._showMoreMenu||this._reorderMode);let o=this.#m(`[data-collections-action="toggle-menu"]`);o&&o.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#g(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#_(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#g(t)}catch{}}#v(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...yO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{CO(e,!0)},onStart:e=>{this.#n=xO(e)},onUnchoose:()=>{CO(e,!1)},onEnd:t=>{let n=bO(e,`[data-directory-item]`,`directoryItem`);SO(e,t,this.#n),this.#n=null,CO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:a}=wO(n,t.newIndex);if(!r)return;let o=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>o.get(e)).filter(e=>e!==void 0),fetch(`/api/collections/directory-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:a??null})}).then(e=>{e.ok?d(this.labels.orderSaved):d(this.labels.saveFailed,`error`)})}}))}#y(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#b(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#p(),this.#h(),this._reorderMode&&this.#v(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#x()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#S()}#x(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=PT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=NT(this.#i.getJSON()))}#S(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=PT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=NT(this.#a.getJSON()))}async#C(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#_(),this._editingDividerId=t.id}catch{d(this.labels.saveFailed,`error`)}}#w(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#T(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){d(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=this._newLinkDescription.trim()||null,r=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,description:n})});if(!r.ok)throw Error(`HTTP ${r.status}`);this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,d(this.labels.linkCreated),await this.#_()}catch{d(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#E(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{d(this.labels.saveFailed,`error`)}}async#D(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{d(this.labels.saveFailed,`error`),await this.#_()}}async#O(e){if(await be({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);d(this.labels.deleted),await this.#_()}catch{d(this.labels.saveFailed,`error`)}}}#k(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#A(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){d(this.labels.labelAndUrlRequired,`error`);return}try{let r=this._editLinkDescription.trim()||null,i=await fetch(`/api/collections/directory-items/${e.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,url:n,description:r})});if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();this._items=this._items.map(r=>r.id===e.id?{...r,label:a.label??t,url:a.url??n,description:a.description??null}:r),this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,d(this.labels.linkSaved)}catch{d(this.labels.saveFailed,`error`),await this.#_()}}async#j(e){if(await be({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,d(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{d(this.labels.saveFailed,`error`)}}}#M(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#N(e,t){let n=e.collection;if(!n)return g;let r=u`
2990
2990
  <div class="collection-directory-main">
2991
2991
  <span class="collection-directory-sequence" aria-hidden="true">
2992
2992
  ${t}
2993
2993
  </span>
2994
2994
  <div class="collection-directory-title-row">
2995
- <a href=${i($z(n.slug))} class="collection-directory-title-link">
2995
+ <a href=${i(nB(n.slug))} class="collection-directory-title-link">
2996
2996
  <span class="collection-directory-title">${n.title}</span>
2997
2997
  </a>
2998
2998
  </div>
2999
2999
  ${n.description?u`
3000
3000
  <div class="collection-directory-description prose">
3001
- ${v(OB(n.description))}
3001
+ ${v(jB(n.description))}
3002
3002
  </div>
3003
3003
  `:g}
3004
3004
  <p class="collection-directory-summary">
@@ -3010,9 +3010,9 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3010
3010
  >
3011
3011
  <time
3012
3012
  class="collection-directory-updated"
3013
- datetime=${AB(n.recentActivityAt)}
3013
+ datetime=${NB(n.recentActivityAt)}
3014
3014
  >
3015
- ${MB(n.recentActivityAt)}
3015
+ ${FB(n.recentActivityAt)}
3016
3016
  </time>
3017
3017
  </p>
3018
3018
  </div>
@@ -3152,7 +3152,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3152
3152
  </div>
3153
3153
  ${e.description?u`
3154
3154
  <div class="collection-directory-description prose">
3155
- ${v(OB(e.description))}
3155
+ ${v(jB(e.description))}
3156
3156
  </div>
3157
3157
  `:u`
3158
3158
  <p class="collection-directory-summary">
@@ -3230,7 +3230,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3230
3230
  >
3231
3231
  ${t?u`
3232
3232
  <a
3233
- href=${i(`${eB(t.slug)}?returnTo=${encodeURIComponent(i(Zz()))}`)}
3233
+ href=${i(`${rB(t.slug)}?returnTo=${encodeURIComponent(i(eB()))}`)}
3234
3234
  class="collections-page-menu-item"
3235
3235
  >
3236
3236
  ${this.labels.edit}
@@ -3322,7 +3322,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3322
3322
  </svg>
3323
3323
  </button>
3324
3324
  </div>
3325
- `;let n=!!e.label,r=oB(this._items,t);return u`
3325
+ `;let n=!!e.label,r=lB(this._items,t);return u`
3326
3326
  <div class="collection-directory-divider">
3327
3327
  <div
3328
3328
  class="collection-directory-divider-row"
@@ -3331,7 +3331,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3331
3331
  ${n?u`
3332
3332
  ${r?u`
3333
3333
  <a
3334
- href=${i($z(r.slugExpression))}
3334
+ href=${i(nB(r.slugExpression))}
3335
3335
  class="collection-directory-divider-link collection-directory-divider-text"
3336
3336
  >
3337
3337
  ${e.label}
@@ -3409,7 +3409,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3409
3409
  ${(()=>{let e=this.#M();return this._items.map((t,n)=>t.type===`collection`?this.#N(t,e[n]):t.type===`link`?this.#F(t,e[n]):this.#L(t,n))})()}
3410
3410
  </div>
3411
3411
  `:u`<p class="text-muted-foreground">${this.labels.emptyState}</p>`}
3412
- `}};customElements.define(`jant-collections-manager`,NB);function PB(e){try{let t=new URL(e,window.location.origin);return t.origin===window.location.origin?t:null}catch{return null}}function FB(){return document.documentElement.dataset.sitePathPrefix||``}function IB(e){let t=FB();return t?e===t?`/`:e.startsWith(`${t}/`)?e.slice(t.length)||`/`:null:e||`/`}function LB(e,t,n){let r=e.split(`+`).filter(Boolean);if(r.length===0||r.length===1)return t;if(!n)return e;let i=!1,a=r.map(e=>e===n?(i=!0,t):e);return i?a.join(`+`):e}function RB(e,t,n){let r=t.cancelHref||i(Zz());if(!e.isEdit||!n)return r;let a=PB(r);if(!a)return i(Qz(n));let o=IB(a.pathname),s=t.initial?.slug?.trim()||void 0;if(s&&o===Qz(s))return a.pathname=i(Qz(n)),`${a.pathname}${a.search}${a.hash}`;let c=o?.match(/^\/collections\/([^/]+)$/);return c&&(a.pathname=i($z(LB(c[1],n,s)))),`${a.pathname}${a.search}${a.hash}`}document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let a=RB(n,r,typeof t?.slug==`string`&&t.slug.length>0?t.slug:void 0);window.location.href=a;return}catch(e){d(e instanceof Error?e.message:i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`,`error`)}finally{r.loading=!1}}});function zB(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(sS(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return u`<svg
3412
+ `}};customElements.define(`jant-collections-manager`,IB);function LB(e){try{let t=new URL(e,window.location.origin);return t.origin===window.location.origin?t:null}catch{return null}}function RB(){return document.documentElement.dataset.sitePathPrefix||``}function zB(e){let t=RB();return t?e===t?`/`:e.startsWith(`${t}/`)?e.slice(t.length)||`/`:null:e||`/`}function BB(e,t,n){let r=e.split(`+`).filter(Boolean);if(r.length===0||r.length===1)return t;if(!n)return e;let i=!1,a=r.map(e=>e===n?(i=!0,t):e);return i?a.join(`+`):e}function VB(e,t,n){let r=t.cancelHref||i(eB());if(!e.isEdit||!n)return r;let a=LB(r);if(!a)return i(tB(n));let o=zB(a.pathname),s=t.initial?.slug?.trim()||void 0;if(s&&o===tB(s))return a.pathname=i(tB(n)),`${a.pathname}${a.search}${a.hash}`;let c=o?.match(/^\/collections\/([^/]+)$/);return c&&(a.pathname=i(nB(BB(c[1],n,s)))),`${a.pathname}${a.search}${a.hash}`}document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let a=VB(n,r,typeof t?.slug==`string`&&t.slug.length>0?t.slug:void 0);window.location.href=a;return}catch(e){d(e instanceof Error?e.message:i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`,`error`)}finally{r.loading=!1}}});function HB(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(sS(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return u`<svg
3413
3413
  width="24"
3414
3414
  height="24"
3415
3415
  viewBox="0 0 24 24"
@@ -3442,7 +3442,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3442
3442
  stroke-linejoin="round"
3443
3443
  >
3444
3444
  ${Ce(`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>`+t)}
3445
- </svg>`}function BB(e){return sS(e.mimeType)===`image`?u`<img
3445
+ </svg>`}function UB(e){return sS(e.mimeType)===`image`?u`<img
3446
3446
  src=${e.thumbUrl}
3447
3447
  alt=${e.alt}
3448
3448
  class="w-full h-full object-cover rounded-lg border"
@@ -3450,15 +3450,15 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3450
3450
  />`:u`<div
3451
3451
  class="w-full h-full rounded-lg border bg-muted flex flex-col items-center justify-center gap-1 p-1 text-muted-foreground"
3452
3452
  >
3453
- ${zB(e.mimeType)}
3453
+ ${HB(e.mimeType)}
3454
3454
  <span class="text-[10px] leading-tight text-center truncate w-full px-1"
3455
3455
  >${e.originalName}</span
3456
3456
  >
3457
- </div>`}function VB(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return u`<p class="text-sm text-muted-foreground">
3457
+ </div>`}function WB(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return u`<p class="text-sm text-muted-foreground">
3458
3458
  ${n.mediaEmptyLabel}
3459
3459
  </p>`;let i=new Map(t.map(e=>[e.id,e]));return u`<div class="grid grid-cols-4 sm:grid-cols-6 gap-2 mb-2">
3460
3460
  ${r.map(t=>{let r=i.get(t);return r?u`<div class="relative group aspect-square" data-media-id=${t}>
3461
- ${BB(r)}
3461
+ ${UB(r)}
3462
3462
  <button
3463
3463
  type="button"
3464
3464
  class="absolute top-1 right-1 w-5 h-5 flex items-center justify-center bg-black/60 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
@@ -3480,7 +3480,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3480
3480
  &times;
3481
3481
  </button>
3482
3482
  </div>`})}
3483
- </div>`}function HB(e){return e.collections.length?u`<div class="field">
3483
+ </div>`}function GB(e){return e.collections.length?u`<div class="field">
3484
3484
  <label class="label">${e.labels.collectionsLabel}</label>
3485
3485
  <div class="flex flex-col gap-1">
3486
3486
  ${e.collections.map(t=>u`<label class="flex items-center gap-2 text-sm">
@@ -3493,7 +3493,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3493
3493
  <span>${t.title}</span>
3494
3494
  </label>`)}
3495
3495
  </div>
3496
- </div>`:g}function UB(e){return u`<form
3496
+ </div>`:g}function KB(e){return u`<form
3497
3497
  class="flex flex-col gap-4 max-w-2xl"
3498
3498
  @submit=${t=>e.handleSubmit(t)}
3499
3499
  >
@@ -3568,7 +3568,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3568
3568
 
3569
3569
  <div class="field">
3570
3570
  <label class="label">${e.labels.mediaLabel}</label>
3571
- ${VB(e)}
3571
+ ${WB(e)}
3572
3572
  <button
3573
3573
  type="button"
3574
3574
  class="btn-outline text-sm"
@@ -3614,7 +3614,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3614
3614
  ${e.labels.pinnedLabel}
3615
3615
  </label>
3616
3616
 
3617
- ${HB(e)}
3617
+ ${GB(e)}
3618
3618
 
3619
3619
  <div class="flex gap-2">
3620
3620
  <button type="submit" class="btn" ?disabled=${e._loading}>
@@ -3664,7 +3664,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3664
3664
  ${e.labels.mediaDialogLoading}
3665
3665
  </p>
3666
3666
  </div>
3667
- </dialog>`}var WB={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},GB={formatLabel:``,noteOption:``,linkOption:``,quoteOption:``,titleLabel:``,titlePlaceholder:``,slugLabel:``,slugPlaceholder:``,slugHelp:``,bodyLabel:``,bodyPlaceholder:``,urlLabel:``,urlPlaceholder:``,quoteTextLabel:``,quoteTextPlaceholder:``,mediaLabel:``,mediaAddButton:``,mediaRemoveButton:``,mediaEmptyLabel:``,statusLabel:``,statusPublished:``,statusDraft:``,visibilityLabel:``,visibilityPublic:``,visibilityHiddenFromLatest:``,pinnedLabel:``,collectionsLabel:``,submitLabel:``,cancelLabel:``,mediaDialogTitle:``,mediaDialogDone:``,mediaDialogLoading:``,submitSuccessMessage:``,submitErrorMessage:``,draftFallbackMessage:``};function KB(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var qB=class e extends c{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...GB},this.initial={...WB},this.collections=[],this.media=[],this.action=``,this.cancelHref=`/`,this.mediaPickerUrl=``,this.siteUrl=``,this.isEdit=!1,this._format=`note`,this._title=``,this._slug=``,this._slugManuallyEdited=!1,this._body=``,this._url=``,this._quoteText=``,this._status=`published`,this._visibility=`public`,this._pinned=!1,this._rating=0,this._collectionIds=[],this._mediaIds=[],this._loading=!1}willUpdate(e){typeof this.labels==`string`&&(this.labels=KB(this.labels,{...GB})),typeof this.initial==`string`&&(this.initial=KB(this.initial,{...WB})),typeof this.collections==`string`&&(this.collections=KB(this.collections,[])),typeof this.media==`string`&&(this.media=KB(this.media,[])),(!this.#e||e.has(`initial`))&&this.#i()}set loading(e){this._loading=e}get loading(){return this._loading}set mediaIds(e){this._mediaIds=[...e]}get mediaIds(){return[...this._mediaIds]}get#r(){return this.querySelector(`#post-media-picker`)}connectedCallback(){super.connectedCallback(),window.addEventListener(`beforeunload`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener(`beforeunload`,this.#n),this._editor?.destroy(),this._editor=null,this.closeMediaPicker()}#i(){let e=this.initial??WB;if(this._format=e.format??`note`,this._title=e.title??``,this._slug=e.slug??``,this._slugManuallyEdited=!!e.slug,this._body=e.body??``,this._url=e.url??``,this._quoteText=e.quoteText??``,this._status=e.status??`published`,this._visibility=e.visibility??`public`,this._pinned=!!e.pinned,this._rating=e.rating??0,this._collectionIds=[...e.collectionIds??[]],this._mediaIds=[...e.mediaIds??[]],this.#e=!0,this._body&&this._body.startsWith(`{`))try{this._bodyJson=JSON.parse(this._body)}catch{this._bodyJson=null}else this._bodyJson=null}initEditor(){if(this._editor)return;let e=this.querySelector(`.post-form-tiptap-body`);e&&(this._editor=MT({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._bodyJson,onUpdate:e=>{this._bodyJson=e,this._body=JSON.stringify(e)},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}))}static#a=new Set([`_format`,`_title`,`_slug`,`_body`,`_url`,`_quoteText`,`_status`,`_visibility`,`_pinned`,`_rating`,`_collectionIds`,`_mediaIds`]);updated(t){if(super.updated(t),this._editor||this.initEditor(),this.#e&&!t.has(`initial`)){for(let n of t.keys())if(e.#a.has(n)){this.#t=!0;break}}}clearDirty(){this.#t=!1}handleInput(e,t){this[e]=t.target.value}handleTitleInput(e){let t=e.target;this._title=t.value,this._slugManuallyEdited||(this._slug=t.value.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``))}handleSlugInput(e){this._slug=e.target.value,this._slugManuallyEdited=!0}toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}removeMedia(e){this._mediaIds=this._mediaIds.filter(t=>t!==e)}openMediaPicker(){let e=this.#r;e&&(e.showModal(),this.dispatchEvent(new CustomEvent(`jant:post-load-media`,{bubbles:!0,detail:{endpoint:this.mediaPickerUrl,selectedIds:[...this._mediaIds]}})))}closeMediaPicker(){this.#r?.close()}handleSubmit(e){if(e.preventDefault(),this._loading||!this.action)return;let t=this._bodyJson?JSON.stringify(this._bodyJson):this._body,n={endpoint:this.action,isEdit:this.isEdit,data:{format:this._format,title:this._title.trim(),slug:this._slug.trim()||void 0,body:t,status:this._status,visibility:this._visibility,pinned:this._pinned,url:this._url.trim(),quoteText:this._quoteText.trim(),rating:this._rating,collectionIds:[...this._collectionIds],mediaIds:[...this._mediaIds]},messages:{success:this.labels.submitSuccessMessage,error:this.labels.submitErrorMessage}};this.dispatchEvent(new CustomEvent(`jant:post-submit`,{bubbles:!0,detail:n}))}render(){return UB(this)}};customElements.define(`jant-post-form`,qB);function JB(e){return e instanceof HTMLElement&&e.tagName===`JANT-POST-FORM`?e:e instanceof HTMLElement?e.closest(`jant-post-form`):document.querySelector(`jant-post-form`)}function YB(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function XB(e){let t=e,n=t.detail;if(!n)return;let r=JB(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await le(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await le(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let a=w(t,`status`),o=w(t,`url`);if(a===`redirect`&&o){r.clearDirty(),y(i),window.location.href=o;return}d(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await le(e),i=w(t,`status`),a=w(t,`url`);if(i===`redirect`&&a){r.clearDirty(),y(n.messages.success),window.location.href=a;return}r.clearDirty(),d(n.messages.success)}catch(e){d(e instanceof Error&&e.message?e.message:n.messages.error,`error`)}finally{r.loading=!1}}}async function ZB(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=JB(t.target);if(!r||!i)return;try{r.innerHTML=`<p class="text-muted-foreground text-sm col-span-4">Loading...</p>`,r.innerHTML=await(await fetch(n.endpoint,{headers:{Accept:`text/html`}})).text()}catch{r.innerHTML=`<p class="text-red-500 text-sm col-span-4">Failed to load media.</p>`;return}let a=new Set(n.selectedIds);r.querySelectorAll(`[data-media-id]`).forEach(e=>{let t=e.dataset.mediaId;t&&YB(e,a.has(t))}),r.onclick=e=>{let t=e.target.closest(`[data-media-id]`);if(!t)return;let n=t.dataset.mediaId;if(!n)return;let r=new Set(i.mediaIds);r.has(n)?(r.delete(n),YB(t,!1)):(r.add(n),YB(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,XB),document.addEventListener(`jant:post-load-media`,ZB);var{I:QB}=l,$B=e=>e,eV=()=>document.createComment(``),tV=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new QB(r.insertBefore(eV(),i),r.insertBefore(eV(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=$B(e).nextSibling;$B(r).insertBefore(e,i),e=t}}}return n},nV=(e,t,n=e)=>(e._$AI(t,n),e),rV={},iV=(e,t=rV)=>e._$AH=t,aV=e=>e._$AH,oV=e=>{e._$AR(),e._$AA.remove()},sV=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},cV=o(class extends f{constructor(e){if(super(e),e.type!==b.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=aV(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,m=0,h=a.length-1;for(;d<=f&&m<=h;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[m])c[m]=nV(i[d],a[m]),d++,m++;else if(s[f]===o[h])c[h]=nV(i[f],a[h]),f--,h--;else if(s[d]===o[h])c[h]=nV(i[d],a[h]),tV(e,c[h+1],i[d]),d++,h--;else if(s[f]===o[m])c[m]=nV(i[f],a[m]),tV(e,i[d],i[f]),f--,m++;else if(l===void 0&&(l=sV(o,m,h),u=sV(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=tV(e,i[d]);nV(t,a[m]),c[m]=t}else c[m]=nV(n,a[m]),tV(e,i[d],n),i[t]=null;m++}else oV(i[f]),f--;else oV(i[d]),d++;for(;m<=h;){let t=tV(e,c[h+1]);nV(t,a[m]),c[m++]=t}for(;d<=f;){let e=i[d++];e!==null&&oV(e)}return this.ut=o,iV(e,c),p}}),lV=class extends c{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#b())};#s=e=>{!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore||(e.preventDefault(),this.#b(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#y.length===0&&this.#b(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#b()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...yO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=xO(e)},onEnd:e=>{let t=e.to,n=e.from,r=n!==t,i=t.id===`nav-items-header`?`header`:`more`,a=this.querySelector(`#nav-items-header`),o=this.querySelector(`#nav-items-more`),s=e.item?.dataset?.navId;if(!s||!a||!o){this.#r=null;return}let c=bO(a,`[data-nav-id]`,`navId`),l=bO(o,`[data-nav-id]`,`navId`);r?(e.item.parentNode?.removeChild(e.item),this.#r?n.insertBefore(e.item,this.#r):e.oldIndex!=null&&e.oldIndex<n.children.length?n.insertBefore(e.item,n.children[e.oldIndex]??null):n.appendChild(e.item)):SO(t,e,this.#r),this.#r=null,this.#c();let u=[...new Set([...c,...l])],f=new Map(this._items.map(e=>[e.id,e.id===s?{...e,placement:i}:{...e}])),p=u.map(e=>f.get(e)).filter(e=>e!==void 0),m=this._items.filter(e=>!u.includes(e.id)).map(e=>e.id===s?{...e,placement:i}:{...e});this._items=[...p,...m];let{movedId:h,afterId:g,beforeId:_}=wO(i===`header`?c:l,e.newIndex);h&&(r?fetch(`/api/nav-items/${s}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({placement:i})}).then(async e=>e.ok?(await fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})})).ok:!1).then(e=>{e?d(this.labels.placementSaved):d(this.labels.saveFailed,`error`)}):fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})}).then(e=>{e.ok?d(this.labels.orderSaved):d(this.labels.saveFailed,`error`)}))}}}#d(e){this._editingId===e.id?this._editingId=null:(this._editingId=e.id,this._editLabel=e.label,this._editUrl=e.url)}#f(e){let t=this._editLabel.trim();if(!t&&e.type!==`system`){d(this.labels.labelRequired,`error`);return}let n={id:e.id,label:t,...e.type===`link`&&{url:this._editUrl.trim()}};this.dispatchEvent(new CustomEvent(`jant:nav-update`,{bubbles:!0,detail:n}))}async#p(e){await be({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){d(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,placement:`header`})});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#c(),this._items=[...this._items,r],this._newLinkLabel=``,this._newLinkUrl=``,this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)}catch{d(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#h(e){if(!(!e||this._addingCollectionId)){this._addingCollectionId=e;try{let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`collection`,collectionId:e,placement:`header`})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,n],this.#a()}catch{d(this.labels.saveFailed,`error`)}finally{this._addingCollectionId=null}}}#g(e){return this._items.some(t=>t.type===`system`&&t.systemKey===e.key)}async#_(e,t){this._togglingKeys=new Set([...this._togglingKeys,e.key]);try{if(t){let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`system`,systemKey:e.key})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,{...n,displayLabel:e.label}]}else{let t=this._items.find(t=>t.type===`system`&&t.systemKey===e.key);if(t){let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);this.#c(),this._items=this._items.filter(e=>e.id!==t.id)}}}catch{d(this.labels.saveFailed,`error`),this.requestUpdate()}finally{let t=new Set(this._togglingKeys);t.delete(e.key),this._togglingKeys=t}}get#v(){return this._items.filter(e=>(e.placement??`header`)===`header`)}get#y(){return this._items.filter(e=>e.placement===`more`)}#b(){this._showPreviewMore=!1,document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#s)}#x(e){if(e.preventDefault(),e.stopPropagation(),this._showPreviewMore){this.#b();return}this._showPreviewMore=!0,document.addEventListener(`keydown`,this.#s),setTimeout(()=>{document.addEventListener(`click`,this.#o)})}#S(){let e=this.#v,t=this.#y;return u`
3667
+ </dialog>`}var qB={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},JB={formatLabel:``,noteOption:``,linkOption:``,quoteOption:``,titleLabel:``,titlePlaceholder:``,slugLabel:``,slugPlaceholder:``,slugHelp:``,bodyLabel:``,bodyPlaceholder:``,urlLabel:``,urlPlaceholder:``,quoteTextLabel:``,quoteTextPlaceholder:``,mediaLabel:``,mediaAddButton:``,mediaRemoveButton:``,mediaEmptyLabel:``,statusLabel:``,statusPublished:``,statusDraft:``,visibilityLabel:``,visibilityPublic:``,visibilityHiddenFromLatest:``,pinnedLabel:``,collectionsLabel:``,submitLabel:``,cancelLabel:``,mediaDialogTitle:``,mediaDialogDone:``,mediaDialogLoading:``,submitSuccessMessage:``,submitErrorMessage:``,draftFallbackMessage:``};function YB(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var XB=class e extends c{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...JB},this.initial={...qB},this.collections=[],this.media=[],this.action=``,this.cancelHref=`/`,this.mediaPickerUrl=``,this.siteUrl=``,this.isEdit=!1,this._format=`note`,this._title=``,this._slug=``,this._slugManuallyEdited=!1,this._body=``,this._url=``,this._quoteText=``,this._status=`published`,this._visibility=`public`,this._pinned=!1,this._rating=0,this._collectionIds=[],this._mediaIds=[],this._loading=!1}willUpdate(e){typeof this.labels==`string`&&(this.labels=YB(this.labels,{...JB})),typeof this.initial==`string`&&(this.initial=YB(this.initial,{...qB})),typeof this.collections==`string`&&(this.collections=YB(this.collections,[])),typeof this.media==`string`&&(this.media=YB(this.media,[])),(!this.#e||e.has(`initial`))&&this.#i()}set loading(e){this._loading=e}get loading(){return this._loading}set mediaIds(e){this._mediaIds=[...e]}get mediaIds(){return[...this._mediaIds]}get#r(){return this.querySelector(`#post-media-picker`)}connectedCallback(){super.connectedCallback(),window.addEventListener(`beforeunload`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener(`beforeunload`,this.#n),this._editor?.destroy(),this._editor=null,this.closeMediaPicker()}#i(){let e=this.initial??qB;if(this._format=e.format??`note`,this._title=e.title??``,this._slug=e.slug??``,this._slugManuallyEdited=!!e.slug,this._body=e.body??``,this._url=e.url??``,this._quoteText=e.quoteText??``,this._status=e.status??`published`,this._visibility=e.visibility??`public`,this._pinned=!!e.pinned,this._rating=e.rating??0,this._collectionIds=[...e.collectionIds??[]],this._mediaIds=[...e.mediaIds??[]],this.#e=!0,this._body&&this._body.startsWith(`{`))try{this._bodyJson=JSON.parse(this._body)}catch{this._bodyJson=null}else this._bodyJson=null}initEditor(){if(this._editor)return;let e=this.querySelector(`.post-form-tiptap-body`);e&&(this._editor=MT({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._bodyJson,onUpdate:e=>{this._bodyJson=e,this._body=JSON.stringify(e)},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}))}static#a=new Set([`_format`,`_title`,`_slug`,`_body`,`_url`,`_quoteText`,`_status`,`_visibility`,`_pinned`,`_rating`,`_collectionIds`,`_mediaIds`]);updated(t){if(super.updated(t),this._editor||this.initEditor(),this.#e&&!t.has(`initial`)){for(let n of t.keys())if(e.#a.has(n)){this.#t=!0;break}}}clearDirty(){this.#t=!1}handleInput(e,t){this[e]=t.target.value}handleTitleInput(e){let t=e.target;this._title=t.value,this._slugManuallyEdited||(this._slug=t.value.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``))}handleSlugInput(e){this._slug=e.target.value,this._slugManuallyEdited=!0}toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}removeMedia(e){this._mediaIds=this._mediaIds.filter(t=>t!==e)}openMediaPicker(){let e=this.#r;e&&(e.showModal(),this.dispatchEvent(new CustomEvent(`jant:post-load-media`,{bubbles:!0,detail:{endpoint:this.mediaPickerUrl,selectedIds:[...this._mediaIds]}})))}closeMediaPicker(){this.#r?.close()}handleSubmit(e){if(e.preventDefault(),this._loading||!this.action)return;let t=this._bodyJson?JSON.stringify(this._bodyJson):this._body,n={endpoint:this.action,isEdit:this.isEdit,data:{format:this._format,title:this._title.trim(),slug:this._slug.trim()||void 0,body:t,status:this._status,visibility:this._visibility,pinned:this._pinned,url:this._url.trim(),quoteText:this._quoteText.trim(),rating:this._rating,collectionIds:[...this._collectionIds],mediaIds:[...this._mediaIds]},messages:{success:this.labels.submitSuccessMessage,error:this.labels.submitErrorMessage}};this.dispatchEvent(new CustomEvent(`jant:post-submit`,{bubbles:!0,detail:n}))}render(){return KB(this)}};customElements.define(`jant-post-form`,XB);function ZB(e){return e instanceof HTMLElement&&e.tagName===`JANT-POST-FORM`?e:e instanceof HTMLElement?e.closest(`jant-post-form`):document.querySelector(`jant-post-form`)}function QB(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function $B(e){let t=e,n=t.detail;if(!n)return;let r=ZB(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await le(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await le(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let a=w(t,`status`),o=w(t,`url`);if(a===`redirect`&&o){r.clearDirty(),y(i),window.location.href=o;return}d(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await le(e),i=w(t,`status`),a=w(t,`url`);if(i===`redirect`&&a){r.clearDirty(),y(n.messages.success),window.location.href=a;return}r.clearDirty(),d(n.messages.success)}catch(e){d(e instanceof Error&&e.message?e.message:n.messages.error,`error`)}finally{r.loading=!1}}}async function eV(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=ZB(t.target);if(!r||!i)return;try{r.innerHTML=`<p class="text-muted-foreground text-sm col-span-4">Loading...</p>`,r.innerHTML=await(await fetch(n.endpoint,{headers:{Accept:`text/html`}})).text()}catch{r.innerHTML=`<p class="text-red-500 text-sm col-span-4">Failed to load media.</p>`;return}let a=new Set(n.selectedIds);r.querySelectorAll(`[data-media-id]`).forEach(e=>{let t=e.dataset.mediaId;t&&QB(e,a.has(t))}),r.onclick=e=>{let t=e.target.closest(`[data-media-id]`);if(!t)return;let n=t.dataset.mediaId;if(!n)return;let r=new Set(i.mediaIds);r.has(n)?(r.delete(n),QB(t,!1)):(r.add(n),QB(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,$B),document.addEventListener(`jant:post-load-media`,eV);var{I:tV}=l,nV=e=>e,rV=()=>document.createComment(``),iV=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new tV(r.insertBefore(rV(),i),r.insertBefore(rV(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=nV(e).nextSibling;nV(r).insertBefore(e,i),e=t}}}return n},aV=(e,t,n=e)=>(e._$AI(t,n),e),oV={},sV=(e,t=oV)=>e._$AH=t,cV=e=>e._$AH,lV=e=>{e._$AR(),e._$AA.remove()},uV=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},dV=o(class extends f{constructor(e){if(super(e),e.type!==b.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=cV(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,m=0,h=a.length-1;for(;d<=f&&m<=h;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[m])c[m]=aV(i[d],a[m]),d++,m++;else if(s[f]===o[h])c[h]=aV(i[f],a[h]),f--,h--;else if(s[d]===o[h])c[h]=aV(i[d],a[h]),iV(e,c[h+1],i[d]),d++,h--;else if(s[f]===o[m])c[m]=aV(i[f],a[m]),iV(e,i[d],i[f]),f--,m++;else if(l===void 0&&(l=uV(o,m,h),u=uV(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=iV(e,i[d]);aV(t,a[m]),c[m]=t}else c[m]=aV(n,a[m]),iV(e,i[d],n),i[t]=null;m++}else lV(i[f]),f--;else lV(i[d]),d++;for(;m<=h;){let t=iV(e,c[h+1]);aV(t,a[m]),c[m++]=t}for(;d<=f;){let e=i[d++];e!==null&&lV(e)}return this.ut=o,sV(e,c),p}}),fV=class extends c{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#b())};#s=e=>{!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore||(e.preventDefault(),this.#b(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#y.length===0&&this.#b(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#b()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...yO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=xO(e)},onEnd:e=>{let t=e.to,n=e.from,r=n!==t,i=t.id===`nav-items-header`?`header`:`more`,a=this.querySelector(`#nav-items-header`),o=this.querySelector(`#nav-items-more`),s=e.item?.dataset?.navId;if(!s||!a||!o){this.#r=null;return}let c=bO(a,`[data-nav-id]`,`navId`),l=bO(o,`[data-nav-id]`,`navId`);r?(e.item.parentNode?.removeChild(e.item),this.#r?n.insertBefore(e.item,this.#r):e.oldIndex!=null&&e.oldIndex<n.children.length?n.insertBefore(e.item,n.children[e.oldIndex]??null):n.appendChild(e.item)):SO(t,e,this.#r),this.#r=null,this.#c();let u=[...new Set([...c,...l])],f=new Map(this._items.map(e=>[e.id,e.id===s?{...e,placement:i}:{...e}])),p=u.map(e=>f.get(e)).filter(e=>e!==void 0),m=this._items.filter(e=>!u.includes(e.id)).map(e=>e.id===s?{...e,placement:i}:{...e});this._items=[...p,...m];let{movedId:h,afterId:g,beforeId:_}=wO(i===`header`?c:l,e.newIndex);h&&(r?fetch(`/api/nav-items/${s}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({placement:i})}).then(async e=>e.ok?(await fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})})).ok:!1).then(e=>{e?d(this.labels.placementSaved):d(this.labels.saveFailed,`error`)}):fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})}).then(e=>{e.ok?d(this.labels.orderSaved):d(this.labels.saveFailed,`error`)}))}}}#d(e){this._editingId===e.id?this._editingId=null:(this._editingId=e.id,this._editLabel=e.label,this._editUrl=e.url)}#f(e){let t=this._editLabel.trim();if(!t&&e.type!==`system`){d(this.labels.labelRequired,`error`);return}let n={id:e.id,label:t,...e.type===`link`&&{url:this._editUrl.trim()}};this.dispatchEvent(new CustomEvent(`jant:nav-update`,{bubbles:!0,detail:n}))}async#p(e){await be({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){d(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,placement:`header`})});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#c(),this._items=[...this._items,r],this._newLinkLabel=``,this._newLinkUrl=``,this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)}catch{d(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#h(e){if(!(!e||this._addingCollectionId)){this._addingCollectionId=e;try{let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`collection`,collectionId:e,placement:`header`})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,n],this.#a()}catch{d(this.labels.saveFailed,`error`)}finally{this._addingCollectionId=null}}}#g(e){return this._items.some(t=>t.type===`system`&&t.systemKey===e.key)}async#_(e,t){this._togglingKeys=new Set([...this._togglingKeys,e.key]);try{if(t){let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`system`,systemKey:e.key})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,{...n,displayLabel:e.label}]}else{let t=this._items.find(t=>t.type===`system`&&t.systemKey===e.key);if(t){let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);this.#c(),this._items=this._items.filter(e=>e.id!==t.id)}}}catch{d(this.labels.saveFailed,`error`),this.requestUpdate()}finally{let t=new Set(this._togglingKeys);t.delete(e.key),this._togglingKeys=t}}get#v(){return this._items.filter(e=>(e.placement??`header`)===`header`)}get#y(){return this._items.filter(e=>e.placement===`more`)}#b(){this._showPreviewMore=!1,document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#s)}#x(e){if(e.preventDefault(),e.stopPropagation(),this._showPreviewMore){this.#b();return}this._showPreviewMore=!0,document.addEventListener(`keydown`,this.#s),setTimeout(()=>{document.addEventListener(`click`,this.#o)})}#S(){let e=this.#v,t=this.#y;return u`
3668
3668
  <div class="nav-preview">
3669
3669
  <div class="nav-preview-chrome">
3670
3670
  <div class="nav-preview-dots">
@@ -3676,7 +3676,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3676
3676
  <div class="site-header-top">
3677
3677
  <a href=${i(`/`)} class="site-logo">${this.siteName}</a>
3678
3678
  <nav class="site-header-nav">
3679
- ${cV(e,e=>e.id,(e,t)=>u`<a
3679
+ ${dV(e,e=>e.id,(e,t)=>u`<a
3680
3680
  class=${t===0?`site-header-link site-header-link-active`:`site-header-link`}
3681
3681
  >
3682
3682
  ${e.displayLabel??e.label}
@@ -3712,7 +3712,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3712
3712
  aria-hidden=${this._showPreviewMore?`false`:`true`}
3713
3713
  @click=${e=>e.stopPropagation()}
3714
3714
  >
3715
- ${cV(t,e=>e.id,e=>u`
3715
+ ${dV(t,e=>e.id,e=>u`
3716
3716
  <span class="site-header-more-link">
3717
3717
  ${e.displayLabel??e.label}
3718
3718
  </span>
@@ -4090,14 +4090,14 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4090
4090
  ${this.labels.emptyState}
4091
4091
  </p>`:g}
4092
4092
  <div id="nav-items-header" class="nav-items-list">
4093
- ${cV(this.#v,e=>e.id,e=>this.#T(e))}
4093
+ ${dV(this.#v,e=>e.id,e=>this.#T(e))}
4094
4094
  </div>
4095
4095
  </section>
4096
4096
 
4097
4097
  <section class="mt-8">
4098
4098
  <h2 class="text-lg font-semibold mb-3">${this.labels.moreSection}</h2>
4099
4099
  <div id="nav-items-more" class="nav-items-list nav-items-list-drop">
4100
- ${this.#y.length>0?cV(this.#y,e=>e.id,e=>this.#T(e)):u`<p class="nav-items-empty-hint">
4100
+ ${this.#y.length>0?dV(this.#y,e=>e.id,e=>this.#T(e)):u`<p class="nav-items-empty-hint">
4101
4101
  ${this.labels.moreEmptyHint}
4102
4102
  </p>`}
4103
4103
  </div>
@@ -4105,7 +4105,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4105
4105
 
4106
4106
  ${this.#E()} ${this.#D()}
4107
4107
  ${this.#O()}
4108
- `}};customElements.define(`jant-nav-manager`,lV),document.addEventListener(`jant:nav-update`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:t.label,...t.url!==void 0&&{url:t.url}})});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{d(`Failed to save. Please try again.`,`error`)}}),document.addEventListener(`jant:nav-delete`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{d(`Failed to delete. Please try again.`,`error`)}});var uV=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,dV=`M4 4 20 20`,fV=360,pV=12;function mV(e){let t=window.innerHeight-e.bottom-pV,n=e.top-pV;return t<fV&&n>t}function hV(e){let t=Array.from(e?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-item`));Array.from(t?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-divider`))?.remove()}var gV=class extends c{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=mV(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{if(e.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},d({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),d(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},d(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),d(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},d(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),d(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},d(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),d(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await be({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.thread-item`),n=t?.closest(`.thread-group`);if(t&&n){if(t.remove(),n.querySelectorAll(`.thread-item:not(.thread-item-gap)`).length===0){let e=n.closest(`.feed-item`),t=e?.parentElement??null;(e??n).remove(),hV(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),hV(n)}d(`Post deleted.`)}catch{d(`Could not delete post. Try again.`,`error`),e?.focus()}}async#S(){if(!this._data)return;let e=this._data.id;this._view=`collections`,this._collectionSearch=``,this._collectionsLoading=!0,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`);try{let[t,n]=await Promise.all([fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}}),fetch(`/api/posts/${e}`)]);if(!t.ok)throw Error();let r=(await t.json()).collections??[],i=this._postCollectionIds;n.ok&&(i=(await n.json()).collectionIds??[]),this.#t=Kx(r,i),this._collections=r,this._postCollectionIds=i}catch{this._collections=this._collections??[],d(`Could not load collections.`,`error`)}this._collectionsLoading=!1,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`)}#C(e){if(!this._data)return;let t=this._data.id,n=this._postCollectionIds.includes(e);n?this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e):this._postCollectionIds=[...this._postCollectionIds,e],this.#e=!0,d(n?`Removed from collection.`:`Added to collection.`),n?fetch(`/api/collections/${e}/posts/${t}`,{method:`DELETE`}).then(e=>{if(!e.ok)throw Error();return this.#k()}).catch(()=>{this._postCollectionIds.includes(e)||(this._postCollectionIds=[...this._postCollectionIds,e]),d(`Could not remove from collection. Try again.`,`error`)}):fetch(`/api/collections/${e}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:t})}).then(e=>{if(!e.ok){if(e.status===409)return this.#k();throw Error()}return this.#k()}).catch(()=>{this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e),d(`Could not add to collection. Try again.`,`error`)})}#w(){this._addCollectionPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()})}#T(){this._addCollectionPanelOpen=!1,this.#r(),this.updateComplete.then(()=>{(this.querySelector(`[data-post-menu-add-collection]`)??this._triggerEl)?.focus()})}async#E(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Could not create collection. Try again.`);if(!t?.id||!t.title||!t.slug)throw Error(`Could not create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug};this._collections=[...this._collections??[],r],this._data&&(await fetch(`/api/collections/${t.id}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})}),this._postCollectionIds=[...this._postCollectionIds,t.id]),await this.#k(),this.#e=!0,this.#T(),d(this.#D()?.createdLabel??`Collection created.`)}catch(e){d(e instanceof Error?e.message:`Could not create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}#D(){return document.querySelector(`jant-compose-dialog`)?.labels?.collectionFormLabels??null}#O(){return document.querySelector(`jant-compose-dialog`)?.labels?.addCollection??`Add Collection`}async#k(){await document.querySelector(`jant-compose-dialog`)?.refreshCollections?.()}#A(e){switch(e){case`private`:return`Private`;case`latest_hidden`:return`Hidden from Latest`;default:return`Public`}}#j(){return u`<svg
4108
+ `}};customElements.define(`jant-nav-manager`,fV),document.addEventListener(`jant:nav-update`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:t.label,...t.url!==void 0&&{url:t.url}})});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{d(`Failed to save. Please try again.`,`error`)}}),document.addEventListener(`jant:nav-delete`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{d(`Failed to delete. Please try again.`,`error`)}});var pV=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,mV=`M4 4 20 20`,hV=360,gV=12;function _V(e){let t=window.innerHeight-e.bottom-gV,n=e.top-gV;return t<hV&&n>t}function vV(e){let t=Array.from(e?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-item`));Array.from(t?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-divider`))?.remove()}var yV=class extends c{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=_V(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{if(e.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},d({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),d(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},d(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),d(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},d(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),d(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},d(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),d(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await be({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.thread-item`),n=t?.closest(`.thread-group`);if(t&&n){if(t.remove(),n.querySelectorAll(`.thread-item:not(.thread-item-gap)`).length===0){let e=n.closest(`.feed-item`),t=e?.parentElement??null;(e??n).remove(),vV(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),vV(n)}d(`Post deleted.`)}catch{d(`Could not delete post. Try again.`,`error`),e?.focus()}}async#S(){if(!this._data)return;let e=this._data.id;this._view=`collections`,this._collectionSearch=``,this._collectionsLoading=!0,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`);try{let[t,n]=await Promise.all([fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}}),fetch(`/api/posts/${e}`)]);if(!t.ok)throw Error();let r=(await t.json()).collections??[],i=this._postCollectionIds;n.ok&&(i=(await n.json()).collectionIds??[]),this.#t=Kx(r,i),this._collections=r,this._postCollectionIds=i}catch{this._collections=this._collections??[],d(`Could not load collections.`,`error`)}this._collectionsLoading=!1,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`)}#C(e){if(!this._data)return;let t=this._data.id,n=this._postCollectionIds.includes(e);n?this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e):this._postCollectionIds=[...this._postCollectionIds,e],this.#e=!0,d(n?`Removed from collection.`:`Added to collection.`),n?fetch(`/api/collections/${e}/posts/${t}`,{method:`DELETE`}).then(e=>{if(!e.ok)throw Error();return this.#k()}).catch(()=>{this._postCollectionIds.includes(e)||(this._postCollectionIds=[...this._postCollectionIds,e]),d(`Could not remove from collection. Try again.`,`error`)}):fetch(`/api/collections/${e}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:t})}).then(e=>{if(!e.ok){if(e.status===409)return this.#k();throw Error()}return this.#k()}).catch(()=>{this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e),d(`Could not add to collection. Try again.`,`error`)})}#w(){this._addCollectionPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()})}#T(){this._addCollectionPanelOpen=!1,this.#r(),this.updateComplete.then(()=>{(this.querySelector(`[data-post-menu-add-collection]`)??this._triggerEl)?.focus()})}async#E(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Could not create collection. Try again.`);if(!t?.id||!t.title||!t.slug)throw Error(`Could not create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug};this._collections=[...this._collections??[],r],this._data&&(await fetch(`/api/collections/${t.id}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})}),this._postCollectionIds=[...this._postCollectionIds,t.id]),await this.#k(),this.#e=!0,this.#T(),d(this.#D()?.createdLabel??`Collection created.`)}catch(e){d(e instanceof Error?e.message:`Could not create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}#D(){return document.querySelector(`jant-compose-dialog`)?.labels?.collectionFormLabels??null}#O(){return document.querySelector(`jant-compose-dialog`)?.labels?.addCollection??`Add Collection`}async#k(){await document.querySelector(`jant-compose-dialog`)?.refreshCollections?.()}#A(e){switch(e){case`private`:return`Private`;case`latest_hidden`:return`Hidden from Latest`;default:return`Public`}}#j(){return u`<svg
4109
4109
  xmlns="http://www.w3.org/2000/svg"
4110
4110
  viewBox="0 0 24 24"
4111
4111
  fill="none"
@@ -4125,7 +4125,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4125
4125
  stroke-linecap="round"
4126
4126
  stroke-linejoin="round"
4127
4127
  >
4128
- <path d=${uV} />
4128
+ <path d=${pV} />
4129
4129
  </svg>`}#N(){return u`<svg
4130
4130
  xmlns="http://www.w3.org/2000/svg"
4131
4131
  viewBox="0 0 24 24"
@@ -4136,8 +4136,8 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4136
4136
  stroke-linecap="round"
4137
4137
  stroke-linejoin="round"
4138
4138
  >
4139
- <path d=${uV} />
4140
- <path d=${dV} />
4139
+ <path d=${pV} />
4140
+ <path d=${mV} />
4141
4141
  </svg>`}#P(){return u`<svg
4142
4142
  xmlns="http://www.w3.org/2000/svg"
4143
4143
  viewBox="0 0 24 24"
@@ -4582,7 +4582,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4582
4582
  </div>
4583
4583
  `}
4584
4584
  ${this._addCollectionPanelOpen?this.#H():g}
4585
- `}};customElements.define(`jant-post-menu`,gV);var _V=e=>{if(!e)return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``};try{return JSON.parse(e)}catch{return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``}}};document.querySelectorAll(`[data-collection-page-actions]`).forEach(e=>{if(e.dataset.collectionPageActionsInitialized===`true`)return;let t=_V(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||Zz(),i=e.querySelector(`[data-collection-page-action='toggle-menu']`),a=e.querySelector(`[data-collection-page-menu]`);if(!n||!i||!a)return;let o=(e=!1)=>{a.hidden||(a.hidden=!0,i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},s=(e=!1)=>{a.hidden=!1,i.setAttribute(`aria-expanded`,`true`),e&&a.querySelector(`[role='menuitem']`)?.focus()},c=async()=>{if(o(!1),await be({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);d(t.deleted),window.location.href=r}catch{d(t.saveFailed,`error`)}};i.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),a.hidden){s(!1);return}o(!1)}),i.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`)&&(e.preventDefault(),a.hidden?s(!0):o(!1)),e.key===`Escape`&&(e.preventDefault(),o(!0))}),a.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),o(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let r=n.closest(`[data-collection-page-action]`);!r||!e.contains(r)||r.dataset.collectionPageAction===`delete`&&(t.preventDefault(),c())}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||o(!1))}),e.dataset.collectionPageActionsInitialized=`true`});function vV(e=document){e.querySelectorAll(`[data-custom-url-actions]`).forEach(e=>{if(e.dataset.customUrlActionsInitialized===`true`)return;let t=e.querySelector(`[data-custom-url-action='toggle-menu']`),n=e.querySelector(`[data-custom-url-menu]`);if(!(t instanceof HTMLButtonElement)||!n)return;let r=(e=!1)=>{n.hidden||(n.hidden=!0,t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},i=(r=!1)=>{document.dispatchEvent(new CustomEvent(`jant:custom-url-menu`,{detail:{source:e}})),n.hidden=!1,t.setAttribute(`aria-expanded`,`true`),r&&n.querySelector(`[role='menuitem']`)?.focus()};t.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),n.hidden){i(!1);return}r(!1)}),t.addEventListener(`keydown`,e=>{if(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`){e.preventDefault(),n.hidden?i(!0):r(!1);return}e.key===`Escape`&&(e.preventDefault(),r(!0))}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),r(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let i=n.closest(`[data-custom-url-action]`);!i||!e.contains(i)||i.dataset.customUrlAction===`delete`&&r(!1)}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||r(!1))}),document.addEventListener(`jant:custom-url-menu`,t=>{t.detail?.source!==e&&r(!1)}),e.dataset.customUrlActionsInitialized=`true`})}vV();var yV=`xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"`,bV={post:`<svg ${yV}><path d="M8 2v4"/><path d="M12 2v4"/><path d="M16 2v4"/><rect width="16" height="18" x="4" y="4" rx="2"/><path d="M8 10h6"/><path d="M8 14h8"/><path d="M8 18h5"/></svg>`,collection:`<svg ${yV} viewBox="0 0 16 16" stroke-width="1.35"><rect x="3" y="5.05" width="10" height="8.15" rx="2.2"/><path d="M5.1 5.05V4.2a1.1 1.1 0 0 1 1.1-1.1h3.6a1.1 1.1 0 0 1 1.1 1.1v.85"/></svg>`,system:`<svg ${yV}><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"/><circle cx="12" cy="12" r="3"/></svg>`,command:`<svg ${yV}><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg>`,search:`<svg ${yV}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`},xV=5;function SV(e){try{let t=globalThis.localStorage.getItem(e);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e):[]}catch{return[]}}function CV(e,t){let n=SV(e).filter(e=>e!==t);n.unshift(t),globalThis.localStorage.setItem(e,JSON.stringify(n.slice(0,xV)))}var wV=`jant:nav-history`,TV=`jant:search-history`,EV=[{title:`Home`,path:`/`,type:`system`},{title:`Featured`,path:`/featured`,type:`system`},{title:`Latest`,path:`/latest`,type:`system`},{title:`Archive`,path:`/archive`,type:`system`},{title:`Collections`,path:`/collections`,type:`system`},{title:`Settings`,path:`/settings`,type:`system`},{title:`General`,path:`/settings/general`,type:`system`},{title:`Navigation`,path:`/settings/navigation`,type:`system`},{title:`Appearance`,path:`/settings/appearance/color-theme`,type:`system`},{title:`Custom URLs`,path:`/settings/custom-urls`,type:`system`},{title:`API Tokens`,path:`/settings/api-tokens`,type:`system`},{title:`Sessions`,path:`/settings/sessions`,type:`system`},{title:`Account`,path:`/settings/account`,type:`system`}],DV=[{label:`New Post`,icon:bV.command,action:()=>void NR()}],OV=class extends c{static properties={_open:{state:!0},_query:{state:!0},_selectedIndex:{state:!0},_loading:{state:!0}};#e=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._selectedIndex=0,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t()}async#t(){if(!this.#e)try{let e=await fetch(`/api/palette`);e.ok?this.#e=(await e.json()).items:this.#e=[]}catch{this.#e=[]}}async open(){if(this._open)return;this.#e||(this._loading=!0,await this.#t(),this._loading=!1),this._open=!0,this._query=``,this._selectedIndex=0,await this.updateComplete;let e=this.querySelector(`.command-palette`);e&&!e.open&&e.showModal(),this.querySelector(`.command-palette-input`)?.focus()}close(){let e=this.querySelector(`.command-palette`);e?.open&&e.close(),this._open=!1,this._query=``,this._selectedIndex=0}get#n(){let e=this._query.charAt(0);return e===`>`||e===`>`?`command`:e===`?`||e===`?`?`search`:`navigate`}get#r(){let e=Wx(this._query),t=[...this.#e??[],...EV];if(!e){let e=SV(wV);if(e.length===0)return t;let n=new Set(e),r=[],i=[];for(let e of t)n.has(e.path)?r.push(e):i.push(e);return r.sort((t,n)=>e.indexOf(t.path)-e.indexOf(n.path)),[...r,...i]}return t.map((t,n)=>({item:t,index:n,rank:Ux([t.title,t.path],e)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item)}get#i(){let e=Wx(this._query.slice(1));return DV.filter(t=>!e||t.label.toLowerCase().includes(e))}get#a(){let e=this.#n;if(e===`command`)return this.#i.map(e=>({label:e.label,icon:e.icon}));if(e===`search`){let e=this._query.slice(1).trim();return e?[{label:`Search for "${e}"`,icon:bV.search,searchQuery:e}]:SV(TV).map(e=>({label:e,icon:bV.search,searchQuery:e}))}let t=this.#r.map(e=>({label:e.title,secondary:(e.type,e.path),icon:bV[e.type]})),n=Wx(this._query);return t.length===0&&n&&t.push({label:`Search for "${this._query.trim()}"`,icon:bV.search,searchQuery:this._query.trim()}),t}#o(e){let t=this.#n;if(t===`command`){let t=this.#i[e];t&&(this.close(),t.action());return}if(t===`search`){let t=this.#a[e]?.searchQuery;t&&(CV(TV,t),this.close(),window.location.href=`/search?q=${encodeURIComponent(t)}`);return}let n=this.#a[e];if(n?.searchQuery){let e=n.searchQuery;CV(TV,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`;return}let r=this.#r[e];r&&(CV(wV,r.path),this.close(),r.type===`system`?window.location.href=r.path:r.type===`collection`?window.location.href=`/collections/${r.path}`:window.location.href=`/${r.path}`)}#s=e=>{this._query=e.target.value,this._selectedIndex=0};#c=e=>{let t=this.#a;if(e.key===`ArrowDown`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex+1)%t.length:0,this.#f();return}if(e.key===`ArrowUp`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex-1+t.length)%t.length:0,this.#f();return}if(e.key===`Enter`){e.preventDefault(),this.#o(this._selectedIndex);return}if(e.key===`Tab`){e.preventDefault();return}if(e.key===`Escape`){e.preventDefault(),this.close();return}};#l=e=>{e.preventDefault(),this.close()};#u=e=>{e.target===e.currentTarget&&this.close()};#d(e){return()=>this.#o(e)}#f(){requestAnimationFrame(()=>{this.querySelector(`.command-palette-result-selected`)?.scrollIntoView({block:`nearest`})})}render(){if(!this._open)return g;let e=this.#a;return u`
4585
+ `}};customElements.define(`jant-post-menu`,yV);var bV=e=>{if(!e)return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``};try{return JSON.parse(e)}catch{return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``}}};document.querySelectorAll(`[data-collection-page-actions]`).forEach(e=>{if(e.dataset.collectionPageActionsInitialized===`true`)return;let t=bV(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||eB(),i=e.querySelector(`[data-collection-page-action='toggle-menu']`),a=e.querySelector(`[data-collection-page-menu]`);if(!n||!i||!a)return;let o=(e=!1)=>{a.hidden||(a.hidden=!0,i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},s=(e=!1)=>{a.hidden=!1,i.setAttribute(`aria-expanded`,`true`),e&&a.querySelector(`[role='menuitem']`)?.focus()},c=async()=>{if(o(!1),await be({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);d(t.deleted),window.location.href=r}catch{d(t.saveFailed,`error`)}};i.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),a.hidden){s(!1);return}o(!1)}),i.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`)&&(e.preventDefault(),a.hidden?s(!0):o(!1)),e.key===`Escape`&&(e.preventDefault(),o(!0))}),a.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),o(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let r=n.closest(`[data-collection-page-action]`);!r||!e.contains(r)||r.dataset.collectionPageAction===`delete`&&(t.preventDefault(),c())}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||o(!1))}),e.dataset.collectionPageActionsInitialized=`true`});function xV(e=document){e.querySelectorAll(`[data-custom-url-actions]`).forEach(e=>{if(e.dataset.customUrlActionsInitialized===`true`)return;let t=e.querySelector(`[data-custom-url-action='toggle-menu']`),n=e.querySelector(`[data-custom-url-menu]`);if(!(t instanceof HTMLButtonElement)||!n)return;let r=(e=!1)=>{n.hidden||(n.hidden=!0,t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},i=(r=!1)=>{document.dispatchEvent(new CustomEvent(`jant:custom-url-menu`,{detail:{source:e}})),n.hidden=!1,t.setAttribute(`aria-expanded`,`true`),r&&n.querySelector(`[role='menuitem']`)?.focus()};t.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),n.hidden){i(!1);return}r(!1)}),t.addEventListener(`keydown`,e=>{if(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`){e.preventDefault(),n.hidden?i(!0):r(!1);return}e.key===`Escape`&&(e.preventDefault(),r(!0))}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),r(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let i=n.closest(`[data-custom-url-action]`);!i||!e.contains(i)||i.dataset.customUrlAction===`delete`&&r(!1)}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||r(!1))}),document.addEventListener(`jant:custom-url-menu`,t=>{t.detail?.source!==e&&r(!1)}),e.dataset.customUrlActionsInitialized=`true`})}xV();var SV=`xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"`,CV={post:`<svg ${SV}><path d="M8 2v4"/><path d="M12 2v4"/><path d="M16 2v4"/><rect width="16" height="18" x="4" y="4" rx="2"/><path d="M8 10h6"/><path d="M8 14h8"/><path d="M8 18h5"/></svg>`,collection:`<svg ${SV} viewBox="0 0 16 16" stroke-width="1.35"><rect x="3" y="5.05" width="10" height="8.15" rx="2.2"/><path d="M5.1 5.05V4.2a1.1 1.1 0 0 1 1.1-1.1h3.6a1.1 1.1 0 0 1 1.1 1.1v.85"/></svg>`,system:`<svg ${SV}><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"/><circle cx="12" cy="12" r="3"/></svg>`,command:`<svg ${SV}><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg>`,search:`<svg ${SV}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`},wV=5;function TV(e){try{let t=globalThis.localStorage.getItem(e);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e):[]}catch{return[]}}function EV(e,t){let n=TV(e).filter(e=>e!==t);n.unshift(t),globalThis.localStorage.setItem(e,JSON.stringify(n.slice(0,wV)))}var DV=`jant:nav-history`,OV=`jant:search-history`,kV=[{title:`Home`,path:`/`,type:`system`},{title:`Featured`,path:`/featured`,type:`system`},{title:`Latest`,path:`/latest`,type:`system`},{title:`Archive`,path:`/archive`,type:`system`},{title:`Collections`,path:`/collections`,type:`system`},{title:`Settings`,path:`/settings`,type:`system`},{title:`General`,path:`/settings/general`,type:`system`},{title:`Navigation`,path:`/settings/navigation`,type:`system`},{title:`Appearance`,path:`/settings/appearance/color-theme`,type:`system`},{title:`Custom URLs`,path:`/settings/custom-urls`,type:`system`},{title:`API Tokens`,path:`/settings/api-tokens`,type:`system`},{title:`Sessions`,path:`/settings/sessions`,type:`system`},{title:`Account`,path:`/settings/account`,type:`system`}],AV=[{label:`New Post`,icon:CV.command,action:()=>void IR()}],jV=class extends c{static properties={_open:{state:!0},_query:{state:!0},_selectedIndex:{state:!0},_loading:{state:!0}};#e=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._selectedIndex=0,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t()}async#t(){if(!this.#e)try{let e=await fetch(`/api/palette`);e.ok?this.#e=(await e.json()).items:this.#e=[]}catch{this.#e=[]}}async open(){if(this._open)return;this.#e||(this._loading=!0,await this.#t(),this._loading=!1),this._open=!0,this._query=``,this._selectedIndex=0,await this.updateComplete;let e=this.querySelector(`.command-palette`);e&&!e.open&&e.showModal(),this.querySelector(`.command-palette-input`)?.focus()}close(){let e=this.querySelector(`.command-palette`);e?.open&&e.close(),this._open=!1,this._query=``,this._selectedIndex=0}get#n(){let e=this._query.charAt(0);return e===`>`||e===`>`?`command`:e===`?`||e===`?`?`search`:`navigate`}get#r(){let e=Wx(this._query),t=[...this.#e??[],...kV];if(!e){let e=TV(DV);if(e.length===0)return t;let n=new Set(e),r=[],i=[];for(let e of t)n.has(e.path)?r.push(e):i.push(e);return r.sort((t,n)=>e.indexOf(t.path)-e.indexOf(n.path)),[...r,...i]}return t.map((t,n)=>({item:t,index:n,rank:Ux([t.title,t.path],e)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item)}get#i(){let e=Wx(this._query.slice(1));return AV.filter(t=>!e||t.label.toLowerCase().includes(e))}get#a(){let e=this.#n;if(e===`command`)return this.#i.map(e=>({label:e.label,icon:e.icon}));if(e===`search`){let e=this._query.slice(1).trim();return e?[{label:`Search for "${e}"`,icon:CV.search,searchQuery:e}]:TV(OV).map(e=>({label:e,icon:CV.search,searchQuery:e}))}let t=this.#r.map(e=>({label:e.title,secondary:(e.type,e.path),icon:CV[e.type]})),n=Wx(this._query);return t.length===0&&n&&t.push({label:`Search for "${this._query.trim()}"`,icon:CV.search,searchQuery:this._query.trim()}),t}#o(e){let t=this.#n;if(t===`command`){let t=this.#i[e];t&&(this.close(),t.action());return}if(t===`search`){let t=this.#a[e]?.searchQuery;t&&(EV(OV,t),this.close(),window.location.href=`/search?q=${encodeURIComponent(t)}`);return}let n=this.#a[e];if(n?.searchQuery){let e=n.searchQuery;EV(OV,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`;return}let r=this.#r[e];r&&(EV(DV,r.path),this.close(),r.type===`system`?window.location.href=r.path:r.type===`collection`?window.location.href=`/collections/${r.path}`:window.location.href=`/${r.path}`)}#s=e=>{this._query=e.target.value,this._selectedIndex=0};#c=e=>{let t=this.#a;if(e.key===`ArrowDown`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex+1)%t.length:0,this.#f();return}if(e.key===`ArrowUp`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex-1+t.length)%t.length:0,this.#f();return}if(e.key===`Enter`){e.preventDefault(),this.#o(this._selectedIndex);return}if(e.key===`Tab`){e.preventDefault();return}if(e.key===`Escape`){e.preventDefault(),this.close();return}};#l=e=>{e.preventDefault(),this.close()};#u=e=>{e.target===e.currentTarget&&this.close()};#d(e){return()=>this.#o(e)}#f(){requestAnimationFrame(()=>{this.querySelector(`.command-palette-result-selected`)?.scrollIntoView({block:`nearest`})})}render(){if(!this._open)return g;let e=this.#a;return u`
4586
4586
  <dialog
4587
4587
  class="command-palette"
4588
4588
  @cancel=${this.#l}
@@ -4595,7 +4595,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4595
4595
  >
4596
4596
  <div class="command-palette-input-wrapper">
4597
4597
  <span class="command-palette-search-icon"
4598
- >${Ce(bV.search)}</span
4598
+ >${Ce(CV.search)}</span
4599
4599
  >
4600
4600
  <input
4601
4601
  type="text"
@@ -4644,4 +4644,4 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4644
4644
  `:this._query.trim()&&!this._loading?u`<div class="command-palette-empty">No results</div>`:g}
4645
4645
  </div>
4646
4646
  </dialog>
4647
- `}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,OV),document.addEventListener(`keydown`,e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.defaultPrevented||e.isComposing)return;e.preventDefault();let t=document.querySelector(`jant-command-palette`);if(t){if(t.querySelector(`dialog[open]`)){t.close();return}document.querySelector(`dialog[open]`)||t.open()}}),document.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof globalThis.Element)||!t.closest(`.site-header-search-link`)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0||e.defaultPrevented)return;let n=document.querySelector(`jant-command-palette`);n&&(document.querySelector(`dialog[open]`)||(e.preventDefault(),n.open()))}),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),ye(),document.querySelector(`jant-command-palette`)||document.body.appendChild(document.createElement(`jant-command-palette`));
4647
+ `}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,jV),document.addEventListener(`keydown`,e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.defaultPrevented||e.isComposing)return;e.preventDefault();let t=document.querySelector(`jant-command-palette`);if(t){if(t.querySelector(`dialog[open]`)){t.close();return}document.querySelector(`dialog[open]`)||t.open()}}),document.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof globalThis.Element)||!t.closest(`.site-header-search-link`)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0||e.defaultPrevented)return;let n=document.querySelector(`jant-command-palette`);n&&(document.querySelector(`dialog[open]`)||(e.preventDefault(),n.open()))}),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),ye(),document.querySelector(`jant-command-palette`)||document.body.appendChild(document.createElement(`jant-command-palette`));