@jant/core 0.6.1 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-CUZaVgsC.js +6 -0
- package/dist/{app-DYQdDMs8.js → app-Ct9c4zYF.js} +296 -50
- package/dist/client/.vite/manifest.json +3 -3
- package/dist/client/_assets/client-Bp2IPjDe.js +275 -0
- package/dist/client/_assets/client-YVrRjAid.css +2 -0
- package/dist/client/_assets/{client-auth-CSNcTJwP.js → client-auth-C4hQWqH1.js} +4 -4
- package/dist/{env-C7e2Nlnt.js → env-CoSe-1y4.js} +1 -1
- package/dist/{export-Bbn86HmS.js → export-O2w3AsZX.js} +4 -4
- package/dist/{github-api-Bh0PH3zr.js → github-api-UD4u_7fa.js} +1 -1
- package/dist/{github-app-D0GvNnqp.js → github-app-DeX6Td1O.js} +1 -1
- package/dist/{github-sync-dXsiZa_e.js → github-sync-BUzIYouS.js} +3 -3
- package/dist/{github-sync-CBQPRZ8H.js → github-sync-D49RADci.js} +3 -3
- package/dist/index.js +5 -5
- package/dist/node.js +6 -6
- package/dist/{url-umUptr5z.js → url-XF0GbKGO.js} +22 -1
- package/package.json +1 -1
- package/src/client/__tests__/image-processor.test.ts +64 -0
- package/src/client/components/__tests__/jant-media-lightbox.test.ts +79 -8
- package/src/client/components/jant-compose-editor.ts +2 -2
- package/src/client/components/jant-media-lightbox.ts +33 -5
- package/src/client/image-processor.ts +89 -30
- package/src/client/media-scroll-hint.ts +62 -9
- package/src/i18n/coverage.generated.ts +2 -2
- package/src/i18n/locales/settings/zh-Hans.po +24 -24
- package/src/i18n/locales/settings/zh-Hans.ts +1 -1
- package/src/i18n/locales/settings/zh-Hant.po +24 -24
- package/src/i18n/locales/settings/zh-Hant.ts +1 -1
- package/src/lib/__tests__/structured-data.test.ts +87 -0
- package/src/lib/post-display.ts +78 -1
- package/src/lib/render.tsx +28 -0
- package/src/lib/structured-data.ts +113 -0
- package/src/lib/url.ts +26 -0
- package/src/routes/api/internal/__tests__/sites.test.ts +65 -0
- package/src/routes/api/internal/sites.ts +19 -0
- package/src/routes/pages/home.tsx +21 -1
- package/src/routes/pages/page.tsx +53 -2
- package/src/services/export-theme/assets/client-site.css +1 -1
- package/src/services/export-theme/assets/client-site.js +30 -29
- package/src/services/export-theme/layouts/partials/media-gallery.html +16 -7
- package/src/services/site-admin.ts +53 -1
- package/src/styles/site-media.css +70 -24
- package/src/styles/ui.css +7 -2
- package/src/ui/layouts/BaseLayout.tsx +110 -16
- package/src/ui/layouts/__tests__/BaseLayout.test.tsx +146 -0
- package/src/ui/shared/MediaGallery.tsx +50 -7
- package/src/ui/shared/__tests__/media-gallery.test.ts +31 -0
- package/dist/app-CMSW_AYG.js +0 -6
- package/dist/client/_assets/client-BRTh1ii1.js +0 -274
- package/dist/client/_assets/client-CO4b-RKd.css +0 -2
|
@@ -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-
|
|
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-Bp2IPjDe.js";var x={maxShortSide:1920,maxLongSide:8192,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){if(Math.max(e,t)>n.maxLongSide)return{passthrough:!0,width:e,height:t};let r=Math.min(e,t);if(r<=n.maxShortSide)return{passthrough:!1,width:e,height:t};let i=n.maxShortSide/r;return{passthrough:!1,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),i=C(r.width,r.height,n);if(i.passthrough)return{blob:e,width:i.width,height:i.height,processed:!1};let a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`);if(!o)throw Error(`Failed to get canvas context`);return o.drawImage(r,0,0,i.width,i.height),{blob:await ee(a,n.mimeType,n.quality),width:i.width,height:i.height,processed:!0}}async function ne(e,t={}){let n=await te(e,t);if(!n.processed)return{file:e,width:n.width,height:n.height};let r={"image/webp":`webp`,"image/jpeg":`jpg`,"image/png":`png`}[n.blob.type]??`png`,i=`${e.name.replace(/\.[^.]+$/,``)}.${r}`;return{file:new File([n.blob],i,{type:n.blob.type}),width:n.width,height:n.height}}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}
|
|
@@ -1993,9 +1993,9 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
1993
1993
|
${this.threadItem?this._renderThreadPostHeader():g}
|
|
1994
1994
|
<section class="compose-body">
|
|
1995
1995
|
${this.format===`note`?this._renderNoteFields():this.format===`link`?this._renderLinkFields():this._renderQuoteFields()}
|
|
1996
|
-
${this._renderStarRating()}
|
|
1997
1996
|
</section>
|
|
1998
|
-
${this._renderAttachmentDock()} ${this.
|
|
1997
|
+
${this._renderAttachmentDock()} ${this._renderStarRating()}
|
|
1998
|
+
${this._renderToolsRow()}
|
|
1999
1999
|
`}};customElements.define(`jant-compose-editor`,$O);var ek=`.tiptap-slash-menu, .tiptap-link-input`,tk=class extends c{static properties={labels:{type:Object},_open:{state:!0},_title:{state:!0},_showTitle:{state:!0},_replyContext:{state:!0},_replyExpanded:{state:!0}};_editor=null;_content=null;_selection=null;_fileInput=null;#e=new Set;createRenderRoot(){return this}constructor(){super(),this.labels={},this._open=!1,this._title=``,this._showTitle=!1,this._replyContext=null,this._replyExpanded=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:fullscreen-open`,this._onOpen),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`keydown`,this._onDocumentKeydown,!0)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`jant:fullscreen-open`,this._onOpen),document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`keydown`,this._onDocumentKeydown,!0),this._fileInput?.remove(),this._destroyEditor()}_onSlashImage=()=>{!this._open||!this._editor||this._triggerImagePicker()};_triggerImagePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`image/*`,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>{let e=this._fileInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._fileInput&&(this._fileInput.value=``)}),document.body.appendChild(this._fileInput)),this._fileInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=QC(t,e).finally(()=>{this.#e.delete(n)});return this.#e.add(n),n}_onOpen=e=>{this._content=e.detail.json,this._selection=e.detail.selection??null,this._title=e.detail.title,e.detail.labels&&(this.labels=e.detail.labels),this._showTitle=e.detail.showTitle||e.detail.title.trim().length>0,this._replyContext=e.detail.replyContext??null,this._replyExpanded=e.detail.replyContext?.expanded??!1,this._open=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-fullscreen-dialog`);e&&!e.open&&e.showModal(),this._initEditor()})};_initEditor(){let e=this.querySelector(`.compose-fullscreen .compose-tiptap-body`);if(!e||this._editor)return;this._editor=kT({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._content,toolbarMode:`compose`,onUpdate:e=>{this._content=e},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`),uploadInlineImage:e=>this._uploadAndInsertImage(e)}});let t=this._selection;if(t){let e=this._editor.state.doc.content.size,n=Math.max(1,Math.min(t.from,e)),r=Math.max(n,Math.min(t.to,e));this._selection={from:n,to:r},this._editor.chain().focus().setTextSelection({from:n,to:r}).run();return}this._editor.commands.focus()}_destroyEditor(){this.#e.clear(),this._editor?.destroy(),this._editor=null}_onDialogCancel=e=>{e.preventDefault(),this._close()};_onDocumentKeydown=e=>{!this._open||e.key!==`Escape`||this._hasActiveEscapeOverlay()||(e.preventDefault(),e.stopPropagation(),this._close())};_hasActiveEscapeOverlay(){let e=this.querySelector(`.compose-fullscreen-dialog[open]`);return e?Array.from(e.querySelectorAll(ek)).some(e=>getComputedStyle(e).display!==`none`):!1}_finishClose(){let e=this._editor?.getJSON()??this._content,t=this._editor?{from:this._editor.state.selection.from,to:this._editor.state.selection.to}:this._selection;this._destroyEditor(),this.querySelector(`.compose-fullscreen-dialog`)?.close(),this._open=!1,this._replyContext=null,document.dispatchEvent(new CustomEvent(`jant:fullscreen-close`,{bubbles:!0,detail:{json:e,title:this._title,showTitle:this._showTitle||this._title.trim().length>0,selection:t,replyExpanded:this._replyExpanded}}))}_close(){this._open&&this._finishClose()}_revealTitle(){this._showTitle=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-fullscreen-title`)?.focus()})}_renderTitleField(e){let t=xe({"compose-fullscreen-title":!0,"compose-fullscreen-title-reply":e===`reply`}),n=xe({"compose-fullscreen-title-placeholder":!0,"compose-fullscreen-title-placeholder-reply":e===`reply`});return this._showTitle?u`
|
|
2000
2000
|
<div class="compose-fullscreen-title-shell">
|
|
2001
2001
|
<input
|
|
@@ -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 oR;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=nk(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&&gM(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??IL,s=await BL(_,{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 KL(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 eR({format:new DL,target:new yL}),n=new KL(c);t.addVideoTrack(n),await t.start();let r=await new RM(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 zM(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 pM(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 pM(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 RM(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 UL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new MM(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:Hk(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 pM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new pM(e):new pM(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 JL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new MM(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??IL,a=await zL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>bA.includes(e))&&u.some(e=>bA.includes(e))&&(s!==rR||c!==iR)){let e=(await zL(u,{numberOfChannels:rR,sampleRate:iR,bitrate:i})).find(e=>bA.includes(e));e&&(l=!0,n=e,s=rR,c=iR)}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 XL({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new HM(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:Hk(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 SM))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 XL({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new lR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new HM(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=Ik(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},oR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},sR=5,cR=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<sR&&(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()>=sR}wait(e){let{promise:t,resolve:n}=Tk();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},lR=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 SM({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 uR(){return typeof AudioEncoder<`u`}async function dR(e,t){let n=new ZP({source:new qP(e),formats:GP}),r=new vL,i=new eR({format:new DL({fastStart:`in-memory`}),target:r});try{let a=await aR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:IL}});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 fR={isSupported:uR,processToFile:dR},pR=new Set([`moov`,`trak`]);function mR(e){return 12+(e===1?32:20)+8+2}function hR(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+mR(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else pR.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var gR=1920,_R=1080,vR=640,yR=32;function bR(){return typeof VideoEncoder<`u`}async function xR(e){let t=new ZP({source:new qP(e),formats:GP});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 zM(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 ZP({source:new qP(e),formats:GP}),d=new vL,f=new eR({format:new DL({fastStart:`in-memory`}),target:d});try{let i=await aR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:IL},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);hR(a);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(!fR.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 fR.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 JO(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:OT(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":.9254658385093167,"zh-Hant":.9254658385093167},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=jT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=AT(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=jT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=AT(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 oR;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=nk(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&&gM(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??IL,s=await BL(_,{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 KL(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 eR({format:new DL,target:new yL}),n=new KL(c);t.addVideoTrack(n),await t.start();let r=await new RM(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 zM(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 pM(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 pM(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 RM(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 UL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new MM(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:Hk(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 pM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new pM(e):new pM(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 JL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new MM(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??IL,a=await zL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>bA.includes(e))&&u.some(e=>bA.includes(e))&&(s!==rR||c!==iR)){let e=(await zL(u,{numberOfChannels:rR,sampleRate:iR,bitrate:i})).find(e=>bA.includes(e));e&&(l=!0,n=e,s=rR,c=iR)}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 XL({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new HM(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:Hk(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 SM))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 XL({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new lR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new HM(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=Ik(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},oR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},sR=5,cR=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<sR&&(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()>=sR}wait(e){let{promise:t,resolve:n}=Tk();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},lR=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 SM({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 uR(){return typeof AudioEncoder<`u`}async function dR(e,t){let n=new ZP({source:new qP(e),formats:GP}),r=new vL,i=new eR({format:new DL({fastStart:`in-memory`}),target:r});try{let a=await aR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:IL}});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 fR={isSupported:uR,processToFile:dR},pR=new Set([`moov`,`trak`]);function mR(e){return 12+(e===1?32:20)+8+2}function hR(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+mR(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else pR.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var gR=1920,_R=1080,vR=640,yR=32;function bR(){return typeof VideoEncoder<`u`}async function xR(e){let t=new ZP({source:new qP(e),formats:GP});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 zM(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 ZP({source:new qP(e),formats:GP}),d=new vL,f=new eR({format:new DL({fastStart:`in-memory`}),target:d});try{let i=await aR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:IL},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);hR(a);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(!fR.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 fR.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 JO(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:OT(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=jT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=AT(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=jT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=AT(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`
|
|
2195
2195
|
<div class="relative" data-locale-picker>
|
|
2196
2196
|
<button
|
|
2197
2197
|
type="button"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { l as normalizeSitePathPrefix, t as buildSiteUrl,
|
|
1
|
+
import { l as normalizeSitePathPrefix, t as buildSiteUrl, y as __exportAll } from "./url-XF0GbKGO.js";
|
|
2
2
|
//#region src/lib/display-text.ts
|
|
3
3
|
/**
|
|
4
4
|
* Normalize a user-visible text value.
|