@jant/core 0.3.43 → 0.3.45
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-GbfwoeDJ.js → app-C-L7wL6o.js} +485 -452
- package/dist/app-Hvqe7Ks_.js +5 -0
- package/dist/client/.vite/manifest.json +3 -3
- package/dist/client/_assets/client-DDs6NzB3.css +2 -0
- package/dist/client/_assets/{client-auth-CXILhW1b.js → client-auth-Dcon89Av.js} +30 -11
- package/dist/client/_assets/{client-D95FNDg5.js → client-dSfWfMe9.js} +7 -7
- package/dist/{github-sync-7y_nTXx1.js → github-sync-CQ1x271f.js} +3 -0
- package/dist/index.js +4 -87
- package/dist/node.js +3 -3
- package/package.json +1 -1
- package/src/client/components/jant-compose-dialog.ts +87 -9
- package/src/client/components/jant-compose-editor.ts +5 -1
- package/src/client/components/jant-post-menu.ts +23 -5
- package/src/client/compose-bridge.ts +2 -1
- package/src/client/toast.ts +29 -2
- package/src/client/upload-session.ts +1 -1
- package/src/db/migrations/0019_bored_magus.sql +2 -0
- package/src/db/migrations/0020_free_zaladane.sql +1 -0
- package/src/db/migrations/meta/0019_snapshot.json +2238 -0
- package/src/db/migrations/meta/0020_snapshot.json +2129 -0
- package/src/db/migrations/meta/_journal.json +14 -0
- package/src/db/migrations/pg/0017_bright_beyonder.sql +2 -0
- package/src/db/migrations/pg/0018_red_warlock.sql +1 -0
- package/src/db/migrations/pg/meta/0017_snapshot.json +2862 -0
- package/src/db/migrations/pg/meta/0018_snapshot.json +2739 -0
- package/src/db/migrations/pg/meta/_journal.json +14 -0
- package/src/db/pg/schema.ts +4 -30
- package/src/db/schema.ts +4 -39
- package/src/i18n/locales/public/en.po +10 -5
- package/src/i18n/locales/public/en.ts +1 -1
- package/src/i18n/locales/public/zh-Hans.po +10 -5
- package/src/i18n/locales/public/zh-Hans.ts +1 -1
- package/src/i18n/locales/public/zh-Hant.po +10 -5
- package/src/i18n/locales/public/zh-Hant.ts +1 -1
- package/src/index.ts +0 -3
- package/src/lib/__tests__/resolve-config.test.ts +4 -4
- package/src/lib/__tests__/startup-config.test.ts +27 -2
- package/src/lib/constants.ts +1 -0
- package/src/lib/github-sync-trigger.ts +7 -51
- package/src/lib/icons.ts +37 -0
- package/src/lib/startup-config.ts +53 -6
- package/src/routes/api/github-sync.tsx +36 -14
- package/src/routes/api/internal/sites.ts +1 -0
- package/src/routes/pages/home.tsx +2 -0
- package/src/routes/pages/latest.tsx +2 -0
- package/src/runtime/__tests__/readiness.test.ts +34 -0
- package/src/runtime/readiness.ts +8 -4
- package/src/services/__tests__/collection.test.ts +13 -11
- package/src/services/__tests__/site-admin.test.ts +85 -0
- package/src/services/github-sync.ts +6 -0
- package/src/services/site-admin.ts +66 -1
- package/src/styles/components.css +14 -0
- package/src/styles/ui.css +109 -0
- package/src/types/bindings.ts +0 -2
- package/src/types/config.ts +1 -1
- package/src/types/props.ts +2 -0
- package/src/ui/__tests__/font-themes.test.ts +2 -2
- package/src/ui/dash/settings/SettingsRootContent.tsx +17 -17
- package/src/ui/feed/LinkCard.tsx +3 -20
- package/src/ui/feed/LinkPreview.tsx +5 -19
- package/src/ui/feed/PostStatusBadges.tsx +4 -38
- package/src/ui/font-themes.ts +17 -17
- package/src/ui/layouts/BaseLayout.tsx +14 -29
- package/src/ui/pages/HomePage.tsx +21 -5
- package/src/ui/shared/DecorativeQuoteMark.tsx +2 -13
- package/src/ui/shared/Icon.tsx +60 -0
- package/src/ui/shared/IconSprite.tsx +57 -0
- package/src/ui/shared/PostFooter.tsx +6 -62
- package/src/ui/shared/custom-icons.ts +132 -0
- package/src/ui/shared/icon-collector.ts +37 -0
- package/dist/app-Ctl0T0zO.js +0 -5
- package/dist/client/_assets/client-C_kImWZj.css +0 -2
- package/src/lib/github-sync-queue-handler.ts +0 -69
- package/src/lib/github-sync-worker.ts +0 -72
- package/src/lib/job-queue-cf.ts +0 -18
- package/src/lib/job-queue-db.ts +0 -149
- package/src/lib/job-queue.ts +0 -35
|
@@ -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-dSfWfMe9.js";var x={maxWidth:1920,maxHeight:1920,quality:.85,mimeType:`image/webp`};function S(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function C(e,t,n,r){if(e<=n&&t<=r)return{width:e,height:t};let i=Math.min(n/e,r/t);return{width:Math.round(e*i),height:Math.round(t*i)}}async function ee(e,t,n){let r=await new Promise((r,i)=>{e.toBlob(e=>e?r(e):i(Error(`Failed to create blob`)),t,n)});return t!==`image/png`&&r.type===`image/png`?new Promise((t,r)=>{e.toBlob(e=>e?t(e):r(Error(`Failed to create blob`)),`image/jpeg`,n)}):r}async function te(e,t={}){let n={...x,...t},r=await S(e),{width:i,height:a}=C(r.width,r.height,n.maxWidth,n.maxHeight),o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),{blob:await ee(o,n.mimeType,n.quality),width:i,height:a}}async function ne(e,t={}){let{blob:n,width:r,height:i}=await te(e,t),a={"image/webp":`webp`,"image/jpeg":`jpg`,"image/png":`png`}[n.type]??`png`,o=`${e.name.replace(/\.[^.]+$/,``)}.${a}`;return{file:new File([n],o,{type:n.type}),width:r,height:i}}var re={process:te,processToFile:ne},ie={ICO_16:16,ICO_32:32,APPLE_TOUCH:512};function ae(e){let t=e.length*16,n=6+t,r=new ArrayBuffer(6+t),i=new DataView(r);i.setUint16(0,0,!0),i.setUint16(2,1,!0),i.setUint16(4,e.length,!0);let a=[];for(let t=0;t<e.length;t++){let r=e[t],o=6+t*16;i.setUint8(o+0,r.size<256?r.size:0),i.setUint8(o+1,r.size<256?r.size:0),i.setUint8(o+2,0),i.setUint8(o+3,0),i.setUint16(o+4,1,!0),i.setUint16(o+6,32,!0),i.setUint32(o+8,r.png.byteLength,!0),i.setUint32(o+12,n,!0),n+=r.png.byteLength,a.push(r.png)}return new Blob([r,...a],{type:`image/x-icon`})}function oe(e){return typeof e==`object`&&!!e}function w(e,t){if(!oe(e))return;let n=e[t];return typeof n==`string`?n:void 0}function se(e,t){if(!oe(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}function ce(e,t){if(!oe(e))return;let n=e[t];return typeof n==`number`?n:void 0}async function le(e){let t=await e.json();return oe(t)?t:{}}var ue=180;function de(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function fe(e,t){let n=document.createElement(`canvas`);n.width=t,n.height=t;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let i=Math.max(t/e.width,t/e.height),a=t/i,o=t/i,s=(e.width-a)/2,c=(e.height-o)/2;return r.drawImage(e,s,c,a,o,0,0,t,t),new Promise((e,t)=>{n.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}function pe(e,t){return e.type===`image/png`&&t.width===t.height&&t.width>=ue&&t.height>=ue}async function me(e,t){let n=e.closest(`form`)?.querySelector(`label`),r=n?.textContent??``;try{n&&(n.textContent=e.dataset.textProcessing||`Processing...`);let r=await de(t),a=t,o=t.name;if(t.type!==`image/svg+xml`){let e=await fe(r,512);a=new File([e],t.name.replace(/\.[^.]+$/,`.png`),{type:`image/png`}),o=a.name}let s=pe(t,r)?Promise.resolve(t):fe(r,ie.APPLE_TOUCH),[c,l,u]=await Promise.all([fe(r,16),fe(r,32),s]),[d,f]=await Promise.all([c.arrayBuffer(),l.arrayBuffer()]),p=ae([{size:16,png:d},{size:32,png:f}]);n&&(n.textContent=e.dataset.textUploading||`Uploading...`);let m=new FormData;m.append(`file`,a,o),m.append(`favicon`,p,`favicon.ico`),m.append(`appleTouch`,u,`apple-touch-icon.png`);let h=await fetch(i(`/settings/avatar`),{method:`POST`,headers:{Accept:`application/json`},body:m});if(!h.ok){let t=e.dataset.textError||`Upload failed. Please try again.`;try{let e=await le(h);t=w(e,`error`)??w(e,`message`)??t}catch{}throw Error(t)}let g=await le(h),_=w(g,`status`),v=w(g,`url`);if(_===`redirect`&&v){window.location.href=v;return}window.location.href=i(`/settings/avatar?saved`)}catch(t){n&&(n.textContent=r),a(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}
|
|
@@ -262,7 +262,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
262
262
|
`)?a[0]?`${i} ${a[0]}`:i:`${i}\n${a.map(e=>ix(e)).join(`
|
|
263
263
|
|
|
264
264
|
`)}`},markdownTokenizer:{name:`footnoteDefinition`,level:`block`,start(e){return e.indexOf(`[^`)},tokenize(e,t,n){let r=sx(e);if(r)return{type:`footnoteDefinition`,raw:r.raw,label:r.label,tokens:r.contentMarkdown?n.blockTokens(r.contentMarkdown):[]}}}});function Fx(e={}){return[Wv.configure({heading:{levels:[1,2,3]},link:{openOnClick:!1,autolink:!1},codeBlock:!1}),wx,Yb.configure({resizable:!1,HTMLAttributes:{class:`tiptap-table`}}),Ib,Pb,Fb,Tx,e.imageExtension??Cx,e.moreBreakExtension??kx,e.embedExtension??Ax,e.htmlBlockExtension??jx,Nx,Px]}function Ix(e){let t={...e};if(t.content&&=t.content.map(Ix),t.marks&&=t.marks.map(e=>{if(!e||typeof e!=`object`)return e;let t={...e,attrs:e.type===`link`?{...e.attrs??{},target:typeof e.attrs?.target==`string`?e.attrs.target:`_blank`}:e.attrs};return t.attrs&&Object.keys(t.attrs).length===0&&delete t.attrs,t}),t.attrs&&typeof t.attrs==`object`){let e={...t.attrs};t.type===`codeBlock`&&e.language==null&&delete e.language,Object.keys(e).length>0?t.attrs=e:delete t.attrs}if(t.type===`doc`&&(!t.content||t.content.length===0)&&(t.content=[{type:`paragraph`}]),t.type===`paragraph`&&t.content){let e=[];for(let n=0;n<t.content.length;n+=1){let r=t.content[n],i=t.content[n+1];if(r?.type===`text`&&typeof r.text==`string`&&i?.type===`footnoteReference`&&r.text.endsWith(`
|
|
265
|
-
`)){let t=r.text.replace(/\n$/,``);t&&e.push({...r,text:t});continue}r&&e.push(r)}t.content=e}return t}function Lx(e){return e}function Rx(e=Fx()){return new Em({extensions:e,markedOptions:mx})}var zx=null;function Bx(){return zx??=Rx(),zx}function Vx(e){return Ix(Bx().parse(e))}function Hx(e){return Lx(Bx().serialize(ox(e)))}function Ux(e,t){let n=Gx(e);return n?n===t?0:n.startsWith(t)?1:n.split(/[\s\-_.:/]+/).filter(Boolean).some(e=>e.startsWith(t))?2:n.includes(t)?3:null:null}function Wx(e,t){let n=null;for(let r of e){let e=Ux(r,t);if(e===0)return 0;e!==null&&(n===null||e<n)&&(n=e)}return n}function Gx(e){if(!e)return``;let t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r>=65281&&r<=65374?t+=String.fromCharCode(r-65248):r===12288?t+=` `:t+=e[n]}return t.trim().toLowerCase()}function Kx(e,t){return Wx([e.title,e.slug],t)}function qx(e,t){if(e.length===0)return[];let n=new Set(t),r=[],i=[];for(let t of e)n.has(t.id)?r.push(t.id):i.push(t.id);return[...r,...i]}function Jx(e,t){if(e.length===0||t.length===0)return[...e];let n=new Map(e.map(e=>[e.id,e])),r=[],i=new Set;for(let e of t){let t=n.get(e);!t||i.has(e)||(r.push(t),i.add(e))}for(let t of e)i.has(t.id)||r.push(t);return r}function Yx(e,t){let n=Gx(t);return n?e.map((e,t)=>({item:e,index:t,rank:Kx(e,n)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):[...e]}var Xx={site:`sit`,siteDomain:`sdm`,post:`pst`,media:`med`,uploadSession:`upl`,collection:`col`,path:`pth`,collectionDirectoryItem:`cdi`,navItem:`nav`,apiToken:`api`,user:`usr`,session:`ses`,account:`acc`,verification:`vrf`};Xx.user,Xx.session,Xx.account,Xx.verification;var Zx=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`,`image/avif`,`image/bmp`,`image/x-icon`],Qx=[`video/mp4`,`video/webm`,`video/quicktime`,`video/x-msvideo`,`video/x-matroska`,`video/mpeg`,`video/3gpp`,`video/x-flv`,`video/ogg`],$x=[`audio/mpeg`,`audio/ogg`,`audio/wav`,`audio/mp4`,`audio/x-m4a`,`audio/flac`,`audio/aac`,`audio/webm`,`audio/x-aiff`,`audio/opus`,`audio/3gpp`,`audio/midi`],eS=[`application/pdf`,`application/epub+zip`,`application/x-mobipocket-ebook`,`application/vnd.amazon.ebook`],tS=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/vnd.oasis.opendocument.presentation`,`application/vnd.apple.pages`,`application/vnd.apple.numbers`,`application/vnd.apple.keynote`],nS=[`text/plain`,`text/markdown`,`text/csv`,`text/html`,`text/css`,`text/javascript`,`text/xml`,`text/rtf`,`text/tab-separated-values`,`text/calendar`,`application/json`,`application/xml`,`application/yaml`,`application/toml`],rS=[`application/zip`,`application/x-tar`,`application/gzip`,`application/x-bzip2`,`application/x-7z-compressed`,`application/x-rar-compressed`,`application/zstd`],iS=[`font/ttf`,`font/otf`,`font/woff`,`font/woff2`],aS=[`model/gltf+json`,`model/gltf-binary`,`model/obj`,`application/x-figma`,`image/vnd.dxf`],oS=[`application/sql`,`application/wasm`,`application/x-ipynb+json`,`application/x-sh`,`application/x-python-code`],sS=new Map([...Zx.map(e=>[e,`image`]),...Qx.map(e=>[e,`video`]),...$x.map(e=>[e,`audio`]),...eS.map(e=>[e,`document`]),...tS.map(e=>[e,`office`]),...nS.map(e=>[e,`text`]),...rS.map(e=>[e,`archive`]),...iS.map(e=>[e,`font`]),...aS.map(e=>[e,`3d`]),...oS.map(e=>[e,`code`])]);function cS(e){return sS.get(e)||(e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:e.startsWith(`font/`)?`font`:e.startsWith(`model/`)?`3d`:e.startsWith(`text/`)?`text`:`archive`)}function lS(e){return e.startsWith(`image/`)}function uS(e,t){return dS(e.type,e.size,t)}function dS(e,t,n){if(n?.imagesOnly&&!lS(e))return`File type not allowed.`;let r=n.maxFileSizeMB;return t>r*1024*1024?`File too large (max ${r}MB).`:null}var fS={SITE_NAME:{defaultValue:`Jant`,envOnly:!1,envKeys:[`SITE_NAME`]},SITE_DESCRIPTION:{defaultValue:``,envOnly:!1,envKeys:[`SITE_DESCRIPTION`]},SITE_LANGUAGE:{defaultValue:`en`,envOnly:!1,envKeys:[`SITE_LANGUAGE`]},CJK_SERIF_FONT:{defaultValue:`off`,envOnly:!1,envKeys:[`CJK_SERIF_FONT`]},HOME_DEFAULT_VIEW:{defaultValue:`latest`,envOnly:!1,envKeys:[`HOME_DEFAULT_VIEW`]},MAIN_RSS_FEED:{defaultValue:`featured`,envOnly:!1,envKeys:[`MAIN_RSS_FEED`]},DEFAULT_THEME:{defaultValue:`tufte`,envOnly:!0,envKeys:[`DEFAULT_THEME`]},DEFAULT_FONT_THEME:{defaultValue:`tufte`,envOnly:!0,envKeys:[`DEFAULT_FONT_THEME`]},SITE_ORIGIN:{defaultValue:``,envOnly:!0,envKeys:[`SITE_ORIGIN`]},SITE_PATH_PREFIX:{defaultValue:``,envOnly:!0,envKeys:[`SITE_PATH_PREFIX`]},AUTH_SECRET:{defaultValue:``,envOnly:!0,envKeys:[`AUTH_SECRET`]},R2_PUBLIC_URL:{defaultValue:``,envOnly:!0,envKeys:[`R2_PUBLIC_URL`]},IMAGE_TRANSFORM_URL:{defaultValue:``,envOnly:!0,envKeys:[`IMAGE_TRANSFORM_URL`]},DEMO_EMAIL:{defaultValue:``,envOnly:!0,envKeys:[`DEMO_EMAIL`]},DEMO_PASSWORD:{defaultValue:``,envOnly:!0,envKeys:[`DEMO_PASSWORD`]},DEMO_MODE:{defaultValue:`false`,envOnly:!0,envKeys:[`DEMO_MODE`]},PAGE_SIZE:{defaultValue:`50`,envOnly:!0,envKeys:[`PAGE_SIZE`]},SEARCH_PAGE_SIZE:{defaultValue:``,envOnly:!0,envKeys:[`SEARCH_PAGE_SIZE`]},ARCHIVE_PAGE_SIZE:{defaultValue:``,envOnly:!0,envKeys:[`ARCHIVE_PAGE_SIZE`]},STORAGE_DRIVER:{defaultValue:`r2`,envOnly:!0,envKeys:[`STORAGE_DRIVER`]},S3_ENDPOINT:{defaultValue:``,envOnly:!0,envKeys:[`S3_ENDPOINT`]},S3_BUCKET:{defaultValue:``,envOnly:!0,envKeys:[`S3_BUCKET`]},S3_ACCESS_KEY_ID:{defaultValue:``,envOnly:!0,envKeys:[`S3_ACCESS_KEY_ID`]},S3_SECRET_ACCESS_KEY:{defaultValue:``,envOnly:!0,envKeys:[`S3_SECRET_ACCESS_KEY`]},S3_REGION:{defaultValue:`auto`,envOnly:!0,envKeys:[`S3_REGION`]},S3_PUBLIC_URL:{defaultValue:``,envOnly:!0,envKeys:[`S3_PUBLIC_URL`]},ASSET_BASE_URL:{defaultValue:``,envOnly:!0,envKeys:[`ASSET_BASE_URL`]},UPLOAD_MAX_FILE_SIZE_MB:{defaultValue:`500`,envOnly:!0,envKeys:[`UPLOAD_MAX_FILE_SIZE_MB`]},SUMMARY_MAX_PARAGRAPHS:{defaultValue:`5`,envOnly:!0,envKeys:[`SUMMARY_MAX_PARAGRAPHS`]},SUMMARY_MAX_CHARS:{defaultValue:`500`,envOnly:!0,envKeys:[`SUMMARY_MAX_CHARS`]},SLUG_ID_LENGTH:{defaultValue:`5`,envOnly:!0,envKeys:[`SLUG_ID_LENGTH`]},RSS_FEED_LIMIT:{defaultValue:`50`,envOnly:!0,envKeys:[`RSS_FEED_LIMIT`]},THEME:{defaultValue:``,envOnly:!1,internal:!0},CUSTOM_CSS:{defaultValue:``,envOnly:!1,internal:!0},CUSTOM_HEAD_HTML:{defaultValue:``,envOnly:!1,internal:!0},CUSTOM_BODY_END_HTML:{defaultValue:``,envOnly:!1,internal:!0},SITE_AVATAR:{defaultValue:``,envOnly:!1,internal:!0},SHOW_HEADER_AVATAR:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_ICO:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_APPLE_TOUCH:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_VERSION:{defaultValue:``,envOnly:!1,internal:!0},FONT_THEME:{defaultValue:``,envOnly:!1,internal:!0},THEME_MODE:{defaultValue:``,envOnly:!1,internal:!0},TIME_ZONE:{defaultValue:`UTC`,envOnly:!1,envKeys:[`TIME_ZONE`]},SITE_FOOTER:{defaultValue:``,envOnly:!1,envKeys:[`SITE_FOOTER`]},SHOW_JANT_BRANDING_ON_HOME:{defaultValue:``,envOnly:!1,envKeys:[`SHOW_JANT_BRANDING_ON_HOME`]},NOINDEX:{defaultValue:``,envOnly:!1,envKeys:[`NOINDEX`]},DISCOVERY_COMPOSE_OPEN_SHORTCUT_AT:{defaultValue:``,envOnly:!1,internal:!0},ONBOARDING_STATUS:{defaultValue:`pending`,envOnly:!1,internal:!0},PASSWORD_RESET_TOKEN:{defaultValue:``,envOnly:!1,internal:!0},DELETE_CSRF_TOKEN:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_ENABLED:{defaultValue:`false`,envOnly:!1,internal:!0},GITHUB_SYNC_REPO:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_TOKEN:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_WEBHOOK_SECRET:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_WEBHOOK_ID:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_LAST_PUSH_SHA:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_LAST_PUSH_AT:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_PENDING:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_PENDING_AT:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_DIRTY:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_LAST_ERROR:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_AUTH_MODE:{defaultValue:`pat`,envOnly:!1,internal:!0},GITHUB_SYNC_APP_INSTALLATION_ID:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_APP_ID:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_ID`]},GITHUB_APP_PRIVATE_KEY:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_PRIVATE_KEY`]},GITHUB_APP_SLUG:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_SLUG`]},GITHUB_APP_WEBHOOK_SECRET:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_WEBHOOK_SECRET`]}},pS=[`featured`,`latest`,`signin`,`signout`,`setup`,`settings`,`dash`,`api`,`feed`,`search`,`archive`,`media`,`pages`,`reset`,`collections`,`compose`,`static`,`assets`,`_assets`,`healthz`,`readyz`];function mS(e){let t=e.split(`/`)[0]?.toLowerCase();return pS.includes(t)}Object.fromEntries(Object.entries(fS).filter(([,e])=>!e.envOnly||`internal`in e).map(([e])=>[e,e]));var hS=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function gS(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function _S(e,t){return gS(e.slice(0,t))}function vS(e,t={}){let n=e.trim();return n?t.maxLength&&n.length>t.maxLength?`too_long`:hS.test(n)?mS(n)||t.additionalReservedValues?.some(e=>e.toLowerCase()===n.toLowerCase())?`reserved`:null:`invalid`:null}var yS=Bv;function bS(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=Tf(t),l=RegExp(`\\s${c}$`),u=a?`^`:``,d=r?``:c,f=s?RegExp(`${u}${c}.*?(?=\\s${d}|$)`,`gm`):RegExp(`${u}(?:^)?${c}[^\\s${d}]*`,`gm`),p=o.nodeBefore?.isText&&o.nodeBefore.text;if(!p)return null;let m=o.pos-p.length,h=Array.from(p.matchAll(f)).pop();if(!h||h.input===void 0||h.index===void 0)return null;let g=h.input.slice(Math.max(0,h.index-1),h.index),_=RegExp(`^[${i?.join(``)}\0]?$`).test(g);if(i!==null&&!_)return null;let v=m+h.index,y=v+h[0].length;return s&&l.test(p.slice(y-1,y+1))&&(h[0]+=` `,y+=1),v<o.pos&&y>=o.pos?{range:{from:v,to:y},query:h[0].slice(t.length),text:h[0]}:null}function xS(e){return e.docChanged?e.steps.some(e=>{let t=e.slice;if(!t?.content)return!1;let n=t.content.textBetween(0,t.content.size,`
|
|
265
|
+
`)){let t=r.text.replace(/\n$/,``);t&&e.push({...r,text:t});continue}r&&e.push(r)}t.content=e}return t}function Lx(e){return e}function Rx(e=Fx()){return new Em({extensions:e,markedOptions:mx})}var zx=null;function Bx(){return zx??=Rx(),zx}function Vx(e){return Ix(Bx().parse(e))}function Hx(e){return Lx(Bx().serialize(ox(e)))}function Ux(e,t){let n=Gx(e);return n?n===t?0:n.startsWith(t)?1:n.split(/[\s\-_.:/]+/).filter(Boolean).some(e=>e.startsWith(t))?2:n.includes(t)?3:null:null}function Wx(e,t){let n=null;for(let r of e){let e=Ux(r,t);if(e===0)return 0;e!==null&&(n===null||e<n)&&(n=e)}return n}function Gx(e){if(!e)return``;let t=``;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r>=65281&&r<=65374?t+=String.fromCharCode(r-65248):r===12288?t+=` `:t+=e[n]}return t.trim().toLowerCase()}function Kx(e,t){return Wx([e.title,e.slug],t)}function qx(e,t){if(e.length===0)return[];let n=new Set(t),r=[],i=[];for(let t of e)n.has(t.id)?r.push(t.id):i.push(t.id);return[...r,...i]}function Jx(e,t){if(e.length===0||t.length===0)return[...e];let n=new Map(e.map(e=>[e.id,e])),r=[],i=new Set;for(let e of t){let t=n.get(e);!t||i.has(e)||(r.push(t),i.add(e))}for(let t of e)i.has(t.id)||r.push(t);return r}function Yx(e,t){let n=Gx(t);return n?e.map((e,t)=>({item:e,index:t,rank:Kx(e,n)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):[...e]}var Xx={site:`sit`,siteDomain:`sdm`,post:`pst`,media:`med`,uploadSession:`upl`,collection:`col`,path:`pth`,collectionDirectoryItem:`cdi`,navItem:`nav`,apiToken:`api`,user:`usr`,session:`ses`,account:`acc`,verification:`vrf`};Xx.user,Xx.session,Xx.account,Xx.verification;var Zx=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`,`image/avif`,`image/bmp`,`image/x-icon`],Qx=[`video/mp4`,`video/webm`,`video/quicktime`,`video/x-msvideo`,`video/x-matroska`,`video/mpeg`,`video/3gpp`,`video/x-flv`,`video/ogg`],$x=[`audio/mpeg`,`audio/ogg`,`audio/wav`,`audio/mp4`,`audio/x-m4a`,`audio/flac`,`audio/aac`,`audio/webm`,`audio/x-aiff`,`audio/opus`,`audio/3gpp`,`audio/midi`],eS=[`application/pdf`,`application/epub+zip`,`application/x-mobipocket-ebook`,`application/vnd.amazon.ebook`],tS=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/vnd.oasis.opendocument.presentation`,`application/vnd.apple.pages`,`application/vnd.apple.numbers`,`application/vnd.apple.keynote`],nS=[`text/plain`,`text/markdown`,`text/csv`,`text/html`,`text/css`,`text/javascript`,`text/xml`,`text/rtf`,`text/tab-separated-values`,`text/calendar`,`application/json`,`application/xml`,`application/yaml`,`application/toml`],rS=[`application/zip`,`application/x-tar`,`application/gzip`,`application/x-bzip2`,`application/x-7z-compressed`,`application/x-rar-compressed`,`application/zstd`],iS=[`font/ttf`,`font/otf`,`font/woff`,`font/woff2`],aS=[`model/gltf+json`,`model/gltf-binary`,`model/obj`,`application/x-figma`,`image/vnd.dxf`],oS=[`application/sql`,`application/wasm`,`application/x-ipynb+json`,`application/x-sh`,`application/x-python-code`],sS=new Map([...Zx.map(e=>[e,`image`]),...Qx.map(e=>[e,`video`]),...$x.map(e=>[e,`audio`]),...eS.map(e=>[e,`document`]),...tS.map(e=>[e,`office`]),...nS.map(e=>[e,`text`]),...rS.map(e=>[e,`archive`]),...iS.map(e=>[e,`font`]),...aS.map(e=>[e,`3d`]),...oS.map(e=>[e,`code`])]);function cS(e){return sS.get(e)||(e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:e.startsWith(`font/`)?`font`:e.startsWith(`model/`)?`3d`:e.startsWith(`text/`)?`text`:`archive`)}function lS(e){return e.startsWith(`image/`)}function uS(e,t){return dS(e.type,e.size,t)}function dS(e,t,n){if(n?.imagesOnly&&!lS(e))return`File type not allowed.`;let r=n.maxFileSizeMB;return t>r*1024*1024?`File too large (max ${r}MB).`:null}var fS={SITE_NAME:{defaultValue:`Jant`,envOnly:!1,envKeys:[`SITE_NAME`]},SITE_DESCRIPTION:{defaultValue:``,envOnly:!1,envKeys:[`SITE_DESCRIPTION`]},SITE_LANGUAGE:{defaultValue:`en`,envOnly:!1,envKeys:[`SITE_LANGUAGE`]},CJK_SERIF_FONT:{defaultValue:`off`,envOnly:!1,envKeys:[`CJK_SERIF_FONT`]},HOME_DEFAULT_VIEW:{defaultValue:`latest`,envOnly:!1,envKeys:[`HOME_DEFAULT_VIEW`]},MAIN_RSS_FEED:{defaultValue:`featured`,envOnly:!1,envKeys:[`MAIN_RSS_FEED`]},DEFAULT_THEME:{defaultValue:`tufte`,envOnly:!0,envKeys:[`DEFAULT_THEME`]},DEFAULT_FONT_THEME:{defaultValue:`classic`,envOnly:!0,envKeys:[`DEFAULT_FONT_THEME`]},SITE_ORIGIN:{defaultValue:``,envOnly:!0,envKeys:[`SITE_ORIGIN`]},SITE_PATH_PREFIX:{defaultValue:``,envOnly:!0,envKeys:[`SITE_PATH_PREFIX`]},AUTH_SECRET:{defaultValue:``,envOnly:!0,envKeys:[`AUTH_SECRET`]},R2_PUBLIC_URL:{defaultValue:``,envOnly:!0,envKeys:[`R2_PUBLIC_URL`]},IMAGE_TRANSFORM_URL:{defaultValue:``,envOnly:!0,envKeys:[`IMAGE_TRANSFORM_URL`]},DEMO_EMAIL:{defaultValue:``,envOnly:!0,envKeys:[`DEMO_EMAIL`]},DEMO_PASSWORD:{defaultValue:``,envOnly:!0,envKeys:[`DEMO_PASSWORD`]},DEMO_MODE:{defaultValue:`false`,envOnly:!0,envKeys:[`DEMO_MODE`]},PAGE_SIZE:{defaultValue:`50`,envOnly:!0,envKeys:[`PAGE_SIZE`]},SEARCH_PAGE_SIZE:{defaultValue:``,envOnly:!0,envKeys:[`SEARCH_PAGE_SIZE`]},ARCHIVE_PAGE_SIZE:{defaultValue:``,envOnly:!0,envKeys:[`ARCHIVE_PAGE_SIZE`]},STORAGE_DRIVER:{defaultValue:`r2`,envOnly:!0,envKeys:[`STORAGE_DRIVER`]},S3_ENDPOINT:{defaultValue:``,envOnly:!0,envKeys:[`S3_ENDPOINT`]},S3_BUCKET:{defaultValue:``,envOnly:!0,envKeys:[`S3_BUCKET`]},S3_ACCESS_KEY_ID:{defaultValue:``,envOnly:!0,envKeys:[`S3_ACCESS_KEY_ID`]},S3_SECRET_ACCESS_KEY:{defaultValue:``,envOnly:!0,envKeys:[`S3_SECRET_ACCESS_KEY`]},S3_REGION:{defaultValue:`auto`,envOnly:!0,envKeys:[`S3_REGION`]},S3_PUBLIC_URL:{defaultValue:``,envOnly:!0,envKeys:[`S3_PUBLIC_URL`]},ASSET_BASE_URL:{defaultValue:``,envOnly:!0,envKeys:[`ASSET_BASE_URL`]},UPLOAD_MAX_FILE_SIZE_MB:{defaultValue:`500`,envOnly:!0,envKeys:[`UPLOAD_MAX_FILE_SIZE_MB`]},SUMMARY_MAX_PARAGRAPHS:{defaultValue:`5`,envOnly:!0,envKeys:[`SUMMARY_MAX_PARAGRAPHS`]},SUMMARY_MAX_CHARS:{defaultValue:`500`,envOnly:!0,envKeys:[`SUMMARY_MAX_CHARS`]},SLUG_ID_LENGTH:{defaultValue:`5`,envOnly:!0,envKeys:[`SLUG_ID_LENGTH`]},RSS_FEED_LIMIT:{defaultValue:`50`,envOnly:!0,envKeys:[`RSS_FEED_LIMIT`]},THEME:{defaultValue:``,envOnly:!1,internal:!0},CUSTOM_CSS:{defaultValue:``,envOnly:!1,internal:!0},CUSTOM_HEAD_HTML:{defaultValue:``,envOnly:!1,internal:!0},CUSTOM_BODY_END_HTML:{defaultValue:``,envOnly:!1,internal:!0},SITE_AVATAR:{defaultValue:``,envOnly:!1,internal:!0},SHOW_HEADER_AVATAR:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_ICO:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_APPLE_TOUCH:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_VERSION:{defaultValue:``,envOnly:!1,internal:!0},FONT_THEME:{defaultValue:``,envOnly:!1,internal:!0},THEME_MODE:{defaultValue:``,envOnly:!1,internal:!0},TIME_ZONE:{defaultValue:`UTC`,envOnly:!1,envKeys:[`TIME_ZONE`]},SITE_FOOTER:{defaultValue:``,envOnly:!1,envKeys:[`SITE_FOOTER`]},SHOW_JANT_BRANDING_ON_HOME:{defaultValue:``,envOnly:!1,envKeys:[`SHOW_JANT_BRANDING_ON_HOME`]},NOINDEX:{defaultValue:``,envOnly:!1,envKeys:[`NOINDEX`]},DISCOVERY_COMPOSE_OPEN_SHORTCUT_AT:{defaultValue:``,envOnly:!1,internal:!0},ONBOARDING_STATUS:{defaultValue:`pending`,envOnly:!1,internal:!0},PASSWORD_RESET_TOKEN:{defaultValue:``,envOnly:!1,internal:!0},DELETE_CSRF_TOKEN:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_ENABLED:{defaultValue:`false`,envOnly:!1,internal:!0},GITHUB_SYNC_REPO:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_TOKEN:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_WEBHOOK_SECRET:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_WEBHOOK_ID:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_LAST_PUSH_SHA:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_LAST_PUSH_AT:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_PENDING:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_PENDING_AT:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_DIRTY:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_LAST_ERROR:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_SYNC_AUTH_MODE:{defaultValue:`pat`,envOnly:!1,internal:!0},GITHUB_SYNC_APP_INSTALLATION_ID:{defaultValue:``,envOnly:!1,internal:!0},GITHUB_APP_ID:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_ID`]},GITHUB_APP_PRIVATE_KEY:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_PRIVATE_KEY`]},GITHUB_APP_SLUG:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_SLUG`]},GITHUB_APP_WEBHOOK_SECRET:{defaultValue:``,envOnly:!0,envKeys:[`GITHUB_APP_WEBHOOK_SECRET`]}},pS=[`featured`,`latest`,`signin`,`signout`,`setup`,`settings`,`dash`,`api`,`feed`,`search`,`archive`,`media`,`pages`,`reset`,`collections`,`compose`,`new`,`static`,`assets`,`_assets`,`healthz`,`readyz`];function mS(e){let t=e.split(`/`)[0]?.toLowerCase();return pS.includes(t)}Object.fromEntries(Object.entries(fS).filter(([,e])=>!e.envOnly||`internal`in e).map(([e])=>[e,e]));var hS=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function gS(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function _S(e,t){return gS(e.slice(0,t))}function vS(e,t={}){let n=e.trim();return n?t.maxLength&&n.length>t.maxLength?`too_long`:hS.test(n)?mS(n)||t.additionalReservedValues?.some(e=>e.toLowerCase()===n.toLowerCase())?`reserved`:null:`invalid`:null}var yS=Bv;function bS(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=Tf(t),l=RegExp(`\\s${c}$`),u=a?`^`:``,d=r?``:c,f=s?RegExp(`${u}${c}.*?(?=\\s${d}|$)`,`gm`):RegExp(`${u}(?:^)?${c}[^\\s${d}]*`,`gm`),p=o.nodeBefore?.isText&&o.nodeBefore.text;if(!p)return null;let m=o.pos-p.length,h=Array.from(p.matchAll(f)).pop();if(!h||h.input===void 0||h.index===void 0)return null;let g=h.input.slice(Math.max(0,h.index-1),h.index),_=RegExp(`^[${i?.join(``)}\0]?$`).test(g);if(i!==null&&!_)return null;let v=m+h.index,y=v+h[0].length;return s&&l.test(p.slice(y-1,y+1))&&(h[0]+=` `,y+=1),v<o.pos&&y>=o.pos?{range:{from:v,to:y},query:h[0].slice(t.length),text:h[0]}:null}function xS(e){return e.docChanged?e.steps.some(e=>{let t=e.slice;if(!t?.content)return!1;let n=t.content.textBetween(0,t.content.size,`
|
|
266
266
|
`);return/\s/.test(n)}):!1}var SS=new Or(`suggestion`);function CS({pluginKey:e=SS,editor:t,char:n=`@`,allowSpaces:r=!1,allowToIncludeChar:i=!1,allowedPrefixes:a=[` `],startOfLine:o=!1,decorationTag:s=`span`,decorationClass:c=`suggestion`,decorationContent:l=``,decorationEmptyClass:u=`is-empty`,command:d=()=>null,items:f=()=>[],render:p=()=>({}),allow:m=()=>!0,findSuggestionMatch:h=bS,shouldShow:g,shouldResetDismissed:_}){let v,y=p?.(),b=r&&!i,x=()=>{let e=t.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=t.view.coordsAtPos(e);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}},S=(n,r)=>r?()=>{let r=e.getState(t.state)?.decorationId;return n.dom.querySelector(`[data-decoration-id="${r}"]`)?.getBoundingClientRect()||null}:x,C=({match:e,dismissedRange:n,state:r,transaction:i})=>_?.({editor:t,state:r,range:n,match:e,transaction:i,allowSpaces:b})?!1:b?e.range.from===n.from:e.range.from===n.from&&!xS(i);function ee(n,r){var i;try{let r=e.getState(n.state),a=r?.decorationId?n.dom.querySelector(`[data-decoration-id="${r.decorationId}"]`):null,o={editor:t,range:r?.range||{from:0,to:0},query:r?.query||null,text:r?.text||null,items:[],command:e=>d({editor:t,range:r?.range||{from:0,to:0},props:e}),decorationNode:a,clientRect:S(n,a)};(i=y?.onExit)==null||i.call(y,o)}catch{}let a=n.state.tr.setMeta(r,{exit:!0});n.dispatch(a)}let te=new Tr({key:e,view(){return{update:async(e,n)=>{var r,i,a,o,s;let c=this.key?.getState(n),l=this.key?.getState(e.state),u=c.active&&l.active&&c.range.from!==l.range.from,p=!c.active&&l.active,m=c.active&&!l.active,h=!p&&!m&&c.query!==l.query,g=p||u&&h,_=h||u,b=m||u&&h;if(!g&&!_&&!b)return;let x=b&&!g?c:l,C=e.dom.querySelector(`[data-decoration-id="${x.decorationId}"]`);v={editor:t,range:x.range,query:x.query,text:x.text,items:[],command:e=>d({editor:t,range:x.range,props:e}),decorationNode:C,clientRect:S(e,C)},g&&((r=y?.onBeforeStart)==null||r.call(y,v)),_&&((i=y?.onBeforeUpdate)==null||i.call(y,v)),(_||g)&&(v.items=await f({editor:t,query:x.query})),b&&((a=y?.onExit)==null||a.call(y,v)),_&&((o=y?.onUpdate)==null||o.call(y,v)),g&&((s=y?.onStart)==null||s.call(y,v))},destroy:()=>{var e;v&&((e=y?.onExit)==null||e.call(y,v))}}},state:{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(s,c,l,u){let{isEditable:d}=t,{composing:f}=t.view,{selection:p}=s,{empty:_,from:v}=p,y={...c},b=s.getMeta(e);if(b&&b.exit)return y.active=!1,y.decorationId=null,y.range={from:0,to:0},y.query=null,y.text=null,y.dismissedRange=c.active?{...c.range}:c.dismissedRange,y;if(y.composing=f,s.docChanged&&y.dismissedRange!==null&&(y.dismissedRange={from:s.mapping.map(y.dismissedRange.from),to:s.mapping.map(y.dismissedRange.to)}),d&&(_||t.view.composing)){(v<c.range.from||v>c.range.to)&&!f&&!c.composing&&(y.active=!1);let e=h({char:n,allowSpaces:r,allowToIncludeChar:i,allowedPrefixes:a,startOfLine:o,$position:p.$from}),l=`id_${Math.floor(Math.random()*4294967295)}`;e&&m({editor:t,state:u,range:e.range,isActive:c.active})&&(!g||g({editor:t,range:e.range,query:e.query,text:e.text,transaction:s}))?(y.dismissedRange!==null&&!C({match:e,dismissedRange:y.dismissedRange,state:u,transaction:s})&&(y.dismissedRange=null),y.dismissedRange===null?(y.active=!0,y.decorationId=c.decorationId?c.decorationId:l,y.range=e.range,y.query=e.query,y.text=e.text):y.active=!1):(e||(y.dismissedRange=null),y.active=!1)}else y.active=!1;return y.active||(y.decorationId=null,y.range={from:0,to:0},y.query=null,y.text=null),y}},props:{handleKeyDown(t,n){var r;let{active:i,range:a}=te.getState(t.state);if(!i)return!1;if(n.key===`Escape`||n.key===`Esc`){let i=te.getState(t.state);return(r=y?.onKeyDown)==null||r.call(y,{view:t,event:n,range:i.range}),ee(t,e),!0}return(y?.onKeyDown)?.call(y,{view:t,event:n,range:a})||!1},decorations(e){let{active:t,range:n,decorationId:r,query:i}=te.getState(e);if(!t)return null;let a=!i?.length,o=[c];return a&&o.push(u),nc.create(e.doc,[$s.inline(n.from,n.to,{nodeName:s,class:o.join(` `),"data-decoration-id":r,"data-decoration-content":l})])}}});return te}var wS=CS;function TS(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}function ES(e,t,n,r,i){let a=n.top,o=n.top+n.height;return e===`top`?Math.max(t.top-a-r-i,0):Math.max(o-t.bottom-r-i,0)}function DS(e){if(!e||e===document.body)return{left:0,top:0,width:window.innerWidth,height:window.innerHeight};let t=e.getBoundingClientRect();return{left:t.left,top:t.top,width:t.width,height:t.height}}function OS(e){let t=e.gap??8,n=e.padding??8,r=e.fallbackPlacement??(e.preferredPlacement===`top`?`bottom`:`top`),i=ES(e.preferredPlacement,e.anchorRect,e.containerRect,t,n),a=ES(r,e.anchorRect,e.containerRect,t,n),o=e.floatingHeight<=i||i>=a?e.preferredPlacement:r,s=o===e.preferredPlacement?i:a,c=s>0&&e.floatingHeight>s?s:null,l=c??e.floatingHeight,u=e.align===`center`?(e.anchorRect.left+e.anchorRect.right)/2-e.floatingWidth/2:e.anchorRect.left,d=n,f=e.containerRect.width-e.floatingWidth-n;return{left:TS(u-e.containerRect.left,d,f),top:TS(o===`top`?e.anchorRect.top-e.containerRect.top-l-t:e.anchorRect.bottom-e.containerRect.top+t,n,e.containerRect.height-l-n),placement:o,maxHeight:c}}var kS=[`https://www.youtube-nocookie.com`],AS=[`https://player.vimeo.com`],jS=[`https://open.spotify.com`],MS=[`https://bandcamp.com`],NS=[`https://codepen.io`],PS=`allow-scripts allow-same-origin allow-popups`,FS=`allow-scripts allow-same-origin allow-popups allow-presentation`;function IS(e,t,n){return{provider:`youtube`,providerName:`YouTube`,src:`https://www.youtube-nocookie.com/embed/${e}${n&&n>0?`?start=${n}`:``}`,url:``,orientation:t?`portrait`:`landscape`,sandbox:FS,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share`,cspFrameSrc:kS,cspScriptSrc:[]}}function LS(e){if(!e)return;if(/^\d+$/.test(e)){let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}let t=e.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/);if(!t)return;let n=Number.parseInt(t[1]??`0`,10)||0,r=Number.parseInt(t[2]??`0`,10)||0,i=Number.parseInt(t[3]??`0`,10)||0,a=n*3600+r*60+i;return a>0?a:void 0}var RS=[{id:`youtube`,name:`YouTube`,pattern:/^(?:https?:\/\/)?(?:www\.|m\.)?youtube\.com\/watch\?(?=[^#]*v=([\w-]{6,}))/i,build:(e,t)=>{let n=e[1];return n?IS(n,!1,LS(t.searchParams.get(`t`))):null}},{id:`youtube`,name:`YouTube`,pattern:/^(?:https?:\/\/)?(?:www\.|m\.)?youtube\.com\/shorts\/([\w-]{6,})/i,build:e=>e[1]?IS(e[1],!0):null},{id:`youtube`,name:`YouTube`,pattern:/^(?:https?:\/\/)?youtu\.be\/([\w-]{6,})/i,build:(e,t)=>{let n=e[1];return n?IS(n,!1,LS(t.searchParams.get(`t`))):null}},{id:`vimeo`,name:`Vimeo`,pattern:/^(?:https?:\/\/)?(?:www\.)?vimeo\.com\/(\d+)(?:\/(\w+))?/i,build:e=>{let t=e[1],n=e[2];return{provider:`vimeo`,providerName:`Vimeo`,src:`https://player.vimeo.com/video/${t}${n?`?h=${n}`:``}`,url:``,orientation:`landscape`,sandbox:FS,allow:`autoplay; fullscreen; picture-in-picture`,cspFrameSrc:AS,cspScriptSrc:[]}}},{id:`spotify`,name:`Spotify`,pattern:/^(?:https?:\/\/)?open\.spotify\.com\/(track|album|playlist|episode|show)\/([\w-]+)/i,build:e=>{let t=e[1];return{provider:`spotify`,providerName:`Spotify`,src:`https://open.spotify.com/embed/${t}/${e[2]}`,url:``,orientation:`auto`,heightPx:t===`track`||t===`episode`?152:352,sandbox:FS,allow:`autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture`,cspFrameSrc:jS,cspScriptSrc:[]}}},{id:`bandcamp`,name:`Bandcamp`,pattern:/^(?:https?:\/\/)?([a-z0-9-]+)\.bandcamp\.com\/(track|album)\/([\w-]+)/i,build:(e,t)=>({provider:`bandcamp`,providerName:`Bandcamp`,src:`https://bandcamp.com/EmbeddedPlayer/v=2/linkcol=0687f5/tracklist=false/artwork=small/url=${encodeURIComponent(t.toString())}`,url:``,orientation:`auto`,heightPx:120,sandbox:FS,cspFrameSrc:MS,cspScriptSrc:[]})},{id:`codepen`,name:`CodePen`,pattern:/^(?:https?:\/\/)?codepen\.io\/([\w-]+)\/(?:pen|full|details)\/([\w-]+)/i,build:e=>({provider:`codepen`,providerName:`CodePen`,src:`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result&theme-id=default`,url:``,orientation:`auto`,heightPx:420,sandbox:PS,cspFrameSrc:NS,cspScriptSrc:[]})}];function zS(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t.startsWith(`http`)?t:`https://${t}`)}catch{return null}if(n.protocol!==`https:`&&n.protocol!==`http:`)return null;for(let e of RS){let r=t.match(e.pattern);if(r){let i=e.build(r,n);if(i)return{...i,url:t}}}return n.protocol===`https:`?{provider:`iframe`,providerName:n.hostname,src:n.toString(),url:t,orientation:`landscape`,sandbox:PS,cspFrameSrc:[n.origin],cspScriptSrc:[]}:null}function BS(e){let t=zS(e);return t!==null&&t.provider!==`iframe`}function VS(e={}){return new Promise(t=>{let n=document.createElement(`dialog`);n.className=`dialog tiptap-embed-dialog`;let r=document.createElement(`div`);r.className=`tiptap-embed-dialog-panel`,r.tabIndex=-1,n.appendChild(r);let i=document.createElement(`h2`);i.className=`tiptap-embed-dialog-title`,i.textContent=`Insert embed`,r.appendChild(i);let a=document.createElement(`div`);a.className=`tiptap-embed-dialog-field`,r.appendChild(a);let o=document.createElement(`label`);o.className=`tiptap-embed-dialog-label`,o.textContent=`URL`,a.appendChild(o);let s=document.createElement(`input`);s.type=`url`,s.className=`input tiptap-embed-dialog-input`,s.placeholder=`https://www.youtube.com/watch?v=…`,s.value=e.initialUrl??``,o.appendChild(s);let c=document.createElement(`p`);c.className=`tiptap-embed-dialog-hint`,a.appendChild(c);let l=document.createElement(`div`);l.className=`tiptap-embed-dialog-field`,r.appendChild(l);let u=document.createElement(`label`);u.className=`tiptap-embed-dialog-label`,u.textContent=`Caption (optional)`,l.appendChild(u);let d=document.createElement(`input`);d.type=`text`,d.className=`input tiptap-embed-dialog-input`,d.value=e.initialCaption??``,u.appendChild(d);let f=document.createElement(`div`);f.className=`tiptap-embed-dialog-field`,f.hidden=!0,r.appendChild(f);let p=document.createElement(`label`);p.className=`tiptap-embed-dialog-label`,p.textContent=`Raw HTML`,f.appendChild(p);let m=document.createElement(`textarea`);m.className=`textarea tiptap-embed-dialog-textarea`,m.rows=8,m.placeholder=`<script data-letterbirduser="you" src="https://letterbird.co/embed/v1.js"><\/script>`,m.value=e.initialHtml??``,p.appendChild(m);let h=document.createElement(`p`);h.className=`tiptap-embed-dialog-warning`,h.textContent=`Anything you paste here runs in your visitors' browsers. Only use code you trust.`,f.appendChild(h);let g=document.createElement(`button`);g.type=`button`,g.className=`tiptap-embed-dialog-toggle`,r.appendChild(g);let _=e.initialMode??`url`;function v(){_===`url`?(i.textContent=`Insert embed`,a.hidden=!1,l.hidden=!1,f.hidden=!0,g.textContent=`Paste raw HTML instead`):(i.textContent=`Paste raw HTML`,a.hidden=!0,l.hidden=!0,f.hidden=!1,g.textContent=`Use a URL instead`),y(),ee(),queueMicrotask(()=>{_===`url`?s.focus():m.focus()})}function y(){if(_!==`url`){c.textContent=``;return}let e=s.value.trim();if(!e){c.textContent=`YouTube, Vimeo, Spotify, CodePen, or any HTTPS page.`;return}let t=zS(e);if(!t){c.textContent=`Not a valid URL.`;return}c.textContent=t.provider===`iframe`?`Generic iframe — ${t.providerName}`:`Detected: ${t.providerName}`}g.addEventListener(`click`,e=>{e.preventDefault(),_=_===`url`?`html`:`url`,v()}),s.addEventListener(`input`,()=>{y(),ee()});let b=document.createElement(`div`);b.className=`tiptap-embed-dialog-actions`,r.appendChild(b);let x=document.createElement(`button`);x.type=`button`,x.className=`tiptap-embed-dialog-link-instead`,x.textContent=`Insert as link instead`,x.addEventListener(`click`,e=>{e.preventDefault();let t=s.value.trim();if(!t){s.focus();return}oe({kind:`link`,url:t})}),b.appendChild(x);let S=document.createElement(`button`);S.type=`button`,S.className=`btn-outline`,S.textContent=`Cancel`,S.addEventListener(`click`,e=>{e.preventDefault(),oe(null)}),b.appendChild(S);let C=document.createElement(`button`);C.type=`button`,C.className=`btn`,C.textContent=`Insert`,C.addEventListener(`click`,e=>{e.preventDefault(),te()}),b.appendChild(C);function ee(){x.hidden=!(_===`url`&&s.value.trim().length>0)}function te(){if(_===`url`){let e=s.value.trim();if(!e){s.focus();return}if(!zS(e)){c.textContent=`Not a valid URL.`,s.focus();return}oe({kind:`embed`,url:e,caption:d.value.trim()||void 0})}else{if(!m.value.trim()){m.focus();return}oe({kind:`html`,html:m.value})}}function ne(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),oe(null);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){if(e.target instanceof HTMLTextAreaElement)return;e.preventDefault(),te()}}function re(e){e.target===n&&oe(null)}function ie(e){e.preventDefault(),oe(null)}let ae=!1;function oe(e){ae||(ae=!0,n.removeEventListener(`cancel`,ie),n.removeEventListener(`click`,re),n.removeEventListener(`keydown`,ne),n.open&&n.close(),n.remove(),t(e))}n.addEventListener(`cancel`,ie),n.addEventListener(`click`,re),n.addEventListener(`keydown`,ne),document.body.appendChild(n),v(),n.showModal(),r.focus()})}var HS={image:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>`,embed:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="3" rx="2" ry="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/><polygon points="10 8 15 11 10 14 10 8" fill="currentColor"/></svg>`,divider:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h18"/></svg>`,readMore:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h18"/><path d="m9 18 3 3 3-3"/><path d="m9 6-3-3-3 3"/><path d="M3 6h18"/></svg>`,footnote:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h10"/><path d="M12 4v11"/><path d="M9 9h6"/><path d="M16 20h4"/><path d="M18 14v6"/></svg>`,table:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v18"/><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/><path d="M3 15h18"/></svg>`,code:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>`,blockquote:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>`,bulletList:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" x2="21" y1="6" y2="6"/><line x1="8" x2="21" y1="12" y2="12"/><line x1="8" x2="21" y1="18" y2="18"/><line x1="3" x2="3.01" y1="6" y2="6"/><line x1="3" x2="3.01" y1="12" y2="12"/><line x1="3" x2="3.01" y1="18" y2="18"/></svg>`,orderedList:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="10" x2="21" y1="6" y2="6"/><line x1="10" x2="21" y1="12" y2="12"/><line x1="10" x2="21" y1="18" y2="18"/><path d="M4 6h1v4"/><path d="M4 10h2"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/></svg>`,h1:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17 12l3-2v10"/></svg>`,h2:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>`,h3:`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2"/><path d="M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"/></svg>`},US={media:`Media`,structure:`Structure`,formatting:`Formatting`,headings:`Headings`},WS=[`media`,`structure`,`formatting`,`headings`],GS=`No matches. Try another command.`,KS={insert:`Insert`,close:`Close`},qS=[{label:`Media`,description:`Upload an image or video.`,group:`media`,keywords:[`image`,`video`,`photo`,`upload`],icon:HS.image,command:(e,t)=>{e.chain().focus().deleteRange(t).run(),document.dispatchEvent(new CustomEvent(`jant:slash-image`,{bubbles:!0}))}},{label:`Embed`,description:`Embed a YouTube video, tweet, or any HTTPS page.`,group:`media`,keywords:[`embed`,`youtube`,`vimeo`,`spotify`,`video`,`iframe`,`html`,`letterbird`],icon:HS.embed,command:(e,t)=>{e.chain().focus().deleteRange(t).run(),VS().then(t=>{if(!t){e.commands.focus();return}t.kind===`embed`?e.chain().focus().setEmbed({url:t.url,caption:t.caption}).run():t.kind===`link`?e.chain().focus().insertContent({type:`text`,text:t.url,marks:[{type:`link`,attrs:{href:t.url}}]}).run():e.chain().focus().setHtmlBlock({html:t.html}).run()})}},{label:`Divider`,description:`Separate one thought from the next.`,group:`structure`,keywords:[`line`,`rule`,`separator`,`break`,`hr`],icon:HS.divider,command:(e,t)=>{e.chain().focus().deleteRange(t).setHorizontalRule().run()}},{label:`Read More`,description:`Collapse the rest of a longer post.`,group:`structure`,keywords:[`excerpt`,`continue`,`teaser`,`more`,`break`],icon:HS.readMore,command:(e,t)=>{e.chain().focus().deleteRange(t).insertMoreBreak().run()}},{label:`Footnote`,description:`Insert a numbered footnote and jump to its note.`,group:`structure`,keywords:[`footnote`,`note`,`citation`,`reference`,`superscript`],icon:HS.footnote,command:(e,t)=>{e.chain().focus().deleteRange(t).insertFootnote().run()}},{label:`Table`,description:`Insert a 3 by 3 table.`,group:`structure`,keywords:[`grid`,`rows`,`columns`,`spreadsheet`],icon:HS.table,command:(e,t)=>{e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()}},{label:`Code Block`,description:`Format a block of code or monospace text.`,group:`formatting`,keywords:[`code`,`snippet`,`pre`,`monospace`],icon:HS.code,command:(e,t)=>{e.chain().focus().deleteRange(t).toggleCodeBlock().run()}},{label:`Blockquote`,description:`Set off quoted text or a pull quote.`,group:`formatting`,keywords:[`quote`,`citation`,`excerpt`,`callout`],icon:HS.blockquote,command:(e,t)=>{e.chain().focus().deleteRange(t).toggleBlockquote().run()}},{label:`Bullet List`,description:`Start an unordered list.`,group:`formatting`,keywords:[`list`,`bullets`,`unordered`,`ul`],icon:HS.bulletList,command:(e,t)=>{e.chain().focus().deleteRange(t).toggleBulletList().run()}},{label:`Ordered List`,description:`Start a numbered list.`,group:`formatting`,keywords:[`list`,`numbered`,`ordered`,`ol`],icon:HS.orderedList,command:(e,t)=>{e.chain().focus().deleteRange(t).toggleOrderedList().run()}},{label:`Heading 1`,description:`Insert the largest section heading.`,group:`headings`,keywords:[`title`,`h1`,`large heading`,`section title`],icon:HS.h1,command:(e,t)=>{e.chain().focus().deleteRange(t).toggleHeading({level:1}).run()}},{label:`Heading 2`,description:`Insert a medium section heading.`,group:`headings`,keywords:[`subtitle`,`h2`,`section heading`],icon:HS.h2,command:(e,t)=>{e.chain().focus().deleteRange(t).toggleHeading({level:2}).run()}},{label:`Heading 3`,description:`Insert a small section heading.`,group:`headings`,keywords:[`subheading`,`h3`,`small heading`],icon:HS.h3,command:(e,t)=>{e.chain().focus().deleteRange(t).toggleHeading({level:3}).run()}}];function JS(e){let t=!1;return e.state.doc.descendants(e=>e.type.name===`moreBreak`?(t=!0,!1):!t),t}function YS(e){return e&&JS(e)?qS.filter(e=>e.label!==`Read More`):qS}var XS=null,ZS=0,QS=[],$S=null,eC=null,tC=null,nC=null;function rC(){return XS?XS.querySelector(`.tiptap-slash-menu-scroll`)??XS:null}function iC(){let e=document.createElement(`div`);return e.className=`tiptap-slash-menu`,e.dataset.editorFloatingUi=`true`,e.style.position=`fixed`,e}function aC(){if(!XS)return;let e=rC();if(!e)return;let t=XS.querySelector(`.tiptap-slash-item.is-selected`);if(!t)return;let n=t.offsetTop-e.offsetTop,r=n+t.offsetHeight,i=e.scrollTop,a=i+e.clientHeight;n<i?e.scrollTop=n:r>a&&(e.scrollTop=r-e.clientHeight)}function oC(){XS?.querySelectorAll(`.tiptap-slash-item`).forEach((e,t)=>{let n=t===ZS;e.classList.toggle(`is-selected`,n),e.setAttribute(`aria-selected`,n?`true`:`false`)}),cC(),aC()}function sC(){return QS[ZS]??null}function cC(){let e=XS?.querySelector(`.tiptap-slash-footer-description`);e&&(e.textContent=sC()?.description??``)}function lC(e){return`<div class="tiptap-slash-footer">
|
|
267
267
|
<span class="tiptap-slash-footer-description">${cx(e?.description??``)}</span>
|
|
268
268
|
<span class="tiptap-slash-footer-actions" aria-hidden="true">
|
|
@@ -295,7 +295,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
295
295
|
</section>`}).join(``);XS.innerHTML=`<div class="tiptap-slash-menu-scroll">
|
|
296
296
|
${n}
|
|
297
297
|
</div>
|
|
298
|
-
${lC(sC())}`,XS.querySelectorAll(`.tiptap-slash-item`).forEach(e=>{e.addEventListener(`mousedown`,n=>{n.preventDefault(),t(parseInt(e.dataset.index??`0`,10))}),e.addEventListener(`mouseenter`,()=>{ZS=parseInt(e.dataset.index??`0`,10),oC()})});let r=rC();r&&(r.scrollTop=0)}function fC(){nC&&=(document.removeEventListener(`mousedown`,nC,!0),null),XS?.remove(),XS=null,ZS=0,QS=[],$S=null,eC=null,tC=null}function pC(e,t){if(!XS)return;XS.style.maxHeight=``;let n=DS(null),r=t?DS(t):n,i=OS({anchorRect:{left:e.left,right:e.left,top:e.top,bottom:e.bottom},containerRect:n,floatingWidth:XS.offsetWidth,floatingHeight:XS.offsetHeight,preferredPlacement:`bottom`,fallbackPlacement:`top`,align:`start`,gap:6});XS.style.left=`${i.left-r.left}px`,XS.style.top=`${i.top-r.top}px`,XS.style.maxHeight=i.maxHeight===null?``:`${i.maxHeight}px`}function mC(){nC=e=>{if(!(!XS||XS.contains(e.target))&&eC&&tC){let{state:e,view:t}=eC;t.dispatch(e.tr.delete(tC.from,tC.to))}},document.addEventListener(`mousedown`,nC,!0)}var hC=new Or(`jantSlashTyping`);function gC(){return new Tr({key:hC,state:{init:()=>({docChanged:!1}),apply:e=>({docChanged:e.docChanged})}})}function _C({state:e,range:t}){let n=e.doc.resolve(t.to),r=n.parent,i=t.to-n.start();if(i>=r.content.size)return!0;let a=r.textBetween(i,i+1,` `,` `);return a?/\s/.test(a):!0}function vC({state:e,range:t,isActive:n}){return _C({state:e,range:t})?n?!0:hC.getState(e)?.docChanged??!1:!1}var yC=M.create({name:`slashCommands`,addOptions(){return{suggestion:{char:`/`,startOfLine:!1,allow:vC,items:({query:e,editor:t})=>{let n=YS(t),r=Gx(e);return r?n.map((e,t)=>({item:e,index:t,rank:Wx([e.label,e.description,...e.keywords],r)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):n},render:()=>{function e(e){let t=e.options.element;return t instanceof globalThis.Element?t:null}return{onStart:t=>{XS=iC(),ZS=0,$S=t.command,eC=t.editor,tC=t.range,dC(t.items,e=>t.command({index:e}));let n=e(t.editor)?.closest(`dialog`)??null;(n??document.body).appendChild(XS);let r=t.clientRect?.();r&&pC(r,n),mC()},onUpdate:t=>{$S=t.command,tC=t.range,dC(t.items,e=>t.command({index:e}));let n=t.clientRect?.();n&&pC(n,e(t.editor)?.closest(`dialog`)??null)},onKeyDown:e=>{let{event:t,view:n,range:r}=e;return t.key===`ArrowDown`?(t.preventDefault(),QS.length===0?!0:(ZS=(ZS+1)%QS.length,oC(),!0)):t.key===`ArrowUp`?(t.preventDefault(),QS.length===0?!0:(ZS=(ZS-1+QS.length)%QS.length,oC(),!0)):t.key===`Enter`?(t.preventDefault(),QS.length===0||$S?.({index:ZS}),!0):t.key===`Escape`?(t.stopPropagation(),t.preventDefault(),n.dispatch(n.state.tr.delete(r.from,r.to)),!0):!1},onExit:()=>{fC()}}},command:({editor:e,range:t,props:n})=>{let r=QS[n.index];r&&r.command(e,t)}}}},addProseMirrorPlugins(){return[gC(),wS({editor:this.editor,...this.options.suggestion})]}}),bC=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~`.split(``),xC=(e,t)=>{var n=``;for(let r=1;r<=t;r++){let i=Math.floor(e)/83**(t-r)%83;n+=bC[Math.floor(i)]}return n},SC=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4},CC=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(t*12.92*255+.5):Math.trunc((1.055*t**.4166666666666667-.055)*255+.5)},wC=e=>e<0?-1:1,TC=(e,t)=>wC(e)*Math.abs(e)**+t,EC=class extends Error{constructor(e){super(e),this.name=`ValidationError`,this.message=e}},DC=4,OC=(e,t,n,r)=>{let i=0,a=0,o=0,s=t*DC;for(let c=0;c<t;c++){let t=DC*c;for(let l=0;l<n;l++){let n=t+l*s,u=r(c,l);i+=u*SC(e[n]),a+=u*SC(e[n+1]),o+=u*SC(e[n+2])}}let c=1/(t*n);return[i*c,a*c,o*c]},kC=e=>{let t=CC(e[0]),n=CC(e[1]),r=CC(e[2]);return(t<<16)+(n<<8)+r},AC=(e,t)=>{let n=Math.floor(Math.max(0,Math.min(18,Math.floor(TC(e[0]/t,.5)*9+9.5)))),r=Math.floor(Math.max(0,Math.min(18,Math.floor(TC(e[1]/t,.5)*9+9.5)))),i=Math.floor(Math.max(0,Math.min(18,Math.floor(TC(e[2]/t,.5)*9+9.5))));return n*19*19+r*19+i},jC=(e,t,n,r,i)=>{if(r<1||r>9||i<1||i>9)throw new EC(`BlurHash must have between 1 and 9 components`);if(t*n*4!==e.length)throw new EC(`Width and height must match the pixels array`);let a=[];for(let o=0;o<i;o++)for(let i=0;i<r;i++){let r=i==0&&o==0?1:2,s=OC(e,t,n,(e,a)=>r*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*o*a/n));a.push(s)}let o=a[0],s=a.slice(1),c=``,l=r-1+(i-1)*9;c+=xC(l,1);let u;if(s.length>0){let e=Math.max(...s.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(e*166-.5))));u=(t+1)/166,c+=xC(t,1)}else u=1,c+=xC(0,1);return c+=xC(kC(o),4),s.forEach(e=>{c+=xC(AC(e,u),2)}),c};async function MC(e){let t=await IC(e),{width:n,height:r}=t,i=Math.min(32/n,32/r,1),a=Math.max(Math.round(n*i),1),o=Math.max(Math.round(r*i),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);return c.drawImage(t,0,0,a,o),{width:n,height:r,blurhash:jC(c.getImageData(0,0,a,o).data,a,o,4,3)}}async function NC(e){let t=URL.createObjectURL(e);try{let e=document.createElement(`video`);e.muted=!0,e.preload=`auto`;let{width:n,height:r,duration:i}=await new Promise((n,r)=>{e.onloadedmetadata=()=>n({width:e.videoWidth,height:e.videoHeight,duration:e.duration}),e.onerror=()=>r(Error(`Failed to load video metadata`)),e.src=t}),a,o;try{let t=Math.min(i*.1,3),s=await Promise.race([LC(e,n,r,t),RC(8e3)]);a=s.blurhash,o=s.poster}catch{}return{width:n,height:r,blurhash:a,poster:o}}finally{URL.revokeObjectURL(t)}}async function PC(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function FC(e){try{if(e.type.startsWith(`image/`))return await MC(e);if(e.type.startsWith(`video/`)){let t=await NC(e);return{width:t.width,height:t.height,blurhash:t.blurhash,poster:t.poster}}if(e.type.startsWith(`audio/`))return{waveform:await PC(e)}}catch{}return{}}function IC(e){return new Promise((t,n)=>{let r=new Image,i=URL.createObjectURL(e);r.onload=()=>{URL.revokeObjectURL(i),t(r)},r.onerror=()=>{URL.revokeObjectURL(i),n(Error(`Failed to load image`))},r.src=i})}function LC(e,t,n,r){return new Promise((i,a)=>{e.currentTime=r,e.onseeked=()=>{try{let r=Math.min(32/t,32/n,1),a=Math.max(Math.round(t*r),1),o=Math.max(Math.round(n*r),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);c.drawImage(e,0,0,a,o);let l=jC(c.getImageData(0,0,a,o).data,a,o,4,3),u=Math.min(640/t,1),d=Math.round(t*u),f=Math.round(n*u),p=document.createElement(`canvas`);p.width=d,p.height=f;let m=p.getContext(`2d`);if(!m){i({blurhash:l});return}m.drawImage(e,0,0,d,f),p.toBlob(e=>{i({blurhash:l,poster:e??void 0})},`image/webp`,.8)}catch(e){a(e)}},e.onerror=()=>a(Error(`Video seek failed`))})}function RC(e){return new Promise((t,n)=>setTimeout(()=>n(Error(`Timeout`)),e))}function zC(e){if(!oe(e))return null;let t=w(e,`kind`),n=w(e,`method`),r=w(e,`url`);if(!t||n!==`PUT`||!r)return null;if(t===`relay`)return{kind:t,method:`PUT`,url:r};if(t===`multipartRelay`){let n=ce(e,`partSize`);return n?{kind:t,method:`PUT`,url:r,partSize:n}:null}if(t===`put`){let n=ce(e,`expiresAt`),i=e.headers;if(!n||!oe(i))return null;let a={};for(let[e,t]of Object.entries(i))typeof t==`string`&&(a[e]=t);return{kind:t,method:`PUT`,url:r,headers:a,expiresAt:n}}return null}async function BC(e){let t=await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()),n=new Uint8Array(t),r=``;for(let e of n)r+=String.fromCharCode(e);return btoa(r)}async function VC(e){let t=await fetch(i(`/api/uploads/init`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({filename:e.name,contentType:e.type,size:e.size,checksumSha256:await BC(e)})});if(!t.ok){let e=await le(t);throw Error(w(e,`error`)??`Failed to start upload`)}let n=await le(t),r=w(n,`id`),a=zC(n.transport);if(!r||!a)throw Error(`Failed to start upload`);return{id:r,transport:a}}async function HC(e,t){if(!(await fetch(i(`/api/uploads/${e}/poster`),{method:`PUT`,headers:{"Content-Type":t.type||`image/webp`},body:t})).ok)throw Error(`Failed to upload poster`)}async function UC(e){await fetch(i(`/api/uploads/${e}/abort`),{method:`POST`}).catch(()=>{})}async function WC(e,t){let n=await fetch(i(`/api/uploads/${e}/complete`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await le(n);throw Error(w(e,`error`)??`Failed to complete upload`)}let r=await le(n),a=w(r,`id`),o=w(r,`filename`),s=w(r,`url`),c=w(r,`mimeType`),l=ce(r,`size`);if(!a||!o||!s||!c||l===void 0)throw Error(`Failed to complete upload`);return{id:a,filename:o,url:s,mimeType:c,size:l}}async function GC(e,t,n,r){let a=Math.ceil(n.size/t.partSize),o=[],s=0;for(let e=0;e<a;e+=1){let a=e*t.partSize,c=Math.min(a+t.partSize,n.size),l=e+1,u=n.slice(a,c),d=await fetch(i(`${t.url}?partNumber=${l}`),{method:`PUT`,body:u});if(!d.ok)throw Error(`Failed to upload part ${l}`);let f=await le(d),p=ce(f,`partNumber`),m=w(f,`etag`);if(!p||!m)throw Error(`Failed to upload part ${l}`);o.push({partNumber:p,etag:m}),s+=c-a,r?.(s/n.size)}return o}async function KC(e,t,n){let{id:r,transport:a}=await VC(e);try{if(a.kind===`put`){if(!(await fetch(a.url,{method:`PUT`,headers:a.headers,body:e})).ok)throw Error(`Upload failed`);n?.(1)}else if(a.kind===`relay`){let t=await fetch(i(a.url),{method:`PUT`,headers:{"Content-Type":e.type},body:e});if(!t.ok){let e=await le(t);throw Error(w(e,`error`)??`Upload failed`)}n?.(1)}let o=a.kind===`multipartRelay`?await GC(r,a,e,n):void 0;return t.poster&&await HC(r,t.poster),WC(r,{...t,parts:o})}catch(e){throw await UC(r),e}}async function qC(e){let{file:t,width:n,height:r}=await re.processToFile(e),i;try{i=(await MC(t)).blurhash}catch{}let a=await KC(t,{width:n,height:r,blurhash:i});return{url:a.url,id:a.id}}var JC=new Map,YC=new Map;function XC(e,t,n){if(e.isDestroyed)return;let{doc:r}=e.state,i=!1;r.descendants((r,a)=>{i||r.type.name!==`image`||r.attrs.src!==t||(e.chain().command(({tr:e})=>(e.setNodeMarkup(a,void 0,{...r.attrs,src:n}),!0)).run(),i=!0)})}function ZC(e,t){if(e.isDestroyed)return;let{doc:n}=e.state;n.descendants((n,r)=>{n.type.name===`image`&&n.attrs.src===t&&e.chain().command(({tr:e})=>(e.delete(r,r+n.nodeSize),!0)).run()})}async function QC(e,t,n=qC){let r=URL.createObjectURL(t);e.chain().focus().setImage({src:r}).run();let i=n(t).then(e=>e.url);JC.set(r,i);try{XC(e,r,await i)}catch{ZC(e,r)}finally{JC.delete(r)&&URL.revokeObjectURL(r)}}function $C(e){let t=[],{doc:n}=e.state;return n.descendants(n=>{if(n.type.name!==`image`)return;let r=n.attrs.src;if(!r?.startsWith(`blob:`))return;let i=JC.get(r);if(!i)return;JC.delete(r),YC.set(r,i);let a=i.then(t=>XC(e,r,t),()=>ZC(e,r)).finally(()=>{YC.delete(r),URL.revokeObjectURL(r)});t.push(a)}),t}async function ew(e){if(!e)return e;let t=new Map;if(tw(e,t),t.size===0)return e;let n=new Map;return await Promise.allSettled(Array.from(t.entries()).map(async([e,t])=>{let r=await t;n.set(e,r)})),nw(e,n)}function tw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=JC.get(e.attrs.src)??YC.get(e.attrs.src);n&&t.set(e.attrs.src,n)}if(e.content)for(let n of e.content)tw(n,t)}function nw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=t.get(e.attrs.src);return n?{...e,attrs:{...e.attrs,src:n}}:{type:`__removed__`}}if(!e.content)return e;let n=e.content.map(e=>nw(e,t)).filter(e=>e.type!==`__removed__`);return n===e.content?e:{...e,content:n}}var rw=new Or(`pasteMedia`);function iw(e){return`${e.name}:${e.type}:${e.size}:${e.lastModified}`}function aw(e){if(!e)return[];let t=Array.from(e.items??[]).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null),n=t.length>0?t:Array.from(e.files??[]),r=new Set;return n.filter(e=>{let t=iw(e);return r.has(t)?!1:(r.add(t),!0)})}var ow=M.create({name:`pasteMedia`,addOptions(){return{shouldInsertInline:void 0,onPasteFiles:void 0}},addProseMirrorPlugins(){let e=this;return[new Tr({key:rw,props:{handlePaste(t,n){let r=aw(n.clipboardData);if(r.length===0)return!1;let i=r.filter(t=>e.options.shouldInsertInline?.(t)===!0),a=r.filter(e=>!i.includes(e));if(i.length===0&&(a.length===0||e.options.onPasteFiles===void 0))return!1;n.preventDefault();for(let t of i){let n=e.options.uploadInlineImage;if(n){n(t);continue}QC(e.editor,t)}return a.length>0&&e.options.onPasteFiles!==void 0&&e.options.onPasteFiles(a),!0}}})]}}),sw=`(pointer: coarse)`;function cw(e){return e===`compose`&&(globalThis.matchMedia?.(sw).matches??!1)}function lw(e,t){let n=t.dom.closest(`jant-compose-editor`),r=t.dom.closest(`jant-compose-dialog, .compose-fullscreen, .compose-attached-panel`)??t.dom.closest(`dialog`),i=16,a=n?.querySelector(`.compose-tools-row`)??r?.querySelector(`.compose-tools-row`),o=r?.querySelector(`.compose-action-row`),s=n?.querySelector(`.compose-attachments-dock`);a&&(i+=a.getBoundingClientRect().height),o&&(i+=o.getBoundingClientRect().height),s&&(i+=s.getBoundingClientRect().height),e.style.setProperty(`--tiptap-docked-offset`,`${i}px`)}var uw=new Or(`linkToolbar`),dw=`hidden`,fw=!1;function pw(){return dw===`input`&&fw}var mw=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/></svg>`;function hw(e){let{selection:t}=e;if(!t.empty)return null;let n=t.$from,r=e.schema.marks.link;if(!r)return null;let i=n.marks().find(e=>e.type===r);if(!i)return null;let a=n.parent,o=n.start(),s=0,c=0,l=!1,u=0;for(let e=0;e<a.childCount;e++){let t=a.child(e),n=o+u,d=n+t.nodeSize;if(t.marks.some(e=>e.type===r&&e.attrs.href===i.attrs.href))l||=(s=n,!0),c=d;else if(l)break;u+=t.nodeSize}return l?{from:s,to:c,href:i.attrs.href}:null}var gw=M.create({name:`linkToolbar`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=null,i=null,a=0,o=0,s=!1,c=!1,l=null;function u(){n=document.createElement(`div`),n.className=`tiptap-link-input`,n.dataset.editorFloatingUi=`true`,n.style.display=`none`;let t=document.createElement(`div`);t.className=`tiptap-link-input-fields`,i=document.createElement(`input`),i.type=`text`,i.className=`tiptap-link-input-text`,i.placeholder=`Link text`,r=document.createElement(`input`),r.type=`url`,r.className=`tiptap-link-input-field`,r.placeholder=`https:// (empty to unlink)`,t.appendChild(i),t.appendChild(r);let a=document.createElement(`button`);a.type=`button`,a.className=`tiptap-link-input-confirm`,a.innerHTML=mw,a.title=`Apply link`,n.appendChild(t),n.appendChild(a);let o=t=>{t.key===`Enter`?(t.preventDefault(),t.stopPropagation(),h()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),c=!0,p(),e.commands.focus())};i.addEventListener(`keydown`,o),r.addEventListener(`keydown`,o);let s=()=>{fw=!0},l=()=>{requestAnimationFrame(()=>{let e=document.activeElement;(!n||!n.contains(e))&&(fw=!1)})};i.addEventListener(`focus`,s),r.addEventListener(`focus`,s),i.addEventListener(`blur`,l),r.addEventListener(`blur`,l),a.addEventListener(`mousedown`,e=>{e.preventDefault(),h()}),n.addEventListener(`mousedown`,e=>{e.stopPropagation()})}function d(e,n,r,i){let a=cw(t);if(e.classList.toggle(`tiptap-link-input-docked`,a),e.style.display=`flex`,a){lw(e,n),e.style.removeProperty(`left`),e.style.removeProperty(`top`);return}let o=n.dom.closest(`dialog`),s=n.coordsAtPos(r),c=n.coordsAtPos(i),l=e.getBoundingClientRect(),u=OS({anchorRect:{left:s.left,right:c.right,top:Math.min(s.top,c.top),bottom:Math.max(s.bottom,c.bottom)},containerRect:DS(o),floatingWidth:l.width,floatingHeight:l.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});e.style.left=`${u.left}px`,e.style.top=`${u.top}px`}function f(e,t){if(!(!n||!r||!i)){if(t.from!==void 0&&t.to!==void 0?(a=t.from,o=t.to):(a=e.state.selection.from,o=e.state.selection.to),dw=`input`,r.value=t.href,i.value=t.text??e.state.doc.textBetween(a,o,``),d(n,e,a,o),t.focus){let e=i.value.length>0?r:i;requestAnimationFrame(()=>{e.focus(),e.select()})}m(),l=e=>{n&&!n.contains(e.target)&&(c=!0,p())},setTimeout(()=>{l&&document.addEventListener(`mousedown`,l,!0)},0)}}function p(){n&&(n.style.display=`none`),dw=`hidden`,fw=!1,m()}function m(){l&&=(document.removeEventListener(`mousedown`,l,!0),null)}function h(){if(!r||!i)return;let t=r.value.trim(),n=e.state.doc.textBetween(a,o,``),c=i.value,l=c.length>0?c:t;if(p(),!t){e.chain().focus().setTextSelection({from:a,to:o}).unsetLink().setTextSelection(o).run(),s=!0;return}let u=l!==n,d=a+l.length;u?e.chain().focus().command(({tr:e})=>(e.insertText(l,a,o),!0)).setTextSelection({from:a,to:d}).setLink({href:t}).setTextSelection(d).run():e.chain().focus().setTextSelection({from:a,to:o}).setLink({href:t}).setTextSelection(o).run(),s=!0}return[new Tr({key:uw,view(e){u();let t=e.dom.closest(`dialog`);n&&(t??document.body).appendChild(n);let r=()=>{c=!1,s=!0,f(e,{href:``,focus:!0})};e.dom.addEventListener(`tiptap:open-link-input`,r);let i=e=>{e.key===`Escape`&&dw===`input`&&(e.preventDefault(),e.stopPropagation(),c=!0,p())};return e.dom.addEventListener(`keydown`,i),{update(e){if(s){s=!1;return}let t=hw(e.state);if(dw===`input`&&fw){n&&d(n,e,a,o);return}if(t){if(c)return;f(e,{href:t.href,from:t.from,to:t.to,focus:!1})}else c=!1,dw===`input`&&p()},destroy(){e.dom.removeEventListener(`tiptap:open-link-input`,r),e.dom.removeEventListener(`keydown`,i),m(),n?.remove(),n=null,dw=`hidden`,fw=!1}}}})]}}),_w=new Or(`bubbleMenu`),vw={bold:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 12h9a4 4 0 0 1 0 8H6V4h8a4 4 0 0 1 0 8"/></svg>`,italic:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>`,h1:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17 12l3-2v10"/></svg>`,h2:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>`,blockquote:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,clear:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m16 22-1-4"/><path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1"/><path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z"/><path d="m8 22 1-4"/></svg>`};function yw(e,t){return t===`compose`?[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)},{key:`clear`,icon:vw.clear,title:`Clear formatting`,action:()=>{let{to:t}=e.state.selection;e.chain().focus().unsetAllMarks().clearNodes().setTextSelection(t).run()},isActive:()=>!1}]:[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`h1`,icon:vw.h1,title:`Heading 1`,action:()=>e.chain().focus().toggleHeading({level:1}).run(),isActive:()=>e.isActive(`heading`,{level:1})},{key:`h2`,icon:vw.h2,title:`Heading 2`,action:()=>e.chain().focus().toggleHeading({level:2}).run(),isActive:()=>e.isActive(`heading`,{level:2})},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`blockquote`,icon:vw.blockquote,title:`Quote`,action:()=>e.chain().focus().toggleBlockquote().run(),isActive:()=>e.isActive(`blockquote`)},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)}]}var bw=M.create({name:`bubbleMenu`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=[],i=new Map;function a(){n=document.createElement(`div`),n.className=`tiptap-bubble-menu`,n.dataset.editorFloatingUi=`true`,n.style.position=`fixed`,n.style.display=`none`,r=yw(e,t);for(let t of r){if(t.key===`sep`){let e=document.createElement(`span`);e.className=`tiptap-bubble-sep`,n.appendChild(e);continue}let r=document.createElement(`button`);r.type=`button`,r.innerHTML=t.icon,r.title=t.title,r.className=`tiptap-bubble-btn`,r.addEventListener(`mousedown`,n=>{n.preventDefault(),t.action(e.view)}),n.appendChild(r),i.set(t.key,r)}}function o(e){if(!n)return;let r=cw(t);if(n.classList.toggle(`tiptap-bubble-menu-docked`,r),n.style.display=`flex`,r){lw(n,e),n.style.removeProperty(`left`),n.style.removeProperty(`top`),c();return}let{from:i,to:a}=e.state.selection,o=e.coordsAtPos(i),s=e.coordsAtPos(a),l=e.dom.closest(`dialog`),u=n.getBoundingClientRect(),d=OS({anchorRect:{left:o.left,right:s.right,top:Math.min(o.top,s.top),bottom:Math.max(o.bottom,s.bottom)},containerRect:DS(l),floatingWidth:u.width,floatingHeight:u.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});n.style.left=`${d.left}px`,n.style.top=`${d.top}px`,c()}function s(){n&&(n.style.display=`none`)}function c(){for(let t of r){if(t.key===`sep`)continue;let n=i.get(t.key);n&&n.classList.toggle(`is-active`,t.isActive(e.view))}}function l(e){let{state:t}=e,{selection:n}=t,{empty:r}=n;return!(r||!n.$from.parent.isTextblock||pw())}return[new Tr({key:_w,view(e){a();let t=e.dom.closest(`dialog`)??document.body;n&&t.appendChild(n);function r(t){let r=t.target;if(!r||e.dom.contains(r)||r.closest(`[data-editor-floating-ui]`)||n?.contains(r))return;let{state:i}=e,a=i.selection.from;e.dispatch(i.tr.setSelection(O.near(i.doc.resolve(a)))),e.dom.blur()}return t.addEventListener(`mousedown`,r),{update(e){l(e)?o(e):s()},destroy(){t.removeEventListener(`mousedown`,r),n?.remove(),n=null}}}})]}}),xw=new Set([`bold`,`italic`,`strike`,`code`,`underline`]);function Sw(e){return e.filter(e=>xw.has(e.type.name))}var Cw=M.create({name:`exitableMarks`,addKeyboardShortcuts(){return{ArrowRight:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;if(!t.empty||n.pos!==n.end())return!1;let r=Sw(n.marks());if(!r.length)return!1;let{tr:i}=e.state;for(let e of r)i.removeStoredMark(e);return e.view.dispatch(i),!0},Enter:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;return!t.empty||n.parent.textContent.length>0||!Sw(e.state.storedMarks??n.marks()).length||requestAnimationFrame(()=>{let{tr:t}=e.state;t.setStoredMarks([]),e.view.dispatch(t)}),!1}}}}),ww=` `,Tw=M.create({name:`tabIndent`,addKeyboardShortcuts(){return{Tab:({editor:e})=>{if(e.isActive(`listItem`))return e.commands.sinkListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a)return n(t.tr.insertText(ww,i)),!0;let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
|
|
298
|
+
${lC(sC())}`,XS.querySelectorAll(`.tiptap-slash-item`).forEach(e=>{e.addEventListener(`mousedown`,n=>{n.preventDefault(),t(parseInt(e.dataset.index??`0`,10))}),e.addEventListener(`mouseenter`,()=>{ZS=parseInt(e.dataset.index??`0`,10),oC()})});let r=rC();r&&(r.scrollTop=0)}function fC(){nC&&=(document.removeEventListener(`mousedown`,nC,!0),null),XS?.remove(),XS=null,ZS=0,QS=[],$S=null,eC=null,tC=null}function pC(e,t){if(!XS)return;XS.style.maxHeight=``;let n=DS(null),r=t?DS(t):n,i=OS({anchorRect:{left:e.left,right:e.left,top:e.top,bottom:e.bottom},containerRect:n,floatingWidth:XS.offsetWidth,floatingHeight:XS.offsetHeight,preferredPlacement:`bottom`,fallbackPlacement:`top`,align:`start`,gap:6});XS.style.left=`${i.left-r.left}px`,XS.style.top=`${i.top-r.top}px`,XS.style.maxHeight=i.maxHeight===null?``:`${i.maxHeight}px`}function mC(){nC=e=>{if(!(!XS||XS.contains(e.target))&&eC&&tC){let{state:e,view:t}=eC;t.dispatch(e.tr.delete(tC.from,tC.to))}},document.addEventListener(`mousedown`,nC,!0)}var hC=new Or(`jantSlashTyping`);function gC(){return new Tr({key:hC,state:{init:()=>({docChanged:!1}),apply:e=>({docChanged:e.docChanged})}})}function _C({state:e,range:t}){let n=e.doc.resolve(t.to),r=n.parent,i=t.to-n.start();if(i>=r.content.size)return!0;let a=r.textBetween(i,i+1,` `,` `);return a?/\s/.test(a):!0}function vC({state:e,range:t,isActive:n}){return _C({state:e,range:t})?n?!0:hC.getState(e)?.docChanged??!1:!1}var yC=M.create({name:`slashCommands`,addOptions(){return{suggestion:{char:`/`,startOfLine:!1,allow:vC,items:({query:e,editor:t})=>{let n=YS(t),r=Gx(e);return r?n.map((e,t)=>({item:e,index:t,rank:Wx([e.label,e.description,...e.keywords],r)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):n},render:()=>{function e(e){let t=e.options.element;return t instanceof globalThis.Element?t:null}return{onStart:t=>{XS=iC(),ZS=0,$S=t.command,eC=t.editor,tC=t.range,dC(t.items,e=>t.command({index:e}));let n=e(t.editor)?.closest(`dialog`)??null;(n??document.body).appendChild(XS);let r=t.clientRect?.();r&&pC(r,n),mC()},onUpdate:t=>{$S=t.command,tC=t.range,dC(t.items,e=>t.command({index:e}));let n=t.clientRect?.();n&&pC(n,e(t.editor)?.closest(`dialog`)??null)},onKeyDown:e=>{let{event:t,view:n,range:r}=e;return t.key===`ArrowDown`?(t.preventDefault(),QS.length===0?!0:(ZS=(ZS+1)%QS.length,oC(),!0)):t.key===`ArrowUp`?(t.preventDefault(),QS.length===0?!0:(ZS=(ZS-1+QS.length)%QS.length,oC(),!0)):t.key===`Enter`?(t.preventDefault(),QS.length===0||$S?.({index:ZS}),!0):t.key===`Escape`?(t.stopPropagation(),t.preventDefault(),n.dispatch(n.state.tr.delete(r.from,r.to)),!0):!1},onExit:()=>{fC()}}},command:({editor:e,range:t,props:n})=>{let r=QS[n.index];r&&r.command(e,t)}}}},addProseMirrorPlugins(){return[gC(),wS({editor:this.editor,...this.options.suggestion})]}}),bC=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~`.split(``),xC=(e,t)=>{var n=``;for(let r=1;r<=t;r++){let i=Math.floor(e)/83**(t-r)%83;n+=bC[Math.floor(i)]}return n},SC=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4},CC=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(t*12.92*255+.5):Math.trunc((1.055*t**.4166666666666667-.055)*255+.5)},wC=e=>e<0?-1:1,TC=(e,t)=>wC(e)*Math.abs(e)**+t,EC=class extends Error{constructor(e){super(e),this.name=`ValidationError`,this.message=e}},DC=4,OC=(e,t,n,r)=>{let i=0,a=0,o=0,s=t*DC;for(let c=0;c<t;c++){let t=DC*c;for(let l=0;l<n;l++){let n=t+l*s,u=r(c,l);i+=u*SC(e[n]),a+=u*SC(e[n+1]),o+=u*SC(e[n+2])}}let c=1/(t*n);return[i*c,a*c,o*c]},kC=e=>{let t=CC(e[0]),n=CC(e[1]),r=CC(e[2]);return(t<<16)+(n<<8)+r},AC=(e,t)=>{let n=Math.floor(Math.max(0,Math.min(18,Math.floor(TC(e[0]/t,.5)*9+9.5)))),r=Math.floor(Math.max(0,Math.min(18,Math.floor(TC(e[1]/t,.5)*9+9.5)))),i=Math.floor(Math.max(0,Math.min(18,Math.floor(TC(e[2]/t,.5)*9+9.5))));return n*19*19+r*19+i},jC=(e,t,n,r,i)=>{if(r<1||r>9||i<1||i>9)throw new EC(`BlurHash must have between 1 and 9 components`);if(t*n*4!==e.length)throw new EC(`Width and height must match the pixels array`);let a=[];for(let o=0;o<i;o++)for(let i=0;i<r;i++){let r=i==0&&o==0?1:2,s=OC(e,t,n,(e,a)=>r*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*o*a/n));a.push(s)}let o=a[0],s=a.slice(1),c=``,l=r-1+(i-1)*9;c+=xC(l,1);let u;if(s.length>0){let e=Math.max(...s.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(e*166-.5))));u=(t+1)/166,c+=xC(t,1)}else u=1,c+=xC(0,1);return c+=xC(kC(o),4),s.forEach(e=>{c+=xC(AC(e,u),2)}),c};async function MC(e){let t=await IC(e),{width:n,height:r}=t,i=Math.min(32/n,32/r,1),a=Math.max(Math.round(n*i),1),o=Math.max(Math.round(r*i),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);return c.drawImage(t,0,0,a,o),{width:n,height:r,blurhash:jC(c.getImageData(0,0,a,o).data,a,o,4,3)}}async function NC(e){let t=URL.createObjectURL(e);try{let e=document.createElement(`video`);e.muted=!0,e.preload=`auto`;let{width:n,height:r,duration:i}=await new Promise((n,r)=>{e.onloadedmetadata=()=>n({width:e.videoWidth,height:e.videoHeight,duration:e.duration}),e.onerror=()=>r(Error(`Failed to load video metadata`)),e.src=t}),a,o;try{let t=Math.min(i*.1,3),s=await Promise.race([LC(e,n,r,t),RC(8e3)]);a=s.blurhash,o=s.poster}catch{}return{width:n,height:r,blurhash:a,poster:o}}finally{URL.revokeObjectURL(t)}}async function PC(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function FC(e){try{if(e.type.startsWith(`image/`))return await MC(e);if(e.type.startsWith(`video/`)){let t=await NC(e);return{width:t.width,height:t.height,blurhash:t.blurhash,poster:t.poster}}if(e.type.startsWith(`audio/`))return{waveform:await PC(e)}}catch{}return{}}function IC(e){return new Promise((t,n)=>{let r=new Image,i=URL.createObjectURL(e);r.onload=()=>{URL.revokeObjectURL(i),t(r)},r.onerror=()=>{URL.revokeObjectURL(i),n(Error(`Failed to load image`))},r.src=i})}function LC(e,t,n,r){return new Promise((i,a)=>{e.currentTime=r,e.onseeked=()=>{try{let r=Math.min(32/t,32/n,1),a=Math.max(Math.round(t*r),1),o=Math.max(Math.round(n*r),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);c.drawImage(e,0,0,a,o);let l=jC(c.getImageData(0,0,a,o).data,a,o,4,3),u=Math.min(640/t,1),d=Math.round(t*u),f=Math.round(n*u),p=document.createElement(`canvas`);p.width=d,p.height=f;let m=p.getContext(`2d`);if(!m){i({blurhash:l});return}m.drawImage(e,0,0,d,f),p.toBlob(e=>{i({blurhash:l,poster:e??void 0})},`image/webp`,.8)}catch(e){a(e)}},e.onerror=()=>a(Error(`Video seek failed`))})}function RC(e){return new Promise((t,n)=>setTimeout(()=>n(Error(`Timeout`)),e))}function zC(e){if(!oe(e))return null;let t=w(e,`kind`),n=w(e,`method`),r=w(e,`url`);if(!t||n!==`PUT`||!r)return null;if(t===`relay`)return{kind:t,method:`PUT`,url:r};if(t===`multipartRelay`){let n=ce(e,`partSize`);return n?{kind:t,method:`PUT`,url:r,partSize:n}:null}if(t===`put`){let n=ce(e,`expiresAt`),i=e.headers;if(!n||!oe(i))return null;let a={};for(let[e,t]of Object.entries(i))typeof t==`string`&&(a[e]=t);return{kind:t,method:`PUT`,url:r,headers:a,expiresAt:n}}return null}async function BC(e){let t=await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()),n=new Uint8Array(t),r=``;for(let e of n)r+=String.fromCharCode(e);return btoa(r)}async function VC(e){let t=await fetch(i(`/api/uploads/init`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({filename:e.name,contentType:e.type||`application/octet-stream`,size:e.size,checksumSha256:await BC(e)})});if(!t.ok){let e=await le(t);throw Error(w(e,`error`)??`Failed to start upload`)}let n=await le(t),r=w(n,`id`),a=zC(n.transport);if(!r||!a)throw Error(`Failed to start upload`);return{id:r,transport:a}}async function HC(e,t){if(!(await fetch(i(`/api/uploads/${e}/poster`),{method:`PUT`,headers:{"Content-Type":t.type||`image/webp`},body:t})).ok)throw Error(`Failed to upload poster`)}async function UC(e){await fetch(i(`/api/uploads/${e}/abort`),{method:`POST`}).catch(()=>{})}async function WC(e,t){let n=await fetch(i(`/api/uploads/${e}/complete`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await le(n);throw Error(w(e,`error`)??`Failed to complete upload`)}let r=await le(n),a=w(r,`id`),o=w(r,`filename`),s=w(r,`url`),c=w(r,`mimeType`),l=ce(r,`size`);if(!a||!o||!s||!c||l===void 0)throw Error(`Failed to complete upload`);return{id:a,filename:o,url:s,mimeType:c,size:l}}async function GC(e,t,n,r){let a=Math.ceil(n.size/t.partSize),o=[],s=0;for(let e=0;e<a;e+=1){let a=e*t.partSize,c=Math.min(a+t.partSize,n.size),l=e+1,u=n.slice(a,c),d=await fetch(i(`${t.url}?partNumber=${l}`),{method:`PUT`,body:u});if(!d.ok)throw Error(`Failed to upload part ${l}`);let f=await le(d),p=ce(f,`partNumber`),m=w(f,`etag`);if(!p||!m)throw Error(`Failed to upload part ${l}`);o.push({partNumber:p,etag:m}),s+=c-a,r?.(s/n.size)}return o}async function KC(e,t,n){let{id:r,transport:a}=await VC(e);try{if(a.kind===`put`){if(!(await fetch(a.url,{method:`PUT`,headers:a.headers,body:e})).ok)throw Error(`Upload failed`);n?.(1)}else if(a.kind===`relay`){let t=await fetch(i(a.url),{method:`PUT`,headers:{"Content-Type":e.type},body:e});if(!t.ok){let e=await le(t);throw Error(w(e,`error`)??`Upload failed`)}n?.(1)}let o=a.kind===`multipartRelay`?await GC(r,a,e,n):void 0;return t.poster&&await HC(r,t.poster),WC(r,{...t,parts:o})}catch(e){throw await UC(r),e}}async function qC(e){let{file:t,width:n,height:r}=await re.processToFile(e),i;try{i=(await MC(t)).blurhash}catch{}let a=await KC(t,{width:n,height:r,blurhash:i});return{url:a.url,id:a.id}}var JC=new Map,YC=new Map;function XC(e,t,n){if(e.isDestroyed)return;let{doc:r}=e.state,i=!1;r.descendants((r,a)=>{i||r.type.name!==`image`||r.attrs.src!==t||(e.chain().command(({tr:e})=>(e.setNodeMarkup(a,void 0,{...r.attrs,src:n}),!0)).run(),i=!0)})}function ZC(e,t){if(e.isDestroyed)return;let{doc:n}=e.state;n.descendants((n,r)=>{n.type.name===`image`&&n.attrs.src===t&&e.chain().command(({tr:e})=>(e.delete(r,r+n.nodeSize),!0)).run()})}async function QC(e,t,n=qC){let r=URL.createObjectURL(t);e.chain().focus().setImage({src:r}).run();let i=n(t).then(e=>e.url);JC.set(r,i);try{XC(e,r,await i)}catch{ZC(e,r)}finally{JC.delete(r)&&URL.revokeObjectURL(r)}}function $C(e){let t=[],{doc:n}=e.state;return n.descendants(n=>{if(n.type.name!==`image`)return;let r=n.attrs.src;if(!r?.startsWith(`blob:`))return;let i=JC.get(r);if(!i)return;JC.delete(r),YC.set(r,i);let a=i.then(t=>XC(e,r,t),()=>ZC(e,r)).finally(()=>{YC.delete(r),URL.revokeObjectURL(r)});t.push(a)}),t}async function ew(e){if(!e)return e;let t=new Map;if(tw(e,t),t.size===0)return e;let n=new Map;return await Promise.allSettled(Array.from(t.entries()).map(async([e,t])=>{let r=await t;n.set(e,r)})),nw(e,n)}function tw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=JC.get(e.attrs.src)??YC.get(e.attrs.src);n&&t.set(e.attrs.src,n)}if(e.content)for(let n of e.content)tw(n,t)}function nw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=t.get(e.attrs.src);return n?{...e,attrs:{...e.attrs,src:n}}:{type:`__removed__`}}if(!e.content)return e;let n=e.content.map(e=>nw(e,t)).filter(e=>e.type!==`__removed__`);return n===e.content?e:{...e,content:n}}var rw=new Or(`pasteMedia`);function iw(e){return`${e.name}:${e.type}:${e.size}:${e.lastModified}`}function aw(e){if(!e)return[];let t=Array.from(e.items??[]).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null),n=t.length>0?t:Array.from(e.files??[]),r=new Set;return n.filter(e=>{let t=iw(e);return r.has(t)?!1:(r.add(t),!0)})}var ow=M.create({name:`pasteMedia`,addOptions(){return{shouldInsertInline:void 0,onPasteFiles:void 0}},addProseMirrorPlugins(){let e=this;return[new Tr({key:rw,props:{handlePaste(t,n){let r=aw(n.clipboardData);if(r.length===0)return!1;let i=r.filter(t=>e.options.shouldInsertInline?.(t)===!0),a=r.filter(e=>!i.includes(e));if(i.length===0&&(a.length===0||e.options.onPasteFiles===void 0))return!1;n.preventDefault();for(let t of i){let n=e.options.uploadInlineImage;if(n){n(t);continue}QC(e.editor,t)}return a.length>0&&e.options.onPasteFiles!==void 0&&e.options.onPasteFiles(a),!0}}})]}}),sw=`(pointer: coarse)`;function cw(e){return e===`compose`&&(globalThis.matchMedia?.(sw).matches??!1)}function lw(e,t){let n=t.dom.closest(`jant-compose-editor`),r=t.dom.closest(`jant-compose-dialog, .compose-fullscreen, .compose-attached-panel`)??t.dom.closest(`dialog`),i=16,a=n?.querySelector(`.compose-tools-row`)??r?.querySelector(`.compose-tools-row`),o=r?.querySelector(`.compose-action-row`),s=n?.querySelector(`.compose-attachments-dock`);a&&(i+=a.getBoundingClientRect().height),o&&(i+=o.getBoundingClientRect().height),s&&(i+=s.getBoundingClientRect().height),e.style.setProperty(`--tiptap-docked-offset`,`${i}px`)}var uw=new Or(`linkToolbar`),dw=`hidden`,fw=!1;function pw(){return dw===`input`&&fw}var mw=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/></svg>`;function hw(e){let{selection:t}=e;if(!t.empty)return null;let n=t.$from,r=e.schema.marks.link;if(!r)return null;let i=n.marks().find(e=>e.type===r);if(!i)return null;let a=n.parent,o=n.start(),s=0,c=0,l=!1,u=0;for(let e=0;e<a.childCount;e++){let t=a.child(e),n=o+u,d=n+t.nodeSize;if(t.marks.some(e=>e.type===r&&e.attrs.href===i.attrs.href))l||=(s=n,!0),c=d;else if(l)break;u+=t.nodeSize}return l?{from:s,to:c,href:i.attrs.href}:null}var gw=M.create({name:`linkToolbar`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=null,i=null,a=0,o=0,s=!1,c=!1,l=null;function u(){n=document.createElement(`div`),n.className=`tiptap-link-input`,n.dataset.editorFloatingUi=`true`,n.style.display=`none`;let t=document.createElement(`div`);t.className=`tiptap-link-input-fields`,i=document.createElement(`input`),i.type=`text`,i.className=`tiptap-link-input-text`,i.placeholder=`Link text`,r=document.createElement(`input`),r.type=`url`,r.className=`tiptap-link-input-field`,r.placeholder=`https:// (empty to unlink)`,t.appendChild(i),t.appendChild(r);let a=document.createElement(`button`);a.type=`button`,a.className=`tiptap-link-input-confirm`,a.innerHTML=mw,a.title=`Apply link`,n.appendChild(t),n.appendChild(a);let o=t=>{t.key===`Enter`?(t.preventDefault(),t.stopPropagation(),h()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),c=!0,p(),e.commands.focus())};i.addEventListener(`keydown`,o),r.addEventListener(`keydown`,o);let s=()=>{fw=!0},l=()=>{requestAnimationFrame(()=>{let e=document.activeElement;(!n||!n.contains(e))&&(fw=!1)})};i.addEventListener(`focus`,s),r.addEventListener(`focus`,s),i.addEventListener(`blur`,l),r.addEventListener(`blur`,l),a.addEventListener(`mousedown`,e=>{e.preventDefault(),h()}),n.addEventListener(`mousedown`,e=>{e.stopPropagation()})}function d(e,n,r,i){let a=cw(t);if(e.classList.toggle(`tiptap-link-input-docked`,a),e.style.display=`flex`,a){lw(e,n),e.style.removeProperty(`left`),e.style.removeProperty(`top`);return}let o=n.dom.closest(`dialog`),s=n.coordsAtPos(r),c=n.coordsAtPos(i),l=e.getBoundingClientRect(),u=OS({anchorRect:{left:s.left,right:c.right,top:Math.min(s.top,c.top),bottom:Math.max(s.bottom,c.bottom)},containerRect:DS(o),floatingWidth:l.width,floatingHeight:l.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});e.style.left=`${u.left}px`,e.style.top=`${u.top}px`}function f(e,t){if(!(!n||!r||!i)){if(t.from!==void 0&&t.to!==void 0?(a=t.from,o=t.to):(a=e.state.selection.from,o=e.state.selection.to),dw=`input`,r.value=t.href,i.value=t.text??e.state.doc.textBetween(a,o,``),d(n,e,a,o),t.focus){let e=i.value.length>0?r:i;requestAnimationFrame(()=>{e.focus(),e.select()})}m(),l=e=>{n&&!n.contains(e.target)&&(c=!0,p())},setTimeout(()=>{l&&document.addEventListener(`mousedown`,l,!0)},0)}}function p(){n&&(n.style.display=`none`),dw=`hidden`,fw=!1,m()}function m(){l&&=(document.removeEventListener(`mousedown`,l,!0),null)}function h(){if(!r||!i)return;let t=r.value.trim(),n=e.state.doc.textBetween(a,o,``),c=i.value,l=c.length>0?c:t;if(p(),!t){e.chain().focus().setTextSelection({from:a,to:o}).unsetLink().setTextSelection(o).run(),s=!0;return}let u=l!==n,d=a+l.length;u?e.chain().focus().command(({tr:e})=>(e.insertText(l,a,o),!0)).setTextSelection({from:a,to:d}).setLink({href:t}).setTextSelection(d).run():e.chain().focus().setTextSelection({from:a,to:o}).setLink({href:t}).setTextSelection(o).run(),s=!0}return[new Tr({key:uw,view(e){u();let t=e.dom.closest(`dialog`);n&&(t??document.body).appendChild(n);let r=()=>{c=!1,s=!0,f(e,{href:``,focus:!0})};e.dom.addEventListener(`tiptap:open-link-input`,r);let i=e=>{e.key===`Escape`&&dw===`input`&&(e.preventDefault(),e.stopPropagation(),c=!0,p())};return e.dom.addEventListener(`keydown`,i),{update(e){if(s){s=!1;return}let t=hw(e.state);if(dw===`input`&&fw){n&&d(n,e,a,o);return}if(t){if(c)return;f(e,{href:t.href,from:t.from,to:t.to,focus:!1})}else c=!1,dw===`input`&&p()},destroy(){e.dom.removeEventListener(`tiptap:open-link-input`,r),e.dom.removeEventListener(`keydown`,i),m(),n?.remove(),n=null,dw=`hidden`,fw=!1}}}})]}}),_w=new Or(`bubbleMenu`),vw={bold:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 12h9a4 4 0 0 1 0 8H6V4h8a4 4 0 0 1 0 8"/></svg>`,italic:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>`,h1:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17 12l3-2v10"/></svg>`,h2:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>`,blockquote:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,clear:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m16 22-1-4"/><path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1"/><path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z"/><path d="m8 22 1-4"/></svg>`};function yw(e,t){return t===`compose`?[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)},{key:`clear`,icon:vw.clear,title:`Clear formatting`,action:()=>{let{to:t}=e.state.selection;e.chain().focus().unsetAllMarks().clearNodes().setTextSelection(t).run()},isActive:()=>!1}]:[{key:`bold`,icon:vw.bold,title:`Bold`,action:()=>e.chain().focus().toggleBold().run(),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:vw.italic,title:`Italic`,action:()=>e.chain().focus().toggleItalic().run(),isActive:()=>e.isActive(`italic`)},{key:`h1`,icon:vw.h1,title:`Heading 1`,action:()=>e.chain().focus().toggleHeading({level:1}).run(),isActive:()=>e.isActive(`heading`,{level:1})},{key:`h2`,icon:vw.h2,title:`Heading 2`,action:()=>e.chain().focus().toggleHeading({level:2}).run(),isActive:()=>e.isActive(`heading`,{level:2})},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`blockquote`,icon:vw.blockquote,title:`Quote`,action:()=>e.chain().focus().toggleBlockquote().run(),isActive:()=>e.isActive(`blockquote`)},{key:`link`,icon:vw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)}]}var bw=M.create({name:`bubbleMenu`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=[],i=new Map;function a(){n=document.createElement(`div`),n.className=`tiptap-bubble-menu`,n.dataset.editorFloatingUi=`true`,n.style.position=`fixed`,n.style.display=`none`,r=yw(e,t);for(let t of r){if(t.key===`sep`){let e=document.createElement(`span`);e.className=`tiptap-bubble-sep`,n.appendChild(e);continue}let r=document.createElement(`button`);r.type=`button`,r.innerHTML=t.icon,r.title=t.title,r.className=`tiptap-bubble-btn`,r.addEventListener(`mousedown`,n=>{n.preventDefault(),t.action(e.view)}),n.appendChild(r),i.set(t.key,r)}}function o(e){if(!n)return;let r=cw(t);if(n.classList.toggle(`tiptap-bubble-menu-docked`,r),n.style.display=`flex`,r){lw(n,e),n.style.removeProperty(`left`),n.style.removeProperty(`top`),c();return}let{from:i,to:a}=e.state.selection,o=e.coordsAtPos(i),s=e.coordsAtPos(a),l=e.dom.closest(`dialog`),u=n.getBoundingClientRect(),d=OS({anchorRect:{left:o.left,right:s.right,top:Math.min(o.top,s.top),bottom:Math.max(o.bottom,s.bottom)},containerRect:DS(l),floatingWidth:u.width,floatingHeight:u.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});n.style.left=`${d.left}px`,n.style.top=`${d.top}px`,c()}function s(){n&&(n.style.display=`none`)}function c(){for(let t of r){if(t.key===`sep`)continue;let n=i.get(t.key);n&&n.classList.toggle(`is-active`,t.isActive(e.view))}}function l(e){let{state:t}=e,{selection:n}=t,{empty:r}=n;return!(r||!n.$from.parent.isTextblock||pw())}return[new Tr({key:_w,view(e){a();let t=e.dom.closest(`dialog`)??document.body;n&&t.appendChild(n);function r(t){let r=t.target;if(!r||e.dom.contains(r)||r.closest(`[data-editor-floating-ui]`)||n?.contains(r))return;let{state:i}=e,a=i.selection.from;e.dispatch(i.tr.setSelection(O.near(i.doc.resolve(a)))),e.dom.blur()}return t.addEventListener(`mousedown`,r),{update(e){l(e)?o(e):s()},destroy(){t.removeEventListener(`mousedown`,r),n?.remove(),n=null}}}})]}}),xw=new Set([`bold`,`italic`,`strike`,`code`,`underline`]);function Sw(e){return e.filter(e=>xw.has(e.type.name))}var Cw=M.create({name:`exitableMarks`,addKeyboardShortcuts(){return{ArrowRight:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;if(!t.empty||n.pos!==n.end())return!1;let r=Sw(n.marks());if(!r.length)return!1;let{tr:i}=e.state;for(let e of r)i.removeStoredMark(e);return e.view.dispatch(i),!0},Enter:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;return!t.empty||n.parent.textContent.length>0||!Sw(e.state.storedMarks??n.marks()).length||requestAnimationFrame(()=>{let{tr:t}=e.state;t.setStoredMarks([]),e.view.dispatch(t)}),!1}}}}),ww=` `,Tw=M.create({name:`tabIndent`,addKeyboardShortcuts(){return{Tab:({editor:e})=>{if(e.isActive(`listItem`))return e.commands.sinkListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a)return n(t.tr.insertText(ww,i)),!0;let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
|
|
299
299
|
`,u-1)+1;f.push(p);let m=p;for(;;){let e=l.indexOf(`
|
|
300
300
|
`,m);if(e===-1||e>=d)break;f.push(e+1),m=e+1}let h=t.tr,g=0;for(let e of f)h=h.insertText(ww,c+e+g),g+=2;let _=i+2,v=a+g;return h.setSelection(k.create(h.doc,_,v)),n(h),!0}return!1},"Shift-Tab":({editor:e})=>{if(e.isActive(`listItem`))return e.commands.liftListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a){let e=i-c,r=l.lastIndexOf(`
|
|
301
301
|
`,e-1)+1,a=l.slice(r),o=a.startsWith(ww)?2:a.startsWith(` `)?1:0;return o===0||n(t.tr.delete(c+r,c+r+o)),!0}let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
|
|
@@ -403,7 +403,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
403
403
|
aria-hidden="true"
|
|
404
404
|
>
|
|
405
405
|
${Se(e)}
|
|
406
|
-
</svg>`}function GT(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=Reflect.get(e,`id`),n=Reflect.get(e,`title`),r=Reflect.get(e,`slug`);return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,title:n,slug:typeof r==`string`?r:``}]}):[]}function KT(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}function qT(e){return e?KT(e)?null:e:null}function JT(e){return String(e).padStart(2,`0`)}function YT(e){let t=new Date(e*1e3);return`${t.getFullYear()}-${JT(t.getMonth()+1)}-${JT(t.getDate())}`}function XT(e){let t=e.trim();if(!t)return null;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=new Date(r,i-1,a);return Number.isNaN(o.getTime())||o.getFullYear()!==r||o.getMonth()!==i-1||o.getDate()!==a?null:{year:r,monthIndex:i-1,day:a}}function ZT(e){let t=new Date(e*1e3);return t.getHours()*60+t.getMinutes()}function QT(e,t){let n=XT(e);if(!n)return null;let r=Math.min(Math.max(t,0),1439),i=Math.floor(r/60),a=r%60;return Math.floor(new Date(n.year,n.monthIndex,n.day,i,a,0,0).getTime()/1e3)}async function $T(e){let t=e.filter(e=>e.type===`media`),n=e.filter(e=>e.type===`text`);return{media:t.map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,originalName:e.originalName,summary:e.summary,chars:e.chars})),textAttachments:await Promise.all(n.map(async e=>{try{let t=await fetch(e.contentUrl);if(t.ok){let n=await t.json(),r=n.contentFormat===`markdown`&&n.content?n.content:``,i=r?Vx(r):null;if(i)return{bodyJson:JSON.stringify(i),bodyHtml:``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:JSON.stringify({type:`doc`,content:[{type:`paragraph`}]}),bodyHtml:``,summary:e.summary??``,mediaId:e.id}})),attachmentOrder:e.map(e=>e.id)}}var eE=class e extends c{static _lastNewPostVisibility=`public`;_sourceCollectionId=null;static _collectionVisibilityKey(e){return`jant:collection-visibility:${e}`}static _getCollectionVisibility(t){try{let n=globalThis.localStorage.getItem(e._collectionVisibilityKey(t));if(n===`public`||n===`latest_hidden`||n===`private`)return n}catch{}return null}static _setCollectionVisibility(t,n){try{globalThis.localStorage.setItem(e._collectionVisibilityKey(t),n)}catch{}}static properties={collections:{type:Array},labels:{type:Object},uploadMaxFileSize:{type:Number,attribute:`upload-max-file-size`},pageMode:{type:Boolean,attribute:`page-mode`},closeHref:{type:String,attribute:`close-href`},autoRestoreDraft:{type:Boolean,attribute:`auto-restore-draft`},_format:{state:!0},_status:{state:!0},_loading:{state:!0},_openingEdit:{state:!0},_collectionIds:{state:!0},_showCollection:{state:!0},_collectionSearch:{state:!0},_altPanelOpen:{state:!0},_altPanelIndex:{state:!0},_attachedPanelOpen:{state:!0},_attachedTextIndex:{state:!0},_confirmPanelOpen:{state:!0},_editPostId:{state:!0},_draftSourceId:{state:!0},_draftsPanelOpen:{state:!0},_drafts:{state:!0},_draftsLoading:{state:!0},_draftsError:{state:!0},_draftMenuOpenId:{state:!0},_addCollectionPanelOpen:{state:!0},_replyToId:{state:!0},_replyToData:{state:!0},_replyExpanded:{state:!0},_threadItems:{state:!0},_focusedThreadIndex:{state:!0},_slug:{state:!0},_publishedAtInput:{state:!0},_visibility:{state:!0},_showPublishPanel:{state:!0},_publishPanelFullscreen:{state:!0},_suggestedSlug:{state:!0},_suggestedSlugLoading:{state:!0},_slugCheckLoading:{state:!0},_slugTaken:{state:!0},_visibilityLocked:{state:!0},_quietReply:{state:!0}};_attachedEditor=null;_attachedTextSnapshot=null;_confirmForDrafts=!1;_confirmForAttachedText=!1;_draftSaveTimer=null;_draftRestored=!1;_initialSnapshot=null;_pageFocusApplied=!1;_pageLeaveRequested=!1;_replyThreadRootId=null;_replyRefreshKind=null;_replyRefreshId=null;_publishedAtTimeMinutes=null;_originalPublishedAt=null;_initialPublishedAtTimeMinutes=null;_initialPublishedAtInput=``;_initialSlug=``;_slugCheckTimer=null;_slugSuggestTimer=null;_slugSuggestRequestId=0;_slugCheckRequestId=0;_slugSuggestionKey=``;_suppressBeforeUnload=!1;_dialogEl=null;_mousedownOnBackdrop=!1;_filePickerActive=!1;_ignoreNextEscapeClose=!1;_openEditRequestId=0;_collectionPickerOrder=[];_suppressCollectionOptionClickUntil=0;_suppressedCollectionOptionId=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.collections=[],this.labels={},this.uploadMaxFileSize=500,this.pageMode=!1,this.closeHref=`/`,this.autoRestoreDraft=!1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._publishPanelFullscreen=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._visibilityLocked=!1,this._quietReply=!1}get _editor(){return this.querySelector(`jant-compose-editor`)}updated(e){super.updated(e),this._initialSnapshot===null&&this._editor&&this._captureInitialSnapshot(),e.has(`_addCollectionPanelOpen`)&&this._addCollectionPanelOpen&&this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()}),e.has(`_showCollection`)&&this._showCollection&&this._scheduleCollectionPickerAutofocus(),(e.has(`_format`)||e.has(`_collectionIds`)||e.has(`_slug`)||e.has(`_publishedAtInput`)||e.has(`_visibility`))&&(this._draftSourceId||this._scheduleDraftSave()),this._showPublishPanel&&this._updatePublishPanelLayout(),this._showCollection&&this._updateCollectionPopoverSide()}reset(){this._openEditRequestId+=1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._closeCollectionPicker(),this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._slugSuggestionKey=``,this._visibilityLocked=!1,this._quietReply=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._initialSnapshot=null,this._pageFocusApplied=!1,this._pageLeaveRequested=!1,this._slugSuggestRequestId+=1,this._slugCheckRequestId+=1,this._suppressBeforeUnload=!1,this._filePickerActive=!1,this._ignoreNextEscapeClose=!1,this._cancelSlugTimers(),this._destroyAttachedEditor(),this._editor?.reset(),this._captureInitialSnapshot()}async refreshCollections(){try{let e=await fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e.ok)return!1;let t=await e.json().catch(()=>null);return Array.isArray(t?.collections)?(this.collections=GT(t.collections),!0):!1}catch{return!1}}async openEdit(e){this.reset();let t=++this._openEditRequestId;this._openingEdit=!0,this._editPostId=e;let n=this.closest(`dialog`);n&&!n.open&&n.showModal(),await this.updateComplete,this._focusDialogShell();try{let n=await fetch(`/api/posts/${e}`);if(!n.ok)throw Error(`Failed to load post`);let r=await n.json();if(t!==this._openEditRequestId||(this._format=r.format,this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAt?YT(r.publishedAt):``,this._publishedAtTimeMinutes=r.publishedAt?ZT(r.publishedAt):null,this._originalPublishedAt=r.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=r.visibility??`public`,this._visibilityLocked=!!r.replyToId,r.replyToId&&(this._replyToId=r.replyToId,await this._fetchReplyContext(r.replyToId),t!==this._openEditRequestId)))return;r.collectionIds?.length&&(this._collectionIds=r.collectionIds);let{media:i,textAttachments:a,attachmentOrder:o}=await $T(r.attachments??[]);if(t!==this._openEditRequestId||(this._openingEdit=!1,await this.updateComplete,t!==this._openEditRequestId))return;this._restoreEditDraftIfAvailable(e)||this._editor?.populate({format:r.format,title:r.format===`quote`?void 0:r.title??void 0,bodyJson:r.body??void 0,url:r.format===`quote`?r.sourceUrl??void 0:r.url??void 0,quoteText:r.quoteText??void 0,quoteAuthor:r.format===`quote`?r.sourceName??void 0:void 0,rating:r.rating??void 0,media:i,textAttachments:a,attachmentOrder:o}),globalThis.requestAnimationFrame(()=>{t===this._openEditRequestId&&(this._focusDialogShell(),this._captureInitialSnapshot())})}catch{if(t!==this._openEditRequestId)return;this._openingEdit=!1,this._closeDialog(),this.reset(),a(this.labels.loadPostFailed,`error`)}}async openNew(t){if(this.reset(),t?.restoreDraft!==!1&&await this.restoreLocalDraft(),t?.initialFormat&&(this._format=t.initialFormat),t?.collectionId&&!this._collectionIds.includes(t.collectionId)&&(this._collectionIds=[t.collectionId,...this._collectionIds]),t?.collectionId){this._sourceCollectionId=t.collectionId;let n=e._getCollectionVisibility(t.collectionId);n&&(this._visibility=n)}this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async openReply(e,t,n,r,i){this.reset(),this._replyToId=e,this._replyThreadRootId=n??e,this._replyRefreshKind=r?.kind??null,this._replyRefreshId=r?.id??null,this._replyToData=t??null,this._visibilityLocked=!0,this._format=i?.initialFormat??`note`,i?.restoreDraft!==!1&&await this.restoreLocalDraft({expectedReplyToId:e}),this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async _fetchReplyContext(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._replyThreadRootId=n.replyToId?n.threadId:n.id;let r=n.publishedAt?new Date(n.publishedAt*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`}):``,i=(n.attachments??[]).filter(e=>e.type===`media`).map(e=>({url:e.url??e.previewUrl,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,width:e.width,height:e.height}));this._replyToData={contentHtml:n.bodyHtml??``,dateText:r,media:i.length>0?i:void 0}}catch{}}set loading(e){this._loading=e}_closeDialog(){let e=this.closest(`dialog`);if(e){e.close(),document.activeElement?.blur();return}this.pageMode&&(this._suppressBeforeUnload=!0,globalThis.location.assign(this.closeHref||i(`/`)))}requestCloseAndLeave(){this._pageLeaveRequested=!0,this.requestClose()}consumePageLeaveRequest(){let e=this._pageLeaveRequested;return this._pageLeaveRequested=!1,e}preparePageLeave(){this._suppressBeforeUnload=!0}_clearFilePickerEscapeState(){this._filePickerActive=!1,this._ignoreNextEscapeClose=!1}_shouldIgnoreEscapeClose(){return this._filePickerActive||this._ignoreNextEscapeClose?(this._clearFilePickerEscapeState(),!0):!1}_hasContent(){if(this._threadItems.length>0){let e=this.querySelector(`jant-compose-editor`);if(!e)return!1;let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.attachments.length>0}let e=this._editor;if(!e)return!1;let t=e.getData();return!!(t.body||t.title.trim()||t.url.trim()||t.quoteText.trim()||t.quoteAuthor.trim()||t.attachedTexts.length>0||t.rating>0||t.attachments.length>0)}_buildSnapshot(){let e=this._editor;if(!e)return null;let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=this._format===`note`&&t.title.trim().length>0?e._showTitle:!1,i=t.rating>0?e._showRating:!1;return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,rating:t.rating,showTitle:r,showRating:i,attachments:e._attachments.map(e=>({clientId:e.clientId,mediaId:e.mediaId,previewUrl:e.previewUrl,mimeType:e.file.type,alt:e.alt,status:e.status,summary:e.summary,chars:e.chars})),attachedTexts:n.map(e=>({clientId:e.clientId,mediaId:e.mediaId??null,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:e.getEffectiveAttachmentOrder()}}_serializeSnapshot(e){return e?JSON.stringify(e):null}_captureInitialSnapshot(){this._initialSnapshot=this._serializeSnapshot(this._buildSnapshot())}_hasUnsavedChanges(){let e=this._serializeSnapshot(this._buildSnapshot());return e===null||!this._editPostId&&!this._draftSourceId&&!this._hasContent()?!1:this._initialSnapshot===null?this._hasContent():e!==this._initialSnapshot}requestClose(){if(!this._loading){if(this._showCollection&&this._closeCollectionPicker(),this._showPublishPanel&&=!1,this._confirmPanelOpen){let e=this._confirmForAttachedText;this._confirmPanelOpen=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._pageLeaveRequested=!1,this.updateComplete.then(()=>{if(e){this._attachedEditor?.commands.focus();return}this._editor?.focusInput()});return}if(this._editPostId){this._hasUnsavedChanges()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset());return}this._hasContent()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this._editor?.hasPendingInlineImageUploads()?this._saveDraftAndOpenDrafts():this._finishDraftSaveAndOpenDrafts()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){if(this._confirmForAttachedText)this._confirmPanelOpen=!1,this._discardAttachedPanel();else if(this._confirmForDrafts){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()}else this._discardAndClose()}_buildEditorPostDetail(e,t,n,r){let i=e.getData(),a=new Map((i.attachments??[]).map(e=>[e.clientId,e])),o=new Map(i.attachedTexts.map(e=>[e.clientId,e])),s=[];for(let e of i.attachmentOrder){let t=a.get(e);if(t){s.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=o.get(e);n?.bodyJson&&s.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:qT(n.originalBodyJson??null)})}let c=n===0;return{format:t,title:i.title,body:i.body,url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,status:r,slug:c&&this._slug.trim()||void 0,publishedAt:c?this._getPublishedAtSubmitValue(r):void 0,visibility:c?this._visibilityLocked?void 0:this._visibility:void 0,rating:i.rating,collectionIds:c?[...this._collectionIds]:[],attachments:s,replyToId:c?this._replyToId??void 0:void 0,replyThreadRootId:c?this._replyThreadRootId??void 0:void 0,replyRefreshKind:c?this._replyRefreshKind??void 0:void 0,replyRefreshId:c?this._replyRefreshId??void 0:void 0}}_buildSubmitDetail(e){let t=this._editor;if(!t)return null;let n=t.getData(),r=new Map((n.attachments??[]).map(e=>[e.clientId,e])),i=new Map(n.attachedTexts.map(e=>[e.clientId,e])),a=[];for(let e of n.attachmentOrder){let t=r.get(e);if(t){a.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=i.get(e);n?.bodyJson&&a.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:qT(n.originalBodyJson??null)})}return{format:this._format,title:n.title,body:n.body,url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug.trim()||void 0,publishedAt:this._getPublishedAtSubmitValue(e),status:e,visibility:this._visibilityLocked?void 0:this._visibility,rating:n.rating,collectionIds:[...this._collectionIds],attachments:a,editPostId:this._editPostId??this._draftSourceId??void 0,replyToId:this._replyToId??void 0,quietReply:this._quietReply||void 0,replyThreadRootId:this._replyThreadRootId??void 0,replyRefreshKind:this._replyRefreshKind??void 0,replyRefreshId:this._replyRefreshId??void 0}}_focusBlockedSubmitField(e){if(e===`published`&&this._getPublishedAtValidationMessage()!==null)return this._revealPublishedAtField(),!0;if(this._getSlugValidationMessage())return this._revealSlugField(),!0;if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<this._threadItems.length;t++){let n=this._threadItems[t],r=e[t];if(r){if(r.getUrlValidationMessage())return r.revealUrlValidation(),r.focusUrlInput(`end`),!0;if(r.getLinkTitleValidationMessage())return r.revealLinkTitleValidation(),r.focusLinkTitleInput(`end`),!0;if(n.format===`quote`&&!r._quoteText.trim())return r.focusInput(`end`),!0}}return!1}let t=this._editor;return t?t.getUrlValidationMessage()?(t.revealUrlValidation(),t.focusUrlInput(`end`),!0):t.getLinkTitleValidationMessage()?(t.revealLinkTitleValidation(),t.focusLinkTitleInput(`end`),!0):this._format===`quote`&&!t._quoteText.trim()?(t.focusInput(`end`),!0):!1:!1}_dispatchSubmit(e){if(this._loading||this._focusBlockedSubmitField(e))return!1;if(this._draftSourceId||(this._cancelDraftSaveTimer(),this._saveDraftToStorage()),this._threadItems.length>0){if(this._threadItems.length>20)return a(this._getThreadLimitMessage(),`error`),!1;let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(t.length!==this._threadItems.length)return!1;let n=[],r=[];for(let i=0;i<this._threadItems.length;i++){let a=this._threadItems[i],o=t[i];if(!o)return!1;n.push(this._buildEditorPostDetail(o,a.format,i,e)),r.push(...(o._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`))}return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n[0],editPostId:this._editPostId??this._draftSourceId??void 0,threadPosts:n,pendingAttachments:r}})),!0}let t=this._editor;if(!t)return!1;let n=this._buildSubmitDetail(e);if(!n)return!1;let r=(t._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`);return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n,pendingAttachments:r}})),!0}_saveDraftAndOpenDrafts(){this._finishDraftSaveAndOpenDrafts()}_finishDraftSaveAndOpenDrafts(){if(!this._dispatchSubmit(`draft`))return;this.reset();let e=()=>{clearTimeout(t),this.isConnected&&this._openDraftsPanel()},t=globalThis.setTimeout(()=>{document.removeEventListener(`jant:compose-submit-complete`,e)},1e4);document.addEventListener(`jant:compose-submit-complete`,e,{once:!0})}_finishSubmit(e){if(this._dispatchSubmit(e)){if(this.pageMode){this._loading=!0;return}this._closeDialog(),this.reset()}}_submit(e){this._showPublishPanel=!1,this._finishSubmit(e)}_toggleCollection(e){this._collectionIds.includes(e)?this._collectionIds=this._collectionIds.filter(t=>t!==e):this._collectionIds=[...this._collectionIds,e]}_selectedCollectionLabel(e){let t=this._collectionIds,n=e.find(e=>e.id===t[0]);if(!n)return``;if(t.length===1)return n.title;if(t.length===2){let r=e.find(e=>e.id===t[1]);return r?`${n.title}, ${r.title}`:n.title}return this.labels.collectionCountLabel.replace(`%name%`,n.title).replace(`%count%`,String(t.length-1))}_prepareCollectionPickerOrder(){this._collectionPickerOrder=qx(this.collections??[],this._collectionIds)}_focusCollectionPickerInitialTarget(){this.querySelector(`.compose-collection-search-input, .compose-collection-option, .compose-collection-add-action`)?.focus()}_focusCollectionSearchInput(){let e=this.querySelector(`.compose-collection-search-input`);if(!e)return!1;e.focus();let t=e.value.length;return e.setSelectionRange(t,t),!0}_closeCollectionPicker(e){if(this._showCollection=!1,this._collectionSearch=``,this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,e?.restoreFocus===`trigger`){this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()});return}e?.restoreFocus===`editor`&&this._restorePageEditorFocus()}_suppressNextCollectionOptionClick(e){this._suppressedCollectionOptionId=e,this._suppressCollectionOptionClickUntil=Date.now()+250}_isTouchViewport(){return globalThis.matchMedia?.(`(hover: none) and (pointer: coarse)`)?.matches??!1}_shouldAutofocusCollectionPicker(){return!this._isTouchViewport()}_shouldAutofocusFormatInput(){return!this._isTouchViewport()}_scheduleCollectionPickerAutofocus(){this._shouldAutofocusCollectionPicker()&&globalThis.requestAnimationFrame(()=>{this._showCollection&&this._focusCollectionPickerInitialTarget()})}_scheduleCollectionSearchFocus(){globalThis.requestAnimationFrame(()=>{this._showCollection&&(this._focusCollectionSearchInput()||this._focusCollectionPickerInitialTarget())})}_isPrintableCollectionSearchKey(e){return e.length===1&&e.trim().length>0}_handleCollectionTriggerKeydown=e=>{if(!(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)){if(e.key===`ArrowDown`){e.preventDefault(),this._scheduleCollectionSearchFocus();return}!this._showCollection||!this._isPrintableCollectionSearchKey(e.key)||(e.preventDefault(),this._collectionSearch+=e.key,this._scheduleCollectionSearchFocus())}};_getCollectionOptionElements(){return Array.from(this.querySelectorAll(`.compose-collection-option`))}_handleCollectionSearchKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this._closeCollectionPicker({restoreFocus:`trigger`});return}if(e.key!==`ArrowDown`)return;let[t]=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-add-action`),r=t??n;r&&(e.preventDefault(),r.focus())};_handleCollectionOptionKeydown=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this._getCollectionOptionElements(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`.compose-collection-add-action`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.compose-collection-search-input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._toggleCollection(t);return}e.key===`Enter`&&(e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._closeCollectionPicker({restoreFocus:`trigger`}))};_handleCollectionOptionClick=e=>{if(this._suppressedCollectionOptionId===e&&Date.now()<=this._suppressCollectionOptionClickUntil){this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0;return}this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,this._toggleCollection(e)};_handleCollectionAddActionKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-search-input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};_updateCollectionPopoverSide(){let e=this.querySelector(`.compose-collection-trigger`),t=this.querySelector(`.compose-collection-popover[data-popover]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=Math.max(0,i-12-a.bottom-4),s=Math.max(0,a.top-r-12-4);t.dataset.side=o>=s?`bottom`:`top`}_cancelSlugTimers(){this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null)}_currentSlugOwnerId(){return this._editPostId??this._draftSourceId??void 0}_hasManualSlug(){return this._slug.trim().length>0}_currentSuggestionTitle(){return this._editor?.getData().title.trim()??``}_canSuggestSlug(){return this._currentSuggestionTitle().length>0}_currentSuggestionKey(){return`${this._currentSlugOwnerId()??``}::${this._currentSuggestionTitle()}`}_scheduleSuggestedSlugRefresh(e=!1){if(!this._showPublishPanel||this._hasManualSlug())return;if(!this._canSuggestSlug()){this._slugSuggestRequestId+=1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``;return}let t=this._currentSuggestionKey();if(this._slugSuggestionKey!==t&&(this._suggestedSlug=``),!e&&!this._suggestedSlugLoading&&this._suggestedSlug&&this._slugSuggestionKey===t)return;this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null);let n=()=>void this._refreshSuggestedSlug(t);if(e){n();return}this._slugSuggestTimer=setTimeout(n,250)}async _refreshSuggestedSlug(e){if(this._slugSuggestTimer=null,this._hasManualSlug()||!this._canSuggestSlug())return;let t=++this._slugSuggestRequestId;this._suggestedSlugLoading=!0;let n=new URLSearchParams({mode:`suggest`}),r=this._currentSuggestionTitle();r&&n.set(`title`,r);let i=this._currentSlugOwnerId();i&&n.set(`postId`,i);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugSuggestRequestId||this._hasManualSlug()||!this._showPublishPanel)return;this._suggestedSlug=i.slug?.trim()??``,this._slugSuggestionKey=e}catch{}finally{t===this._slugSuggestRequestId&&(this._suggestedSlugLoading=!1)}}_scheduleSlugAvailabilityCheck(){if(!this._hasManualSlug()){this._slugTaken=!1,this._slugCheckLoading=!1;return}if(this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._getSlugSyncValidationMessage()){this._slugTaken=!1,this._slugCheckLoading=!1;return}this._slugCheckLoading=!0;let e=this._slug.trim();this._slugCheckTimer=setTimeout(()=>{this._checkSlugAvailability(e)},250)}async _checkSlugAvailability(e){this._slugCheckTimer=null;let t=++this._slugCheckRequestId,n=new URLSearchParams({mode:`check`,slug:e}),r=this._currentSlugOwnerId();r&&n.set(`postId`,r);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugCheckRequestId||this._slug.trim()!==e)return;this._slugTaken=i.available===!1}catch{}finally{t===this._slugCheckRequestId&&(this._slugCheckLoading=!1)}}_useSuggestedSlug(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugTaken=!1,this._slugCheckLoading=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()}))}_resetCustomSlug(){this._slug=``,this._slugTaken=!1,this._slugCheckLoading=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}connectedCallback(){super.connectedCallback(),this._syncPublishPanelPresentation(),this.addEventListener(`keydown`,this._handleKeydown),this.addEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.addEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.addEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.addEventListener(`jant:compose-content-changed`,this._onContentChanged),this.addEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.addEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.addEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.addEventListener(`pointerdown`,this._handlePointerDown),document.addEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.addEventListener(`beforeunload`,this._onBeforeUnload),window.addEventListener(`resize`,this._handleViewportChange),window.addEventListener(`scroll`,this._handleViewportChange,{passive:!0}),globalThis.visualViewport?.addEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.addEventListener(`scroll`,this._handleViewportChange),this._dialogEl=this.closest(`dialog`),this._dialogEl&&(this._dialogEl.addEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.addEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.addEventListener(`click`,this._handleDialogClick)),this.pageMode&&this.updateComplete.then(()=>this._focusPageEditorOnMount())}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener(`keydown`,this._handleKeydown),this.removeEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.removeEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.removeEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.removeEventListener(`jant:compose-content-changed`,this._onContentChanged),this.removeEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.removeEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.removeEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.removeEventListener(`pointerdown`,this._handlePointerDown),document.removeEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.removeEventListener(`beforeunload`,this._onBeforeUnload),window.removeEventListener(`resize`,this._handleViewportChange),window.removeEventListener(`scroll`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`scroll`,this._handleViewportChange),this._cancelSlugTimers(),this._destroyAttachedEditor(),this._cancelDraftSaveTimer(),this._dialogEl&&=(this._dialogEl.removeEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.removeEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.removeEventListener(`click`,this._handleDialogClick),null)}_handleFilePickerOpen=()=>{this._filePickerActive=!0,this._ignoreNextEscapeClose=!1};_handleFilePickerClose=e=>{this._filePickerActive=!1,this._ignoreNextEscapeClose=!!e.detail?.cancelled};_handlePointerDown=()=>{this._clearFilePickerEscapeState()};_syncPublishPanelPresentation(){let e=globalThis.matchMedia?.(IT)?.matches??!1;e!==this._publishPanelFullscreen&&(this._publishPanelFullscreen=e)}_handleViewportChange=()=>{this._syncPublishPanelPresentation(),this._showPublishPanel&&this.updateComplete.then(()=>this._updatePublishPanelLayout()),this._showCollection&&this.updateComplete.then(()=>this._updateCollectionPopoverSide())};_handleDialogCancel=e=>{e.preventDefault(),!this._shouldIgnoreEscapeClose()&&(this._dismissEscapeOverlay()||this.requestClose())};_handleDialogMousedown=e=>{this._mousedownOnBackdrop=e.target===this._dialogEl};_handleDialogClick=e=>{if(!this._dialogEl||e.target!==this._dialogEl||!this._mousedownOnBackdrop)return;let t=e,n=document.elementFromPoint(t.clientX,t.clientY);n instanceof globalThis.Element&&n.closest(FT)||this.requestClose()};_focusDialogShell(){let e=this.querySelector(`.compose-dialog-inner`);if(e){e.focus();return}this._dialogEl?.focus()}_restorePageEditorFocus(){this.updateComplete.then(()=>this._editor?.focusInput())}_dismissEscapeOverlay(){return this._confirmPanelOpen?(this.requestClose(),!0):this._addCollectionPanelOpen?(this._closeAddCollectionPanel(),!0):this._editor?.isEmojiPickerOpen()?(this._editor.closeEmojiPicker({restoreFocus:!0}),!0):this._showCollection?(this._closeCollectionPicker({restoreFocus:`editor`}),!0):this._showPublishPanel?(this._closePublishPanel(!0),!0):this._altPanelOpen?(this._closeAltPanel(),this._restorePageEditorFocus(),!0):this._draftMenuOpenId?(this._draftMenuOpenId=null,!0):this._draftsPanelOpen?(this._closeDraftsPanel(),!0):this._attachedPanelOpen?(this._cancelAttachedPanel(),!0):!1}_handleKeydown=t=>{let n=t;if(n.key!==`Escape`&&this._clearFilePickerEscapeState(),n.key===`Escape`){if(n.preventDefault(),n.stopPropagation(),this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay())return;this.requestClose()}else if(n.key===`Enter`&&this._confirmPanelOpen)n.preventDefault(),this._handleConfirmSave();else if((n.metaKey||n.ctrlKey)&&n.key===`Enter`){if(t.preventDefault(),this._attachedPanelOpen){this._doneAttachedPanel();return}if(!this._canPublish()){this._focusBlockedSubmitField(`published`);return}this._submit(`published`)}else if((n.metaKey||n.ctrlKey)&&!n.altKey&&!n.shiftKey&&n.key>=`1`&&n.key<=String(e._FORMATS.length)){n.preventDefault();let t=e._FORMATS[Number(n.key)-1];this._threadItems.length>0?this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.dispatchEvent(new CustomEvent(`jant:thread-format-change`,{detail:{format:t},bubbles:!0})):this._switchFormat(t)}};_handleAltPanelOpen=e=>{this._altPanelIndex=e.detail.index,this._altPanelOpen=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-alt-input`)?.focus()})};_handleAltPanelClose=()=>{this._altPanelOpen=!1};_getAltAttachment(){return this._editor?._attachments[this._altPanelIndex]??null}_onAltInput(e){let t=e.target.value;this._editor?.updateAlt(this._altPanelIndex,t)}_closeAltPanel(){this._altPanelOpen=!1}_handleFullscreenClose=e=>{let t=this._editor;t&&(t.setEditorState(e.detail.json,e.detail.title,e.detail.showTitle,e.detail.selection),t.adoptPendingUploads(),this.updateComplete.then(()=>t.focusSelection(e.detail.selection))),this._replyExpanded=e.detail.replyExpanded};_buildFullscreenReplyContext(){return!this._replyToId||!this._replyToData?null:{contentHtml:this._replyToData.contentHtml,dateText:this._replyToData.dateText,expanded:this._replyExpanded}}_handleFullscreenOpen=e=>{e.detail.replyContext=this._buildFullscreenReplyContext()};_handleAttachedPanelOpen=e=>{this._attachedTextIndex=e.detail.index,this._attachedPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-attached-tiptap`);if(!e)return;let t=this._editor?._attachedTexts[this._attachedTextIndex]?.bodyJson??null;this._attachedTextSnapshot=t?JSON.parse(JSON.stringify(t)):null,this._attachedEditor=MT({element:e,placeholder:this.labels.attachedTextPlaceholder,content:t,toolbarMode:`compose`}),this._focusAttachedEditorBoundary(t)})};_focusAttachedEditorBoundary(e){if(!this._attachedEditor)return;let t=qT(e??this._attachedEditor.getJSON())?`end`:`start`;this._attachedEditor.commands.focus(t)}_isAttachedTextDirty(){return this._attachedEditor?JSON.stringify(qT(this._attachedEditor.getJSON()))!==JSON.stringify(qT(this._attachedTextSnapshot)):!1}_destroyAttachedEditor(){this._attachedEditor&&=(this._attachedEditor.destroy(),null),this._attachedTextSnapshot=null}_doneAttachedPanel(){if(this._attachedEditor){let e=this._attachedEditor.getJSON(),t=this._attachedEditor.getHTML();this._editor?.updateAttachedText(this._attachedTextIndex,e,t)}this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_cancelAttachedPanel(){if(this._isAttachedTextDirty()){this._confirmForDrafts=!1,this._confirmForAttachedText=!0,this._confirmPanelOpen=!0;return}this._discardAttachedPanel()}_handleAttachedEditorMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this._focusAttachedEditorBoundary())}_handleDraftButtonClick(){this._loading||(this._hasContent()?(this._confirmForDrafts=!0,this._confirmPanelOpen=!0):this._openDraftsPanel())}async _openDraftsPanel(){this._draftsPanelOpen=!0,this._draftsLoading=!0,this._draftsError=null,this._draftMenuOpenId=null;try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(!e.ok)throw Error(`Failed to load drafts`);let t=await e.json(),n=(Array.isArray(t)?t:t.posts??[]).map(e=>({id:e.id,format:e.format,title:(e.format===`quote`?e.sourceName:e.title)??null,bodyText:e.bodyText??null,bodyHtml:e.bodyHtml??null,url:(e.format===`quote`?e.sourceUrl:e.url)??null,quoteText:e.quoteText??null,replyToId:e.replyToId??null,updatedAt:e.updatedAt,mediaAttachments:(e.attachments??[]).filter(e=>e.type===`media`).map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt??null,mimeType:e.mimeType}))})),r=new Set(n.map(e=>e.id));this._drafts=n.filter(e=>!e.replyToId||!r.has(e.replyToId))}catch{this._draftsError=`Could not load drafts. Try again.`,this._drafts=[]}finally{this._draftsLoading=!1}}_closeDraftsPanel(){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.updateComplete.then(()=>this._editor?.focusInput())}async _populateEditorFromPost(e,t){let{media:n,textAttachments:r,attachmentOrder:i}=await $T(t.attachments??[]);e.populate({format:t.format,title:t.format===`quote`?void 0:t.title??void 0,bodyJson:t.body??void 0,url:t.format===`quote`?t.sourceUrl??void 0:t.url??void 0,quoteText:t.quoteText??void 0,quoteAuthor:t.format===`quote`?t.sourceName??void 0:void 0,rating:t.rating??void 0,media:n,textAttachments:r,attachmentOrder:i})}async _loadDraft(e){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._draftSourceId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=n.publishedAt?YT(n.publishedAt):``,this._publishedAtTimeMinutes=n.publishedAt?ZT(n.publishedAt):null,this._originalPublishedAt=n.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,n.collectionIds?.length&&(this._collectionIds=n.collectionIds),n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),n.threadId===n.id||n.threadId===void 0)try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(e.ok){let t=await e.json(),r=(Array.isArray(t)?t:t.posts??[]).filter(e=>e.id!==n.id&&e.threadId===n.id&&e.status===`draft`).map(e=>({id:e.id,format:e.format,replyToId:e.replyToId??null,title:e.title??null,body:e.body??null,url:e.url??null,sourceUrl:e.sourceUrl??null,sourceName:e.sourceName??null,quoteText:e.quoteText??null,rating:e.rating??null,attachments:e.attachments??[],visibility:e.visibility??null}));if(r.length>0){let e=[],t=n.id;for(let n=0;n<r.length;n++){let n=r.find(e=>e.replyToId===t);if(!n)break;e.push(n),t=n.id}for(let t of r)e.includes(t)||e.push(t);this._threadItems=[{id:crypto.randomUUID(),format:n.format},...e.map(e=>({id:crypto.randomUUID(),format:e.format}))],this._focusedThreadIndex=0,await this.updateComplete;let i=Array.from(this.querySelectorAll(`jant-compose-editor`)),a=i[0];a&&await this._populateEditorFromPost(a,n);for(let t=0;t<e.length;t++){let r=i[t+1];if(!r)continue;let a=e[t];await this._populateEditorFromPost(r,{id:a.id,threadId:n.id,format:a.format,replyToId:a.replyToId,title:a.title,body:a.body,url:a.url,sourceUrl:a.sourceUrl,sourceName:a.sourceName,quoteText:a.quoteText,rating:a.rating,attachments:a.attachments,visibility:a.visibility})}globalThis.requestAnimationFrame(()=>{i[0]?.focusInput(),this._captureInitialSnapshot()});return}}}catch{}await this.updateComplete;let r=this._editor;r&&await this._populateEditorFromPost(r,n),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async _deleteDraft(e){this._draftMenuOpenId=null,this._drafts=this._drafts.filter(t=>t.id!==e);try{if(!(await fetch(`/api/posts/${e}`,{method:`DELETE`})).ok)throw Error();a(this.labels.draftDeleted)}catch{a(`Failed to delete draft. Try again.`,`error`),this._openDraftsPanel()}}_formatDraftDate(e){let t=Date.now()/1e3-e;return t<60?`now`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:t<604800?`${Math.floor(t/86400)}d`:new Date(e*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}_getDraftPreview(e){return e.bodyText?e.bodyText:e.title?e.title:e.quoteText?e.quoteText:e.url?e.url:null}_getThreadLimitMessage(){return this.labels.threadLimitReached||`Threads can include up to 20 posts.`}static _DRAFT_KEY=`jant:compose-draft`;static _EDIT_DRAFT_KEY_PREFIX=`jant:compose-edit:`;static _DRAFT_MAX_AGE=10080*60*1e3;_currentDraftStorageKey(){return this._editPostId?e._EDIT_DRAFT_KEY_PREFIX+this._editPostId:e._DRAFT_KEY}_onContentChanged=()=>{this.requestUpdate(),this._hasManualSlug()||this._scheduleSuggestedSlugRefresh(),this._draftSourceId||this._scheduleDraftSave()};_cancelDraftSaveTimer(){this._draftSaveTimer!==null&&(clearTimeout(this._draftSaveTimer),this._draftSaveTimer=null)}_scheduleDraftSave(){this._cancelDraftSaveTimer(),this._draftSaveTimer=setTimeout(()=>this._saveDraftToStorage(),1e3)}_onBeforeUnload=e=>{if(this._suppressBeforeUnload)return;this._draftSaveTimer!==null&&(this._cancelDraftSaveTimer(),this._saveDraftToStorage());let t=this.closest(`dialog`);this._hasUnsavedChanges()&&(this.pageMode||t?.open===!0)&&(e.preventDefault(),e.returnValue=``)};_saveDraftToStorage(){if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));if(!e.some(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.rating>0||t.attachedTexts.length>0||t.attachments.length>0})){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let t=this._threadItems.map((t,n)=>{let r=e[n];if(!r)return null;let i=r.getData();return{format:t.format,title:i.title,bodyJson:r.getNormalizedBodyJson(),url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,attachedTexts:i.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...i.attachmentOrder]}}).filter(e=>e!==null),n={format:this._threadItems[0]?.format??this._format,title:``,bodyJson:null,url:``,quoteText:``,quoteAuthor:``,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:0,showTitle:!1,showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:[],attachmentOrder:[],threadItems:t,savedAt:Date.now()};try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(n))}catch{}return}let t=this._editor;if(!t)return;let n=t.getData();if(!(n.body||n.title.trim()||n.url.trim()||n.quoteText.trim()||n.quoteAuthor.trim()||n.rating>0||n.attachedTexts.length>0)){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}let r={format:this._format,title:n.title,bodyJson:t.getNormalizedBodyJson(),url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:n.rating,showTitle:this._format===`note`&&n.title.trim().length>0?t._showTitle:!1,showRating:n.rating>0?t._showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:n.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...n.attachmentOrder],savedAt:Date.now()};try{globalThis.localStorage.setItem(e._DRAFT_KEY,JSON.stringify(r))}catch{}}_clearDraftFromStorage(){this._cancelDraftSaveTimer(),globalThis.localStorage.removeItem(this._currentDraftStorageKey())}clearLocalDraftFromStorage(){this._clearDraftFromStorage()}clearEditDraftFromStorage(t){globalThis.localStorage.removeItem(e._EDIT_DRAFT_KEY_PREFIX+t)}async restoreLocalDraft(t){if(this._editPostId||this._draftSourceId||this._hasContent())return;let n;try{n=globalThis.localStorage.getItem(e._DRAFT_KEY)}catch{return}if(!n)return;let r;try{r=JSON.parse(n)}catch{globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(Date.now()-r.savedAt>e._DRAFT_MAX_AGE){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(t?.expectedReplyToId!==void 0&&r.replyToId!==t.expectedReplyToId)return;if(this._collectionIds=[...r.collectionIds??[]],this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAtInput??``,this._publishedAtTimeMinutes=r.publishedAtTimeMinutes??null,this._visibility=r.visibility??`public`,r.replyToId&&(this._replyToId=r.replyToId,this._visibilityLocked=!0,await this._fetchReplyContext(r.replyToId)),r.threadItems&&r.threadItems.length>=2){this._format=r.threadItems[0].format,this._threadItems=r.threadItems.map(e=>({id:crypto.randomUUID(),format:e.format})),this._focusedThreadIndex=0,await this.updateComplete;let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<r.threadItems.length;t++){let n=r.threadItems[t],i=e[t];if(!i)continue;let a=n.attachedTexts?.flatMap(e=>{let t=qT(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});i.populate({format:n.format,title:n.title||void 0,bodyJson:n.bodyJson?JSON.stringify(n.bodyJson):void 0,url:n.url||void 0,quoteText:n.quoteText||void 0,quoteAuthor:n.quoteAuthor||void 0,textAttachments:a?.length?a:void 0,attachmentOrder:n.attachmentOrder})}this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()});return}this._format=r.format,await this.updateComplete;let i=r.attachedTexts?.flatMap(e=>{let t=qT(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});this._editor?.populate({format:r.format,title:r.title||void 0,bodyJson:r.bodyJson?JSON.stringify(r.bodyJson):void 0,url:r.url||void 0,quoteText:r.quoteText||void 0,quoteAuthor:r.quoteAuthor||void 0,rating:r.rating||void 0,showTitle:r.showTitle,showRating:r.showRating,textAttachments:i?.length?i:void 0,attachmentOrder:r.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()})}_restoreEditDraftIfAvailable(t){let n=e._EDIT_DRAFT_KEY_PREFIX+t,r;try{r=globalThis.localStorage.getItem(n)}catch{return!1}if(!r)return!1;let i;try{i=JSON.parse(r)}catch{return globalThis.localStorage.removeItem(n),!1}if(Date.now()-i.savedAt>e._DRAFT_MAX_AGE)return globalThis.localStorage.removeItem(n),!1;this._format=i.format,this._collectionIds=[...i.collectionIds??[]],this._slug=i.slug??``,this._publishedAtInput=i.publishedAtInput??``,this._publishedAtTimeMinutes=i.publishedAtTimeMinutes??null,this._visibility=i.visibility??`public`;let o=i.attachedTexts?.flatMap(e=>{let t=qT(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});return this._editor?.populate({format:i.format,title:i.title||void 0,bodyJson:i.bodyJson?JSON.stringify(i.bodyJson):void 0,url:i.url||void 0,quoteText:i.quoteText||void 0,quoteAuthor:i.quoteAuthor||void 0,rating:i.rating||void 0,showTitle:i.showTitle,showRating:i.showRating,textAttachments:o?.length?o:void 0,attachmentOrder:i.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),!0}async _focusPageEditorOnMount(){this._pageFocusApplied||(this.autoRestoreDraft&&await this.restoreLocalDraft(),await this.updateComplete,globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._pageFocusApplied=!0}))}_renderDraftsPanel(){return this._draftsPanelOpen?u`
|
|
406
|
+
</svg>`}function GT(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=Reflect.get(e,`id`),n=Reflect.get(e,`title`),r=Reflect.get(e,`slug`);return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,title:n,slug:typeof r==`string`?r:``}]}):[]}function KT(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}function qT(e){return e?KT(e)?null:e:null}function JT(e){return String(e).padStart(2,`0`)}function YT(e){let t=new Date(e*1e3);return`${t.getFullYear()}-${JT(t.getMonth()+1)}-${JT(t.getDate())}`}function XT(e){let t=e.trim();if(!t)return null;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=new Date(r,i-1,a);return Number.isNaN(o.getTime())||o.getFullYear()!==r||o.getMonth()!==i-1||o.getDate()!==a?null:{year:r,monthIndex:i-1,day:a}}function ZT(e){let t=new Date(e*1e3);return t.getHours()*60+t.getMinutes()}function QT(e,t){let n=XT(e);if(!n)return null;let r=Math.min(Math.max(t,0),1439),i=Math.floor(r/60),a=r%60;return Math.floor(new Date(n.year,n.monthIndex,n.day,i,a,0,0).getTime()/1e3)}async function $T(e){let t=e.filter(e=>e.type===`media`),n=e.filter(e=>e.type===`text`);return{media:t.map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,originalName:e.originalName,summary:e.summary,chars:e.chars})),textAttachments:await Promise.all(n.map(async e=>{try{let t=await fetch(e.contentUrl);if(t.ok){let n=await t.json(),r=n.contentFormat===`markdown`&&n.content?n.content:``,i=r?Vx(r):null;if(i)return{bodyJson:JSON.stringify(i),bodyHtml:``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:JSON.stringify({type:`doc`,content:[{type:`paragraph`}]}),bodyHtml:``,summary:e.summary??``,mediaId:e.id}})),attachmentOrder:e.map(e=>e.id)}}var eE=class e extends c{static _lastNewPostVisibility=`public`;_sourceCollectionId=null;static _collectionVisibilityKey(e){return`jant:collection-visibility:${e}`}static _getCollectionVisibility(t){try{let n=globalThis.localStorage.getItem(e._collectionVisibilityKey(t));if(n===`public`||n===`latest_hidden`||n===`private`)return n}catch{}return null}static _setCollectionVisibility(t,n){try{globalThis.localStorage.setItem(e._collectionVisibilityKey(t),n)}catch{}}static properties={collections:{type:Array},labels:{type:Object},uploadMaxFileSize:{type:Number,attribute:`upload-max-file-size`},pageMode:{type:Boolean,attribute:`page-mode`},closeHref:{type:String,attribute:`close-href`},autoRestoreDraft:{type:Boolean,attribute:`auto-restore-draft`},_format:{state:!0},_status:{state:!0},_loading:{state:!0},_openingEdit:{state:!0},_collectionIds:{state:!0},_showCollection:{state:!0},_collectionSearch:{state:!0},_altPanelOpen:{state:!0},_altPanelIndex:{state:!0},_attachedPanelOpen:{state:!0},_attachedTextIndex:{state:!0},_confirmPanelOpen:{state:!0},_editPostId:{state:!0},_draftSourceId:{state:!0},_draftsPanelOpen:{state:!0},_drafts:{state:!0},_draftsLoading:{state:!0},_draftsError:{state:!0},_draftMenuOpenId:{state:!0},_addCollectionPanelOpen:{state:!0},_replyToId:{state:!0},_replyToData:{state:!0},_replyExpanded:{state:!0},_threadItems:{state:!0},_focusedThreadIndex:{state:!0},_slug:{state:!0},_publishedAtInput:{state:!0},_visibility:{state:!0},_showPublishPanel:{state:!0},_publishPanelFullscreen:{state:!0},_suggestedSlug:{state:!0},_suggestedSlugLoading:{state:!0},_slugCheckLoading:{state:!0},_slugTaken:{state:!0},_visibilityLocked:{state:!0},_quietReply:{state:!0}};_attachedEditor=null;_attachedTextSnapshot=null;_confirmForDrafts=!1;_confirmForAttachedText=!1;_draftSaveTimer=null;_draftRestored=!1;_initialSnapshot=null;_pageFocusApplied=!1;_pageLeaveRequested=!1;_replyThreadRootId=null;_replyRefreshKind=null;_replyRefreshId=null;_publishedAtTimeMinutes=null;_originalPublishedAt=null;_initialPublishedAtTimeMinutes=null;_initialPublishedAtInput=``;_initialSlug=``;_slugCheckTimer=null;_slugSuggestTimer=null;_slugSuggestRequestId=0;_slugCheckRequestId=0;_slugSuggestionKey=``;_suppressBeforeUnload=!1;_dialogEl=null;_mousedownOnBackdrop=!1;_mousedownPos=null;_filePickerActive=!1;_ignoreNextEscapeClose=!1;_openEditRequestId=0;_collectionPickerOrder=[];_suppressCollectionOptionClickUntil=0;_suppressedCollectionOptionId=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.collections=[],this.labels={},this.uploadMaxFileSize=500,this.pageMode=!1,this.closeHref=`/`,this.autoRestoreDraft=!1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._publishPanelFullscreen=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._visibilityLocked=!1,this._quietReply=!1}get _editor(){return this.querySelector(`jant-compose-editor`)}updated(e){super.updated(e),this._initialSnapshot===null&&this._editor&&this._captureInitialSnapshot(),e.has(`_addCollectionPanelOpen`)&&this._addCollectionPanelOpen&&this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()}),e.has(`_showCollection`)&&this._showCollection&&this._scheduleCollectionPickerAutofocus(),(e.has(`_format`)||e.has(`_collectionIds`)||e.has(`_slug`)||e.has(`_publishedAtInput`)||e.has(`_visibility`))&&(this._draftSourceId||this._scheduleDraftSave()),this._showPublishPanel&&this._updatePublishPanelLayout(),this._showCollection&&this._updateCollectionPopoverSide()}reset(){this._openEditRequestId+=1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._closeCollectionPicker(),this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._slugSuggestionKey=``,this._visibilityLocked=!1,this._quietReply=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._initialSnapshot=null,this._pageFocusApplied=!1,this._pageLeaveRequested=!1,this._slugSuggestRequestId+=1,this._slugCheckRequestId+=1,this._suppressBeforeUnload=!1,this._filePickerActive=!1,this._ignoreNextEscapeClose=!1,this._cancelSlugTimers(),this._destroyAttachedEditor(),this._editor?.reset(),this._captureInitialSnapshot()}async refreshCollections(){try{let e=await fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e.ok)return!1;let t=await e.json().catch(()=>null);return Array.isArray(t?.collections)?(this.collections=GT(t.collections),!0):!1}catch{return!1}}async openEdit(e){this.reset();let t=++this._openEditRequestId;this._openingEdit=!0,this._editPostId=e;let n=this.closest(`dialog`);n&&!n.open&&n.showModal(),await this.updateComplete,this._focusDialogShell();try{let n=await fetch(`/api/posts/${e}`);if(!n.ok)throw Error(`Failed to load post`);let r=await n.json();if(t!==this._openEditRequestId||(this._format=r.format,this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAt?YT(r.publishedAt):``,this._publishedAtTimeMinutes=r.publishedAt?ZT(r.publishedAt):null,this._originalPublishedAt=r.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=r.visibility??`public`,this._visibilityLocked=!!r.replyToId,r.replyToId&&(this._replyToId=r.replyToId,await this._fetchReplyContext(r.replyToId),t!==this._openEditRequestId)))return;r.collectionIds?.length&&(this._collectionIds=r.collectionIds);let{media:i,textAttachments:a,attachmentOrder:o}=await $T(r.attachments??[]);if(t!==this._openEditRequestId||(this._openingEdit=!1,await this.updateComplete,t!==this._openEditRequestId))return;this._restoreEditDraftIfAvailable(e)||this._editor?.populate({format:r.format,title:r.format===`quote`?void 0:r.title??void 0,bodyJson:r.body??void 0,url:r.format===`quote`?r.sourceUrl??void 0:r.url??void 0,quoteText:r.quoteText??void 0,quoteAuthor:r.format===`quote`?r.sourceName??void 0:void 0,rating:r.rating??void 0,media:i,textAttachments:a,attachmentOrder:o}),globalThis.requestAnimationFrame(()=>{t===this._openEditRequestId&&(this._focusDialogShell(),this._captureInitialSnapshot())})}catch{if(t!==this._openEditRequestId)return;this._openingEdit=!1,this._closeDialog(),this.reset(),a(this.labels.loadPostFailed,`error`)}}async openNew(t){if(this.reset(),t?.restoreDraft!==!1&&await this.restoreLocalDraft(),t?.initialFormat&&(this._format=t.initialFormat),t?.collectionId&&!this._collectionIds.includes(t.collectionId)&&(this._collectionIds=[t.collectionId,...this._collectionIds]),t?.collectionId){this._sourceCollectionId=t.collectionId;let n=e._getCollectionVisibility(t.collectionId);n&&(this._visibility=n)}this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async openReply(e,t,n,r,i){this.reset(),this._replyToId=e,this._replyThreadRootId=n??e,this._replyRefreshKind=r?.kind??null,this._replyRefreshId=r?.id??null,this._replyToData=t??null,this._visibilityLocked=!0,this._format=i?.initialFormat??`note`,i?.restoreDraft!==!1&&await this.restoreLocalDraft({expectedReplyToId:e}),this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async _fetchReplyContext(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._replyThreadRootId=n.replyToId?n.threadId:n.id;let r=n.publishedAt?new Date(n.publishedAt*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`}):``,i=(n.attachments??[]).filter(e=>e.type===`media`).map(e=>({url:e.url??e.previewUrl,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,width:e.width,height:e.height}));this._replyToData={contentHtml:n.bodyHtml??``,dateText:r,media:i.length>0?i:void 0}}catch{}}set loading(e){this._loading=e}_closeDialog(){let e=this.closest(`dialog`);if(e){e.close(),document.activeElement?.blur();return}this.pageMode&&(this._suppressBeforeUnload=!0,globalThis.location.assign(this.closeHref||i(`/`)))}requestCloseAndLeave(){this._pageLeaveRequested=!0,this.requestClose()}consumePageLeaveRequest(){let e=this._pageLeaveRequested;return this._pageLeaveRequested=!1,e}preparePageLeave(){this._suppressBeforeUnload=!0}_clearFilePickerEscapeState(){this._filePickerActive=!1,this._ignoreNextEscapeClose=!1}_shouldIgnoreEscapeClose(){return this._filePickerActive||this._ignoreNextEscapeClose?(this._clearFilePickerEscapeState(),!0):!1}_hasContent(){if(this._threadItems.length>0){let e=this.querySelector(`jant-compose-editor`);if(!e)return!1;let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.attachments.length>0}let e=this._editor;if(!e)return!1;let t=e.getData();return!!(t.body||t.title.trim()||t.url.trim()||t.quoteText.trim()||t.quoteAuthor.trim()||t.attachedTexts.length>0||t.rating>0||t.attachments.length>0)}_buildSnapshot(){let e=this._editor;if(!e)return null;let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=this._format===`note`&&t.title.trim().length>0?e._showTitle:!1,i=t.rating>0?e._showRating:!1;return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,rating:t.rating,showTitle:r,showRating:i,attachments:e._attachments.map(e=>({clientId:e.clientId,mediaId:e.mediaId,previewUrl:e.previewUrl,mimeType:e.file.type,alt:e.alt,status:e.status,summary:e.summary,chars:e.chars})),attachedTexts:n.map(e=>({clientId:e.clientId,mediaId:e.mediaId??null,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:e.getEffectiveAttachmentOrder()}}_serializeSnapshot(e){return e?JSON.stringify(e):null}_captureInitialSnapshot(){this._initialSnapshot=this._serializeSnapshot(this._buildSnapshot())}_hasUnsavedChanges(){let e=this._serializeSnapshot(this._buildSnapshot());return e===null||!this._editPostId&&!this._draftSourceId&&!this._hasContent()?!1:this._initialSnapshot===null?this._hasContent():e!==this._initialSnapshot}requestClose(){if(!this._loading){if(this._showCollection&&this._closeCollectionPicker(),this._showPublishPanel&&=!1,this._confirmPanelOpen){let e=this._confirmForAttachedText;this._confirmPanelOpen=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._pageLeaveRequested=!1,this.updateComplete.then(()=>{if(e){this._attachedEditor?.commands.focus();return}this._editor?.focusInput()});return}if(this._editPostId){this._hasUnsavedChanges()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset());return}this._hasContent()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this._editor?.hasPendingInlineImageUploads()?this._saveDraftAndOpenDrafts():this._finishDraftSaveAndOpenDrafts()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){if(this._confirmForAttachedText)this._confirmPanelOpen=!1,this._discardAttachedPanel();else if(this._confirmForDrafts){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()}else this._discardAndClose()}_buildEditorPostDetail(e,t,n,r){let i=e.getData(),a=new Map((i.attachments??[]).map(e=>[e.clientId,e])),o=new Map(i.attachedTexts.map(e=>[e.clientId,e])),s=[];for(let e of i.attachmentOrder){let t=a.get(e);if(t){s.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=o.get(e);n?.bodyJson&&s.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:qT(n.originalBodyJson??null)})}let c=n===0;return{format:t,title:i.title,body:i.body,url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,status:r,slug:c&&this._slug.trim()||void 0,publishedAt:c?this._getPublishedAtSubmitValue(r):void 0,visibility:c?this._visibilityLocked?void 0:this._visibility:void 0,rating:i.rating,collectionIds:c?[...this._collectionIds]:[],attachments:s,replyToId:c?this._replyToId??void 0:void 0,replyThreadRootId:c?this._replyThreadRootId??void 0:void 0,replyRefreshKind:c?this._replyRefreshKind??void 0:void 0,replyRefreshId:c?this._replyRefreshId??void 0:void 0}}_buildSubmitDetail(e){let t=this._editor;if(!t)return null;let n=t.getData(),r=new Map((n.attachments??[]).map(e=>[e.clientId,e])),i=new Map(n.attachedTexts.map(e=>[e.clientId,e])),a=[];for(let e of n.attachmentOrder){let t=r.get(e);if(t){a.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=i.get(e);n?.bodyJson&&a.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:qT(n.originalBodyJson??null)})}return{format:this._format,title:n.title,body:n.body,url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug.trim()||void 0,publishedAt:this._getPublishedAtSubmitValue(e),status:e,visibility:this._visibilityLocked?void 0:this._visibility,rating:n.rating,collectionIds:[...this._collectionIds],attachments:a,editPostId:this._editPostId??this._draftSourceId??void 0,replyToId:this._replyToId??void 0,quietReply:this._quietReply||void 0,replyThreadRootId:this._replyThreadRootId??void 0,replyRefreshKind:this._replyRefreshKind??void 0,replyRefreshId:this._replyRefreshId??void 0}}_focusBlockedSubmitField(e){if(e===`published`&&this._getPublishedAtValidationMessage()!==null)return this._revealPublishedAtField(),!0;if(this._getSlugValidationMessage())return this._revealSlugField(),!0;if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<this._threadItems.length;t++){let n=this._threadItems[t],r=e[t];if(r){if(r.getUrlValidationMessage())return r.revealUrlValidation(),r.focusUrlInput(`end`),!0;if(r.getLinkTitleValidationMessage())return r.revealLinkTitleValidation(),r.focusLinkTitleInput(`end`),!0;if(n.format===`quote`&&!r._quoteText.trim())return r.focusInput(`end`),!0}}return!1}let t=this._editor;return t?t.getUrlValidationMessage()?(t.revealUrlValidation(),t.focusUrlInput(`end`),!0):t.getLinkTitleValidationMessage()?(t.revealLinkTitleValidation(),t.focusLinkTitleInput(`end`),!0):this._format===`quote`&&!t._quoteText.trim()?(t.focusInput(`end`),!0):!1:!1}_dispatchSubmit(e){if(this._loading||this._focusBlockedSubmitField(e))return!1;if(this._draftSourceId||(this._cancelDraftSaveTimer(),this._saveDraftToStorage()),this._threadItems.length>0){if(this._threadItems.length>20)return a(this._getThreadLimitMessage(),`error`),!1;let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(t.length!==this._threadItems.length)return!1;let n=[],r=[];for(let i=0;i<this._threadItems.length;i++){let a=this._threadItems[i],o=t[i];if(!o)return!1;n.push(this._buildEditorPostDetail(o,a.format,i,e)),r.push(...(o._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`))}return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n[0],editPostId:this._editPostId??this._draftSourceId??void 0,threadPosts:n,pendingAttachments:r}})),!0}let t=this._editor;if(!t)return!1;let n=this._buildSubmitDetail(e);if(!n)return!1;let r=(t._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`);return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n,pendingAttachments:r}})),!0}_saveDraftAndOpenDrafts(){this._finishDraftSaveAndOpenDrafts()}_finishDraftSaveAndOpenDrafts(){if(!this._dispatchSubmit(`draft`))return;this.reset();let e=()=>{clearTimeout(t),this.isConnected&&this._openDraftsPanel()},t=globalThis.setTimeout(()=>{document.removeEventListener(`jant:compose-submit-complete`,e)},1e4);document.addEventListener(`jant:compose-submit-complete`,e,{once:!0})}_finishSubmit(e){if(this._dispatchSubmit(e)){if(this.pageMode){this._loading=!0;return}this._closeDialog(),this.reset()}}_submit(e){this._showPublishPanel=!1,this._finishSubmit(e)}_toggleCollection(e){this._collectionIds.includes(e)?this._collectionIds=this._collectionIds.filter(t=>t!==e):this._collectionIds=[...this._collectionIds,e]}_selectedCollectionLabel(e){let t=this._collectionIds,n=e.find(e=>e.id===t[0]);if(!n)return``;if(t.length===1)return n.title;if(t.length===2){let r=e.find(e=>e.id===t[1]);return r?`${n.title}, ${r.title}`:n.title}return this.labels.collectionCountLabel.replace(`%name%`,n.title).replace(`%count%`,String(t.length-1))}_prepareCollectionPickerOrder(){this._collectionPickerOrder=qx(this.collections??[],this._collectionIds)}_focusCollectionPickerInitialTarget(){this.querySelector(`.compose-collection-search-input, .compose-collection-option, .compose-collection-add-action`)?.focus()}_focusCollectionSearchInput(){let e=this.querySelector(`.compose-collection-search-input`);if(!e)return!1;e.focus();let t=e.value.length;return e.setSelectionRange(t,t),!0}_closeCollectionPicker(e){if(this._showCollection=!1,this._collectionSearch=``,this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,e?.restoreFocus===`trigger`){this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()});return}e?.restoreFocus===`editor`&&this._restorePageEditorFocus()}_suppressNextCollectionOptionClick(e){this._suppressedCollectionOptionId=e,this._suppressCollectionOptionClickUntil=Date.now()+250}_isTouchViewport(){return globalThis.matchMedia?.(`(hover: none) and (pointer: coarse)`)?.matches??!1}_shouldAutofocusCollectionPicker(){return!this._isTouchViewport()}_shouldAutofocusFormatInput(){return!this._isTouchViewport()}_scheduleCollectionPickerAutofocus(){this._shouldAutofocusCollectionPicker()&&globalThis.requestAnimationFrame(()=>{this._showCollection&&this._focusCollectionPickerInitialTarget()})}_scheduleCollectionSearchFocus(){globalThis.requestAnimationFrame(()=>{this._showCollection&&(this._focusCollectionSearchInput()||this._focusCollectionPickerInitialTarget())})}_isPrintableCollectionSearchKey(e){return e.length===1&&e.trim().length>0}_handleCollectionTriggerKeydown=e=>{if(!(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)){if(e.key===`ArrowDown`){e.preventDefault(),this._scheduleCollectionSearchFocus();return}!this._showCollection||!this._isPrintableCollectionSearchKey(e.key)||(e.preventDefault(),this._collectionSearch+=e.key,this._scheduleCollectionSearchFocus())}};_getCollectionOptionElements(){return Array.from(this.querySelectorAll(`.compose-collection-option`))}_handleCollectionSearchKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this._closeCollectionPicker({restoreFocus:`trigger`});return}if(e.key!==`ArrowDown`)return;let[t]=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-add-action`),r=t??n;r&&(e.preventDefault(),r.focus())};_handleCollectionOptionKeydown=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this._getCollectionOptionElements(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`.compose-collection-add-action`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.compose-collection-search-input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._toggleCollection(t);return}e.key===`Enter`&&(e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._closeCollectionPicker({restoreFocus:`trigger`}))};_handleCollectionOptionClick=e=>{if(this._suppressedCollectionOptionId===e&&Date.now()<=this._suppressCollectionOptionClickUntil){this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0;return}this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,this._toggleCollection(e)};_handleCollectionAddActionKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-search-input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};_updateCollectionPopoverSide(){let e=this.querySelector(`.compose-collection-trigger`),t=this.querySelector(`.compose-collection-popover[data-popover]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=Math.max(0,i-12-a.bottom-4),s=Math.max(0,a.top-r-12-4);t.dataset.side=o>=s?`bottom`:`top`}_cancelSlugTimers(){this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null)}_currentSlugOwnerId(){return this._editPostId??this._draftSourceId??void 0}_hasManualSlug(){return this._slug.trim().length>0}_currentSuggestionTitle(){return this._editor?.getData().title.trim()??``}_canSuggestSlug(){return this._currentSuggestionTitle().length>0}_currentSuggestionKey(){return`${this._currentSlugOwnerId()??``}::${this._currentSuggestionTitle()}`}_scheduleSuggestedSlugRefresh(e=!1){if(!this._showPublishPanel||this._hasManualSlug())return;if(!this._canSuggestSlug()){this._slugSuggestRequestId+=1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``;return}let t=this._currentSuggestionKey();if(this._slugSuggestionKey!==t&&(this._suggestedSlug=``),!e&&!this._suggestedSlugLoading&&this._suggestedSlug&&this._slugSuggestionKey===t)return;this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null);let n=()=>void this._refreshSuggestedSlug(t);if(e){n();return}this._slugSuggestTimer=setTimeout(n,250)}async _refreshSuggestedSlug(e){if(this._slugSuggestTimer=null,this._hasManualSlug()||!this._canSuggestSlug())return;let t=++this._slugSuggestRequestId;this._suggestedSlugLoading=!0;let n=new URLSearchParams({mode:`suggest`}),r=this._currentSuggestionTitle();r&&n.set(`title`,r);let i=this._currentSlugOwnerId();i&&n.set(`postId`,i);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugSuggestRequestId||this._hasManualSlug()||!this._showPublishPanel)return;this._suggestedSlug=i.slug?.trim()??``,this._slugSuggestionKey=e}catch{}finally{t===this._slugSuggestRequestId&&(this._suggestedSlugLoading=!1)}}_scheduleSlugAvailabilityCheck(){if(!this._hasManualSlug()){this._slugTaken=!1,this._slugCheckLoading=!1;return}if(this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._getSlugSyncValidationMessage()){this._slugTaken=!1,this._slugCheckLoading=!1;return}this._slugCheckLoading=!0;let e=this._slug.trim();this._slugCheckTimer=setTimeout(()=>{this._checkSlugAvailability(e)},250)}async _checkSlugAvailability(e){this._slugCheckTimer=null;let t=++this._slugCheckRequestId,n=new URLSearchParams({mode:`check`,slug:e}),r=this._currentSlugOwnerId();r&&n.set(`postId`,r);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugCheckRequestId||this._slug.trim()!==e)return;this._slugTaken=i.available===!1}catch{}finally{t===this._slugCheckRequestId&&(this._slugCheckLoading=!1)}}_useSuggestedSlug(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugTaken=!1,this._slugCheckLoading=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()}))}_resetCustomSlug(){this._slug=``,this._slugTaken=!1,this._slugCheckLoading=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}connectedCallback(){super.connectedCallback(),this._syncPublishPanelPresentation(),this.addEventListener(`keydown`,this._handleKeydown),this.addEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.addEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.addEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.addEventListener(`jant:compose-content-changed`,this._onContentChanged),this.addEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.addEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.addEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.addEventListener(`pointerdown`,this._handlePointerDown),document.addEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.addEventListener(`beforeunload`,this._onBeforeUnload),window.addEventListener(`resize`,this._handleViewportChange),window.addEventListener(`scroll`,this._handleViewportChange,{passive:!0}),globalThis.visualViewport?.addEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.addEventListener(`scroll`,this._handleViewportChange),this._dialogEl=this.closest(`dialog`),this._dialogEl&&(this._dialogEl.addEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.addEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.addEventListener(`click`,this._handleDialogClick)),this.pageMode&&this.updateComplete.then(()=>this._focusPageEditorOnMount())}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener(`keydown`,this._handleKeydown),this.removeEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.removeEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.removeEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.removeEventListener(`jant:compose-content-changed`,this._onContentChanged),this.removeEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.removeEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.removeEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.removeEventListener(`pointerdown`,this._handlePointerDown),document.removeEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.removeEventListener(`beforeunload`,this._onBeforeUnload),window.removeEventListener(`resize`,this._handleViewportChange),window.removeEventListener(`scroll`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`scroll`,this._handleViewportChange),this._cancelSlugTimers(),this._destroyAttachedEditor(),this._cancelDraftSaveTimer(),this._dialogEl&&=(this._dialogEl.removeEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.removeEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.removeEventListener(`click`,this._handleDialogClick),null)}_handleFilePickerOpen=()=>{this._filePickerActive=!0,this._ignoreNextEscapeClose=!1};_handleFilePickerClose=e=>{this._filePickerActive=!1,this._ignoreNextEscapeClose=!!e.detail?.cancelled};_handlePointerDown=()=>{this._clearFilePickerEscapeState()};_syncPublishPanelPresentation(){let e=globalThis.matchMedia?.(IT)?.matches??!1;e!==this._publishPanelFullscreen&&(this._publishPanelFullscreen=e)}_handleViewportChange=()=>{this._syncPublishPanelPresentation(),this._showPublishPanel&&this.updateComplete.then(()=>this._updatePublishPanelLayout()),this._showCollection&&this.updateComplete.then(()=>this._updateCollectionPopoverSide())};_handleDialogCancel=e=>{e.preventDefault(),!this._shouldIgnoreEscapeClose()&&(this._dismissEscapeOverlay()||this.requestClose())};_pointInOpenPopover(e,t){for(let n of document.querySelectorAll(`:popover-open`)){let r=n.getBoundingClientRect();if(e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom)return!0}return!1}_handleDialogMousedown=e=>{let t=e;this._mousedownOnBackdrop=e.target===this._dialogEl&&!this._pointInOpenPopover(t.clientX,t.clientY),this._mousedownPos=this._mousedownOnBackdrop?{x:t.clientX,y:t.clientY}:null};_handleDialogClick=e=>{if(!this._dialogEl||e.target!==this._dialogEl||!this._mousedownOnBackdrop)return;let t=e;if(this._mousedownPos){let e=t.clientX-this._mousedownPos.x,n=t.clientY-this._mousedownPos.y;if(e*e+n*n>16)return}let n=document.getSelection();if(n&&!n.isCollapsed||this._pointInOpenPopover(t.clientX,t.clientY))return;let r=document.elementFromPoint(t.clientX,t.clientY);r instanceof globalThis.Element&&r.closest(FT)||this.requestClose()};_focusDialogShell(){let e=this.querySelector(`.compose-dialog-inner`);if(e){e.focus();return}this._dialogEl?.focus()}_restorePageEditorFocus(){this.updateComplete.then(()=>this._editor?.focusInput())}_dismissEscapeOverlay(){return this._confirmPanelOpen?(this.requestClose(),!0):this._addCollectionPanelOpen?(this._closeAddCollectionPanel(),!0):this._editor?.isEmojiPickerOpen()?(this._editor.closeEmojiPicker({restoreFocus:!0}),!0):this._showCollection?(this._closeCollectionPicker({restoreFocus:`editor`}),!0):this._showPublishPanel?(this._closePublishPanel(!0),!0):this._altPanelOpen?(this._closeAltPanel(),this._restorePageEditorFocus(),!0):this._draftMenuOpenId?(this._draftMenuOpenId=null,!0):this._draftsPanelOpen?(this._closeDraftsPanel(),!0):this._attachedPanelOpen?(this._cancelAttachedPanel(),!0):!1}_handleKeydown=t=>{let n=t;if(n.key!==`Escape`&&this._clearFilePickerEscapeState(),n.key===`Escape`){if(n.preventDefault(),n.stopPropagation(),this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay())return;this.requestClose()}else if(n.key===`Enter`&&this._confirmPanelOpen)n.preventDefault(),this._handleConfirmSave();else if((n.metaKey||n.ctrlKey)&&n.key===`Enter`){if(t.preventDefault(),this._attachedPanelOpen){this._doneAttachedPanel();return}if(!this._canPublish()){this._focusBlockedSubmitField(`published`);return}this._submit(`published`)}else if((n.metaKey||n.ctrlKey)&&!n.altKey&&!n.shiftKey&&n.key>=`1`&&n.key<=String(e._FORMATS.length)){n.preventDefault();let t=e._FORMATS[Number(n.key)-1];this._threadItems.length>0?this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.dispatchEvent(new CustomEvent(`jant:thread-format-change`,{detail:{format:t},bubbles:!0})):this._switchFormat(t)}};_handleAltPanelOpen=e=>{this._altPanelIndex=e.detail.index,this._altPanelOpen=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-alt-input`)?.focus()})};_handleAltPanelClose=()=>{this._altPanelOpen=!1};_getAltAttachment(){return this._editor?._attachments[this._altPanelIndex]??null}_onAltInput(e){let t=e.target.value;this._editor?.updateAlt(this._altPanelIndex,t)}_closeAltPanel(){this._altPanelOpen=!1}_handleFullscreenClose=e=>{let t=this._editor;t&&(t.setEditorState(e.detail.json,e.detail.title,e.detail.showTitle,e.detail.selection),t.adoptPendingUploads(),this.updateComplete.then(()=>t.focusSelection(e.detail.selection))),this._replyExpanded=e.detail.replyExpanded};_buildFullscreenReplyContext(){return!this._replyToId||!this._replyToData?null:{contentHtml:this._replyToData.contentHtml,dateText:this._replyToData.dateText,expanded:this._replyExpanded}}_handleFullscreenOpen=e=>{e.detail.replyContext=this._buildFullscreenReplyContext()};_handleAttachedPanelOpen=e=>{this._attachedTextIndex=e.detail.index,this._attachedPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-attached-tiptap`);if(!e)return;let t=this._editor?._attachedTexts[this._attachedTextIndex]?.bodyJson??null;this._attachedTextSnapshot=t?JSON.parse(JSON.stringify(t)):null,this._attachedEditor=MT({element:e,placeholder:this.labels.attachedTextPlaceholder,content:t,toolbarMode:`compose`}),this._focusAttachedEditorBoundary(t)})};_focusAttachedEditorBoundary(e){if(!this._attachedEditor)return;let t=qT(e??this._attachedEditor.getJSON())?`end`:`start`;this._attachedEditor.commands.focus(t)}_isAttachedTextDirty(){return this._attachedEditor?JSON.stringify(qT(this._attachedEditor.getJSON()))!==JSON.stringify(qT(this._attachedTextSnapshot)):!1}_destroyAttachedEditor(){this._attachedEditor&&=(this._attachedEditor.destroy(),null),this._attachedTextSnapshot=null}_doneAttachedPanel(){if(this._attachedEditor){let e=this._attachedEditor.getJSON(),t=this._attachedEditor.getHTML();this._editor?.updateAttachedText(this._attachedTextIndex,e,t)}this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_cancelAttachedPanel(){if(this._isAttachedTextDirty()){this._confirmForDrafts=!1,this._confirmForAttachedText=!0,this._confirmPanelOpen=!0;return}this._discardAttachedPanel()}_handleAttachedEditorMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this._focusAttachedEditorBoundary())}_handleDraftButtonClick(){this._loading||(this._hasContent()?(this._confirmForDrafts=!0,this._confirmPanelOpen=!0):this._openDraftsPanel())}async _openDraftsPanel(){this._draftsPanelOpen=!0,this._draftsLoading=!0,this._draftsError=null,this._draftMenuOpenId=null;try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(!e.ok)throw Error(`Failed to load drafts`);let t=await e.json(),n=(Array.isArray(t)?t:t.posts??[]).map(e=>({id:e.id,format:e.format,title:(e.format===`quote`?e.sourceName:e.title)??null,bodyText:e.bodyText??null,bodyHtml:e.bodyHtml??null,url:(e.format===`quote`?e.sourceUrl:e.url)??null,quoteText:e.quoteText??null,replyToId:e.replyToId??null,updatedAt:e.updatedAt,mediaAttachments:(e.attachments??[]).filter(e=>e.type===`media`).map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt??null,mimeType:e.mimeType}))})),r=new Set(n.map(e=>e.id));this._drafts=n.filter(e=>!e.replyToId||!r.has(e.replyToId))}catch{this._draftsError=`Could not load drafts. Try again.`,this._drafts=[]}finally{this._draftsLoading=!1}}_closeDraftsPanel(){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.updateComplete.then(()=>this._editor?.focusInput())}async _populateEditorFromPost(e,t){let{media:n,textAttachments:r,attachmentOrder:i}=await $T(t.attachments??[]);e.populate({format:t.format,title:t.format===`quote`?void 0:t.title??void 0,bodyJson:t.body??void 0,url:t.format===`quote`?t.sourceUrl??void 0:t.url??void 0,quoteText:t.quoteText??void 0,quoteAuthor:t.format===`quote`?t.sourceName??void 0:void 0,rating:t.rating??void 0,media:n,textAttachments:r,attachmentOrder:i})}async _loadDraft(e){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._draftSourceId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=n.publishedAt?YT(n.publishedAt):``,this._publishedAtTimeMinutes=n.publishedAt?ZT(n.publishedAt):null,this._originalPublishedAt=n.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,n.collectionIds?.length&&(this._collectionIds=n.collectionIds),n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),n.threadId===n.id||n.threadId===void 0)try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(e.ok){let t=await e.json(),r=(Array.isArray(t)?t:t.posts??[]).filter(e=>e.id!==n.id&&e.threadId===n.id&&e.status===`draft`).map(e=>({id:e.id,format:e.format,replyToId:e.replyToId??null,title:e.title??null,body:e.body??null,url:e.url??null,sourceUrl:e.sourceUrl??null,sourceName:e.sourceName??null,quoteText:e.quoteText??null,rating:e.rating??null,attachments:e.attachments??[],visibility:e.visibility??null}));if(r.length>0){let e=[],t=n.id;for(let n=0;n<r.length;n++){let n=r.find(e=>e.replyToId===t);if(!n)break;e.push(n),t=n.id}for(let t of r)e.includes(t)||e.push(t);this._threadItems=[{id:crypto.randomUUID(),format:n.format},...e.map(e=>({id:crypto.randomUUID(),format:e.format}))],this._focusedThreadIndex=0,await this.updateComplete;let i=Array.from(this.querySelectorAll(`jant-compose-editor`)),a=i[0];a&&await this._populateEditorFromPost(a,n);for(let t=0;t<e.length;t++){let r=i[t+1];if(!r)continue;let a=e[t];await this._populateEditorFromPost(r,{id:a.id,threadId:n.id,format:a.format,replyToId:a.replyToId,title:a.title,body:a.body,url:a.url,sourceUrl:a.sourceUrl,sourceName:a.sourceName,quoteText:a.quoteText,rating:a.rating,attachments:a.attachments,visibility:a.visibility})}globalThis.requestAnimationFrame(()=>{i[0]?.focusInput(),this._captureInitialSnapshot()});return}}}catch{}await this.updateComplete;let r=this._editor;r&&await this._populateEditorFromPost(r,n),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async _deleteDraft(e){this._draftMenuOpenId=null,this._drafts=this._drafts.filter(t=>t.id!==e);try{if(!(await fetch(`/api/posts/${e}`,{method:`DELETE`})).ok)throw Error();a(this.labels.draftDeleted)}catch{a(`Failed to delete draft. Try again.`,`error`),this._openDraftsPanel()}}_formatDraftDate(e){let t=Date.now()/1e3-e;return t<60?`now`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:t<604800?`${Math.floor(t/86400)}d`:new Date(e*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}_getDraftPreview(e){return e.bodyText?e.bodyText:e.title?e.title:e.quoteText?e.quoteText:e.url?e.url:null}_getThreadLimitMessage(){return this.labels.threadLimitReached||`Threads can include up to 20 posts.`}static _DRAFT_KEY=`jant:compose-draft`;static _EDIT_DRAFT_KEY_PREFIX=`jant:compose-edit:`;static _DRAFT_MAX_AGE=10080*60*1e3;_currentDraftStorageKey(){return this._editPostId?e._EDIT_DRAFT_KEY_PREFIX+this._editPostId:e._DRAFT_KEY}_onContentChanged=()=>{this.requestUpdate(),this._hasManualSlug()||this._scheduleSuggestedSlugRefresh(),this._draftSourceId||this._scheduleDraftSave()};_cancelDraftSaveTimer(){this._draftSaveTimer!==null&&(clearTimeout(this._draftSaveTimer),this._draftSaveTimer=null)}_scheduleDraftSave(){this._cancelDraftSaveTimer(),this._draftSaveTimer=setTimeout(()=>this._saveDraftToStorage(),1e3)}_onBeforeUnload=e=>{if(this._suppressBeforeUnload)return;this._draftSaveTimer!==null&&(this._cancelDraftSaveTimer(),this._saveDraftToStorage());let t=this.closest(`dialog`);this._hasUnsavedChanges()&&(this.pageMode||t?.open===!0)&&(e.preventDefault(),e.returnValue=``)};_saveDraftToStorage(){if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));if(!e.some(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.rating>0||t.attachedTexts.length>0||t.attachments.length>0})){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let t=this._threadItems.map((t,n)=>{let r=e[n];if(!r)return null;let i=r.getData();return{format:t.format,title:i.title,bodyJson:r.getNormalizedBodyJson(),url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,attachedTexts:i.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...i.attachmentOrder]}}).filter(e=>e!==null),n={format:this._threadItems[0]?.format??this._format,title:``,bodyJson:null,url:``,quoteText:``,quoteAuthor:``,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:0,showTitle:!1,showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:[],attachmentOrder:[],threadItems:t,savedAt:Date.now()};try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(n))}catch{}return}let t=this._editor;if(!t)return;let n=t.getData();if(!(n.body||n.title.trim()||n.url.trim()||n.quoteText.trim()||n.quoteAuthor.trim()||n.rating>0||n.attachedTexts.length>0)){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}let r={format:this._format,title:n.title,bodyJson:t.getNormalizedBodyJson(),url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:n.rating,showTitle:this._format===`note`&&n.title.trim().length>0?t._showTitle:!1,showRating:n.rating>0?t._showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:n.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...n.attachmentOrder],savedAt:Date.now()};try{globalThis.localStorage.setItem(e._DRAFT_KEY,JSON.stringify(r))}catch{}}_clearDraftFromStorage(){this._cancelDraftSaveTimer(),globalThis.localStorage.removeItem(this._currentDraftStorageKey())}clearLocalDraftFromStorage(){this._clearDraftFromStorage()}clearEditDraftFromStorage(t){globalThis.localStorage.removeItem(e._EDIT_DRAFT_KEY_PREFIX+t)}async restoreLocalDraft(t){if(this._editPostId||this._draftSourceId||this._hasContent())return;let n;try{n=globalThis.localStorage.getItem(e._DRAFT_KEY)}catch{return}if(!n)return;let r;try{r=JSON.parse(n)}catch{globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(Date.now()-r.savedAt>e._DRAFT_MAX_AGE){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(t?.expectedReplyToId!==void 0&&r.replyToId!==t.expectedReplyToId)return;if(this._collectionIds=[...r.collectionIds??[]],this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAtInput??``,this._publishedAtTimeMinutes=r.publishedAtTimeMinutes??null,this._visibility=r.visibility??`public`,r.replyToId&&(this._replyToId=r.replyToId,this._visibilityLocked=!0,await this._fetchReplyContext(r.replyToId)),r.threadItems&&r.threadItems.length>=2){this._format=r.threadItems[0].format,this._threadItems=r.threadItems.map(e=>({id:crypto.randomUUID(),format:e.format})),this._focusedThreadIndex=0,await this.updateComplete;let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<r.threadItems.length;t++){let n=r.threadItems[t],i=e[t];if(!i)continue;let a=n.attachedTexts?.flatMap(e=>{let t=qT(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});i.populate({format:n.format,title:n.title||void 0,bodyJson:n.bodyJson?JSON.stringify(n.bodyJson):void 0,url:n.url||void 0,quoteText:n.quoteText||void 0,quoteAuthor:n.quoteAuthor||void 0,textAttachments:a?.length?a:void 0,attachmentOrder:n.attachmentOrder})}this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()});return}this._format=r.format,await this.updateComplete;let i=r.attachedTexts?.flatMap(e=>{let t=qT(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});this._editor?.populate({format:r.format,title:r.title||void 0,bodyJson:r.bodyJson?JSON.stringify(r.bodyJson):void 0,url:r.url||void 0,quoteText:r.quoteText||void 0,quoteAuthor:r.quoteAuthor||void 0,rating:r.rating||void 0,showTitle:r.showTitle,showRating:r.showRating,textAttachments:i?.length?i:void 0,attachmentOrder:r.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()})}_restoreEditDraftIfAvailable(t){let n=e._EDIT_DRAFT_KEY_PREFIX+t,r;try{r=globalThis.localStorage.getItem(n)}catch{return!1}if(!r)return!1;let i;try{i=JSON.parse(r)}catch{return globalThis.localStorage.removeItem(n),!1}if(Date.now()-i.savedAt>e._DRAFT_MAX_AGE)return globalThis.localStorage.removeItem(n),!1;this._format=i.format,this._collectionIds=[...i.collectionIds??[]],this._slug=i.slug??``,this._publishedAtInput=i.publishedAtInput??``,this._publishedAtTimeMinutes=i.publishedAtTimeMinutes??null,this._visibility=i.visibility??`public`;let o=i.attachedTexts?.flatMap(e=>{let t=qT(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});return this._editor?.populate({format:i.format,title:i.title||void 0,bodyJson:i.bodyJson?JSON.stringify(i.bodyJson):void 0,url:i.url||void 0,quoteText:i.quoteText||void 0,quoteAuthor:i.quoteAuthor||void 0,rating:i.rating||void 0,showTitle:i.showTitle,showRating:i.showRating,textAttachments:o?.length?o:void 0,attachmentOrder:i.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),!0}async _focusPageEditorOnMount(){this._pageFocusApplied||(this.autoRestoreDraft&&await this.restoreLocalDraft(),await this.updateComplete,globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._pageFocusApplied=!0}))}_renderDraftsPanel(){return this._draftsPanelOpen?u`
|
|
407
407
|
<div class="compose-drafts-panel">
|
|
408
408
|
<div class="compose-alt-header">
|
|
409
409
|
<button
|
|
@@ -1204,6 +1204,21 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
1204
1204
|
${this._renderDesktopPublishPanel()}
|
|
1205
1205
|
</div>
|
|
1206
1206
|
</div>
|
|
1207
|
+
`}_renderHideFromLatestQuickToggleRow(){return this._visibilityLocked||this._visibility===`private`?g:u`
|
|
1208
|
+
<div class="compose-quick-actions-row">
|
|
1209
|
+
${this._renderHideFromLatestQuickToggle()}
|
|
1210
|
+
</div>
|
|
1211
|
+
`}_renderHideFromLatestQuickToggle(){return this._visibilityLocked||this._visibility===`private`?g:u`
|
|
1212
|
+
<label class="compose-publish-quick-toggle">
|
|
1213
|
+
<input
|
|
1214
|
+
type="checkbox"
|
|
1215
|
+
class="input compose-publish-quick-toggle-input"
|
|
1216
|
+
.checked=${this._visibility===`latest_hidden`}
|
|
1217
|
+
?disabled=${this._loading}
|
|
1218
|
+
@change=${e=>{let t=e.target;this._setVisibility(t.checked?`latest_hidden`:`public`)}}
|
|
1219
|
+
/>
|
|
1220
|
+
<span>${this.labels.publishHideFromLatest}</span>
|
|
1221
|
+
</label>
|
|
1207
1222
|
`}_renderEditLoadingState(){return u`
|
|
1208
1223
|
<div
|
|
1209
1224
|
class="compose-edit-loading"
|
|
@@ -1335,10 +1350,12 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
1335
1350
|
`:r}
|
|
1336
1351
|
${n||t||this._editPostId?g:this._renderAddThreadTrigger()}
|
|
1337
1352
|
${n?g:u`<div
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1353
|
+
class=${T({"compose-action-row":!0,"compose-action-row-overlay-open":this._showPublishPanel||this._showCollection})}
|
|
1354
|
+
>
|
|
1355
|
+
${this._renderCollectionSelector()}
|
|
1356
|
+
${this._renderPublishButton()}
|
|
1357
|
+
</div>
|
|
1358
|
+
${this._renderHideFromLatestQuickToggleRow()}`}
|
|
1342
1359
|
${this._renderMobilePublishPanel()} ${this._renderAttachedPanel()}
|
|
1343
1360
|
${this._renderAltPanel()} ${this._renderDraftsPanel()}
|
|
1344
1361
|
${this._renderConfirmPanel()}
|
|
@@ -1704,6 +1721,9 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
1704
1721
|
</svg>
|
|
1705
1722
|
<span class="compose-retry-label">${this.labels.retryAll}</span>
|
|
1706
1723
|
</span>
|
|
1724
|
+
${e.error?u`<span class="compose-attachment-error-msg"
|
|
1725
|
+
>${e.error}</span
|
|
1726
|
+
>`:g}
|
|
1707
1727
|
</button>
|
|
1708
1728
|
`:g}
|
|
1709
1729
|
${this._renderAttachmentRemoveButton(e=>{e.stopPropagation(),this._removeAttachment(t)})}
|
|
@@ -1711,7 +1731,6 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
1711
1731
|
<button
|
|
1712
1732
|
type="button"
|
|
1713
1733
|
class="compose-attachment-remove"
|
|
1714
|
-
title=${this.labels.removeAttachment}
|
|
1715
1734
|
aria-label=${this.labels.removeAttachment}
|
|
1716
1735
|
@click=${e}
|
|
1717
1736
|
>
|
|
@@ -2144,7 +2163,7 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
|
|
|
2144
2163
|
The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),t.includes(`flac`)&&e.push(`
|
|
2145
2164
|
The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
|
|
2146
2165
|
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.
|
|
2147
|
-
`+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 BL;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=LO(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&&Zj(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??gL,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 EL(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 PL({format:new sL,target:new $I}),n=new EL(c);t.addVideoTrack(n),await t.start();let r=await new yM(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 bM(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=>{H(o),H(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new Jj(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 Jj(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&&(H(c!==null),H(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 yM(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{H(i),H(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&&(H(o!==null),H(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new CL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(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});H(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:Ck(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 Jj?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new Jj(e):new Jj(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 OL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(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});H(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??gL,a=await yL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>tA.includes(e))&&u.some(e=>tA.includes(e))&&(s!==LL||c!==RL)){let e=(await yL(u,{numberOfChannels:LL,sampleRate:RL,bitrate:i})).find(e=>tA.includes(e));e&&(l=!0,n=e,s=LL,c=RL)}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 AL({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new CM(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:Ck(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 rM))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 AL({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new UL({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new CM(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;H(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=_k(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},BL=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},VL=5,HL=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<VL&&(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()>=VL}wait(e){let{promise:t,resolve:n}=ok();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},UL=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(){H(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;H(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 rM({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 WL(){return typeof AudioEncoder<`u`}async function GL(e,t){let n=new MP({source:new OP(e),formats:EP}),r=new QI,i=new PL({format:new sL({fastStart:`in-memory`}),target:r});try{let a=await zL.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:gL}});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 KL={isSupported:WL,processToFile:GL},qL=1920,JL=1080,YL=640,XL=32;function ZL(){return typeof VideoEncoder<`u`}async function QL(e){let t=new MP({source:new OP(e),formats:EP});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 bM(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(YL/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(XL/d,XL/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:jC(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 $L(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await QL(e),c=i||qL,l=a||JL;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(qL/e,JL/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new MP({source:new OP(e),formats:EP}),d=new QI,f=new PL({format:new sL({fastStart:`in-memory`}),target:d});try{let i=await zL.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:gL},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await rR(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&(nR(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await rR(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var eR=[65536,0,0,0,65536,0,0,0,1073741824];function tR(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`)&&tR(e,i+8,i+t,r),i+=t}}function nR(e){let t=new DataView(e);tR(t,0,e.byteLength,(n,r,i)=>{if(i!==`tkhd`)return;let a=n+8,o=a+(t.getUint8(a)===0?40:52);if(o+36>e.byteLength)return;let s=!0;for(let e=0;e<9;e++)if(t.getInt32(o+e*4)!==eR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,eR[e])})}function rR(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 iR={isSupported:ZL,processToFile:$L};function aR(){return document.querySelector(`jant-compose-dialog`)}function oR(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function sR(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 cR(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 lR(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()??``}}function uR(e){let t=e.dataset.format;if(t===`note`||t===`link`||t===`quote`)return t}async function dR(e){await aR()?.openNew(e)}async function fR(e){let t=e.dataset.postId;if(!t)return;let n=aR();if(!n)return;let r=e.dataset.threadRootId??t,i=uR(e);await n.openReply(t,lR(e),r,cR(e)??void 0,i?{initialFormat:i}:void 0)}function pR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function mR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function hR(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function gR(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 hR(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,y(t),!0):!1}catch{return!1}}async function _R(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await hR(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,y(e),!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);if(!r)return!1;r.outerHTML=n;let i=document.querySelector(`article[data-post-id="${e}"]`);return i&&y(i),!0}catch{return!1}}async function vR(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await hR(`/_/post-view/${encodeURIComponent(e)}`);if(!n)return!1;t.outerHTML=n;let r=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);return r&&y(r),!0}catch{return!1}}async function yR(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?gR(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?vR(e.replyRefreshId):_R(e.replyRefreshId)}var bR=new Map,xR=new Set,SR=new Map;function CR(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 wR(e,t,n){try{let r,i,o,s,c,l,u;if(e.type.startsWith(`video/`)){if(!iR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;CR(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let a=await iR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});r=a.file,i=a.width,o=a.height,s=a.durationSeconds,c=a.blurhash,u=a.poster,u&&n?.updateAttachmentPoster(t,u)}else if(e.type.startsWith(`audio/`)){if(!KL.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{l=await PC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),r=(await KL.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file}else if(e.type.startsWith(`image/`)||/\.heic$/i.test(e.name)||/\.heif$/i.test(e.name)){let s=e;try{let{isHeic:a,heicTo:c}=await kO(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(e)){n?.updateAttachmentStatus(t,`processing`,null,null);let r=await c({blob:e,type:`image/jpeg`,quality:.92});s=new File([r],e.name.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,s)}let l=await re.processToFile(s);r=l.file,i=l.width,o=l.height}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else r=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!e.type.startsWith(`video/`)){let e=await FC(r);i??=e.width,o??=e.height,c??=e.blurhash,l??=e.waveform,!u&&e.poster&&(u=e.poster,n?.updateAttachmentPoster(t,u))}let d,f;if(cS(e.type)===`text`)try{let e=await r.text(),t=e.replace(/\s+/g,` `).trim();f=e.length,d=t.length<=100?t:t.slice(0,100)+`…`}catch{}let p=await KC(r,{width:i,height:o,durationSeconds:s,blurhash:c,waveform:l,poster:u,summary:d,chars:f},e=>{n?.updateAttachmentProgress(t,e)});return n?.updateAttachmentStatus(t,`done`,p.id,null),SR.set(t,p.id),p.id}catch(e){let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),a(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;SR.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):xR.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=pR(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=wR(e,r,n).then(e=>xR.has(r)?(xR.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);bR.set(r,t),t.finally(()=>bR.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&&fR(n)});function TR(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 ER(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function DR(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??SR.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!ER(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:jT(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=mR(t.target)??document.querySelector(`jant-compose-dialog`),o=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>e.body.includes(`"blob:`)):n.body.includes(`"blob:`),u=n.pendingAttachments.length>0||l,f=s?.published??`Published!`,p=s?.view??`View`;u&&d(`compose-deferred`,c);let h=(e,t=`success`)=>{u?_(`compose-deferred`,e,t):a(e,t)},g=()=>{!o||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},v=()=>{!o||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||o)){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=>{v(),await b(),h(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{m(e,`success`,t)},ee=()=>!o||!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=>bR.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!SR.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let c=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=a[t];n&&r&&c.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=>TR(e,DR(e,c))),a={posts:i};te&&n.editPostId&&(a.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(a)});if(!l.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`,y();let e=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(e);return}}await x(w(await le(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let u=await le(l),d=w(u,`status`),m=w(u,`permalink`),_=w(u,`toast`);d===`published`?(y(),o?(await S(),g(),h(f)):(C(f,m?{label:p,href:m}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),h(_??`Draft saved.`),OR(r,`draft`));return}let u=DR(n,c);if(l)try{let e=await ew(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let d=te?`/api/posts/${n.editPostId}`:`/compose`,m=te?`PUT`:`POST`,_=TR({...n,status:re?`draft`:n.status},u),v=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!v.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await le(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(n);let r=w(e,`toast`);r&&h(r);return}}await x(w(await le(v),`error`)??`Something went wrong`);return}if(te){y();let e=await le(v),t=n.editPostId??``,r=w(e,`slug`),a=r?i(`/${r}`):null;if(o)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await vR(t)?h(`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}"]`))await vR(t)?h(`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 gR(e):await _R(t))?h(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let b=await le(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),o)await S(),g(),h(f);else if(n.replyToId){if(await S(),!await yR(n)){C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}h(f)}else C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),h(oe??`Draft saved.`),OR(r,`draft`)}catch{await x(`Something went wrong`)}});function OR(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var kR=`.compose-prompt`,AR=`.compose-prompt-trigger`,jR=`jant.composeOpenShortcutDiscovery`,MR=`/api/settings/discovery/compose-open-shortcut`,NR=350,PR=1800,FR=3,IR=`compose-prompt-discovery-visible`,LR=!1,RR=null,zR=null,BR=null;function VR(){try{return globalThis.localStorage!==void 0}catch{return!1}}function HR(){if(!VR())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(jR);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(jR),{shownCount:0,completed:!1}}}function UR(e){if(VR())try{globalThis.localStorage.setItem(jR,JSON.stringify(e))}catch{}}function WR(){RR!==null&&(clearTimeout(RR),RR=null)}function GR(){zR!==null&&(clearTimeout(zR),zR=null)}function KR(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function qR(e){return HR().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function JR(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(IR)),document.querySelectorAll(kR).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(IR)})}function YR(){let e=HR();e.completed||LR||e.shownCount>=FR||(LR=!0,UR({...e,shownCount:e.shownCount+1}))}function XR(e){return!KR()||qR(e)?!1:HR().shownCount<FR||LR}function ZR(e){WR(),GR(),e?e.classList.remove(IR):BR&&BR.classList.remove(IR),(!e||e===BR)&&(BR=null)}function QR(e){XR(e)&&(ZR(BR),BR=e,e.classList.add(IR),YR(),zR=setTimeout(()=>{ZR(e)},PR))}function $R(e){XR(e)&&(e.classList.contains(IR)||(WR(),RR=setTimeout(()=>{QR(e)},NR)))}function ez(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(AR);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{$R(e)}),t.addEventListener(`pointerleave`,()=>{ZR(e)}),t.addEventListener(`focusin`,()=>{$R(e)}),t.addEventListener(`focusout`,()=>{ZR(e)}))}function tz(e=document){e.querySelectorAll(kR).forEach(e=>ez(e))}function nz(){let e=HR();e.completed||UR({shownCount:Math.max(e.shownCount,FR),completed:!0}),JR(BR),ZR(BR),typeof globalThis.fetch==`function`&&globalThis.fetch(MR,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{tz()}):tz();var rz=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function iz(e){return e instanceof globalThis.Element&&e.closest(rz)!==null}function az(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!aR()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return iz(e.target)||t!==e.target&&iz(t)}async function oz(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`),a(t?`Added to Featured.`:`Removed from Featured.`)}catch{a(`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(),nz();let n=oR(),r=t===`l`?`link`:t===`q`?`quote`:void 0;dR({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=sR();if(n){if(t===`r`){e.preventDefault(),fR(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=aR();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(),oz(t,!n.hasAttribute(`data-post-featured`),n);return}}});var sz=class extends c{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},languages:{type:Array},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},_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.languages=[],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._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}disconnectedCallback(){super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=PT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=NT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`3rem`)}_initFooterEditor(){let e=this.querySelector(`[data-settings-footer-editor]`);if(!e||this._footerEditor)return;this._footerEditor=PT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=NT(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_syncFeedDirty(){this._feedDirty=this._mainRssFeed!==this._origMainRssFeed}_saveFeeds(){this._feedLoading||!this._feedDirty||(this._feedLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/feeds`,data:{mainRssFeed:this._mainRssFeed},section:`feeds`}})))}_saveHomeToggle(e){this._homeLoading||(this._showJantBrandingOnHome=e,this._homeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/home`,data:{showJantBrandingOnHome:e},section:`home`}})))}_saveSearchToggle(e){this.demoMode||this._searchLoading||(this._noindex=!e,this._searchLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/search`,data:{allowIndexing:e},section:`search`}})))}_onKeydown(e,t,n,r){e.key===`Enter`&&!r&&n&&!(e.target instanceof HTMLTextAreaElement)&&(e.preventDefault(),t())}_renderSaveAction(e,t,n){return u`
|
|
2166
|
+
`+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 BL;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=LO(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&&Zj(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??gL,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 EL(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 PL({format:new sL,target:new $I}),n=new EL(c);t.addVideoTrack(n),await t.start();let r=await new yM(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 bM(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=>{H(o),H(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new Jj(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 Jj(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&&(H(c!==null),H(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 yM(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{H(i),H(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&&(H(o!==null),H(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new CL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(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});H(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:Ck(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 Jj?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new Jj(e):new Jj(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 OL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(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});H(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??gL,a=await yL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>tA.includes(e))&&u.some(e=>tA.includes(e))&&(s!==LL||c!==RL)){let e=(await yL(u,{numberOfChannels:LL,sampleRate:RL,bitrate:i})).find(e=>tA.includes(e));e&&(l=!0,n=e,s=LL,c=RL)}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 AL({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new CM(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:Ck(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 rM))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 AL({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new UL({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new CM(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;H(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=_k(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},BL=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},VL=5,HL=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<VL&&(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()>=VL}wait(e){let{promise:t,resolve:n}=ok();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},UL=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(){H(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;H(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 rM({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 WL(){return typeof AudioEncoder<`u`}async function GL(e,t){let n=new MP({source:new OP(e),formats:EP}),r=new QI,i=new PL({format:new sL({fastStart:`in-memory`}),target:r});try{let a=await zL.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:gL}});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 KL={isSupported:WL,processToFile:GL},qL=1920,JL=1080,YL=640,XL=32;function ZL(){return typeof VideoEncoder<`u`}async function QL(e){let t=new MP({source:new OP(e),formats:EP});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 bM(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(YL/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(XL/d,XL/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:jC(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 $L(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await QL(e),c=i||qL,l=a||JL;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(qL/e,JL/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new MP({source:new OP(e),formats:EP}),d=new QI,f=new PL({format:new sL({fastStart:`in-memory`}),target:d});try{let i=await zL.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:gL},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await rR(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&(nR(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await rR(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var eR=[65536,0,0,0,65536,0,0,0,1073741824];function tR(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`)&&tR(e,i+8,i+t,r),i+=t}}function nR(e){let t=new DataView(e);tR(t,0,e.byteLength,(n,r,i)=>{if(i!==`tkhd`)return;let a=n+8,o=a+(t.getUint8(a)===0?40:52);if(o+36>e.byteLength)return;let s=!0;for(let e=0;e<9;e++)if(t.getInt32(o+e*4)!==eR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,eR[e])})}function rR(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 iR={isSupported:ZL,processToFile:$L};function aR(){return document.querySelector(`jant-compose-dialog`)}function oR(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function sR(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 cR(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 lR(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()??``}}function uR(e){let t=e.dataset.format;if(t===`note`||t===`link`||t===`quote`)return t}async function dR(e){await aR()?.openNew(e)}async function fR(e){let t=e.dataset.postId;if(!t)return;let n=aR();if(!n)return;let r=e.dataset.threadRootId??t,i=uR(e);await n.openReply(t,lR(e),r,cR(e)??void 0,i?{initialFormat:i}:void 0)}function pR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function mR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function hR(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function gR(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 hR(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,y(t),!0):!1}catch{return!1}}async function _R(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await hR(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,y(e),!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);if(!r)return!1;r.outerHTML=n;let i=document.querySelector(`article[data-post-id="${e}"]`);return i&&y(i),!0}catch{return!1}}async function vR(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await hR(`/_/post-view/${encodeURIComponent(e)}`);if(!n)return!1;t.outerHTML=n;let r=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);return r&&y(r),!0}catch{return!1}}async function yR(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?gR(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?vR(e.replyRefreshId):_R(e.replyRefreshId)}var bR=new Map,xR=new Set,SR=new Map;function CR(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 wR(e,t,n){try{let r,i,o,s,c,l,u;if(e.type.startsWith(`video/`)){if(!iR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;CR(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let a=await iR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});r=a.file,i=a.width,o=a.height,s=a.durationSeconds,c=a.blurhash,u=a.poster,u&&n?.updateAttachmentPoster(t,u)}else if(e.type.startsWith(`audio/`)){if(!KL.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{l=await PC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),r=(await KL.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file}else if(e.type.startsWith(`image/`)||/\.heic$/i.test(e.name)||/\.heif$/i.test(e.name)){let s=e;try{let{isHeic:a,heicTo:c}=await kO(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(e)){n?.updateAttachmentStatus(t,`processing`,null,null);let r=await c({blob:e,type:`image/jpeg`,quality:.92});s=new File([r],e.name.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,s)}let l=await re.processToFile(s);r=l.file,i=l.width,o=l.height}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else r=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!e.type.startsWith(`video/`)){let e=await FC(r);i??=e.width,o??=e.height,c??=e.blurhash,l??=e.waveform,!u&&e.poster&&(u=e.poster,n?.updateAttachmentPoster(t,u))}let d,f;if(cS(e.type)===`text`)try{let e=await r.text(),t=e.replace(/\s+/g,` `).trim();f=e.length,d=t.length<=100?t:t.slice(0,100)+`…`}catch{}let p=await KC(r,{width:i,height:o,durationSeconds:s,blurhash:c,waveform:l,poster:u,summary:d,chars:f},e=>{n?.updateAttachmentProgress(t,e)});return n?.updateAttachmentStatus(t,`done`,p.id,null),SR.set(t,p.id),p.id}catch(e){let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),n||a(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;SR.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):xR.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=pR(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=wR(e,r,n).then(e=>xR.has(r)?(xR.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);bR.set(r,t),t.finally(()=>bR.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&&fR(n)});function TR(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 ER(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function DR(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??SR.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!ER(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:jT(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=mR(t.target)??document.querySelector(`jant-compose-dialog`),o=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>e.body.includes(`"blob:`)):n.body.includes(`"blob:`),u=n.pendingAttachments.length>0||l,f=s?.published??`Published!`,p=s?.view??`View`;u&&d(`compose-deferred`,c);let h=(e,t=`success`)=>{u?_(`compose-deferred`,e,t):a(e,t)},g=()=>{!o||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},v=()=>{!o||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||o)){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=>{v(),await b(),h(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{m(e,`success`,t)},ee=()=>!o||!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=>bR.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!SR.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let c=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=a[t];n&&r&&c.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=>TR(e,DR(e,c))),a={posts:i};te&&n.editPostId&&(a.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(a)});if(!l.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`,y();let e=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(e);return}}await x(w(await le(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let u=await le(l),d=w(u,`status`),m=w(u,`permalink`),_=w(u,`toast`);d===`published`?(y(),o?(await S(),g(),h(f)):(C(f,m?{label:p,href:m}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),h(_??`Draft saved.`),OR(r,`draft`));return}let u=DR(n,c);if(l)try{let e=await ew(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let d=te?`/api/posts/${n.editPostId}`:`/compose`,m=te?`PUT`:`POST`,_=TR({...n,status:re?`draft`:n.status},u),v=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!v.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await le(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(n);let r=w(e,`toast`);r&&h(r);return}}await x(w(await le(v),`error`)??`Something went wrong`);return}if(te){y();let e=await le(v),t=n.editPostId??``,r=w(e,`slug`),a=r?i(`/${r}`):null;if(o)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await vR(t)?h(`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}"]`))await vR(t)?h(`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 gR(e):await _R(t))?h(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let b=await le(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),o)await S(),g(),h(f);else if(n.replyToId){if(await S(),!await yR(n)){C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}h(f)}else C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),h(oe??`Draft saved.`),OR(r,`draft`)}catch{await x(`Something went wrong`)}});function OR(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var kR=`.compose-prompt`,AR=`.compose-prompt-trigger`,jR=`jant.composeOpenShortcutDiscovery`,MR=`/api/settings/discovery/compose-open-shortcut`,NR=350,PR=1800,FR=3,IR=`compose-prompt-discovery-visible`,LR=!1,RR=null,zR=null,BR=null;function VR(){try{return globalThis.localStorage!==void 0}catch{return!1}}function HR(){if(!VR())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(jR);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(jR),{shownCount:0,completed:!1}}}function UR(e){if(VR())try{globalThis.localStorage.setItem(jR,JSON.stringify(e))}catch{}}function WR(){RR!==null&&(clearTimeout(RR),RR=null)}function GR(){zR!==null&&(clearTimeout(zR),zR=null)}function KR(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function qR(e){return HR().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function JR(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(IR)),document.querySelectorAll(kR).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(IR)})}function YR(){let e=HR();e.completed||LR||e.shownCount>=FR||(LR=!0,UR({...e,shownCount:e.shownCount+1}))}function XR(e){return!KR()||qR(e)?!1:HR().shownCount<FR||LR}function ZR(e){WR(),GR(),e?e.classList.remove(IR):BR&&BR.classList.remove(IR),(!e||e===BR)&&(BR=null)}function QR(e){XR(e)&&(ZR(BR),BR=e,e.classList.add(IR),YR(),zR=setTimeout(()=>{ZR(e)},PR))}function $R(e){XR(e)&&(e.classList.contains(IR)||(WR(),RR=setTimeout(()=>{QR(e)},NR)))}function ez(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(AR);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{$R(e)}),t.addEventListener(`pointerleave`,()=>{ZR(e)}),t.addEventListener(`focusin`,()=>{$R(e)}),t.addEventListener(`focusout`,()=>{ZR(e)}))}function tz(e=document){e.querySelectorAll(kR).forEach(e=>ez(e))}function nz(){let e=HR();e.completed||UR({shownCount:Math.max(e.shownCount,FR),completed:!0}),JR(BR),ZR(BR),typeof globalThis.fetch==`function`&&globalThis.fetch(MR,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{tz()}):tz();var rz=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function iz(e){return e instanceof globalThis.Element&&e.closest(rz)!==null}function az(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!aR()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return iz(e.target)||t!==e.target&&iz(t)}async function oz(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`),a(t?`Added to Featured.`:`Removed from Featured.`)}catch{a(`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(),nz();let n=oR(),r=t===`l`?`link`:t===`q`?`quote`:void 0;dR({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=sR();if(n){if(t===`r`){e.preventDefault(),fR(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=aR();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(),oz(t,!n.hasAttribute(`data-post-featured`),n);return}}});var sz=class extends c{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},languages:{type:Array},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},_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.languages=[],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._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}disconnectedCallback(){super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=PT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=NT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`3rem`)}_initFooterEditor(){let e=this.querySelector(`[data-settings-footer-editor]`);if(!e||this._footerEditor)return;this._footerEditor=PT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=NT(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_syncFeedDirty(){this._feedDirty=this._mainRssFeed!==this._origMainRssFeed}_saveFeeds(){this._feedLoading||!this._feedDirty||(this._feedLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/feeds`,data:{mainRssFeed:this._mainRssFeed},section:`feeds`}})))}_saveHomeToggle(e){this._homeLoading||(this._showJantBrandingOnHome=e,this._homeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/home`,data:{showJantBrandingOnHome:e},section:`home`}})))}_saveSearchToggle(e){this.demoMode||this._searchLoading||(this._noindex=!e,this._searchLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/search`,data:{allowIndexing:e},section:`search`}})))}_onKeydown(e,t,n,r){e.key===`Enter`&&!r&&n&&!(e.target instanceof HTMLTextAreaElement)&&(e.preventDefault(),t())}_renderSaveAction(e,t,n){return u`
|
|
2148
2167
|
<div class="flex mt-4">
|
|
2149
2168
|
<button
|
|
2150
2169
|
type="button"
|
|
@@ -4005,7 +4024,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4005
4024
|
|
|
4006
4025
|
${this.#E()} ${this.#D()}
|
|
4007
4026
|
${this.#O()}
|
|
4008
|
-
`}};customElements.define(`jant-nav-manager`,OB),document.addEventListener(`jant:nav-update`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:t.label,...t.url!==void 0&&{url:t.url}})});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to save. Please try again.`,`error`)}}),document.addEventListener(`jant:nav-delete`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to delete. Please try again.`,`error`)}});var kB=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,AB=`M4 4 20 20`,jB=360,MB=12;function NB(e){let t=window.innerHeight-e.bottom-MB,n=e.top-MB;return t<jB&&n>t}function PB(e){let t=Array.from(e?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-item`));Array.from(t?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-divider`))?.remove()}var FB=class extends c{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=NB(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{if(e.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},a({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),a(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},a(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),a(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},a(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),a(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},a(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),a(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await be({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.feed-item`),n=t?.parentElement;(t??e)?.remove(),PB(n),a(`Post deleted.`)}catch{a(`Could not delete post. Try again.`,`error`),e?.focus()}}async#S(){if(!this._data)return;let e=this._data.id;this._view=`collections`,this._collectionSearch=``,this._collectionsLoading=!0,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`);try{let[t,n]=await Promise.all([fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}}),fetch(`/api/posts/${e}`)]);if(!t.ok)throw Error();let r=(await t.json()).collections??[],i=this._postCollectionIds;n.ok&&(i=(await n.json()).collectionIds??[]),this.#t=qx(r,i),this._collections=r,this._postCollectionIds=i}catch{this._collections=this._collections??[],a(`Could not load collections.`,`error`)}this._collectionsLoading=!1,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`)}#C(e){if(!this._data)return;let t=this._data.id,n=this._postCollectionIds.includes(e);n?this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e):this._postCollectionIds=[...this._postCollectionIds,e],this.#e=!0,a(n?`Removed from collection.`:`Added to collection.`),n?fetch(`/api/collections/${e}/posts/${t}`,{method:`DELETE`}).then(e=>{if(!e.ok)throw Error();return this.#k()}).catch(()=>{this._postCollectionIds.includes(e)||(this._postCollectionIds=[...this._postCollectionIds,e]),a(`Could not remove from collection. Try again.`,`error`)}):fetch(`/api/collections/${e}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:t})}).then(e=>{if(!e.ok){if(e.status===409)return this.#k();throw Error()}return this.#k()}).catch(()=>{this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e),a(`Could not add to collection. Try again.`,`error`)})}#w(){this._addCollectionPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()})}#T(){this._addCollectionPanelOpen=!1,this.#r(),this.updateComplete.then(()=>{(this.querySelector(`[data-post-menu-add-collection]`)??this._triggerEl)?.focus()})}async#E(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Could not create collection. Try again.`);if(!t?.id||!t.title||!t.slug)throw Error(`Could not create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug};this._collections=[...this._collections??[],r],this._data&&(await fetch(`/api/collections/${t.id}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})}),this._postCollectionIds=[...this._postCollectionIds,t.id]),await this.#k(),this.#e=!0,this.#T(),a(this.#D()?.createdLabel??`Collection created.`)}catch(e){a(e instanceof Error?e.message:`Could not create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}#D(){return document.querySelector(`jant-compose-dialog`)?.labels?.collectionFormLabels??null}#O(){return document.querySelector(`jant-compose-dialog`)?.labels?.addCollection??`Add Collection`}async#k(){await document.querySelector(`jant-compose-dialog`)?.refreshCollections?.()}#A(e){switch(e){case`private`:return`Private`;case`latest_hidden`:return`Hidden from Latest`;default:return`Public`}}#j(){return u`<svg
|
|
4027
|
+
`}};customElements.define(`jant-nav-manager`,OB),document.addEventListener(`jant:nav-update`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:t.label,...t.url!==void 0&&{url:t.url}})});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to save. Please try again.`,`error`)}}),document.addEventListener(`jant:nav-delete`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to delete. Please try again.`,`error`)}});var kB=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,AB=`M4 4 20 20`,jB=360,MB=12;function NB(e){let t=window.innerHeight-e.bottom-MB,n=e.top-MB;return t<jB&&n>t}function PB(e){let t=Array.from(e?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-item`));Array.from(t?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-divider`))?.remove()}var FB=class extends c{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=NB(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{if(e.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},a({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),a(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},a(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),a(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},a(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),a(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},a(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),a(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await be({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.thread-item`),n=t?.closest(`.thread-group`);if(t&&n){if(t.remove(),n.querySelectorAll(`.thread-item:not(.thread-item-gap)`).length===0){let e=n.closest(`.feed-item`),t=e?.parentElement??null;(e??n).remove(),PB(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),PB(n)}a(`Post deleted.`)}catch{a(`Could not delete post. Try again.`,`error`),e?.focus()}}async#S(){if(!this._data)return;let e=this._data.id;this._view=`collections`,this._collectionSearch=``,this._collectionsLoading=!0,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`);try{let[t,n]=await Promise.all([fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}}),fetch(`/api/posts/${e}`)]);if(!t.ok)throw Error();let r=(await t.json()).collections??[],i=this._postCollectionIds;n.ok&&(i=(await n.json()).collectionIds??[]),this.#t=qx(r,i),this._collections=r,this._postCollectionIds=i}catch{this._collections=this._collections??[],a(`Could not load collections.`,`error`)}this._collectionsLoading=!1,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`)}#C(e){if(!this._data)return;let t=this._data.id,n=this._postCollectionIds.includes(e);n?this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e):this._postCollectionIds=[...this._postCollectionIds,e],this.#e=!0,a(n?`Removed from collection.`:`Added to collection.`),n?fetch(`/api/collections/${e}/posts/${t}`,{method:`DELETE`}).then(e=>{if(!e.ok)throw Error();return this.#k()}).catch(()=>{this._postCollectionIds.includes(e)||(this._postCollectionIds=[...this._postCollectionIds,e]),a(`Could not remove from collection. Try again.`,`error`)}):fetch(`/api/collections/${e}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:t})}).then(e=>{if(!e.ok){if(e.status===409)return this.#k();throw Error()}return this.#k()}).catch(()=>{this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e),a(`Could not add to collection. Try again.`,`error`)})}#w(){this._addCollectionPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()})}#T(){this._addCollectionPanelOpen=!1,this.#r(),this.updateComplete.then(()=>{(this.querySelector(`[data-post-menu-add-collection]`)??this._triggerEl)?.focus()})}async#E(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Could not create collection. Try again.`);if(!t?.id||!t.title||!t.slug)throw Error(`Could not create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug};this._collections=[...this._collections??[],r],this._data&&(await fetch(`/api/collections/${t.id}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})}),this._postCollectionIds=[...this._postCollectionIds,t.id]),await this.#k(),this.#e=!0,this.#T(),a(this.#D()?.createdLabel??`Collection created.`)}catch(e){a(e instanceof Error?e.message:`Could not create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}#D(){return document.querySelector(`jant-compose-dialog`)?.labels?.collectionFormLabels??null}#O(){return document.querySelector(`jant-compose-dialog`)?.labels?.addCollection??`Add Collection`}async#k(){await document.querySelector(`jant-compose-dialog`)?.refreshCollections?.()}#A(e){switch(e){case`private`:return`Private`;case`latest_hidden`:return`Hidden from Latest`;default:return`Public`}}#j(){return u`<svg
|
|
4009
4028
|
xmlns="http://www.w3.org/2000/svg"
|
|
4010
4029
|
viewBox="0 0 24 24"
|
|
4011
4030
|
fill="none"
|