@jant/core 0.6.11 → 0.6.12
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/bin/commands/import-site.js +45 -20
- package/dist/app-B5P1b4TF.js +6 -0
- package/dist/{app-CpmficmQ.js → app-D-zAhayc.js} +331 -55
- package/dist/client/.vite/manifest.json +3 -3
- package/dist/client/_assets/client-BUxR-E8O.css +2 -0
- package/dist/client/_assets/{client-Dd9U383b.js → client-S1cdvulk.js} +1 -1
- package/dist/client/_assets/{client-auth-DkpSdIDz.js → client-auth-YW92ZH7u.js} +116 -55
- package/dist/{export-Ba7NJImL.js → export-Ckwh4BiE.js} +4 -4
- package/dist/{github-sync-BD4w2m8-.js → github-sync-BMmK3JZ0.js} +2 -2
- package/dist/{github-sync-Cb4_6_i7.js → github-sync-Dl9wQMar.js} +1 -1
- package/dist/index.js +3 -3
- package/dist/node.js +4 -4
- package/package.json +1 -1
- package/src/__tests__/import-site-command.test.ts +75 -0
- package/src/__tests__/vite-dev-plugins.test.ts +34 -0
- package/src/client/__tests__/compose-launch.test.ts +50 -1
- package/src/client/__tests__/compose-shortcuts.test.ts +74 -18
- package/src/client/components/__tests__/jant-command-palette.test.ts +63 -0
- package/src/client/components/__tests__/jant-compose-dialog.test.ts +33 -0
- package/src/client/components/__tests__/jant-compose-editor-rehost-notice.test.ts +20 -1
- package/src/client/components/__tests__/jant-nav-manager.test.ts +77 -1
- package/src/client/components/__tests__/jant-settings-avatar.test.ts +6 -0
- package/src/client/components/__tests__/jant-settings-general.test.ts +71 -0
- package/src/client/components/jant-command-palette.ts +67 -2
- package/src/client/components/jant-compose-dialog.ts +8 -2
- package/src/client/components/jant-nav-manager.ts +142 -2
- package/src/client/components/jant-settings-general.ts +56 -0
- package/src/client/components/nav-manager-types.ts +14 -0
- package/src/client/components/settings-types.ts +30 -0
- package/src/client/compose-launch.ts +30 -0
- package/src/client/compose-shortcuts.ts +46 -3
- package/src/client/tiptap/__tests__/rehost-images.test.ts +66 -13
- package/src/client/tiptap/rehost-images.ts +5 -1
- package/src/i18n/__tests__/fallback.test.ts +24 -0
- package/src/i18n/locales/public/zh-Hans.po +2 -2
- package/src/i18n/locales/public/zh-Hans.ts +1 -1
- package/src/i18n/locales/public/zh-Hant.po +2 -2
- package/src/i18n/locales/public/zh-Hant.ts +1 -1
- package/src/i18n/locales/settings/en.po +54 -0
- package/src/i18n/locales/settings/en.ts +1 -1
- package/src/i18n/locales/settings/zh-Hans.po +64 -10
- package/src/i18n/locales/settings/zh-Hans.ts +1 -1
- package/src/i18n/locales/settings/zh-Hant.po +56 -2
- package/src/i18n/locales/settings/zh-Hant.ts +1 -1
- package/src/lib/__tests__/feed.test.ts +96 -10
- package/src/lib/feed.ts +63 -3
- package/src/lib/post-display.ts +14 -8
- package/src/preset.css +60 -18
- package/src/routes/dash/settings.tsx +41 -2
- package/src/routes/pages/__tests__/draft-about-edit.test.ts +65 -0
- package/src/routes/pages/page.tsx +44 -12
- package/src/services/__tests__/about-page.test.ts +116 -0
- package/src/services/__tests__/navigation.test.ts +190 -1
- package/src/services/__tests__/post-timeline.test.ts +119 -2
- package/src/services/about-page.ts +143 -0
- package/src/services/export-theme/layouts/_default/rss.xml +2 -1
- package/src/services/export-theme/layouts/partials/feed-post-content.xml +25 -1
- package/src/services/export-theme/styles/main.css +46 -14
- package/src/services/index.ts +27 -17
- package/src/services/navigation.ts +155 -1
- package/src/services/post.ts +24 -7
- package/src/styles/components.css +20 -0
- package/src/styles/tokens.css +26 -8
- package/src/styles/ui.css +149 -7
- package/src/types/views.ts +13 -0
- package/src/ui/dash/appearance/NavigationContent.tsx +57 -0
- package/src/ui/dash/appearance/__tests__/NavigationContent.test.tsx +19 -0
- package/src/ui/dash/settings/GeneralContent.tsx +44 -0
- package/src/ui/dash/settings/__tests__/GeneralContent.test.tsx +8 -0
- package/src/ui/feed/__tests__/timeline-cards.test.ts +162 -1
- package/dist/app-DqKkZenB.js +0 -6
- package/dist/client/_assets/client-BhHHVvSY.css +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,n as t,o as n,t as r}from"./chunks/url-pLre2DM_.js";import{_ as i,a,b as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,m,n as h,o as g,p as _,r as v,s as y,t as b,u as x,v as S,y as C}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,b as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,m,n as h,o as g,p as _,r as v,s as y,t as b,u as x,v as S,y as C}from"./client-S1cdvulk.js";var ee={maxShortSide:1920,maxLongSide:8192,quality:.85,mimeType:`image/webp`};function te(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 ne(e,t,n){if(Math.max(e,t)>n.maxLongSide)return{passthrough:!0,width:e,height:t};let r=Math.min(e,t);if(r<=n.maxShortSide)return{passthrough:!1,width:e,height:t};let i=n.maxShortSide/r;return{passthrough:!1,width:Math.round(e*i),height:Math.round(t*i)}}async function re(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 ie(e,t={}){let n={...ee,...t},r=await te(e),i=ne(r.width,r.height,n);if(i.passthrough)return{blob:e,width:i.width,height:i.height,processed:!1};let a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`);if(!o)throw Error(`Failed to get canvas context`);return o.drawImage(r,0,0,i.width,i.height),{blob:await re(a,n.mimeType,n.quality),width:i.width,height:i.height,processed:!0}}async function ae(e,t={}){let n=await ie(e,t);if(!n.processed)return{file:e,width:n.width,height:n.height};let r={"image/webp":`webp`,"image/jpeg":`jpg`,"image/png":`png`}[n.blob.type]??`png`,i=`${e.name.replace(/\.[^.]+$/,``)}.${r}`;return{file:new File([n.blob],i,{type:n.blob.type}),width:n.width,height:n.height}}var oe={process:ie,processToFile:ae},se={ICO_16:16,ICO_32:32,APPLE_TOUCH:512};function ce(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 le(e){return typeof e==`object`&&!!e}function w(e,t){if(!le(e))return;let n=e[t];return typeof n==`string`?n:void 0}function ue(e,t){if(!le(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}function de(e,t){if(!le(e))return;let n=e[t];return typeof n==`number`?n:void 0}async function fe(e){let t=await e.text();if(!t.trim())return{};try{let e=JSON.parse(t);return le(e)?e:{}}catch{throw Error(`Expected JSON (HTTP ${e.status}) but got: ${ge(t.trim(),200)}`)}}async function pe(e,t){let n;try{n=await e.text()}catch{return t}return he(n,t)}function me(e,t){return he(e,t)}function he(e,t){let n=e.trim();if(!n)return t;try{let e=JSON.parse(n);if(le(e)){let t=w(e,`error`);if(t)return t}}catch{}return ge(n,200)}function ge(e,t){return e.length>t?`${e.slice(0,t)}…`:e}var _e=180;function ve(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 ye(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 be(e,t){return e.type===`image/png`&&t.width===t.height&&t.width>=_e&&t.height>=_e}async function xe(e,t){let n=e.closest(`form`)?.querySelector(`label`),r=n?.textContent??``;try{n&&(n.textContent=e.dataset.textProcessing||`Processing...`);let r=await ve(t),i=t,a=t.name;if(t.type!==`image/svg+xml`){let e=await ye(r,512);i=new File([e],t.name.replace(/\.[^.]+$/,`.png`),{type:`image/png`}),a=i.name}let s=be(t,r)?Promise.resolve(t):ye(r,se.APPLE_TOUCH),[c,l,u]=await Promise.all([ye(r,16),ye(r,32),s]),[d,f]=await Promise.all([c.arrayBuffer(),l.arrayBuffer()]),p=ce([{size:16,png:d},{size:32,png:f}]);n&&(n.textContent=e.dataset.textUploading||`Uploading...`);let m=new FormData;m.append(`file`,i,a),m.append(`favicon`,p,`favicon.ico`),m.append(`appleTouch`,u,`apple-touch-icon.png`);let h=await fetch(o(`/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 fe(h);t=w(e,`error`)??w(e,`message`)??t}catch{}throw Error(t)}let g=await fe(h),_=w(g,`status`),v=w(g,`url`);if(_===`redirect`&&v){window.location.href=v;return}window.location.href=o(`/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 Se(){document.addEventListener(`change`,e=>{let t=e.target.closest(`[data-avatar-upload]`);t?.files?.[0]&&(e.stopPropagation(),xe(t,t.files[0]))})}Se();var Ce=`default`,we=class extends _{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=Ce}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??Ce,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??Ce,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=Ce,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 m;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}
|
|
@@ -305,7 +305,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
305
305
|
`,m);if(e===-1||e>=d)break;f.push(e+1),m=e+1}let h=t.tr,g=0,_=0;for(let e=0;e<f.length;e++){let t=f[e],n=l.slice(t),r=n.startsWith(Ww)?2:n.startsWith(` `)?1:0;if(r>0){let n=c+t+g;h=h.delete(n,n+r),g-=r,e===0&&(_=r)}}if(g<0){let e=Math.max(i-_,c),t=a+g;h.setSelection(k.create(h.doc,e,Math.max(t,e)))}return n(h),!0}return!1}}}}),Kw=/\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\)/,qw=RegExp(Kw.source+`$`),Jw=RegExp(Kw.source+`\\s$`),Yw=/((?:https?:\/\/|mailto:)[^\s<]+)\s$/,Xw=N.create({name:`linkInputRules`,addInputRules(){let e=this.editor.schema.marks.link;if(!e)return[];function n(n,r,i,a){let o=i[1]?.trim(),s=t(i[2]??``);if(!o||!s)return null;let c=a?o+a:o;n.tr.insertText(c,r.from,r.to),n.tr.addMark(r.from,r.from+o.length,e.create({href:s})),n.tr.removeStoredMark(e)}return[new qd({find:Yw,handler:({state:n,range:r,match:i})=>{let a=t(i[1]??``);if(!a)return null;let o=r.from+a.length;if(n.doc.rangeHasMark(r.from,o,e))return null;n.tr.addMark(r.from,o,e.create({href:a})),n.tr.removeStoredMark(e)}}),new qd({find:qw,handler:({state:e,range:t,match:r})=>{n(e,t,r,``)}}),new qd({find:Jw,handler:({state:e,range:t,match:r})=>{n(e,t,r,` `)}})]}});function Zw(e){return new qd({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Pu(e.getAttributes,void 0,r)||{},a=t.tr.delete(n.from,n.to),o=a.doc.resolve(n.from).blockRange(),s=o&&On(o,e.type,i);if(!s)return null;a.wrap(o,s)}})}var Qw=N.create({name:`wrappingInputRules`,priority:1e3,addInputRules(){let{schema:e}=this.editor,t=[],n=e.nodes.blockquote;n&&t.push(Zw({find:/^\s*>\s$/,type:n}));let r=e.nodes.bulletList;r&&t.push(Zw({find:/^\s*([-+*])\s$/,type:r}));let i=e.nodes.orderedList;return i&&t.push(Zw({find:/^(\d+)\.\s$/,type:i,getAttributes:e=>({start:Number(e[1])})})),t}});function $w(e,t){let{state:n}=e,r=n.schema.nodes.paragraph;if(!r)return!1;let{selection:i}=n,{$from:a,$to:o}=i,s;s=a.depth===0?t===`above`?i.from:i.to:t===`above`?a.before(1):o.after(1);let c=n.tr.insert(s,r.create());return c.setSelection(k.create(c.doc,s+1)),e.view.dispatch(c.scrollIntoView()),!0}var eT=N.create({name:`insertParagraphAround`,addKeyboardShortcuts(){let e=({editor:e})=>{let{state:t}=e,{selection:n}=t;if(!n.empty)return!1;let{$from:r}=n;if(r.depth<1||r.pos!==r.depth)return!1;let i=t.doc.firstChild;return!i||i.type.name===`paragraph`?!1:$w(e,`above`)};return{ArrowUp:e,ArrowLeft:e,"Mod-Shift-Enter":({editor:e})=>$w(e,`above`),"Mod-Alt-Enter":({editor:e})=>$w(e,`below`)}}}),tT=/\[\^([^\]\n]+)\]([ \t.,!?;)]$)/,nT=/^\[\^([^\]\n]+)\]: $/,rT=/\[\^([^\]\n]+)\]$/;function iT(e){let t=new Set;return e.descendants(e=>{if(e.type.name!==`footnoteReference`&&e.type.name!==`footnoteDefinition`)return!0;let n=ax(e.attrs.label);return n&&t.add(ox(n)),!0}),t}function aT(e){let t=iT(e),n=1;for(;t.has(String(n));)n+=1;return String(n)}function oT(e){let t=e.content.size;return e.forEach((e,n)=>{e.type.name===`footnoteDefinition`&&(t=n+e.nodeSize)}),t}function sT(e,t){let n=ox(t),r=null;return e.forEach((e,t)=>{r===null&&e.type.name===`footnoteDefinition`&&ox(e.attrs.label)===n&&(r=t)}),r}function cT(e,t){let n=ox(t),r=null;return e.forEach((e,t)=>{r===null&&e.type.name===`footnoteDefinition`&&ox(e.attrs.label)===n&&(r={from:t,to:t+e.nodeSize})}),r}function lT(e,t){let n=ox(t),r=[];return e.descendants((e,t)=>(e.type.name===`footnoteReference`&&ox(e.attrs.label)===n&&r.push({from:t,to:t+e.nodeSize}),!0)),r}function uT(e,t){let n=e.schema.nodes.footnoteReference;return n?n.create({label:t}):null}function dT(e,t){let n=e.schema.nodes.footnoteDefinition,r=e.schema.nodes.paragraph;return!n||!r?null:n.create({label:t},[r.create()])}function fT(e,t){let n=Math.min(t+2,e.doc.content.size);e.setSelection(k.near(e.doc.resolve(n),1))}function pT(e,t){let n=null,r=null;e.doc.forEach((e,i)=>{i===t&&e.type.name===`paragraph`&&e.content.size===0&&(n=i,r=i+e.nodeSize)}),n!==null&&r!==null&&e.delete(n,r)}function mT(e,t,n){let r=sT(t.doc,n);if(r!==null)return r;let i=dT(e,n);if(!i)return null;let a=oT(t.doc);return t.insert(a,i),pT(t,a+i.nodeSize),a}function hT(e,t){if(t.doc.childCount>0)return;let n=e.schema.nodes.paragraph;n&&t.insert(0,n.create())}function gT(e,t){if(!t||e.doc.childCount<2)return;let n=e.doc.lastChild,r=e.doc.child(e.doc.childCount-2);n?.type.name===`paragraph`&&n.content.size===0&&r.type.name!==`footnoteDefinition`&&e.delete(e.doc.content.size-n.nodeSize,e.doc.content.size)}function _T(e,t){let n=Math.min(Math.max(t,0),e.doc.content.size);e.setSelection(k.near(e.doc.resolve(n),-1))}function vT(e,t){let n=[...t].sort((e,t)=>t.from-e.from);for(let t of n)e.delete(t.from,t.to)}function yT(e,t){let n=cT(e.doc,t),r=[...lT(e.doc,t),...n?[n]:[]];if(r.length===0)return null;let i=e.tr;return vT(i,r),hT(e,i),gT(i,n),_T(i,r[0]?.from??0),i.scrollIntoView(),i}function bT(e,t){let n=e.doc.nodeAt(t.from);if(!n||n.type.name!==`footnoteReference`)return null;let r=ax(n.attrs.label);if(!r)return null;let i=lT(e.doc,r),a=cT(e.doc,r),o=i.length<=1?[t,...a?[a]:[]]:[t],s=e.tr;return vT(s,o),hT(e,s),gT(s,i.length<=1?a:null),_T(s,t.from),s.scrollIntoView(),s}function xT(e,t){let{selection:n}=e;if(n instanceof A)return n.node.type.name===`footnoteReference`?{from:n.from,to:n.to}:null;if(!n.empty)return null;let{$from:r}=n,i=t===`backward`?r.nodeBefore:r.nodeAfter;if(!i||i.type.name!==`footnoteReference`)return null;let a=t===`backward`?n.from-i.nodeSize:n.from;return{from:a,to:a+i.nodeSize}}function ST(e){let{selection:t}=e;if(t instanceof A)return t.node.type.name===`footnoteDefinition`?ax(t.node.attrs.label):null;if(!t.empty)return null;let{$from:n}=t,r=-1;for(let e=n.depth;e>0;--e)if(n.node(e).type.name===`footnoteDefinition`){r=e;break}return r===-1||!(n.parent.type.name===`paragraph`&&n.parentOffset===0&&n.index(r)===0)?null:ax(n.node(r).attrs.label)}function CT(e,t,n,r,i){let a=uT(e,t);if(!a)return!1;let o=[a];n&&o.push(e.schema.text(n));let s=e.tr;return s.replaceWith(r,i,E.fromArray(o)),mT(e,s,t)!==null}function wT(e,t){let n=dT(e,t);if(!n)return!1;let{$from:r}=e.selection;if(r.depth!==1||r.parent.type.name!==`paragraph`)return!1;let i=e.tr.replaceWith(r.before(),r.after(),n);return pT(i,r.before()+n.nodeSize),fT(i,r.before()),i.scrollIntoView(),!0}function TT(e,t){let n=dT(e,t);if(!n)return!1;let{$from:r}=e.selection;if(r.parent.type.name!==`paragraph`||r.depth<2||r.node(r.depth-1).type.name!==`footnoteDefinition`)return!1;let i=r.depth,a=r.before(i),o=r.after(i),s=i-1,c=r.node(s),l=r.after(s),u=e.tr;c.childCount===1?u.delete(a+1,o-1):u.delete(a,o);let d=u.mapping.map(l);return u.insert(d,n),pT(u,d+n.nodeSize),fT(u,d),u.scrollIntoView(),!0}function ET(e){let{$from:t}=e.selection;for(let e=t.depth;e>0;--e)if(t.node(e).type.name===`footnoteDefinition`)return!0;return!1}function DT(e){let{selection:t}=e,{$from:n}=t;if(!t.empty||ET(e)||!n.parent.inlineContent||n.parent.type.name!==`paragraph`||n.parentOffset!==n.parent.content.size)return null;let r=n.parent.textBetween(0,n.parentOffset,void 0,``).match(rT),i=ax(r?.[1]);return!r||!i?null:{label:i,from:t.from-r[0].length,to:t.from}}function OT(e){let t=DT(e);if(t){let n=uT(e,t.label);if(!n)return null;let r=e.tr.replaceWith(t.from,t.to,n),i=mT(e,r,t.label);return i===null?null:(fT(r,i),r.scrollIntoView(),r)}return null}function kT(){return[new qd({find:nT,handler:({state:e,match:t})=>{let n=ax(t[1]);if(!n)return null;let{$from:r}=e.selection;return r.depth!==1||r.parent.type.name!==`paragraph`?TT(e,n)?void 0:null:wT(e,n)?void 0:null}}),new qd({find:tT,handler:({state:e,range:t,match:n})=>{let r=ax(n[1]),i=n[2]??``;return!r||!i||!e.selection.$from.parent.inlineContent?null:CT(e,r,i,t.from,t.to)?void 0:null}})]}var AT=N.create({name:`footnotes`,addCommands(){return{insertFootnote:()=>({state:e,dispatch:t})=>{if(!e.selection.$from.parent.inlineContent)return!1;let n=aT(e.doc),r=uT(e,n),i=dT(e,n);if(!r||!i)return!1;let a=oT(e.doc),o=e.tr.replaceSelectionWith(r,!1),s=o.mapping.map(a);return o.insert(s,i),pT(o,s+i.nodeSize),fT(o,s),t&&t(o.scrollIntoView()),!0}}},addInputRules(){return kT()},addKeyboardShortcuts(){return{Enter:({editor:e})=>{let t=OT(e.state);return t?(e.view.dispatch(t),!0):!1},Backspace:({editor:e})=>{let t=ST(e.state);if(t){let n=yT(e.state,t);return n?(e.view.dispatch(n),!0):!1}let n=xT(e.state,`backward`);if(!n)return!1;let r=bT(e.state,n);return r?(e.view.dispatch(r),!0):!1},Delete:({editor:e})=>{let t=xT(e.state,`forward`);if(!t)return!1;let n=bT(e.state,t);return n?(e.view.dispatch(n),!0):!1}}}});function jT(e,t,n=`paragraph`){let{$to:r}=e.selection,i=r.end();if(r.nodeAfter)r.nodeAfter.isTextblock?e.setSelection(k.create(e.doc,r.pos+1)):r.nodeAfter.isBlock?e.setSelection(A.create(e.doc,r.pos)):e.setSelection(k.create(e.doc,r.pos));else{let a=(t.nodes[n]??r.parent.type.contentMatch.defaultType)?.create();a&&(e.insert(i,a),e.setSelection(k.create(e.doc,i+1)))}e.scrollIntoView()}var MT={regular:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="3" y="3" width="10" height="10" rx="1.5"/></svg>`,wide:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="1.5" y="4" width="13" height="8" rx="1.5"/></svg>`,full:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="0.75" y="3" width="14.5" height="10" rx="1"/><path d="M4 8h8M4 6l-1.5 2L4 10M12 6l1.5 2L12 10"/></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>`,replace:`<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="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></svg>`,expand:`<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="M15 3h6v6"/><path d="M9 21H3v-6"/><path d="M21 3l-7 7"/><path d="M3 21l7-7"/></svg>`},NT=class{dom;img;figcaption;captionInput;altBtn;toolbar;captionBar;layoutBtns=new Map;node;view;getPos;editor;editingAlt=!1;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`figure`);i.className=`tiptap-image-figure`,i.dataset.selected=`false`,i.dataset.layout=String(e.attrs.layout||`regular`),this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-image-container`,i.appendChild(a);let o=document.createElement(`img`);o.src=String(e.attrs.src??``),o.alt=String(e.attrs.alt??``),e.attrs.title&&(o.title=String(e.attrs.title)),o.draggable=!1,a.appendChild(o),this.img=o;let s=document.createElement(`div`);s.className=`tiptap-image-toolbar`,a.appendChild(s),this.toolbar=s;let c=[[`regular`,MT.regular,`Content width`],[`wide`,MT.wide,`Wide — max 1200px`],[`full`,MT.full,`Full width — edge to edge`]];for(let[t,n,r]of c){this.layoutBtns.size>0&&s.appendChild(this.sep());let i=document.createElement(`button`);i.type=`button`,i.innerHTML=n,i.title=r,i.dataset.layout=t,t===(e.attrs.layout||`regular`)&&(i.className=`is-active`),i.addEventListener(`mousedown`,e=>{e.preventDefault(),this.updateAttrs({layout:t})}),s.appendChild(i),this.layoutBtns.set(t,i)}s.appendChild(this.sep());let l=this.iconBtn(MT.link,`Add link`);l.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleLink()}),s.appendChild(l),s.appendChild(this.sep());let u=this.iconBtn(MT.replace,`Replace image`);u.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleReplace()}),s.appendChild(u),s.appendChild(this.sep());let d=this.iconBtn(MT.expand,`Preview fullscreen`);d.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleExpand()}),s.appendChild(d);let f=document.createElement(`div`);f.className=`tiptap-image-caption-bar`,i.appendChild(f),this.captionBar=f;let p=document.createElement(`input`);p.type=`text`,p.placeholder=`Add a caption…`,p.value=String(e.attrs.caption??``),p.addEventListener(`input`,()=>{this.editingAlt?this.updateAttrs({alt:p.value}):this.updateAttrs({caption:p.value})}),p.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),this.view.focus())}),f.appendChild(p),this.captionInput=p;let m=document.createElement(`button`);m.type=`button`,m.className=`tiptap-image-alt-btn`,m.textContent=`Alt`,m.addEventListener(`mousedown`,e=>{e.preventDefault(),this.toggleAltMode()}),f.appendChild(m),this.altBtn=m;let h=document.createElement(`figcaption`);h.className=`tiptap-image-figcaption`,h.textContent=String(e.attrs.caption??``),i.appendChild(h),this.figcaption=h}update(e){if(e.type!==this.node.type)return!1;this.node=e,this.img.src=String(e.attrs.src??``),this.img.alt=String(e.attrs.alt??``),this.img.title=String(e.attrs.title??``),this.dom.dataset.layout=String(e.attrs.layout||`regular`),this.layoutBtns.forEach((t,n)=>{t.classList.toggle(`is-active`,n===(e.attrs.layout||`regular`))});let t=String(e.attrs.caption??``);return this.figcaption.textContent=t,document.activeElement!==this.captionInput&&(this.editingAlt?this.captionInput.value=String(e.attrs.alt??``):this.captionInput.value=t),!0}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`,this.editingAlt=!1,this.altBtn.classList.remove(`is-active`),this.captionInput.placeholder=`Add a caption…`,this.captionInput.value=String(this.node.attrs.caption??``)}stopEvent(e){let t=e.target;return!!(t.closest(`.tiptap-image-toolbar`)||t.closest(`.tiptap-image-caption-bar`))}ignoreMutation(){return!0}destroy(){}sep(){let e=document.createElement(`span`);return e.className=`tiptap-toolbar-sep`,e}iconBtn(e,t){let n=document.createElement(`button`);return n.type=`button`,n.innerHTML=e,n.title=t,n}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}handleLink(){if(String(this.node.attrs.href??``))this.updateAttrs({href:``});else{let e=globalThis.prompt(`Enter URL`);e&&this.updateAttrs({href:e})}}handleReplace(){let e=document.createElement(`input`);e.type=`file`,e.accept=`image/*`,e.addEventListener(`change`,async()=>{let t=e.files?.[0];if(t)try{let e=await dw(t);this.updateAttrs({src:e.url})}catch{}}),e.click()}handleExpand(){let e=document.querySelector(`jant-media-lightbox`);e&&e.open([{url:String(this.node.attrs.src??``),alt:String(this.node.attrs.alt??``)}],0)}toggleAltMode(){this.editingAlt=!this.editingAlt,this.altBtn.classList.toggle(`is-active`,this.editingAlt),this.editingAlt?(this.captionInput.placeholder=`Add alt text…`,this.captionInput.value=String(this.node.attrs.alt??``)):(this.captionInput.placeholder=`Add a caption…`,this.captionInput.value=String(this.node.attrs.caption??``)),this.captionInput.focus()}},PT=Wf.create({name:`image`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{src:{default:``},alt:{default:``},title:{default:``},caption:{default:``},href:{default:``},layout:{default:`regular`}}},parseHTML(){return[{tag:`figure[data-image]`,getAttrs(e){let t=e,n=t.querySelector(`img`),r=t.querySelector(`figcaption`),i=t.querySelector(`a`);return{src:n?.getAttribute(`src`)??``,alt:n?.getAttribute(`alt`)??``,title:n?.getAttribute(`title`)??``,caption:r?.textContent??``,href:i?.getAttribute(`href`)??``,layout:t.dataset.layout??`regular`}}},{tag:`figure`,getAttrs(e){let t=e,n=t.querySelector(`img`);if(!n)return!1;let r=t.querySelector(`figcaption`),i=t.querySelector(`a`);return{src:n.getAttribute(`src`)??``,alt:n.getAttribute(`alt`)??``,title:n.getAttribute(`title`)??``,caption:r?.textContent??``,href:i?.getAttribute(`href`)??``,layout:t.dataset.layout??`regular`}}},{tag:`img[src]`,getAttrs(e){let t=e;return{src:t.getAttribute(`src`)??``,alt:t.getAttribute(`alt`)??``,title:t.getAttribute(`title`)??``}}}]},renderHTML({node:e}){let t={};e.attrs.layout&&e.attrs.layout!==`regular`&&(t[`data-layout`]=e.attrs.layout),t[`data-image`]=``;let n={src:e.attrs.src};e.attrs.alt&&(n.alt=e.attrs.alt),e.attrs.title&&(n.title=e.attrs.title);let r=[`img`,n],i=[];return e.attrs.href?i.push([`a`,{href:e.attrs.href},r]):i.push(r),e.attrs.caption&&i.push([`figcaption`,{},e.attrs.caption]),[`figure`,t,...i]},parseMarkdown:(e,t)=>t.createNode(`image`,{src:e.href,title:e.title??``,alt:e.text??``}),renderMarkdown:e=>yx(e.attrs??{}),addCommands(){return{setImage:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let{$to:r}=n.selection,i=t();return vd(n.selection)?i.insertContentAt(r.pos,{type:this.name,attrs:e}):i.insertContent({type:this.name,attrs:e}),i.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new NT(e,t,n,r)}}),FT=`<!--more-->`,IT=Wf.create({name:`moreBreak`,group:`block`,atom:!0,selectable:!0,draggable:!1,parseHTML(){return[{tag:`div[data-more-break]`}]},renderHTML(){return[`div`,{"data-more-break":``,class:`tiptap-more-break`},`Read More ↓`]},renderText(){return FT},parseMarkdown:(e,t)=>t.createNode(`moreBreak`),renderMarkdown:()=>FT,markdownTokenizer:Px(),addCommands(){return{insertMoreBreak:()=>({chain:e,state:t})=>{if(!Af(t,t.schema.nodes[this.name]))return!1;let{$to:n}=t.selection,r=e();return vd(t.selection)?r.insertContentAt(n.pos,{type:this.name}):r.insertContent({type:this.name}),r.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}}}),LT=class{dom;node;view;getPos;editor;providerLabel;urlLink;captionInput;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`div`);i.className=`tiptap-embed-card`,i.dataset.selected=`false`,this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-embed-card-header`,i.appendChild(a);let o=document.createElement(`span`);o.className=`tiptap-embed-card-provider`,a.appendChild(o),this.providerLabel=o;let s=document.createElement(`span`);s.className=`tiptap-embed-card-actions`,a.appendChild(s);let c=document.createElement(`button`);c.type=`button`,c.textContent=`Edit`,c.className=`tiptap-embed-card-btn`,c.addEventListener(`mousedown`,e=>{e.preventDefault(),this.requestEdit()}),s.appendChild(c);let l=document.createElement(`a`);l.className=`tiptap-embed-card-url`,l.target=`_blank`,l.rel=`noopener noreferrer`,i.appendChild(l),this.urlLink=l;let u=document.createElement(`input`);u.type=`text`,u.placeholder=`Add a caption…`,u.className=`tiptap-embed-card-caption`,u.value=String(e.attrs.caption??``),u.addEventListener(`input`,()=>{this.updateAttrs({caption:u.value})}),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),this.view.focus())}),i.appendChild(u),this.captionInput=u,this.refresh()}update(e){return e.type===this.node.type?(this.node=e,document.activeElement!==this.captionInput&&(this.captionInput.value=String(e.attrs.caption??``)),this.refresh(),!0):!1}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`}stopEvent(e){let t=e.target;return!!(t.closest(`.tiptap-embed-card-header`)||t.closest(`.tiptap-embed-card-caption`))}ignoreMutation(){return!0}destroy(){}refresh(){let e=String(this.node.attrs.url??``),t=String(this.node.attrs.providerName??``)||RT(e);this.providerLabel.textContent=t,this.urlLink.href=e,this.urlLink.textContent=e}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}requestEdit(){iC({initialUrl:String(this.node.attrs.url??``),initialCaption:String(this.node.attrs.caption??``)}).then(e=>{if(!e)return;let t=this.getPos();if(t===void 0)return;if(e.kind===`link`){let n=t,r=t+this.node.nodeSize;this.editor.chain().focus().insertContentAt({from:n,to:r},{type:`paragraph`,content:[{type:`text`,text:e.url,marks:[{type:`link`,attrs:{href:e.url}}]}]}).run();return}if(e.kind!==`embed`)return;let n=nC(e.url),r=n?{url:n.url||e.url,provider:n.provider,providerName:n.providerName,src:n.src,orientation:n.orientation,heightPx:n.heightPx??null,sandbox:n.sandbox,allow:n.allow??``,caption:e.caption??``}:{...this.node.attrs,url:e.url,caption:e.caption??``},i=this.view.state.tr.setNodeMarkup(t,void 0,r);this.view.dispatch(i)})}};function RT(e){if(!e)return`Embed`;try{return new URL(e.startsWith(`http`)?e:`https://${e}`).hostname}catch{return`Embed`}}var zT=Wf.create({name:`embed`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{url:{default:``},provider:{default:``},providerName:{default:``},src:{default:``},orientation:{default:`landscape`},heightPx:{default:null},sandbox:{default:``},allow:{default:``},caption:{default:``}}},parseHTML(){return[{tag:`figure[data-jant-node="embed"]`,getAttrs(e){let t=e;return{url:t.getAttribute(`data-url`)??``,provider:t.getAttribute(`data-provider`)??``,providerName:t.getAttribute(`data-provider-name`)??``,src:t.getAttribute(`data-src`)??``,orientation:t.getAttribute(`data-orientation`)??`landscape`}}}]},renderHTML({node:e}){let t={"data-jant-node":`embed`};return e.attrs.provider&&(t[`data-provider`]=String(e.attrs.provider)),e.attrs.providerName&&(t[`data-provider-name`]=String(e.attrs.providerName)),e.attrs.url&&(t[`data-url`]=String(e.attrs.url)),e.attrs.src&&(t[`data-src`]=String(e.attrs.src)),e.attrs.orientation&&(t[`data-orientation`]=String(e.attrs.orientation)),[`figure`,t]},parseMarkdown:(e,t)=>{let n=typeof e.url==`string`?e.url:``,r=e.attrs&&typeof e.attrs==`object`?e.attrs:{};return t.createNode(`embed`,{url:n,caption:r.caption??``})},renderMarkdown:e=>{let t=e.attrs??{},n=typeof t.url==`string`?t.url.trim():``;if(!n)return``;let r=[n],i=typeof t.caption==`string`?t.caption.trim():``;return i&&r.push(`caption=${i}`),["```jant-embed",...r,"```"].join(`
|
|
306
306
|
`)},markdownTokenizer:Mx(),addCommands(){return{setEmbed:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let r=nC(e.url),i=r?{url:r.url||e.url,provider:r.provider,providerName:r.providerName,src:r.src,orientation:r.orientation,heightPx:r.heightPx??null,sandbox:r.sandbox,allow:r.allow??``,caption:e.caption??``}:{url:e.url,caption:e.caption??``},{$to:a}=n.selection,o=t();return vd(n.selection)?o.insertContentAt(a.pos,{type:this.name,attrs:i}):o.insertContent({type:this.name,attrs:i}),o.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new LT(e,t,n,r)}}),BT=class{dom;node;view;getPos;editor;textarea;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`div`);i.className=`tiptap-html-block-card`,i.dataset.selected=`false`,this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-html-block-header`,a.textContent=`Raw HTML`,i.appendChild(a);let o=document.createElement(`textarea`);o.className=`tiptap-html-block-textarea`,o.spellcheck=!1,o.value=String(e.attrs.html??``),o.rows=Math.max(3,o.value.split(`
|
|
307
307
|
`).length),o.addEventListener(`input`,()=>{this.updateAttrs({html:o.value}),this.autoGrow()}),i.appendChild(o),this.textarea=o;let s=document.createElement(`p`);s.className=`tiptap-html-block-hint`,s.textContent=`Renders on the published page only.`,i.appendChild(s),queueMicrotask(()=>this.autoGrow())}update(e){return e.type===this.node.type?(this.node=e,document.activeElement!==this.textarea&&(this.textarea.value=String(e.attrs.html??``),this.autoGrow()),!0):!1}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`}stopEvent(e){return e.target.closest(`.tiptap-html-block-textarea`)!==null}ignoreMutation(){return!0}destroy(){}autoGrow(){this.textarea.style.height=`auto`,this.textarea.style.height=`${this.textarea.scrollHeight}px`}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}},VT=Wf.create({name:`htmlBlock`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{html:{default:``}}},parseHTML(){return[{tag:`div[data-jant-node="html-block"]`,getAttrs(e){return{html:e.textContent??``}}}]},renderHTML({node:e}){return[`div`,{"data-jant-node":`html-block`},String(e.attrs.html??``)]},parseMarkdown:(e,t)=>{let n=typeof e.html==`string`?e.html:``;return t.createNode(`htmlBlock`,{html:n})},renderMarkdown:e=>["```jant-html",typeof e.attrs?.html==`string`?e.attrs.html:``,"```"].join(`
|
|
308
|
-
`),markdownTokenizer:Nx(),addCommands(){return{setHtmlBlock:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let r={html:e.html},{$to:i}=n.selection,a=t();return vd(n.selection)?a.insertContentAt(i.pos,{type:this.name,attrs:r}):a.insertContent({type:this.name,attrs:r}),a.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new BT(e,t,n,r)}}),HT=/^https?:\/\/\S+$/i,UT=new Pr(`jantEmbedPaste`),WT=N.create({name:`embedPaste`,addProseMirrorPlugins(){let e=this.editor;return[new j({key:UT,props:{handlePaste(t,n){let r=n.clipboardData;if(!r)return!1;let i=r.getData(`text/plain`)?.trim()??``;if(!i||!HT.test(i))return!1;let{selection:a}=t.state;if(!a.empty)return!1;let o=a.$from,s=o.parent;if(s.type.name!==`paragraph`||s.content.size>0||!rC(i)||!nC(i))return!1;n.preventDefault();let c=t.state.schema.marks.link,l=o.pos,u=t.state.tr.insertText(i,l);return c&&u.addMark(l,l+i.length,c.create({href:i})),t.dispatch(u),queueMicrotask(()=>{let n=l,r=l+i.length,a=Fv(t.state.tr).delete(n,r);t.dispatch(a),e.commands.setEmbed({url:i})}),!0}}})]}}),GT=50,KT=new Pr(`jantRehostImages`),qT=new Set;function JT(e){qT.delete(e)}var YT=N.create({name:`rehostImages`,addOptions(){return{shouldRehost:void 0,rehost:void 0}},addProseMirrorPlugins(){let e=this.options;return[new j({key:KT,appendTransaction(t,n,r){if(!t.some(e=>e.docChanged))return null;let{shouldRehost:i,rehost:a}=e;if(!i||!a)return null;let o=[],s=new Set;if(r.doc.descendants(e=>{if(e.type.name!==`image`)return;let t=e.attrs.src;typeof t!=`string`||!t||s.has(t)||qT.has(t)||i(t)&&(s.add(t),o.push(t))}),o.length===0)return null;let c=o.slice(0,GT),l=o.length-c.length;l>0&&console.warn(`[jant] ${l} pasted image(s) left as external links — per-paste rehost cap of ${GT} reached.`);for(let e of c)qT.add(e),queueMicrotask(()=>a(e));return null}})]}});function XT(e){return e instanceof E?e:e.content}function ZT(e){if(/data-vscode-/i.test(e))return!0;let t=e.match(/^[^<]*(?:<(?:meta|html|head|body)\b[^>]*>\s*)*<(?:div|pre)\b[^>]*style="([^"]*)"/i);if(t){let e=t[1]??``,n=/font-family:[^;"]*\b(?:monospace|Menlo|Monaco|Consolas|Courier|JetBrains Mono|Fira Code|Source Code Pro)\b/i.test(e),r=/white-space:\s*pre\b/i.test(e);if(n&&r)return!0}return!1}var QT=N.create({name:`markdownClipboard`,addProseMirrorPlugins(){return[new j({props:{handlePaste:(e,t)=>{let n=t.clipboardData?.getData(`text/html`)??``;if(!n||!ZT(n))return!1;let r=t.clipboardData?.getData(`text/plain`)?.trim()??``;if(!r||!this.editor.markdown)return!1;let i=this.editor.markdown.parse(r);if(i.type!==`doc`||!i.content)return!1;let a=ql(i,e.state.schema,{slice:!1}),o=D.maxOpen(XT(a));return t.preventDefault(),e.dispatch(e.state.tr.replaceSelection(o).scrollIntoView()),!0},clipboardTextParser:(e,t,n,r)=>{if(!e.trim()||!this.editor.markdown)return D.empty;let i=this.editor.markdown.parse(e);if(i.type!==`doc`||!i.content)return D.empty;if(i.content.length===1&&i.content[0]?.type===`paragraph`){let e=i.content[0];if(!e?.content)return D.empty;let t=ql(e.content,r.state.schema,{slice:!0});return D.maxOpen(XT(t))}let a=ql(i,r.state.schema,{slice:!1});return D.maxOpen(XT(a))}}})]}}),$T=N.create({name:`reclaimModEnter`,priority:1e3,addKeyboardShortcuts(){return{"Mod-Enter":()=>!0}}});function eE(e={}){return[...Vx(),Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??``}),$T,Xw,Qw,QT,Uw,eT,Bw.configure({toolbarMode:`compose`}),Fw]}function tE(e={}){return[...Vx({imageExtension:PT,moreBreakExtension:IT,embedExtension:zT,htmlBlockExtension:VT}),$T,Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??`Write something…`}),AT,Xw,Qw,QT,IC,WT,Ow.configure(e.pasteMedia??{}),YT.configure(e.rehostImages??{}),Bw.configure({toolbarMode:e.toolbarMode??`default`}),Fw,Uw,eT,Gw]}function nE(e){try{let t=JSON.parse(e);return t.type===`doc`?Jx(t).trimEnd():``}catch{return``}}function rE(e){return new Tf({element:e.element,extensions:tE({placeholder:e.placeholder,toolbarMode:e.toolbarMode,pasteMedia:e.pasteMedia,rehostImages:e.rehostImages}),content:e.content??void 0,editorProps:{scrollMargin:{top:5,right:5,bottom:80,left:5},scrollThreshold:{top:5,right:5,bottom:80,left:5}},onUpdate:({editor:t})=>{e.onUpdate?.(fx(t.getJSON()))},onFocus:()=>{e.onFocus?.()},onSelectionUpdate:({editor:t})=>{e.onSelectionUpdate?.({from:t.state.selection.from,to:t.state.selection.to})}})}function iE(e){return nE(JSON.stringify(e))}function aE(e){let t=e.content?qx(e.content):void 0;return new Tf({element:e.element,extensions:eE({placeholder:e.placeholder}),content:t,onUpdate:({editor:t})=>{e.onUpdate?.(iE(t.getJSON()))}})}var oE=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),sE=`[data-editor-floating-ui]`,cE=`(max-width: 700px), (max-height: 760px), (hover: none) and (pointer: coarse)`,lE={drafts:`
|
|
308
|
+
`),markdownTokenizer:Nx(),addCommands(){return{setHtmlBlock:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let r={html:e.html},{$to:i}=n.selection,a=t();return vd(n.selection)?a.insertContentAt(i.pos,{type:this.name,attrs:r}):a.insertContent({type:this.name,attrs:r}),a.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new BT(e,t,n,r)}}),HT=/^https?:\/\/\S+$/i,UT=new Pr(`jantEmbedPaste`),WT=N.create({name:`embedPaste`,addProseMirrorPlugins(){let e=this.editor;return[new j({key:UT,props:{handlePaste(t,n){let r=n.clipboardData;if(!r)return!1;let i=r.getData(`text/plain`)?.trim()??``;if(!i||!HT.test(i))return!1;let{selection:a}=t.state;if(!a.empty)return!1;let o=a.$from,s=o.parent;if(s.type.name!==`paragraph`||s.content.size>0||!rC(i)||!nC(i))return!1;n.preventDefault();let c=t.state.schema.marks.link,l=o.pos,u=t.state.tr.insertText(i,l);return c&&u.addMark(l,l+i.length,c.create({href:i})),t.dispatch(u),queueMicrotask(()=>{let n=l,r=l+i.length,a=Fv(t.state.tr).delete(n,r);t.dispatch(a),e.commands.setEmbed({url:i})}),!0}}})]}}),GT=50,KT=new Pr(`jantRehostImages`),qT=new Set;function JT(e){qT.delete(e)}var YT=N.create({name:`rehostImages`,addOptions(){return{shouldRehost:void 0,rehost:void 0}},addProseMirrorPlugins(){let e=this.options;return[new j({key:KT,appendTransaction(t,n,r){if(!t.some(e=>e.docChanged&&e.getMeta(`paste`)))return null;let{shouldRehost:i,rehost:a}=e;if(!i||!a)return null;let o=[],s=new Set;if(r.doc.descendants(e=>{if(e.type.name!==`image`)return;let t=e.attrs.src;typeof t!=`string`||!t||s.has(t)||qT.has(t)||i(t)&&(s.add(t),o.push(t))}),o.length===0)return null;let c=o.slice(0,GT),l=o.length-c.length;l>0&&console.warn(`[jant] ${l} pasted image(s) left as external links — per-paste rehost cap of ${GT} reached.`);for(let e of c)qT.add(e),queueMicrotask(()=>a(e));return null}})]}});function XT(e){return e instanceof E?e:e.content}function ZT(e){if(/data-vscode-/i.test(e))return!0;let t=e.match(/^[^<]*(?:<(?:meta|html|head|body)\b[^>]*>\s*)*<(?:div|pre)\b[^>]*style="([^"]*)"/i);if(t){let e=t[1]??``,n=/font-family:[^;"]*\b(?:monospace|Menlo|Monaco|Consolas|Courier|JetBrains Mono|Fira Code|Source Code Pro)\b/i.test(e),r=/white-space:\s*pre\b/i.test(e);if(n&&r)return!0}return!1}var QT=N.create({name:`markdownClipboard`,addProseMirrorPlugins(){return[new j({props:{handlePaste:(e,t)=>{let n=t.clipboardData?.getData(`text/html`)??``;if(!n||!ZT(n))return!1;let r=t.clipboardData?.getData(`text/plain`)?.trim()??``;if(!r||!this.editor.markdown)return!1;let i=this.editor.markdown.parse(r);if(i.type!==`doc`||!i.content)return!1;let a=ql(i,e.state.schema,{slice:!1}),o=D.maxOpen(XT(a));return t.preventDefault(),e.dispatch(e.state.tr.replaceSelection(o).scrollIntoView()),!0},clipboardTextParser:(e,t,n,r)=>{if(!e.trim()||!this.editor.markdown)return D.empty;let i=this.editor.markdown.parse(e);if(i.type!==`doc`||!i.content)return D.empty;if(i.content.length===1&&i.content[0]?.type===`paragraph`){let e=i.content[0];if(!e?.content)return D.empty;let t=ql(e.content,r.state.schema,{slice:!0});return D.maxOpen(XT(t))}let a=ql(i,r.state.schema,{slice:!1});return D.maxOpen(XT(a))}}})]}}),$T=N.create({name:`reclaimModEnter`,priority:1e3,addKeyboardShortcuts(){return{"Mod-Enter":()=>!0}}});function eE(e={}){return[...Vx(),Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??``}),$T,Xw,Qw,QT,Uw,eT,Bw.configure({toolbarMode:`compose`}),Fw]}function tE(e={}){return[...Vx({imageExtension:PT,moreBreakExtension:IT,embedExtension:zT,htmlBlockExtension:VT}),$T,Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??`Write something…`}),AT,Xw,Qw,QT,IC,WT,Ow.configure(e.pasteMedia??{}),YT.configure(e.rehostImages??{}),Bw.configure({toolbarMode:e.toolbarMode??`default`}),Fw,Uw,eT,Gw]}function nE(e){try{let t=JSON.parse(e);return t.type===`doc`?Jx(t).trimEnd():``}catch{return``}}function rE(e){return new Tf({element:e.element,extensions:tE({placeholder:e.placeholder,toolbarMode:e.toolbarMode,pasteMedia:e.pasteMedia,rehostImages:e.rehostImages}),content:e.content??void 0,editorProps:{scrollMargin:{top:5,right:5,bottom:80,left:5},scrollThreshold:{top:5,right:5,bottom:80,left:5}},onUpdate:({editor:t})=>{e.onUpdate?.(fx(t.getJSON()))},onFocus:()=>{e.onFocus?.()},onSelectionUpdate:({editor:t})=>{e.onSelectionUpdate?.({from:t.state.selection.from,to:t.state.selection.to})}})}function iE(e){return nE(JSON.stringify(e))}function aE(e){let t=e.content?qx(e.content):void 0;return new Tf({element:e.element,extensions:eE({placeholder:e.placeholder}),content:t,onUpdate:({editor:t})=>{e.onUpdate?.(iE(t.getJSON()))}})}var oE=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),sE=`[data-editor-floating-ui]`,cE=`(max-width: 700px), (max-height: 760px), (hover: none) and (pointer: coarse)`,lE={drafts:`
|
|
309
309
|
<rect x="3.85" y="3.45" width="7.85" height="8.35" rx="2.35" />
|
|
310
310
|
<rect
|
|
311
311
|
x="6.15"
|
|
@@ -1306,7 +1306,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
1306
1306
|
</div>
|
|
1307
1307
|
`}_renderThreadComposeLayout(){let e=!!(this._replyToId&&this._replyToData),t=this._threadItems,n=t.length>1;return u`
|
|
1308
1308
|
<div
|
|
1309
|
-
class
|
|
1309
|
+
class=${T({"compose-thread-layout":!0,"compose-thread-compose-layout":!0,"compose-reply-compose-layout":e})}
|
|
1310
1310
|
@jant:compose-content-changed=${()=>this._scheduleDraftSave()}
|
|
1311
1311
|
>
|
|
1312
1312
|
${e?this._renderReplyContext():m}
|
|
@@ -1352,7 +1352,9 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
1352
1352
|
>
|
|
1353
1353
|
${this._renderHeader()}
|
|
1354
1354
|
${n?this._renderEditLoadingState():t?this._renderThreadComposeLayout():e?u`
|
|
1355
|
-
<div
|
|
1355
|
+
<div
|
|
1356
|
+
class="compose-thread-layout compose-reply-compose-layout"
|
|
1357
|
+
>
|
|
1356
1358
|
${this._renderReplyContext()}
|
|
1357
1359
|
<div
|
|
1358
1360
|
class="compose-editor-row"
|
|
@@ -2193,7 +2195,7 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
|
|
|
2193
2195
|
The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),t.includes(`flac`)&&e.push(`
|
|
2194
2196
|
The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
|
|
2195
2197
|
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.
|
|
2196
|
-
`+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 PR;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=Ak(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&WM(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??uR,s=await mR(_,{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 bR(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 OR({format:new tR,target:new qL}),n=new bR(c);t.addVideoTrack(n),await t.start();let r=await new fN(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 pN(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new VM(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 VM(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(U(c!==null),U(r!==void 0),await l(Math.floor(c*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let n=new fN(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{U(i),U(r!==void 0);let o=Math.round((n-a)*r);for(let n=1;n<o;n++)i.setTimestamp(a+n/r),i.setDuration(1/r),await this._registerVideoSample(e,t,m,i);i.close()};for await(let c of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){c.close(),i?.close();return}let n=Math.max(c.timestamp-this._startTimestamp,0);if(o=n+c.duration,r!==void 0){let e=Math.floor(n*r)/r;if(i!==null)if(e<=a){i.close(),i=c,a=e;continue}else await s(e);n=e,c.setDuration(1/r)}c.setTimestamp(n),await this._registerVideoSample(e,t,m,c),r===void 0?c.close():(i=c,a=n)}i&&(U(o!==null),U(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new _R(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new oN(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:gA(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 VM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new VM(e):new VM(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 SR(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new oN(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}let n=null;t.codec&&(u=u.filter(e=>e===t.codec));let i=t.bitrate??uR,a=await pR(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>JA.includes(e))&&u.some(e=>JA.includes(e))&&(s!==jR||c!==MR)){let e=(await pR(u,{numberOfChannels:jR,sampleRate:MR,bitrate:i})).find(e=>JA.includes(e));e&&(l=!0,n=e,s=jR,c=MR)}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 wR({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new gN(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:gA(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 XM))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 wR({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new LR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new gN(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=uA(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},PR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},FR=5,IR=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<FR&&(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()>=FR}wait(e){let{promise:t,resolve:n}=$k();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},LR=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){U(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+a,this.endTime-this.startTime),s=Math.floor(i*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;U(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new XM({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 RR(){return typeof AudioEncoder<`u`}async function zR(e,t){let n=new TF({source:new xF(e),formats:yF}),r=new KL,i=new OR({format:new tR({fastStart:`in-memory`}),target:r});try{let a=await NR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:uR}});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 BR={isSupported:RR,processToFile:zR},VR=new Set([`moov`,`trak`]);function HR(e){return 12+(e===1?32:20)+8+2}function UR(e){let t=new DataView(e),n=(e,r)=>{let i=e;for(;i+8<=r;){let e=t.getUint32(i),a=String.fromCharCode(t.getUint8(i+4),t.getUint8(i+5),t.getUint8(i+6),t.getUint8(i+7));if(e===0&&(e=r-i),e<8||i+e>r)break;if(a===`tkhd`){let n=t.getUint8(i+8),r=i+HR(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else VR.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var WR=1920,GR=1080,KR=640,qR=32;function JR(){return typeof VideoEncoder<`u`}async function YR(e){let t=new TF({source:new xF(e),formats:yF});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=l(a),s=Math.min(a*.1,1),c=await new pN(e).getCanvas(s);if(!c)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=c.canvas,d=u.width,f=u.height,p=Math.min(KR/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(qR/d,qR/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 XR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await YR(e),c=i||WR,l=a||GR;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(WR/e,GR/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new TF({source:new xF(e),formats:yF}),d=new KL,f=new OR({format:new tR({fastStart:`in-memory`}),target:d});try{let i=await NR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:uR},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);UR(a);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ez(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&($R(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ez(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var ZR=[65536,0,0,0,65536,0,0,0,1073741824];function QR(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`)&&QR(e,i+8,i+t,r),i+=t}}function $R(e){let t=new DataView(e);QR(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)!==ZR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,ZR[e])})}function ez(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 tz={isSupported:JR,processToFile:XR};function nz(){return document.querySelector(`jant-compose-dialog`)}function rz(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function iz(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 az(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 oz(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}async function sz(e){await nz()?.openNew(e)}async function cz(e){let t=e.dataset.postId;if(!t)return;let n=nz();if(!n)return;let r=e.dataset.threadRootId??t;await n.openReply(t,oz(e),r,az(e)??void 0)}function lz(e){b(e),S(e),C(e)}function uz(e){try{return Sw(JSON.parse(e))}catch{return!1}}function dz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function fz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function pz(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function mz(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 pz(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,lz(t),!0):!1}catch{return!1}}async function hz(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await pz(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,lz(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&&lz(i),!0}catch{return!1}}async function gz(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await pz(`/_/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&&lz(r),!0}catch{return!1}}async function _z(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?mz(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?gz(e.replyRefreshId):hz(e.replyRefreshId)}var vz=new Map,yz=new Set,bz=new Map,xz=null;function Sz(){if(!xz)return;let{clientIds:e,baseMsg:t}=xz;if(e.length===0)return;let n=0,r=0;for(let t of e){let e=bz.get(t)??0;n+=Math.min(1,Math.max(0,e)),e>=1&&(r+=1)}let i=e.length,a=Math.floor(n/i*100),o=Math.min(r+1,i);g(`compose-deferred`,i===1?`${t} ${a}%`:`${t} ${a}% ${o}/${i}`)}var Cz=new Map;function wz(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 Tz(e,t,n){let r=e.type,i=e.name;try{let o,s,c,l,u,d,f;if(r.startsWith(`video/`)){if(!tz.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;wz(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let r=await tz.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});o=r.file,e=null,s=r.width,c=r.height,l=r.durationSeconds,u=r.blurhash,f=r.poster,f&&n?.updateAttachmentPoster(t,f)}else if(r.startsWith(`audio/`)){if(!BR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{d=await ZC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),o=(await BR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file,e=null}else if(r.startsWith(`image/`)||/\.heic$/i.test(i)||/\.heif$/i.test(i)){let r=e;try{let{isHeic:a,heicTo:l}=await Sk(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(r)){n?.updateAttachmentStatus(t,`processing`,null,null);let e=await l({blob:r,type:`image/jpeg`,quality:.92});r=new File([e],i.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,r)}let u=await oe.processToFile(r);o=u.file,s=u.width,c=u.height,e=null,r=null}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else o=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!r.startsWith(`video/`)){let e=await QC(o);s??=e.width,c??=e.height,u??=e.blurhash,d??=e.waveform,!f&&e.poster&&(f=e.poster,n?.updateAttachmentPoster(t,f))}let p,m;if(TS(r)===`text`)try{let e=await o.text(),t=e.replace(/\s+/g,` `).trim();m=e.length,p=t.length<=100?t:t.slice(0,100)+`…`}catch{}bz.set(t,0),Sz();let h=await uw(o,{width:s,height:c,durationSeconds:l,blurhash:u,waveform:d,poster:f,summary:p,chars:m},e=>{n?.updateAttachmentProgress(t,e),bz.set(t,e),Sz()});return bz.set(t,1),Sz(),n?.updateAttachmentStatus(t,`done`,h.id,null),Cz.set(t,h.id),h.id}catch(e){bz.delete(t),Sz();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;Cz.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):yz.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=dz(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=Tz(e,r,n).then(e=>yz.has(r)?(yz.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);vz.set(r,t),t.finally(()=>vz.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&&cz(n)});function Ez(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 Dz(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function Oz(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??Cz.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!Dz(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:nE(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=fz(t.target)??document.querySelector(`jant-compose-dialog`),i=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>uz(e.body)):uz(n.body),u=n.pendingAttachments.length>0||l,d=s?.published??`Published!`,p=s?.view??`View`;u&&(f(`compose-deferred`,c),n.pendingAttachments.length>0&&(xz={clientIds:n.pendingAttachments.map(e=>e.clientId),baseMsg:c},Sz()));let m=(e,t=`success`)=>{if(xz){for(let e of xz.clientIds)bz.delete(e);xz=null}u?v(`compose-deferred`,e,t):a(e,t)},g=()=>{!i||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},_=()=>{!i||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||i)){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=>{_(),await b(),m(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{h(e,`success`,t)},ee=()=>!i||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||o(`/`)),!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=>vz.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!Cz.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,a=(await Promise.all(e.map(async e=>{let n=e.body;if(uz(n))try{let e=await xw(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>Ez(e,Oz(e,c))),o={posts:a};te&&n.editPostId&&(o.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(o)});if(!l.ok){if(n.status===`published`&&!re){let e={posts:a.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(),m(e);return}}await x(w(await fe(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),m(e);return}let u=await fe(l),f=w(u,`status`),h=w(u,`permalink`),_=w(u,`toast`);f===`published`?(y(),i?(await S(),g(),m(d)):(C(d,h?{label:p,href:h}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),m(_??`Draft saved.`),kz(r,`draft`));return}let u=Oz(n,c);if(l)try{let e=await xw(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let f=te?`/api/posts/${n.editPostId}`:`/compose`,h=te?`PUT`:`POST`,_=Ez({...n,status:re?`draft`:n.status},u),v=await fetch(f,{method:h,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(f,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await fe(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),m(n);let r=w(e,`toast`);r&&m(r);return}}await x(w(await fe(v),`error`)??`Something went wrong`);return}if(te){y();let e=await fe(v),t=n.editPostId??``,r=w(e,`slug`),a=r?o(`/${r}`):null;if(i)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await gz(t)?m(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`)){if(a&&a!==globalThis.location.pathname){C(`Post updated.`),globalThis.location.assign(a);return}await gz(t)?m(`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 mz(e):await hz(t))?m(`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(),m(e);return}let b=await fe(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),i)await S(),g(),m(d);else if(n.replyToId){if(await S(),!await _z(n)){C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}m(d)}else C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),m(oe??`Draft saved.`),kz(r,`draft`)}catch{await x(`Something went wrong`)}});function kz(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var Az=`.compose-prompt`,jz=`.compose-prompt-trigger`,Mz=`jant.composeOpenShortcutDiscovery`,Nz=`/api/settings/discovery/compose-open-shortcut`,Pz=350,Fz=1800,Iz=3,Lz=`compose-prompt-discovery-visible`,Rz=!1,zz=null,Bz=null,Vz=null;function Hz(){try{return globalThis.localStorage!==void 0}catch{return!1}}function Uz(){if(!Hz())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(Mz);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(Mz),{shownCount:0,completed:!1}}}function Wz(e){if(Hz())try{globalThis.localStorage.setItem(Mz,JSON.stringify(e))}catch{}}function Gz(){zz!==null&&(clearTimeout(zz),zz=null)}function Kz(){Bz!==null&&(clearTimeout(Bz),Bz=null)}function qz(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function Jz(e){return Uz().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function Yz(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Lz)),document.querySelectorAll(Az).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Lz)})}function Xz(){let e=Uz();e.completed||Rz||e.shownCount>=Iz||(Rz=!0,Wz({...e,shownCount:e.shownCount+1}))}function Zz(e){return!qz()||Jz(e)?!1:Uz().shownCount<Iz||Rz}function Qz(e){Gz(),Kz(),e?e.classList.remove(Lz):Vz&&Vz.classList.remove(Lz),(!e||e===Vz)&&(Vz=null)}function $z(e){Zz(e)&&(Qz(Vz),Vz=e,e.classList.add(Lz),Xz(),Bz=setTimeout(()=>{Qz(e)},Fz))}function eB(e){Zz(e)&&(e.classList.contains(Lz)||(Gz(),zz=setTimeout(()=>{$z(e)},Pz)))}function tB(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(jz);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{eB(e)}),t.addEventListener(`pointerleave`,()=>{Qz(e)}),t.addEventListener(`focusin`,()=>{eB(e)}),t.addEventListener(`focusout`,()=>{Qz(e)}))}function nB(e=document){e.querySelectorAll(Az).forEach(e=>tB(e))}function rB(){let e=Uz();e.completed||Wz({shownCount:Math.max(e.shownCount,Iz),completed:!0}),Yz(Vz),Qz(Vz),typeof globalThis.fetch==`function`&&globalThis.fetch(Nz,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{nB()}):nB(),document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{});var iB=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function aB(e){return e instanceof globalThis.Element&&e.closest(iB)!==null}function oB(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!nz()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return aB(e.target)||t!==e.target&&aB(t)}async function sB(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`||oB(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),rB();let n=rz(),r=t===`l`?`link`:t===`q`?`quote`:void 0;sz({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=iz();if(n){if(t===`r`){e.preventDefault(),cz(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=nz();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(),sB(t,!n.hasAttribute(`data-post-featured`),n);return}}});var cB=[`en`,`zh-Hans`,`zh-Hant`];function lB(e){return typeof e==`string`&&cB.includes(e)}function uB(e){let t=e.trim();if(!t)return`en`;let n;try{n=new Intl.Locale(t)}catch{return`en`}if(lB(n.baseName))return n.baseName;if(n.language===`zh`){let e=n.region;return n.script===`Hant`||e===`TW`||e===`HK`||e===`MO`?`zh-Hant`:`zh-Hans`}return`en`}var dB={en:1,"zh-Hans":1,"zh-Hant":1},fB=`en.zh-Hans.zh-Hant.ja.ko.es.fr.de.it.pt.ru.ar.hi.bn.ur.tr.vi.th.id.fa.he.nl.pl.sv.da.no.fi.cs.hu.el.ro.uk.en-GB.en-US.fr-CA.pt-BR.es-MX`.split(`.`),pB=null;function mB(e){let t=e,n=e;try{let n=new Intl.DisplayNames([e],{type:`language`}).of(e);typeof n==`string`&&n.length>0&&(t=n)}catch{}try{let t=new Intl.DisplayNames([`en`],{type:`language`}).of(e);typeof t==`string`&&t.length>0&&(n=t)}catch{}return{tag:e,native:t,english:n,coverage:hB(e)}}function hB(e){let t=uB(e);if(t===`en`){let t;try{t=new Intl.Locale(e).language}catch{return 0}if(t!==`en`)return 0}return dB[t]}function gB(){return pB||(pB=fB.map(mB),pB)}function _B(e){let t=e.trim();return gB().find(e=>e.tag===t)||mB(t)}var vB=class extends _{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},dashboardLanguages:{type:Array,attribute:`dashboard-languages`},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`},archiveFeedUrl:{type:String,attribute:`archive-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_dashboardLanguage:{state:!0},_localeOpen:{state:!0},_localeQuery:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.dashboardLanguages=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/latest/feed`,this.featuredFeedUrl=`/featured/feed`,this.archiveFeedUrl=`/archive/feed`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._dashboardLanguage=`en`,this._localeOpen=!1,this._localeQuery=``,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,dashboardLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onLocalePickerDocumentClick),document.addEventListener(`keydown`,this._onLocalePickerKeydown)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this._onLocalePickerDocumentClick),document.removeEventListener(`keydown`,this._onLocalePickerKeydown),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._dashboardLanguage=e.dashboardLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,dashboardLanguage:e.dashboardLanguage,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,dashboardLanguage:this._dashboardLanguage,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=aE({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=iE(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=aE({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=iE(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._dashboardLanguage!==this._origLocale.dashboardLanguage||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,dashboardLanguage:this._dashboardLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_filteredLocaleEntries(){let e=gB(),t=this._localeQuery.trim().toLowerCase();return t?e.filter(e=>e.tag.toLowerCase().includes(t)||e.native.toLowerCase().includes(t)||e.english.toLowerCase().includes(t)):e}_toggleLocalePicker=()=>{this._localeOpen=!this._localeOpen,this._localeOpen?this.updateComplete.then(()=>{this.querySelector(`[data-locale-search]`)?.focus()}):this._localeQuery=``};_selectLocale(e){this._siteLanguage=e,this._localeOpen=!1,this._localeQuery=``,this._syncLocaleDirty()}_onLocalePickerDocumentClick=e=>{if(!this._localeOpen)return;let t=e.target,n=this.querySelector(`[data-locale-picker]`);n&&t&&!n.contains(t)&&(this._localeOpen=!1)};_onLocalePickerKeydown=e=>{e.isComposing||e.keyCode===229||e.key===`Escape`&&this._localeOpen&&(this._localeOpen=!1,this._localeQuery=``)};_renderLanguagePicker(){let e=_B(this._siteLanguage||`en`),t=this._filteredLocaleEntries(),n=this.labels.siteLanguageSearchPlaceholder||`Search…`,r=this.labels.siteLanguageNoMatches||`No matches.`;return u`
|
|
2198
|
+
`+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 PR;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=Ak(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&WM(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??uR,s=await mR(_,{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 bR(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 OR({format:new tR,target:new qL}),n=new bR(c);t.addVideoTrack(n),await t.start();let r=await new fN(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 pN(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new VM(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 VM(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(U(c!==null),U(r!==void 0),await l(Math.floor(c*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let n=new fN(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{U(i),U(r!==void 0);let o=Math.round((n-a)*r);for(let n=1;n<o;n++)i.setTimestamp(a+n/r),i.setDuration(1/r),await this._registerVideoSample(e,t,m,i);i.close()};for await(let c of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){c.close(),i?.close();return}let n=Math.max(c.timestamp-this._startTimestamp,0);if(o=n+c.duration,r!==void 0){let e=Math.floor(n*r)/r;if(i!==null)if(e<=a){i.close(),i=c,a=e;continue}else await s(e);n=e,c.setDuration(1/r)}c.setTimestamp(n),await this._registerVideoSample(e,t,m,c),r===void 0?c.close():(i=c,a=n)}i&&(U(o!==null),U(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new _R(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new oN(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:gA(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 VM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new VM(e):new VM(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 SR(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new oN(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}let n=null;t.codec&&(u=u.filter(e=>e===t.codec));let i=t.bitrate??uR,a=await pR(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>JA.includes(e))&&u.some(e=>JA.includes(e))&&(s!==jR||c!==MR)){let e=(await pR(u,{numberOfChannels:jR,sampleRate:MR,bitrate:i})).find(e=>JA.includes(e));e&&(l=!0,n=e,s=jR,c=MR)}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 wR({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new gN(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:gA(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 XM))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 wR({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new LR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new gN(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=uA(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},PR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},FR=5,IR=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<FR&&(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()>=FR}wait(e){let{promise:t,resolve:n}=$k();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},LR=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){U(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+a,this.endTime-this.startTime),s=Math.floor(i*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;U(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new XM({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 RR(){return typeof AudioEncoder<`u`}async function zR(e,t){let n=new TF({source:new xF(e),formats:yF}),r=new KL,i=new OR({format:new tR({fastStart:`in-memory`}),target:r});try{let a=await NR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:uR}});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 BR={isSupported:RR,processToFile:zR},VR=new Set([`moov`,`trak`]);function HR(e){return 12+(e===1?32:20)+8+2}function UR(e){let t=new DataView(e),n=(e,r)=>{let i=e;for(;i+8<=r;){let e=t.getUint32(i),a=String.fromCharCode(t.getUint8(i+4),t.getUint8(i+5),t.getUint8(i+6),t.getUint8(i+7));if(e===0&&(e=r-i),e<8||i+e>r)break;if(a===`tkhd`){let n=t.getUint8(i+8),r=i+HR(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else VR.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var WR=1920,GR=1080,KR=640,qR=32;function JR(){return typeof VideoEncoder<`u`}async function YR(e){let t=new TF({source:new xF(e),formats:yF});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=l(a),s=Math.min(a*.1,1),c=await new pN(e).getCanvas(s);if(!c)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=c.canvas,d=u.width,f=u.height,p=Math.min(KR/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(qR/d,qR/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 XR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await YR(e),c=i||WR,l=a||GR;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(WR/e,GR/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new TF({source:new xF(e),formats:yF}),d=new KL,f=new OR({format:new tR({fastStart:`in-memory`}),target:d});try{let i=await NR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:uR},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);UR(a);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ez(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&($R(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ez(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var ZR=[65536,0,0,0,65536,0,0,0,1073741824];function QR(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`)&&QR(e,i+8,i+t,r),i+=t}}function $R(e){let t=new DataView(e);QR(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)!==ZR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,ZR[e])})}function ez(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 tz={isSupported:JR,processToFile:XR};function nz(){return document.querySelector(`jant-compose-dialog`)}function rz(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function iz(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 az(e){let t=e.querySelector(`.thread-group-detail[data-page='post']`);if(!t)return null;let n=t.querySelectorAll(`.thread-detail-item article[data-post]`);return n.length>0?n.item(n.length-1):null}function oz(e=document){let t=az(e);if(t)return t;if(e===document){let e=document.querySelector(`[data-page='post'] article[data-post]:hover`);if(e)return e}return iz(e)}function sz(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 cz(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}async function lz(e){await nz()?.openNew(e)}async function uz(e){let t=e.dataset.postId;if(!t)return;let n=nz();if(!n)return;let r=e.dataset.threadRootId??t;await n.openReply(t,cz(e),r,sz(e)??void 0)}function dz(e){b(e),S(e),C(e)}function fz(e){try{return Sw(JSON.parse(e))}catch{return!1}}function pz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function mz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function hz(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function gz(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 hz(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,dz(t),!0):!1}catch{return!1}}async function _z(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await hz(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,dz(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&&dz(i),!0}catch{return!1}}async function vz(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await hz(`/_/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&&dz(r),!0}catch{return!1}}async function yz(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?gz(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?vz(e.replyRefreshId):_z(e.replyRefreshId)}var bz=new Map,xz=new Set,Sz=new Map,Cz=null;function wz(){if(!Cz)return;let{clientIds:e,baseMsg:t}=Cz;if(e.length===0)return;let n=0,r=0;for(let t of e){let e=Sz.get(t)??0;n+=Math.min(1,Math.max(0,e)),e>=1&&(r+=1)}let i=e.length,a=Math.floor(n/i*100),o=Math.min(r+1,i);g(`compose-deferred`,i===1?`${t} ${a}%`:`${t} ${a}% ${o}/${i}`)}var Tz=new Map;function Ez(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 Dz(e,t,n){let r=e.type,i=e.name;try{let o,s,c,l,u,d,f;if(r.startsWith(`video/`)){if(!tz.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;Ez(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let r=await tz.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});o=r.file,e=null,s=r.width,c=r.height,l=r.durationSeconds,u=r.blurhash,f=r.poster,f&&n?.updateAttachmentPoster(t,f)}else if(r.startsWith(`audio/`)){if(!BR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{d=await ZC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),o=(await BR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file,e=null}else if(r.startsWith(`image/`)||/\.heic$/i.test(i)||/\.heif$/i.test(i)){let r=e;try{let{isHeic:a,heicTo:l}=await Sk(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(r)){n?.updateAttachmentStatus(t,`processing`,null,null);let e=await l({blob:r,type:`image/jpeg`,quality:.92});r=new File([e],i.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,r)}let u=await oe.processToFile(r);o=u.file,s=u.width,c=u.height,e=null,r=null}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else o=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!r.startsWith(`video/`)){let e=await QC(o);s??=e.width,c??=e.height,u??=e.blurhash,d??=e.waveform,!f&&e.poster&&(f=e.poster,n?.updateAttachmentPoster(t,f))}let p,m;if(TS(r)===`text`)try{let e=await o.text(),t=e.replace(/\s+/g,` `).trim();m=e.length,p=t.length<=100?t:t.slice(0,100)+`…`}catch{}Sz.set(t,0),wz();let h=await uw(o,{width:s,height:c,durationSeconds:l,blurhash:u,waveform:d,poster:f,summary:p,chars:m},e=>{n?.updateAttachmentProgress(t,e),Sz.set(t,e),wz()});return Sz.set(t,1),wz(),n?.updateAttachmentStatus(t,`done`,h.id,null),Tz.set(t,h.id),h.id}catch(e){Sz.delete(t),wz();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;Tz.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):xz.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=pz(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=Dz(e,r,n).then(e=>xz.has(r)?(xz.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);bz.set(r,t),t.finally(()=>bz.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&&uz(n)});function Oz(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 kz(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function Az(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??Tz.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!kz(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:nE(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=mz(t.target)??document.querySelector(`jant-compose-dialog`),i=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>fz(e.body)):fz(n.body),u=n.pendingAttachments.length>0||l,d=s?.published??`Published!`,p=s?.view??`View`;u&&(f(`compose-deferred`,c),n.pendingAttachments.length>0&&(Cz={clientIds:n.pendingAttachments.map(e=>e.clientId),baseMsg:c},wz()));let m=(e,t=`success`)=>{if(Cz){for(let e of Cz.clientIds)Sz.delete(e);Cz=null}u?v(`compose-deferred`,e,t):a(e,t)},g=()=>{!i||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},_=()=>{!i||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||i)){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=>{_(),await b(),m(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{h(e,`success`,t)},ee=()=>!i||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||o(`/`)),!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=>bz.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!Tz.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,a=(await Promise.all(e.map(async e=>{let n=e.body;if(fz(n))try{let e=await xw(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>Oz(e,Az(e,c))),o={posts:a};te&&n.editPostId&&(o.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(o)});if(!l.ok){if(n.status===`published`&&!re){let e={posts:a.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(),m(e);return}}await x(w(await fe(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),m(e);return}let u=await fe(l),f=w(u,`status`),h=w(u,`permalink`),_=w(u,`toast`);f===`published`?(y(),i?(await S(),g(),m(d)):(C(d,h?{label:p,href:h}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),m(_??`Draft saved.`),jz(r,`draft`));return}let u=Az(n,c);if(l)try{let e=await xw(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let f=te?`/api/posts/${n.editPostId}`:`/compose`,h=te?`PUT`:`POST`,_=Oz({...n,status:re?`draft`:n.status},u),v=await fetch(f,{method:h,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(f,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await fe(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),m(n);let r=w(e,`toast`);r&&m(r);return}}await x(w(await fe(v),`error`)??`Something went wrong`);return}if(te){y();let e=await fe(v),t=n.editPostId??``,r=w(e,`slug`),a=r?o(`/${r}`):null;if(i)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await vz(t)?m(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`)){if(a&&a!==globalThis.location.pathname){C(`Post updated.`),globalThis.location.assign(a);return}await vz(t)?m(`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 gz(e):await _z(t))?m(`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(),m(e);return}let b=await fe(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),i)await S(),g(),m(d);else if(n.replyToId){if(await S(),!await yz(n)){C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}m(d)}else C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),m(oe??`Draft saved.`),jz(r,`draft`)}catch{await x(`Something went wrong`)}});function jz(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var Mz=`.compose-prompt`,Nz=`.compose-prompt-trigger`,Pz=`jant.composeOpenShortcutDiscovery`,Fz=`/api/settings/discovery/compose-open-shortcut`,Iz=350,Lz=1800,Rz=3,zz=`compose-prompt-discovery-visible`,Bz=!1,Vz=null,Hz=null,Uz=null;function Wz(){try{return globalThis.localStorage!==void 0}catch{return!1}}function Gz(){if(!Wz())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(Pz);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(Pz),{shownCount:0,completed:!1}}}function Kz(e){if(Wz())try{globalThis.localStorage.setItem(Pz,JSON.stringify(e))}catch{}}function qz(){Vz!==null&&(clearTimeout(Vz),Vz=null)}function Jz(){Hz!==null&&(clearTimeout(Hz),Hz=null)}function Yz(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function Xz(e){return Gz().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function Zz(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(zz)),document.querySelectorAll(Mz).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(zz)})}function Qz(){let e=Gz();e.completed||Bz||e.shownCount>=Rz||(Bz=!0,Kz({...e,shownCount:e.shownCount+1}))}function $z(e){return!Yz()||Xz(e)?!1:Gz().shownCount<Rz||Bz}function eB(e){qz(),Jz(),e?e.classList.remove(zz):Uz&&Uz.classList.remove(zz),(!e||e===Uz)&&(Uz=null)}function tB(e){$z(e)&&(eB(Uz),Uz=e,e.classList.add(zz),Qz(),Hz=setTimeout(()=>{eB(e)},Lz))}function nB(e){$z(e)&&(e.classList.contains(zz)||(qz(),Vz=setTimeout(()=>{tB(e)},Iz)))}function rB(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(Nz);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{nB(e)}),t.addEventListener(`pointerleave`,()=>{eB(e)}),t.addEventListener(`focusin`,()=>{nB(e)}),t.addEventListener(`focusout`,()=>{eB(e)}))}function iB(e=document){e.querySelectorAll(Mz).forEach(e=>rB(e))}function aB(){let e=Gz();e.completed||Kz({shownCount:Math.max(e.shownCount,Rz),completed:!0}),Zz(Uz),eB(Uz),typeof globalThis.fetch==`function`&&globalThis.fetch(Fz,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{iB()}):iB(),document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{});var oB=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function sB(e){return e instanceof globalThis.Element&&e.closest(oB)!==null}function cB(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!nz()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return sB(e.target)||t!==e.target&&sB(t)}function lB(){return new URL(window.location.href).searchParams.get(`edit`)===`1`}function uB(){let e=new URL(window.location.href);e.searchParams.delete(`edit`);let t=e.searchParams.toString();globalThis.history.replaceState(globalThis.history.state,``,`${e.pathname}${t?`?${t}`:``}${e.hash}`)}function dB(){if(!document.body?.hasAttribute(`data-authenticated`)||!lB())return;let e=iz()?.dataset.postId,t=nz();!e||!t||(uB(),t.openEdit(e))}async function fB(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`||cB(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),aB();let n=rz(),r=t===`l`?`link`:t===`q`?`quote`:void 0;lz({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}if(t===`r`){let t=oz();if(!t)return;e.preventDefault(),uz(t);return}let n=iz();if(n){if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=nz();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(),fB(t,!n.hasAttribute(`data-post-featured`),n);return}}}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,dB,{once:!0}):dB();var pB=[`en`,`zh-Hans`,`zh-Hant`];function mB(e){return typeof e==`string`&&pB.includes(e)}function hB(e){let t=e.trim();if(!t)return`en`;let n;try{n=new Intl.Locale(t)}catch{return`en`}if(mB(n.baseName))return n.baseName;if(n.language===`zh`){let e=n.region;return n.script===`Hant`||e===`TW`||e===`HK`||e===`MO`?`zh-Hant`:`zh-Hans`}return`en`}var gB={en:1,"zh-Hans":1,"zh-Hant":1},_B=`en.zh-Hans.zh-Hant.ja.ko.es.fr.de.it.pt.ru.ar.hi.bn.ur.tr.vi.th.id.fa.he.nl.pl.sv.da.no.fi.cs.hu.el.ro.uk.en-GB.en-US.fr-CA.pt-BR.es-MX`.split(`.`),vB=null;function yB(e){let t=e,n=e;try{let n=new Intl.DisplayNames([e],{type:`language`}).of(e);typeof n==`string`&&n.length>0&&(t=n)}catch{}try{let t=new Intl.DisplayNames([`en`],{type:`language`}).of(e);typeof t==`string`&&t.length>0&&(n=t)}catch{}return{tag:e,native:t,english:n,coverage:bB(e)}}function bB(e){let t=hB(e);if(t===`en`){let t;try{t=new Intl.Locale(e).language}catch{return 0}if(t!==`en`)return 0}return gB[t]}function xB(){return vB||(vB=_B.map(yB),vB)}function SB(e){let t=e.trim();return xB().find(e=>e.tag===t)||yB(t)}var CB=class extends _{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},dashboardLanguages:{type:Array,attribute:`dashboard-languages`},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`},archiveFeedUrl:{type:String,attribute:`archive-feed-url`},aboutPage:{type:Object,attribute:`about-page`},aboutEditUrl:{type:String,attribute:`about-edit-url`},aboutCreateUrl:{type:String,attribute:`about-create-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_dashboardLanguage:{state:!0},_localeOpen:{state:!0},_localeQuery:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.dashboardLanguages=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/latest/feed`,this.featuredFeedUrl=`/featured/feed`,this.archiveFeedUrl=`/archive/feed`,this.aboutPage={state:`missing`,path:`/about`},this.aboutEditUrl=`/about?edit=1`,this.aboutCreateUrl=`/settings/general/about-page`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._dashboardLanguage=`en`,this._localeOpen=!1,this._localeQuery=``,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,dashboardLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onLocalePickerDocumentClick),document.addEventListener(`keydown`,this._onLocalePickerKeydown)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this._onLocalePickerDocumentClick),document.removeEventListener(`keydown`,this._onLocalePickerKeydown),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._dashboardLanguage=e.dashboardLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,dashboardLanguage:e.dashboardLanguage,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,dashboardLanguage:this._dashboardLanguage,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=aE({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=iE(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=aE({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=iE(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._dashboardLanguage!==this._origLocale.dashboardLanguage||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,dashboardLanguage:this._dashboardLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_filteredLocaleEntries(){let e=xB(),t=this._localeQuery.trim().toLowerCase();return t?e.filter(e=>e.tag.toLowerCase().includes(t)||e.native.toLowerCase().includes(t)||e.english.toLowerCase().includes(t)):e}_toggleLocalePicker=()=>{this._localeOpen=!this._localeOpen,this._localeOpen?this.updateComplete.then(()=>{this.querySelector(`[data-locale-search]`)?.focus()}):this._localeQuery=``};_selectLocale(e){this._siteLanguage=e,this._localeOpen=!1,this._localeQuery=``,this._syncLocaleDirty()}_onLocalePickerDocumentClick=e=>{if(!this._localeOpen)return;let t=e.target,n=this.querySelector(`[data-locale-picker]`);n&&t&&!n.contains(t)&&(this._localeOpen=!1)};_onLocalePickerKeydown=e=>{e.isComposing||e.keyCode===229||e.key===`Escape`&&this._localeOpen&&(this._localeOpen=!1,this._localeQuery=``)};_renderLanguagePicker(){let e=SB(this._siteLanguage||`en`),t=this._filteredLocaleEntries(),n=this.labels.siteLanguageSearchPlaceholder||`Search…`,r=this.labels.siteLanguageNoMatches||`No matches.`;return u`
|
|
2197
2199
|
<div class="relative w-fit max-w-full" data-locale-picker>
|
|
2198
2200
|
<button
|
|
2199
2201
|
type="button"
|
|
@@ -2312,6 +2314,35 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
2312
2314
|
</button>
|
|
2313
2315
|
</div>
|
|
2314
2316
|
</div>
|
|
2317
|
+
`}_renderAboutPageRow(){let e=this.aboutPage;return u`
|
|
2318
|
+
<div class="mt-2 text-sm text-muted-foreground" data-about-page-row>
|
|
2319
|
+
${this.labels.aboutPagePrompt}
|
|
2320
|
+
${e.state===`ready`?u`
|
|
2321
|
+
<a
|
|
2322
|
+
class="font-medium text-foreground underline-offset-4 hover:underline"
|
|
2323
|
+
href=${this.aboutEditUrl}
|
|
2324
|
+
>
|
|
2325
|
+
${this.labels.editAboutPage}
|
|
2326
|
+
</a>
|
|
2327
|
+
`:e.state===`missing`?u`
|
|
2328
|
+
<form
|
|
2329
|
+
class="inline"
|
|
2330
|
+
method="post"
|
|
2331
|
+
action=${this.aboutCreateUrl}
|
|
2332
|
+
>
|
|
2333
|
+
<button
|
|
2334
|
+
type="submit"
|
|
2335
|
+
class="inline cursor-pointer border-0 bg-transparent p-0 font-medium text-foreground underline-offset-4 hover:underline"
|
|
2336
|
+
>
|
|
2337
|
+
${this.labels.createAboutPage}
|
|
2338
|
+
</button>
|
|
2339
|
+
</form>
|
|
2340
|
+
`:u`
|
|
2341
|
+
<span class="text-destructive"
|
|
2342
|
+
>${this.labels.aboutPageConflict}</span
|
|
2343
|
+
>
|
|
2344
|
+
`}
|
|
2345
|
+
</div>
|
|
2315
2346
|
`}_renderGeneralForm(){return u`
|
|
2316
2347
|
<div class="flex flex-col gap-8">
|
|
2317
2348
|
<div>
|
|
@@ -2341,6 +2372,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
2341
2372
|
<p class="text-sm text-muted-foreground mt-1">
|
|
2342
2373
|
${this.labels.aboutBlogHelp}
|
|
2343
2374
|
</p>
|
|
2375
|
+
${this._renderAboutPageRow()}
|
|
2344
2376
|
</div>
|
|
2345
2377
|
|
|
2346
2378
|
<div class="field">
|
|
@@ -2516,7 +2548,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
2516
2548
|
<div class="flex flex-col">
|
|
2517
2549
|
${this._renderGeneralForm()} ${this._renderSearchForm()}
|
|
2518
2550
|
</div>
|
|
2519
|
-
`}};customElements.define(`jant-settings-general`,
|
|
2551
|
+
`}};customElements.define(`jant-settings-general`,CB);var wB=class extends _{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}removeError(){this._removeLoading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}async _removeAvatar(){await De({message:this.labels.confirmRemoveAvatar,confirmLabel:this.labels.remove,cancelLabel:this.labels.cancel,tone:`danger`})&&(this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}}))))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?u`
|
|
2520
2552
|
<div class=${e}>
|
|
2521
2553
|
<img
|
|
2522
2554
|
src=${this.avatarUrl}
|
|
@@ -2624,7 +2656,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
2624
2656
|
</div>
|
|
2625
2657
|
</div>
|
|
2626
2658
|
</div>
|
|
2627
|
-
`}};customElements.define(`jant-settings-avatar`,
|
|
2659
|
+
`}};customElements.define(`jant-settings-avatar`,wB);function TB(e){let t=w(e,`siteName`),n=w(e,`siteDescription`),r=w(e,`siteLanguage`),i=w(e,`dashboardLanguage`)??``,a=w(e,`cjkSerifFont`),o=w(e,`mainRssFeed`),s=w(e,`timeZone`),c=w(e,`siteFooter`),l=ue(e,`showJantBrandingOnHome`),u=ue(e,`noindex`);return t===void 0||n===void 0||r===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,dashboardLanguage:i,cjkSerifFont:a,mainRssFeed:o,timeZone:s,siteFooter:c,showJantBrandingOnHome:l,noindex:u}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),o=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n)});if(!e.ok)throw Error(`HTTP ${e.status}`);let s=await fe(e),c=w(s,`status`),l=w(s,`url`),u=w(s,`toast`);if(c===`redirect`&&l){window.location.href=l;return}u&&a(u),r===`avatar-display`?o?.saved():i?.sectionSaved(r)}catch{a(`Failed to save. Please try again.`,`error`),r===`avatar-display`?o?.saveError():i?.sectionError(r)}}),document.addEventListener(`jant:avatar-remove`,async e=>{let{endpoint:t}=e.detail,n=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await fe(e),r=w(n,`status`),i=w(n,`url`);if(r===`redirect`&&i){window.location.href=i;return}}catch{a(`Failed to remove avatar. Please try again.`,`error`),n?.removeError()}});function EB(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=TB(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,EB):queueMicrotask(EB);var DB=300,OB=1,kB=class extends _{static properties={labels:{type:Object},apiBase:{type:String,attribute:`api-base`},connectUrl:{type:String,attribute:`connect-url`},installUrl:{type:String,attribute:`install-url`},cancelUrl:{type:String,attribute:`cancel-url`},createRepoNameHint:{type:String,attribute:`create-repo-name-hint`},_installations:{state:!0},_selectedOwner:{state:!0},_ownerOpen:{state:!0},_repos:{state:!0},_totalCount:{state:!0},_hasMore:{state:!0},_nextPage:{state:!0},_reposMode:{state:!0},_repoOpen:{state:!0},_repoSearch:{state:!0},_loadingRepos:{state:!0},_selectedRepo:{state:!0},_classification:{state:!0},_classifying:{state:!0},_confirmText:{state:!0},_connecting:{state:!0},_error:{state:!0}};#e=null;#t=0;#n=!1;#r=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.apiBase=``,this.connectUrl=``,this.installUrl=``,this.cancelUrl=``,this.createRepoNameHint=``,this._installations=[],this._selectedOwner=null,this._ownerOpen=!1,this._repos=[],this._totalCount=0,this._hasMore=!1,this._nextPage=null,this._reposMode=`list`,this._repoOpen=!1,this._repoSearch=``,this._loadingRepos=!1,this._selectedRepo=null,this._classification=null,this._classifying=!1,this._confirmText=``,this._connecting=!1,this._error=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#m),document.addEventListener(`keydown`,this.#h),window.addEventListener(`focus`,this.#g),this.#i()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#m),document.removeEventListener(`keydown`,this.#h),window.removeEventListener(`focus`,this.#g),this.#e&&clearTimeout(this.#e)}async#i(){try{let e=await fetch(`${this.apiBase}/installations`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._installations=t.installations;let n=t.installations.length===1?t.installations[0]:null;n&&this.#u(n)}catch(e){this._error=e instanceof Error?e.message:String(e)}}async#a(e,t={}){let n=++this.#t;this._loadingRepos=!0;try{let r=new URLSearchParams({installationId:e});t.q&&r.set(`q`,t.q);let i=await fetch(`${this.apiBase}/repos?${r.toString()}`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(n!==this.#t)return;if(i.status===410){this._installations=this._installations.filter(t=>t.installationId!==e),this._selectedOwner=null,this._repos=[];return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let a=await i.json();this._repos=a.repos,this._totalCount=a.totalCount,this._hasMore=a.hasMore,this._nextPage=a.nextPage,this._reposMode=a.mode}catch(e){n===this.#t&&(this._error=e instanceof Error?e.message:String(e))}finally{n===this.#t&&(this._loadingRepos=!1)}}async#o(e,t){this._classifying=!0,this._classification=null,this._confirmText=``;try{let n=await fetch(`${this.apiBase}/classify`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:e,repo:t})}),r=await n.json();if(!n.ok||!r.classification)throw Error(r.error??`HTTP ${n.status}`);this._classification=r.classification}catch(e){this._error=e instanceof Error?e.message:String(e)}finally{this._classifying=!1}}async#s(){if(!(!this._selectedOwner||!this._selectedRepo||!this._classification)){this._connecting=!0,this._error=null;try{let e=this._classification.kind===`foreign`||this._classification.kind===`owned-by-other-site`,t=await fetch(this.connectUrl,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:this._selectedOwner.installationId,repo:this._selectedRepo.fullName,confirmForeign:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw Error(n.error??`HTTP ${t.status}`);window.location.href=n.redirect??this.cancelUrl}catch(e){this._error=e instanceof Error?e.message:String(e),this._connecting=!1}}}#c(){let e=this._selectedOwner;if(!e)return;let t=this.createRepoNameHint||``,n=new URL(`https://github.com/new`);t&&n.searchParams.set(`name`,t),n.searchParams.set(`owner`,e.account.login),n.searchParams.set(`visibility`,`private`),this.#n=!0,this.#r=t||null,window.open(n.toString(),`_blank`,`noopener,noreferrer`),this._repoOpen=!1}#l(){if(!this._selectedOwner)return;let e=this._repoSearch.trim();this.#a(this._selectedOwner.installationId,e?{q:e}:{})}#u(e){if(this._selectedOwner?.installationId===e.installationId){this._ownerOpen=!1;return}this._selectedOwner=e,this._ownerOpen=!1,this._selectedRepo=null,this._classification=null,this._confirmText=``,this._repoSearch=``,this.#a(e.installationId)}#d(e){this._selectedRepo=e,this._repoOpen=!1,this._repoSearch=``,this._selectedOwner&&this.#o(this._selectedOwner.installationId,e.fullName)}#f(e){let t=e.target.value;if(this._repoSearch=t,this.#e&&clearTimeout(this.#e),!this._selectedOwner)return;let n=t.trim();if(n.length<OB){this._reposMode===`search`&&this.#a(this._selectedOwner.installationId);return}this.#e=setTimeout(()=>{this._selectedOwner&&this.#a(this._selectedOwner.installationId,{q:n})},DB)}#p(){let e=this._repoSearch.trim().toLowerCase();return!e||this._reposMode===`search`?this._repos:this._repos.filter(t=>t.name.toLowerCase().includes(e)||t.fullName.toLowerCase().includes(e))}#m=e=>{if(!this._ownerOpen&&!this._repoOpen)return;let t=e.target,n=this.querySelector(`.repo-picker-owner`),r=this.querySelector(`.repo-picker-repo`);n&&!n.contains(t)&&(this._ownerOpen=!1),r&&!r.contains(t)&&(this._repoOpen=!1)};#h=e=>{e.key===`Escape`&&(e.isComposing||e.keyCode===229||(this._ownerOpen||this._repoOpen)&&(this._ownerOpen=!1,this._repoOpen=!1))};#g=()=>{if(!this.#n)return;let e=this._selectedOwner;if(!e){this.#n=!1;return}let t=this.#r;this.#n=!1,this.#r=null,(async()=>{if(this._repoSearch=``,await this.#a(e.installationId),t){let e=this._repos.find(e=>e.name===t);e&&this.#d(e)}})()};#_(){this._ownerOpen=!this._ownerOpen,this._repoOpen=!1}#v(){this._selectedOwner&&(this._repoOpen=!this._repoOpen,this._ownerOpen=!1,this._repoOpen&&queueMicrotask(()=>{this.querySelector(`.repo-picker-repo-search`)?.focus()}))}render(){return u`
|
|
2628
2660
|
<div class="flex flex-col gap-6 max-w-lg">
|
|
2629
2661
|
<div>
|
|
2630
2662
|
<h2 class="text-lg font-medium mb-1">${this.labels.pageTitle}</h2>
|
|
@@ -2835,7 +2867,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
2835
2867
|
</button>
|
|
2836
2868
|
<a href=${this.cancelUrl} class="btn-ghost">${this.labels.cancel}</a>
|
|
2837
2869
|
</div>
|
|
2838
|
-
`}};customElements.define(`jant-repo-picker`,
|
|
2870
|
+
`}};customElements.define(`jant-repo-picker`,kB);var AB=`/collections`;function jB(e){return e.includes(`+`)}function MB(){return AB}function NB(e){return`/${e}`}function PB(e){return jB(e)?`${AB}/${e}`:NB(e)}function FB(e){return`${AB}/${e}/edit`}var IB,LB;function RB(){return IB?Promise.resolve(IB):(LB||=Sk(()=>import(`./chunks/url-pLre2DM_.js`).then(e=>e.i).then(e=>(IB=e.slugify,e.slugify)),[]),LB)}async function zB(e){return(await RB())(e)}var BB=class extends _{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;_descEditor=null;#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t=e=>{e.isComposing||e.keyCode===229||(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),this.#f(e))},this.addEventListener(`keydown`,this.#t)}disconnectedCallback(){this.#t&&=(this.removeEventListener(`keydown`,this.#t),null),super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null}update(e){(!this.#e||e.has(`initial`))&&this.#n(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#n(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`,this.variant!==`quick`&&this.updateComplete.then(()=>this.#r()))}#r(){let e=this.querySelector(`[data-collection-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=aE({element:e,placeholder:this.isEdit?void 0:this.labels.descriptionPlaceholder,content:this._description||void 0,onUpdate:e=>{this._description=e}}),this._description=iE(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`5rem`)}async#i(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=PS(await zB(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#a(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#o(){let e=FS(this._slug,{maxLength:200});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#s(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#c(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#l(){let e=o(NB(this._slug.trim()||`example`)),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}#u(){let e=this.#o();return e?u`<p
|
|
2839
2871
|
class="text-xs text-destructive mt-1"
|
|
2840
2872
|
data-collection-slug-error
|
|
2841
2873
|
>
|
|
@@ -2892,7 +2924,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
2892
2924
|
</button>
|
|
2893
2925
|
</div>
|
|
2894
2926
|
</div>
|
|
2895
|
-
`}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=PS(await
|
|
2927
|
+
`}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=PS(await zB(t),200),this._slug=n,this._suggestedSlug=n),!n||this.#o()){this.variant===`quick`&&!this._showSlugEditor&&this.#s(),this.updateComplete.then(()=>{this.querySelector(`[data-collection-slug-input]`)?.focus()});return}let r={endpoint:this.action,isEdit:this.isEdit,data:{title:t,slug:n,description:this.variant===`quick`?void 0:this._description.trim()||void 0,sortOrder:this.variant===`quick`?void 0:this._sortOrder||void 0}};this.dispatchEvent(new CustomEvent(`jant:collection-submit`,{bubbles:!0,detail:r}))}render(){let e=this.variant===`quick`;return u`
|
|
2896
2928
|
<form
|
|
2897
2929
|
class=${e?`flex flex-col gap-4`:`collection-editor-form`}
|
|
2898
2930
|
@submit=${e=>void this.#f(e)}
|
|
@@ -3007,20 +3039,20 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3007
3039
|
</div>
|
|
3008
3040
|
`}
|
|
3009
3041
|
</form>
|
|
3010
|
-
`}};customElements.define(`jant-collection-form`,
|
|
3011
|
-
`;default:return(e.content??[]).map(GB).join(``)}}function KB(e,t,n){let r=WB(t.attrs,`colspan`),i=WB(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function qB(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var JB=null;function YB(e,t){let n=ax(UB(e.attrs,`label`)),r=lx(n),i=JB?.get(n),a=i?qB(t.renderChildren(i.content)):``;return`<label for="sn-${mx(r)}" class="margin-toggle sidenote-number footref"></label><input type="checkbox" id="sn-${mx(r)}" class="margin-toggle footref-toggle"/><span class="sidenote">${a}</span>`}var XB={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=mx(t(UB(n.attrs,`href`))),i=UB(n.attrs,`target`);return`<a href="${r}"${i?` target="${mx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},ZB={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=ax(UB(e.attrs,`label`));t&&r.set(t,e)}JB=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{JB=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(WB(e.attrs,`level`)??1,1),6);return`<h${n}>${t.renderChildren(e.content)}</h${n}>`},text:(e,t)=>t.renderText(e.text??``,e.marks),bulletList:(e,t)=>`<ul>${t.renderChildren(e.content)}</ul>`,orderedList:(e,t)=>{let n=WB(e.attrs,`start`);return`<ol${n!==null&&n!==1?` start="${n}"`:``}>${t.renderChildren(e.content)}</ol>`},listItem:(e,t)=>`<li>${t.renderChildren(e.content)}</li>`,blockquote:(e,t)=>`<blockquote>${t.renderChildren(e.content)}</blockquote>`,codeBlock:e=>{let t=UB(e.attrs,`language`);return`<pre><code${t?` class="language-${mx(t)}"`:``}>${GB(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>KB(`td`,e,t),tableHeader:(e,t)=>KB(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>_x(e.attrs??{}),embed:e=>HB(e.attrs),htmlBlock:e=>{let t=UB(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>YB(e,t),footnoteDefinition:()=>``};function QB(e,t=[]){let n=mx(e);for(let e of t){let t=XB[e.type];t&&(n=t(n,e))}return n}function $B(e=[]){return e.map(tV).join(``)}function eV(e,t){return e.content?t.renderChildren(e.content):``}function tV(e){return(ZB[e.type]??eV)(e,nV)}var nV={renderChildren:$B,renderNode:tV,renderText:QB};function rV(e){return e.type===`doc`?tV(fx(e)):``}function iV(e){return e.trim()?rV(qx(e)):``}function aV(){return Math.floor(Date.now()/1e3)}function oV(e){return new Date(e*1e3).toISOString()}function sV(e,t=`UTC`){let n=aV()-e;if(n<60)return`1m`;let r=Math.floor(n/60);if(r<60)return`${r}m`;let i=Math.floor(n/3600);if(i<24)return`${i}h`;let a=Math.floor(n/86400);return a<=7?`${a}d`:new Date(e*1e3).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,timeZone:t})}function cV(e,t=`UTC`){let n=sV(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var lV=class extends _{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#v();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#_();break;case`divider`:this.#x();break;case`link`:this.#S();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#d()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#d(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#f(e){return this.#r?.querySelector(e)??null}#p(){let e=this.#f(`[data-collections-action="done"]`);e&&(e.hidden=!this._reorderMode);let t=this.#f(`[data-collections-reorder-actions]`);t&&(t.hidden=!this._reorderMode);let n=this.#f(`[data-collections-toolbar]`);n&&(n.hidden=this._reorderMode);let r=this.#f(`[data-collections-hint]`);r&&(r.hidden=!this._reorderMode);let i=this.#f(`[data-collections-more-menu]`);i&&(i.hidden=!this._showMoreMenu||this._reorderMode);let a=this.#f(`[data-collections-action="toggle-menu"]`);a&&a.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#m(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#h(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#m(t)}catch{}}#g(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...WO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{JO(e,!0)},onStart:e=>{this.#n=KO(e)},onUnchoose:()=>{JO(e,!1)},onEnd:t=>{let n=GO(e,`[data-directory-item]`,`directoryItem`);qO(e,t,this.#n),this.#n=null,JO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:o}=YO(n,t.newIndex);if(!r)return;let s=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>s.get(e)).filter(e=>e!==void 0),fetch(`/api/collections/directory-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:o??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)})}}))}#_(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#v(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#d(),this.#p(),this._reorderMode&&this.#g(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#y()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#b()}#y(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=aE({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=iE(this.#i.getJSON()))}#b(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=aE({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=iE(this.#a.getJSON()))}async#x(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#h(),this._editingDividerId=t.id}catch{a(this.labels.saveFailed,`error`)}}#S(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#C(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=this._newLinkDescription.trim()||null,r=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,description:n})});if(!r.ok)throw Error(`HTTP ${r.status}`);this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,a(this.labels.linkCreated),await this.#h()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#w(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{a(this.labels.saveFailed,`error`)}}async#T(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#E(e){if(await De({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(this.labels.deleted),await this.#h()}catch{a(this.labels.saveFailed,`error`)}}}#D(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#O(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){a(this.labels.labelAndUrlRequired,`error`);return}try{let r=this._editLinkDescription.trim()||null,i=await fetch(`/api/collections/directory-items/${e.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,url:n,description:r})});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();this._items=this._items.map(r=>r.id===e.id?{...r,label:o.label??t,url:o.url??n,description:o.description??null}:r),this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkSaved)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#k(e){if(await De({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{a(this.labels.saveFailed,`error`)}}}#A(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#j(e,t){let n=e.collection;if(!n)return m;let r=u`
|
|
3042
|
+
`}};customElements.define(`jant-collection-form`,BB);function VB(e,t){let n=e[t];if(!n||n.type!==`divider`||!n.label)return null;let r=[];for(let n=t+1;n<e.length;n+=1){let t=e[n];if(!t||t.type===`divider`)break;let i=t.collection?.slug;i&&r.push(i)}return r.length<2?null:{slugExpression:r.join(`+`),collectionCount:r.length}}function HB(e){return typeof e==`string`?e:``}function UB(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function WB(e){let n=mx(t(e.src));if(!n)return``;let r=` sandbox="${mx(e.sandbox)}"`,i=e.allow?` allow="${mx(e.allow)}"`:``;return`<iframe src="${n}"${` title="${mx(e.providerName)} embed"`}${r}${i} loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`}function GB(e){let t=e.orientation===`portrait`?`portrait`:e.orientation===`square`?`square`:e.orientation===`auto`?`auto`:`landscape`,n=[];e.heightPx&&e.heightPx>0&&n.push(`--tiptap-embed-height:${Math.round(e.heightPx)}px`);let r=n.length>0?` style="${mx(n.join(`;`))}"`:``;return` data-orientation="${mx(t)}"${r}`}function KB(e,n){let r=WB(e);if(!r)return``;let i=mx(t(e.url||e.src)),a=mx(e.providerName),o=i?`<a class="tiptap-embed-fallback" href="${i}" target="_blank" rel="noopener noreferrer">${a} →</a>`:``,s=mx(e.provider),c=n?.trim()?`<figcaption>${mx(n.trim())}</figcaption>`:``;return`<figure class="tiptap-embed-figure" data-provider="${s}"${GB(e)}><div class="tiptap-embed-frame">${r}</div>`+o+c+`</figure>`}function qB(e){let n=e??{},r=HB(n.url),i=HB(n.src),a=null;if(i){let e=t(i);e&&(a={provider:HB(n.provider)||`iframe`,providerName:HB(n.providerName)||`Embed`,src:e,url:r||e,orientation:HB(n.orientation)||`landscape`,heightPx:UB(n.heightPx)??void 0,sandbox:HB(n.sandbox)||`allow-scripts allow-same-origin allow-popups`,allow:HB(n.allow)||void 0,cspFrameSrc:[],cspScriptSrc:[]})}if(!a&&r&&(a=nC(r)),!a){if(!r)return``;let e=mx(t(r));return e?`<p class="tiptap-embed-fallback"><a href="${e}" target="_blank" rel="noopener noreferrer">${e}</a></p>`:``}return KB(a,HB(n.caption))}function JB(e,t){let n=e?.[t];return typeof n==`string`?n:``}function YB(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function XB(e){switch(e.type){case`text`:return mx(e.text??``);case`hardBreak`:return`
|
|
3043
|
+
`;default:return(e.content??[]).map(XB).join(``)}}function ZB(e,t,n){let r=YB(t.attrs,`colspan`),i=YB(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function QB(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var $B=null;function eV(e,t){let n=ax(JB(e.attrs,`label`)),r=lx(n),i=$B?.get(n),a=i?QB(t.renderChildren(i.content)):``;return`<label for="sn-${mx(r)}" class="margin-toggle sidenote-number footref"></label><input type="checkbox" id="sn-${mx(r)}" class="margin-toggle footref-toggle"/><span class="sidenote">${a}</span>`}var tV={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=mx(t(JB(n.attrs,`href`))),i=JB(n.attrs,`target`);return`<a href="${r}"${i?` target="${mx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},nV={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=ax(JB(e.attrs,`label`));t&&r.set(t,e)}$B=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{$B=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(YB(e.attrs,`level`)??1,1),6);return`<h${n}>${t.renderChildren(e.content)}</h${n}>`},text:(e,t)=>t.renderText(e.text??``,e.marks),bulletList:(e,t)=>`<ul>${t.renderChildren(e.content)}</ul>`,orderedList:(e,t)=>{let n=YB(e.attrs,`start`);return`<ol${n!==null&&n!==1?` start="${n}"`:``}>${t.renderChildren(e.content)}</ol>`},listItem:(e,t)=>`<li>${t.renderChildren(e.content)}</li>`,blockquote:(e,t)=>`<blockquote>${t.renderChildren(e.content)}</blockquote>`,codeBlock:e=>{let t=JB(e.attrs,`language`);return`<pre><code${t?` class="language-${mx(t)}"`:``}>${XB(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>ZB(`td`,e,t),tableHeader:(e,t)=>ZB(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>_x(e.attrs??{}),embed:e=>qB(e.attrs),htmlBlock:e=>{let t=JB(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>eV(e,t),footnoteDefinition:()=>``};function rV(e,t=[]){let n=mx(e);for(let e of t){let t=tV[e.type];t&&(n=t(n,e))}return n}function iV(e=[]){return e.map(oV).join(``)}function aV(e,t){return e.content?t.renderChildren(e.content):``}function oV(e){return(nV[e.type]??aV)(e,sV)}var sV={renderChildren:iV,renderNode:oV,renderText:rV};function cV(e){return e.type===`doc`?oV(fx(e)):``}function lV(e){return e.trim()?cV(qx(e)):``}function uV(){return Math.floor(Date.now()/1e3)}function dV(e){return new Date(e*1e3).toISOString()}function fV(e,t=`UTC`){let n=uV()-e;if(n<60)return`1m`;let r=Math.floor(n/60);if(r<60)return`${r}m`;let i=Math.floor(n/3600);if(i<24)return`${i}h`;let a=Math.floor(n/86400);return a<=7?`${a}d`:new Date(e*1e3).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,timeZone:t})}function pV(e,t=`UTC`){let n=fV(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var mV=class extends _{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#v();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#_();break;case`divider`:this.#x();break;case`link`:this.#S();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#d()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#d(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#f(e){return this.#r?.querySelector(e)??null}#p(){let e=this.#f(`[data-collections-action="done"]`);e&&(e.hidden=!this._reorderMode);let t=this.#f(`[data-collections-reorder-actions]`);t&&(t.hidden=!this._reorderMode);let n=this.#f(`[data-collections-toolbar]`);n&&(n.hidden=this._reorderMode);let r=this.#f(`[data-collections-hint]`);r&&(r.hidden=!this._reorderMode);let i=this.#f(`[data-collections-more-menu]`);i&&(i.hidden=!this._showMoreMenu||this._reorderMode);let a=this.#f(`[data-collections-action="toggle-menu"]`);a&&a.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#m(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#h(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#m(t)}catch{}}#g(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...WO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{JO(e,!0)},onStart:e=>{this.#n=KO(e)},onUnchoose:()=>{JO(e,!1)},onEnd:t=>{let n=GO(e,`[data-directory-item]`,`directoryItem`);qO(e,t,this.#n),this.#n=null,JO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:o}=YO(n,t.newIndex);if(!r)return;let s=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>s.get(e)).filter(e=>e!==void 0),fetch(`/api/collections/directory-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:o??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)})}}))}#_(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#v(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#d(),this.#p(),this._reorderMode&&this.#g(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#y()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#b()}#y(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=aE({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=iE(this.#i.getJSON()))}#b(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=aE({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=iE(this.#a.getJSON()))}async#x(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#h(),this._editingDividerId=t.id}catch{a(this.labels.saveFailed,`error`)}}#S(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#C(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=this._newLinkDescription.trim()||null,r=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,description:n})});if(!r.ok)throw Error(`HTTP ${r.status}`);this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,a(this.labels.linkCreated),await this.#h()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#w(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{a(this.labels.saveFailed,`error`)}}async#T(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#E(e){if(await De({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(this.labels.deleted),await this.#h()}catch{a(this.labels.saveFailed,`error`)}}}#D(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#O(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){a(this.labels.labelAndUrlRequired,`error`);return}try{let r=this._editLinkDescription.trim()||null,i=await fetch(`/api/collections/directory-items/${e.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,url:n,description:r})});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();this._items=this._items.map(r=>r.id===e.id?{...r,label:o.label??t,url:o.url??n,description:o.description??null}:r),this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkSaved)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#k(e){if(await De({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{a(this.labels.saveFailed,`error`)}}}#A(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#j(e,t){let n=e.collection;if(!n)return m;let r=u`
|
|
3012
3044
|
<div class="collection-directory-main">
|
|
3013
3045
|
<span class="collection-directory-sequence" aria-hidden="true">
|
|
3014
3046
|
${t}
|
|
3015
3047
|
</span>
|
|
3016
3048
|
<div class="collection-directory-title-row">
|
|
3017
|
-
<a href=${o(
|
|
3049
|
+
<a href=${o(PB(n.slug))} class="collection-directory-title-link">
|
|
3018
3050
|
<span class="collection-directory-title">${n.title}</span>
|
|
3019
3051
|
</a>
|
|
3020
3052
|
</div>
|
|
3021
3053
|
${n.description?u`
|
|
3022
3054
|
<div class="collection-directory-description prose">
|
|
3023
|
-
${s(
|
|
3055
|
+
${s(lV(n.description))}
|
|
3024
3056
|
</div>
|
|
3025
3057
|
`:m}
|
|
3026
3058
|
<p class="collection-directory-summary">
|
|
@@ -3032,9 +3064,9 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3032
3064
|
>
|
|
3033
3065
|
<time
|
|
3034
3066
|
class="collection-directory-updated"
|
|
3035
|
-
datetime=${
|
|
3067
|
+
datetime=${dV(n.recentActivityAt)}
|
|
3036
3068
|
>
|
|
3037
|
-
${
|
|
3069
|
+
${pV(n.recentActivityAt)}
|
|
3038
3070
|
</time>
|
|
3039
3071
|
</p>
|
|
3040
3072
|
</div>
|
|
@@ -3174,7 +3206,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3174
3206
|
</div>
|
|
3175
3207
|
${e.description?u`
|
|
3176
3208
|
<div class="collection-directory-description prose">
|
|
3177
|
-
${s(
|
|
3209
|
+
${s(lV(e.description))}
|
|
3178
3210
|
</div>
|
|
3179
3211
|
`:u`
|
|
3180
3212
|
<p class="collection-directory-summary">
|
|
@@ -3252,7 +3284,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3252
3284
|
>
|
|
3253
3285
|
${t?u`
|
|
3254
3286
|
<a
|
|
3255
|
-
href=${o(`${
|
|
3287
|
+
href=${o(`${FB(t.slug)}?returnTo=${encodeURIComponent(o(MB()))}`)}
|
|
3256
3288
|
class="collections-page-menu-item"
|
|
3257
3289
|
>
|
|
3258
3290
|
${this.labels.edit}
|
|
@@ -3344,7 +3376,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3344
3376
|
</svg>
|
|
3345
3377
|
</button>
|
|
3346
3378
|
</div>
|
|
3347
|
-
`;let n=!!e.label,r=
|
|
3379
|
+
`;let n=!!e.label,r=VB(this._items,t);return u`
|
|
3348
3380
|
<div class="collection-directory-divider">
|
|
3349
3381
|
<div
|
|
3350
3382
|
class="collection-directory-divider-row"
|
|
@@ -3353,7 +3385,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3353
3385
|
${n?u`
|
|
3354
3386
|
${r?u`
|
|
3355
3387
|
<a
|
|
3356
|
-
href=${o(
|
|
3388
|
+
href=${o(PB(r.slugExpression))}
|
|
3357
3389
|
class="collection-directory-divider-link collection-directory-divider-text"
|
|
3358
3390
|
>
|
|
3359
3391
|
${e.label}
|
|
@@ -3431,7 +3463,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3431
3463
|
${(()=>{let e=this.#A();return this._items.map((t,n)=>t.type===`collection`?this.#j(t,e[n]):t.type===`link`?this.#N(t,e[n]):this.#F(t,n))})()}
|
|
3432
3464
|
</div>
|
|
3433
3465
|
`:u`<p class="text-muted-foreground">${this.labels.emptyState}</p>`}
|
|
3434
|
-
`}};customElements.define(`jant-collections-manager`,
|
|
3466
|
+
`}};customElements.define(`jant-collections-manager`,mV);function hV(e){try{let t=new URL(e,window.location.origin);return t.origin===window.location.origin?t:null}catch{return null}}function gV(){return document.documentElement.dataset.sitePathPrefix||``}function _V(e){let t=gV();return t?e===t?`/`:e.startsWith(`${t}/`)?e.slice(t.length)||`/`:null:e||`/`}function vV(e,t,n){let r=e.split(`+`).filter(Boolean);if(r.length===0||r.length===1)return t;if(!n)return e;let i=!1,a=r.map(e=>e===n?(i=!0,t):e);return i?a.join(`+`):e}function yV(e,t,n){let r=t.cancelHref||o(MB());if(!e.isEdit||!n)return r;let i=hV(r);if(!i)return o(NB(n));let a=_V(i.pathname),s=t.initial?.slug?.trim()||void 0;if(s&&a===NB(s))return i.pathname=o(NB(n)),`${i.pathname}${i.search}${i.hash}`;let c=a?.match(/^\/collections\/([^/]+)$/);return c&&(i.pathname=o(PB(vV(c[1],n,s)))),`${i.pathname}${i.search}${i.hash}`}document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let a=yV(n,r,typeof t?.slug==`string`&&t.slug.length>0?t.slug:void 0);window.location.href=a;return}catch(e){a(e instanceof Error?e.message:i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`,`error`)}finally{r.loading=!1}}});function bV(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(TS(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return u`<svg
|
|
3435
3467
|
width="24"
|
|
3436
3468
|
height="24"
|
|
3437
3469
|
viewBox="0 0 24 24"
|
|
@@ -3464,7 +3496,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3464
3496
|
stroke-linejoin="round"
|
|
3465
3497
|
>
|
|
3466
3498
|
${ke(`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>`+t)}
|
|
3467
|
-
</svg>`}function
|
|
3499
|
+
</svg>`}function xV(e){return TS(e.mimeType)===`image`?u`<img
|
|
3468
3500
|
src=${e.thumbUrl}
|
|
3469
3501
|
alt=${e.alt}
|
|
3470
3502
|
class="w-full h-full object-cover rounded-lg border"
|
|
@@ -3472,15 +3504,15 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3472
3504
|
/>`:u`<div
|
|
3473
3505
|
class="w-full h-full rounded-lg border bg-muted flex flex-col items-center justify-center gap-1 p-1 text-muted-foreground"
|
|
3474
3506
|
>
|
|
3475
|
-
${
|
|
3507
|
+
${bV(e.mimeType)}
|
|
3476
3508
|
<span class="text-[10px] leading-tight text-center truncate w-full px-1"
|
|
3477
3509
|
>${e.originalName}</span
|
|
3478
3510
|
>
|
|
3479
|
-
</div>`}function
|
|
3511
|
+
</div>`}function SV(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return u`<p class="text-sm text-muted-foreground">
|
|
3480
3512
|
${n.mediaEmptyLabel}
|
|
3481
3513
|
</p>`;let i=new Map(t.map(e=>[e.id,e]));return u`<div class="grid grid-cols-4 sm:grid-cols-6 gap-2 mb-2">
|
|
3482
3514
|
${r.map(t=>{let r=i.get(t);return r?u`<div class="relative group aspect-square" data-media-id=${t}>
|
|
3483
|
-
${
|
|
3515
|
+
${xV(r)}
|
|
3484
3516
|
<button
|
|
3485
3517
|
type="button"
|
|
3486
3518
|
class="absolute top-1 right-1 w-5 h-5 flex items-center justify-center bg-black/60 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
|
|
@@ -3502,7 +3534,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3502
3534
|
×
|
|
3503
3535
|
</button>
|
|
3504
3536
|
</div>`})}
|
|
3505
|
-
</div>`}function
|
|
3537
|
+
</div>`}function CV(e){return e.collections.length?u`<div class="field">
|
|
3506
3538
|
<label class="label">${e.labels.collectionsLabel}</label>
|
|
3507
3539
|
<div class="flex flex-col gap-1">
|
|
3508
3540
|
${e.collections.map(t=>u`<label class="flex items-center gap-2 text-sm">
|
|
@@ -3515,7 +3547,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3515
3547
|
<span>${t.title}</span>
|
|
3516
3548
|
</label>`)}
|
|
3517
3549
|
</div>
|
|
3518
|
-
</div>`:m}function
|
|
3550
|
+
</div>`:m}function wV(e){return u`<form
|
|
3519
3551
|
class="flex flex-col gap-4 max-w-2xl"
|
|
3520
3552
|
@submit=${t=>e.handleSubmit(t)}
|
|
3521
3553
|
>
|
|
@@ -3590,7 +3622,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3590
3622
|
|
|
3591
3623
|
<div class="field">
|
|
3592
3624
|
<label class="label">${e.labels.mediaLabel}</label>
|
|
3593
|
-
${
|
|
3625
|
+
${SV(e)}
|
|
3594
3626
|
<button
|
|
3595
3627
|
type="button"
|
|
3596
3628
|
class="btn-outline text-sm"
|
|
@@ -3636,7 +3668,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3636
3668
|
${e.labels.pinnedLabel}
|
|
3637
3669
|
</label>
|
|
3638
3670
|
|
|
3639
|
-
${
|
|
3671
|
+
${CV(e)}
|
|
3640
3672
|
|
|
3641
3673
|
<div class="flex gap-2">
|
|
3642
3674
|
<button type="submit" class="btn" ?disabled=${e._loading}>
|
|
@@ -3686,7 +3718,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3686
3718
|
${e.labels.mediaDialogLoading}
|
|
3687
3719
|
</p>
|
|
3688
3720
|
</div>
|
|
3689
|
-
</dialog>`}var bV={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},xV={formatLabel:``,noteOption:``,linkOption:``,quoteOption:``,titleLabel:``,titlePlaceholder:``,slugLabel:``,slugPlaceholder:``,slugHelp:``,bodyLabel:``,bodyPlaceholder:``,urlLabel:``,urlPlaceholder:``,quoteTextLabel:``,quoteTextPlaceholder:``,mediaLabel:``,mediaAddButton:``,mediaRemoveButton:``,mediaEmptyLabel:``,statusLabel:``,statusPublished:``,statusDraft:``,visibilityLabel:``,visibilityPublic:``,visibilityHiddenFromLatest:``,pinnedLabel:``,collectionsLabel:``,submitLabel:``,cancelLabel:``,mediaDialogTitle:``,mediaDialogDone:``,mediaDialogLoading:``,submitSuccessMessage:``,submitErrorMessage:``,draftFallbackMessage:``};function SV(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var CV=class e extends _{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...xV},this.initial={...bV},this.collections=[],this.media=[],this.action=``,this.cancelHref=`/`,this.mediaPickerUrl=``,this.siteUrl=``,this.isEdit=!1,this._format=`note`,this._title=``,this._slug=``,this._slugManuallyEdited=!1,this._body=``,this._url=``,this._quoteText=``,this._status=`published`,this._visibility=`public`,this._pinned=!1,this._rating=0,this._collectionIds=[],this._mediaIds=[],this._loading=!1}willUpdate(e){typeof this.labels==`string`&&(this.labels=SV(this.labels,{...xV})),typeof this.initial==`string`&&(this.initial=SV(this.initial,{...bV})),typeof this.collections==`string`&&(this.collections=SV(this.collections,[])),typeof this.media==`string`&&(this.media=SV(this.media,[])),(!this.#e||e.has(`initial`))&&this.#i()}set loading(e){this._loading=e}get loading(){return this._loading}set mediaIds(e){this._mediaIds=[...e]}get mediaIds(){return[...this._mediaIds]}get#r(){return this.querySelector(`#post-media-picker`)}connectedCallback(){super.connectedCallback(),window.addEventListener(`beforeunload`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener(`beforeunload`,this.#n),this._editor?.destroy(),this._editor=null,this.closeMediaPicker()}#i(){let e=this.initial??bV;if(this._format=e.format??`note`,this._title=e.title??``,this._slug=e.slug??``,this._slugManuallyEdited=!!e.slug,this._body=e.body??``,this._url=e.url??``,this._quoteText=e.quoteText??``,this._status=e.status??`published`,this._visibility=e.visibility??`public`,this._pinned=!!e.pinned,this._rating=e.rating??0,this._collectionIds=[...e.collectionIds??[]],this._mediaIds=[...e.mediaIds??[]],this.#e=!0,this._body&&this._body.startsWith(`{`))try{this._bodyJson=JSON.parse(this._body)}catch{this._bodyJson=null}else this._bodyJson=null}initEditor(){if(this._editor)return;let e=this.querySelector(`.post-form-tiptap-body`);e&&(this._editor=rE({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._bodyJson,onUpdate:e=>{this._bodyJson=e,this._body=JSON.stringify(e)},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}))}static#a=new Set([`_format`,`_title`,`_slug`,`_body`,`_url`,`_quoteText`,`_status`,`_visibility`,`_pinned`,`_rating`,`_collectionIds`,`_mediaIds`]);updated(t){if(super.updated(t),this._editor||this.initEditor(),this.#e&&!t.has(`initial`)){for(let n of t.keys())if(e.#a.has(n)){this.#t=!0;break}}}clearDirty(){this.#t=!1}handleInput(e,t){this[e]=t.target.value}handleTitleInput(e){let t=e.target;this._title=t.value,this._slugManuallyEdited||(this._slug=t.value.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``))}handleSlugInput(e){this._slug=e.target.value,this._slugManuallyEdited=!0}toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}removeMedia(e){this._mediaIds=this._mediaIds.filter(t=>t!==e)}openMediaPicker(){let e=this.#r;e&&(e.showModal(),this.dispatchEvent(new CustomEvent(`jant:post-load-media`,{bubbles:!0,detail:{endpoint:this.mediaPickerUrl,selectedIds:[...this._mediaIds]}})))}closeMediaPicker(){this.#r?.close()}handleSubmit(e){if(e.preventDefault(),this._loading||!this.action)return;let t=this._bodyJson?JSON.stringify(this._bodyJson):this._body,n={endpoint:this.action,isEdit:this.isEdit,data:{format:this._format,title:this._title.trim(),slug:this._slug.trim()||void 0,body:t,status:this._status,visibility:this._visibility,pinned:this._pinned,url:this._url.trim(),quoteText:this._quoteText.trim(),rating:this._rating,collectionIds:[...this._collectionIds],mediaIds:[...this._mediaIds]},messages:{success:this.labels.submitSuccessMessage,error:this.labels.submitErrorMessage}};this.dispatchEvent(new CustomEvent(`jant:post-submit`,{bubbles:!0,detail:n}))}render(){return yV(this)}};customElements.define(`jant-post-form`,CV);function wV(e){return e instanceof HTMLElement&&e.tagName===`JANT-POST-FORM`?e:e instanceof HTMLElement?e.closest(`jant-post-form`):document.querySelector(`jant-post-form`)}function TV(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function EV(e){let t=e,n=t.detail;if(!n)return;let r=wV(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await fe(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await fe(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let o=w(t,`status`),s=w(t,`url`);if(o===`redirect`&&s){r.clearDirty(),h(i),window.location.href=s;return}a(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await fe(e),i=w(t,`status`),o=w(t,`url`);if(i===`redirect`&&o){r.clearDirty(),h(n.messages.success),window.location.href=o;return}r.clearDirty(),a(n.messages.success)}catch(e){a(e instanceof Error&&e.message?e.message:n.messages.error,`error`)}finally{r.loading=!1}}}async function DV(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=wV(t.target);if(!r||!i)return;try{r.innerHTML=`<p class="text-muted-foreground text-sm col-span-4">Loading...</p>`,r.innerHTML=await(await fetch(n.endpoint,{headers:{Accept:`text/html`}})).text()}catch{r.innerHTML=`<p class="text-red-500 text-sm col-span-4">Failed to load media.</p>`;return}let a=new Set(n.selectedIds);r.querySelectorAll(`[data-media-id]`).forEach(e=>{let t=e.dataset.mediaId;t&&TV(e,a.has(t))}),r.onclick=e=>{let t=e.target.closest(`[data-media-id]`);if(!t)return;let n=t.dataset.mediaId;if(!n)return;let r=new Set(i.mediaIds);r.has(n)?(r.delete(n),TV(t,!1)):(r.add(n),TV(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,EV),document.addEventListener(`jant:post-load-media`,DV);var{I:OV}=i,kV=e=>e,AV=()=>document.createComment(``),jV=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new OV(r.insertBefore(AV(),i),r.insertBefore(AV(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=kV(e).nextSibling;kV(r).insertBefore(e,i),e=t}}}return n},MV=(e,t,n=e)=>(e._$AI(t,n),e),NV={},PV=(e,t=NV)=>e._$AH=t,FV=e=>e._$AH,IV=e=>{e._$AR(),e._$AA.remove()},LV=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},RV=p(class extends x{constructor(e){if(super(e),e.type!==c.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=FV(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,f=0,p=i.length-1,m=0,h=a.length-1;for(;f<=p&&m<=h;)if(i[f]===null)f++;else if(i[p]===null)p--;else if(s[f]===o[m])c[m]=MV(i[f],a[m]),f++,m++;else if(s[p]===o[h])c[h]=MV(i[p],a[h]),p--,h--;else if(s[f]===o[h])c[h]=MV(i[f],a[h]),jV(e,c[h+1],i[f]),f++,h--;else if(s[p]===o[m])c[m]=MV(i[p],a[m]),jV(e,i[f],i[p]),p--,m++;else if(l===void 0&&(l=LV(o,m,h),u=LV(s,f,p)),l.has(s[f]))if(l.has(s[p])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=jV(e,i[f]);MV(t,a[m]),c[m]=t}else c[m]=MV(n,a[m]),jV(e,i[f],n),i[t]=null;m++}else IV(i[p]),p--;else IV(i[f]),f++;for(;m<=h;){let t=jV(e,c[h+1]);MV(t,a[m]),c[m++]=t}for(;f<=p;){let e=i[f++];e!==null&&IV(e)}return this.ut=o,PV(e,c),d}}),zV=class extends _{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#b())};#s=e=>{if(!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore)return;let t=e;t.isComposing||t.keyCode===229||(e.preventDefault(),this.#b(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#y.length===0&&this.#b(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#b()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...WO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=KO(e)},onEnd:e=>{let t=e.to,n=e.from,r=n!==t,i=t.id===`nav-items-header`?`header`:`more`,o=this.querySelector(`#nav-items-header`),s=this.querySelector(`#nav-items-more`),c=e.item?.dataset?.navId;if(!c||!o||!s){this.#r=null;return}let l=GO(o,`[data-nav-id]`,`navId`),u=GO(s,`[data-nav-id]`,`navId`);r?(e.item.parentNode?.removeChild(e.item),this.#r?n.insertBefore(e.item,this.#r):e.oldIndex!=null&&e.oldIndex<n.children.length?n.insertBefore(e.item,n.children[e.oldIndex]??null):n.appendChild(e.item)):qO(t,e,this.#r),this.#r=null,this.#c();let d=[...new Set([...l,...u])],f=new Map(this._items.map(e=>[e.id,e.id===c?{...e,placement:i}:{...e}])),p=d.map(e=>f.get(e)).filter(e=>e!==void 0),m=this._items.filter(e=>!d.includes(e.id)).map(e=>e.id===c?{...e,placement:i}:{...e});this._items=[...p,...m];let{movedId:h,afterId:g,beforeId:_}=YO(i===`header`?l:u,e.newIndex);h&&(r?fetch(`/api/nav-items/${c}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({placement:i})}).then(async e=>e.ok?(await fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})})).ok:!1).then(e=>{e?a(this.labels.placementSaved):a(this.labels.saveFailed,`error`)}):fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)}))}}}#d(e){this._editingId===e.id?this._editingId=null:(this._editingId=e.id,this._editLabel=e.label,this._editUrl=e.url)}#f(e){let t=this._editLabel.trim();if(!t&&e.type!==`system`){a(this.labels.labelRequired,`error`);return}let n={id:e.id,label:t,...e.type===`link`&&{url:this._editUrl.trim()}};this.dispatchEvent(new CustomEvent(`jant:nav-update`,{bubbles:!0,detail:n}))}async#p(e){await De({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,placement:`header`})});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#c(),this._items=[...this._items,r],this._newLinkLabel=``,this._newLinkUrl=``,this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#h(e){if(!(!e||this._addingCollectionId)){this._addingCollectionId=e;try{let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`collection`,collectionId:e,placement:`header`})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,n],this.#a()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingCollectionId=null}}}#g(e){return this._items.some(t=>t.type===`system`&&t.systemKey===e.key)}async#_(e,t){this._togglingKeys=new Set([...this._togglingKeys,e.key]);try{if(t){let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`system`,systemKey:e.key})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,{...n,displayLabel:e.label}]}else{let t=this._items.find(t=>t.type===`system`&&t.systemKey===e.key);if(t){let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);this.#c(),this._items=this._items.filter(e=>e.id!==t.id)}}}catch{a(this.labels.saveFailed,`error`),this.requestUpdate()}finally{let t=new Set(this._togglingKeys);t.delete(e.key),this._togglingKeys=t}}get#v(){return this._items.filter(e=>(e.placement??`header`)===`header`)}get#y(){return this._items.filter(e=>e.placement===`more`)}#b(){this._showPreviewMore=!1,document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#s)}#x(e){if(e.preventDefault(),e.stopPropagation(),this._showPreviewMore){this.#b();return}this._showPreviewMore=!0,document.addEventListener(`keydown`,this.#s),setTimeout(()=>{document.addEventListener(`click`,this.#o)})}#S(){let e=this.#v,t=this.#y;return u`
|
|
3721
|
+
</dialog>`}var TV={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},EV={formatLabel:``,noteOption:``,linkOption:``,quoteOption:``,titleLabel:``,titlePlaceholder:``,slugLabel:``,slugPlaceholder:``,slugHelp:``,bodyLabel:``,bodyPlaceholder:``,urlLabel:``,urlPlaceholder:``,quoteTextLabel:``,quoteTextPlaceholder:``,mediaLabel:``,mediaAddButton:``,mediaRemoveButton:``,mediaEmptyLabel:``,statusLabel:``,statusPublished:``,statusDraft:``,visibilityLabel:``,visibilityPublic:``,visibilityHiddenFromLatest:``,pinnedLabel:``,collectionsLabel:``,submitLabel:``,cancelLabel:``,mediaDialogTitle:``,mediaDialogDone:``,mediaDialogLoading:``,submitSuccessMessage:``,submitErrorMessage:``,draftFallbackMessage:``};function DV(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var OV=class e extends _{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...EV},this.initial={...TV},this.collections=[],this.media=[],this.action=``,this.cancelHref=`/`,this.mediaPickerUrl=``,this.siteUrl=``,this.isEdit=!1,this._format=`note`,this._title=``,this._slug=``,this._slugManuallyEdited=!1,this._body=``,this._url=``,this._quoteText=``,this._status=`published`,this._visibility=`public`,this._pinned=!1,this._rating=0,this._collectionIds=[],this._mediaIds=[],this._loading=!1}willUpdate(e){typeof this.labels==`string`&&(this.labels=DV(this.labels,{...EV})),typeof this.initial==`string`&&(this.initial=DV(this.initial,{...TV})),typeof this.collections==`string`&&(this.collections=DV(this.collections,[])),typeof this.media==`string`&&(this.media=DV(this.media,[])),(!this.#e||e.has(`initial`))&&this.#i()}set loading(e){this._loading=e}get loading(){return this._loading}set mediaIds(e){this._mediaIds=[...e]}get mediaIds(){return[...this._mediaIds]}get#r(){return this.querySelector(`#post-media-picker`)}connectedCallback(){super.connectedCallback(),window.addEventListener(`beforeunload`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener(`beforeunload`,this.#n),this._editor?.destroy(),this._editor=null,this.closeMediaPicker()}#i(){let e=this.initial??TV;if(this._format=e.format??`note`,this._title=e.title??``,this._slug=e.slug??``,this._slugManuallyEdited=!!e.slug,this._body=e.body??``,this._url=e.url??``,this._quoteText=e.quoteText??``,this._status=e.status??`published`,this._visibility=e.visibility??`public`,this._pinned=!!e.pinned,this._rating=e.rating??0,this._collectionIds=[...e.collectionIds??[]],this._mediaIds=[...e.mediaIds??[]],this.#e=!0,this._body&&this._body.startsWith(`{`))try{this._bodyJson=JSON.parse(this._body)}catch{this._bodyJson=null}else this._bodyJson=null}initEditor(){if(this._editor)return;let e=this.querySelector(`.post-form-tiptap-body`);e&&(this._editor=rE({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._bodyJson,onUpdate:e=>{this._bodyJson=e,this._body=JSON.stringify(e)},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}))}static#a=new Set([`_format`,`_title`,`_slug`,`_body`,`_url`,`_quoteText`,`_status`,`_visibility`,`_pinned`,`_rating`,`_collectionIds`,`_mediaIds`]);updated(t){if(super.updated(t),this._editor||this.initEditor(),this.#e&&!t.has(`initial`)){for(let n of t.keys())if(e.#a.has(n)){this.#t=!0;break}}}clearDirty(){this.#t=!1}handleInput(e,t){this[e]=t.target.value}handleTitleInput(e){let t=e.target;this._title=t.value,this._slugManuallyEdited||(this._slug=t.value.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``))}handleSlugInput(e){this._slug=e.target.value,this._slugManuallyEdited=!0}toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}removeMedia(e){this._mediaIds=this._mediaIds.filter(t=>t!==e)}openMediaPicker(){let e=this.#r;e&&(e.showModal(),this.dispatchEvent(new CustomEvent(`jant:post-load-media`,{bubbles:!0,detail:{endpoint:this.mediaPickerUrl,selectedIds:[...this._mediaIds]}})))}closeMediaPicker(){this.#r?.close()}handleSubmit(e){if(e.preventDefault(),this._loading||!this.action)return;let t=this._bodyJson?JSON.stringify(this._bodyJson):this._body,n={endpoint:this.action,isEdit:this.isEdit,data:{format:this._format,title:this._title.trim(),slug:this._slug.trim()||void 0,body:t,status:this._status,visibility:this._visibility,pinned:this._pinned,url:this._url.trim(),quoteText:this._quoteText.trim(),rating:this._rating,collectionIds:[...this._collectionIds],mediaIds:[...this._mediaIds]},messages:{success:this.labels.submitSuccessMessage,error:this.labels.submitErrorMessage}};this.dispatchEvent(new CustomEvent(`jant:post-submit`,{bubbles:!0,detail:n}))}render(){return wV(this)}};customElements.define(`jant-post-form`,OV);function kV(e){return e instanceof HTMLElement&&e.tagName===`JANT-POST-FORM`?e:e instanceof HTMLElement?e.closest(`jant-post-form`):document.querySelector(`jant-post-form`)}function AV(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function jV(e){let t=e,n=t.detail;if(!n)return;let r=kV(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await fe(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await fe(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let o=w(t,`status`),s=w(t,`url`);if(o===`redirect`&&s){r.clearDirty(),h(i),window.location.href=s;return}a(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await fe(e),i=w(t,`status`),o=w(t,`url`);if(i===`redirect`&&o){r.clearDirty(),h(n.messages.success),window.location.href=o;return}r.clearDirty(),a(n.messages.success)}catch(e){a(e instanceof Error&&e.message?e.message:n.messages.error,`error`)}finally{r.loading=!1}}}async function MV(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=kV(t.target);if(!r||!i)return;try{r.innerHTML=`<p class="text-muted-foreground text-sm col-span-4">Loading...</p>`,r.innerHTML=await(await fetch(n.endpoint,{headers:{Accept:`text/html`}})).text()}catch{r.innerHTML=`<p class="text-red-500 text-sm col-span-4">Failed to load media.</p>`;return}let a=new Set(n.selectedIds);r.querySelectorAll(`[data-media-id]`).forEach(e=>{let t=e.dataset.mediaId;t&&AV(e,a.has(t))}),r.onclick=e=>{let t=e.target.closest(`[data-media-id]`);if(!t)return;let n=t.dataset.mediaId;if(!n)return;let r=new Set(i.mediaIds);r.has(n)?(r.delete(n),AV(t,!1)):(r.add(n),AV(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,jV),document.addEventListener(`jant:post-load-media`,MV);var{I:NV}=i,PV=e=>e,FV=()=>document.createComment(``),IV=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new NV(r.insertBefore(FV(),i),r.insertBefore(FV(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=PV(e).nextSibling;PV(r).insertBefore(e,i),e=t}}}return n},LV=(e,t,n=e)=>(e._$AI(t,n),e),RV={},zV=(e,t=RV)=>e._$AH=t,BV=e=>e._$AH,VV=e=>{e._$AR(),e._$AA.remove()},HV=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},UV=p(class extends x{constructor(e){if(super(e),e.type!==c.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=BV(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,f=0,p=i.length-1,m=0,h=a.length-1;for(;f<=p&&m<=h;)if(i[f]===null)f++;else if(i[p]===null)p--;else if(s[f]===o[m])c[m]=LV(i[f],a[m]),f++,m++;else if(s[p]===o[h])c[h]=LV(i[p],a[h]),p--,h--;else if(s[f]===o[h])c[h]=LV(i[f],a[h]),IV(e,c[h+1],i[f]),f++,h--;else if(s[p]===o[m])c[m]=LV(i[p],a[m]),IV(e,i[f],i[p]),p--,m++;else if(l===void 0&&(l=HV(o,m,h),u=HV(s,f,p)),l.has(s[f]))if(l.has(s[p])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=IV(e,i[f]);LV(t,a[m]),c[m]=t}else c[m]=LV(n,a[m]),IV(e,i[f],n),i[t]=null;m++}else VV(i[p]),p--;else VV(i[f]),f++;for(;m<=h;){let t=IV(e,c[h+1]);LV(t,a[m]),c[m++]=t}for(;f<=p;){let e=i[f++];e!==null&&VV(e)}return this.ut=o,zV(e,c),d}}),WV=class extends _{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},suggestedLinks:{type:Array,attribute:`suggested-links`},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0},_addingSuggestedKey:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#w())};#s=e=>{if(!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore)return;let t=e;t.isComposing||t.keyCode===229||(e.preventDefault(),this.#w(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.suggestedLinks=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1,this._addingSuggestedKey=null}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#C.length===0&&this.#w(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#w()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...WO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=KO(e)},onEnd:e=>{let t=e.to,n=e.from,r=n!==t,i=t.id===`nav-items-header`?`header`:`more`,o=this.querySelector(`#nav-items-header`),s=this.querySelector(`#nav-items-more`),c=e.item?.dataset?.navId;if(!c||!o||!s){this.#r=null;return}let l=GO(o,`[data-nav-id]`,`navId`),u=GO(s,`[data-nav-id]`,`navId`);r?(e.item.parentNode?.removeChild(e.item),this.#r?n.insertBefore(e.item,this.#r):e.oldIndex!=null&&e.oldIndex<n.children.length?n.insertBefore(e.item,n.children[e.oldIndex]??null):n.appendChild(e.item)):qO(t,e,this.#r),this.#r=null,this.#c();let d=[...new Set([...l,...u])],f=new Map(this._items.map(e=>[e.id,e.id===c?{...e,placement:i}:{...e}])),p=d.map(e=>f.get(e)).filter(e=>e!==void 0),m=this._items.filter(e=>!d.includes(e.id)).map(e=>e.id===c?{...e,placement:i}:{...e});this._items=[...p,...m];let{movedId:h,afterId:g,beforeId:_}=YO(i===`header`?l:u,e.newIndex);h&&(r?fetch(`/api/nav-items/${c}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({placement:i})}).then(async e=>e.ok?(await fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})})).ok:!1).then(e=>{e?a(this.labels.placementSaved):a(this.labels.saveFailed,`error`)}):fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)}))}}}#d(e){this._editingId===e.id?this._editingId=null:(this._editingId=e.id,this._editLabel=e.label,this._editUrl=e.url)}#f(e){let t=this._editLabel.trim();if(!t&&e.type!==`system`){a(this.labels.labelRequired,`error`);return}let n={id:e.id,label:t,...e.type===`link`&&{url:this._editUrl.trim()}};this.dispatchEvent(new CustomEvent(`jant:nav-update`,{bubbles:!0,detail:n}))}async#p(e){await De({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,placement:`header`})});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#c(),this._items=[...this._items,r],this._newLinkLabel=``,this._newLinkUrl=``,this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#h(e){if(!(!e||this._addingCollectionId)){this._addingCollectionId=e;try{let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`collection`,collectionId:e,placement:`header`})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,n],this.#a()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingCollectionId=null}}}#g(e){if(e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`//`)||e.startsWith(`mailto:`)||e.startsWith(`tel:`)||e.startsWith(`#`))return null;try{let t=new URL(e,`https://jant.invalid`).pathname.trim().toLowerCase().replace(/^\/+|\/+$/g,``).replace(/\/+/g,`/`);return t?`/${t}`:`/`}catch{return null}}#_(e){let t=this.#g(e.url);return t!==null&&this._items.some(e=>this.#g(e.url)===t)?!0:!!(e.collectionId&&this._items.some(t=>t.type===`collection`&&t.collectionId===e.collectionId))}get#v(){return(this.suggestedLinks??[]).filter(e=>!this.#_(e))}async#y(e){if(!this._addingSuggestedKey){this._addingSuggestedKey=e.key;try{let t=e.navItemType===`collection`&&e.collectionId?{type:`collection`,collectionId:e.collectionId,placement:`header`}:{type:`link`,label:e.label,url:e.url,placement:`header`},n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(t)});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#c(),this._items=[...this._items,r],a(this.labels.suggestedLinkAdded)}catch{a(this.labels.saveFailed,`error`)}finally{this._addingSuggestedKey=null}}}#b(e){return this._items.some(t=>t.type===`system`&&t.systemKey===e.key)}async#x(e,t){this._togglingKeys=new Set([...this._togglingKeys,e.key]);try{if(t){let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`system`,systemKey:e.key})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,{...n,displayLabel:e.label}]}else{let t=this._items.find(t=>t.type===`system`&&t.systemKey===e.key);if(t){let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);this.#c(),this._items=this._items.filter(e=>e.id!==t.id)}}}catch{a(this.labels.saveFailed,`error`),this.requestUpdate()}finally{let t=new Set(this._togglingKeys);t.delete(e.key),this._togglingKeys=t}}get#S(){return this._items.filter(e=>(e.placement??`header`)===`header`)}get#C(){return this._items.filter(e=>e.placement===`more`)}#w(){this._showPreviewMore=!1,document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#s)}#T(e){if(e.preventDefault(),e.stopPropagation(),this._showPreviewMore){this.#w();return}this._showPreviewMore=!0,document.addEventListener(`keydown`,this.#s),setTimeout(()=>{document.addEventListener(`click`,this.#o)})}#E(){let e=this.#S,t=this.#C;return u`
|
|
3690
3722
|
<div class="nav-preview">
|
|
3691
3723
|
<div class="nav-preview-chrome">
|
|
3692
3724
|
<div class="nav-preview-dots">
|
|
@@ -3698,7 +3730,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3698
3730
|
<div class="site-header-top">
|
|
3699
3731
|
<a href=${o(`/`)} class="site-logo">${this.siteName}</a>
|
|
3700
3732
|
<nav class="site-header-nav">
|
|
3701
|
-
${
|
|
3733
|
+
${UV(e,e=>e.id,(e,t)=>u`<a
|
|
3702
3734
|
class=${t===0?`site-header-link site-header-link-active`:`site-header-link`}
|
|
3703
3735
|
>
|
|
3704
3736
|
${e.displayLabel??e.label}
|
|
@@ -3711,7 +3743,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3711
3743
|
data-preview-more-trigger
|
|
3712
3744
|
aria-haspopup="menu"
|
|
3713
3745
|
aria-expanded=${this._showPreviewMore?`true`:`false`}
|
|
3714
|
-
@click=${this.#
|
|
3746
|
+
@click=${this.#T}
|
|
3715
3747
|
>
|
|
3716
3748
|
${this.labels.moreSection}
|
|
3717
3749
|
<svg
|
|
@@ -3734,7 +3766,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3734
3766
|
aria-hidden=${this._showPreviewMore?`false`:`true`}
|
|
3735
3767
|
@click=${e=>e.stopPropagation()}
|
|
3736
3768
|
>
|
|
3737
|
-
${
|
|
3769
|
+
${UV(t,e=>e.id,e=>u`
|
|
3738
3770
|
<span class="site-header-more-link">
|
|
3739
3771
|
${e.displayLabel??e.label}
|
|
3740
3772
|
</span>
|
|
@@ -3746,7 +3778,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3746
3778
|
</div>
|
|
3747
3779
|
</div>
|
|
3748
3780
|
</div>
|
|
3749
|
-
`}#
|
|
3781
|
+
`}#D(e){return u`<span class="badge-secondary">${e===`system`?this.labels.system:e===`collection`?this.labels.collection:this.labels.link}</span>`}#O(e){return this._editingId===e.id?e.type===`system`?u`
|
|
3750
3782
|
<div class="nav-item-edit">
|
|
3751
3783
|
<div class="field">
|
|
3752
3784
|
<label class="label">${this.labels.label}</label>
|
|
@@ -3762,7 +3794,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3762
3794
|
<button
|
|
3763
3795
|
type="button"
|
|
3764
3796
|
class="btn-sm-ghost text-destructive"
|
|
3765
|
-
@click=${()=>{let t=this.systemNavItems.find(t=>t.key===e.systemKey);t&&(this._editingId=null,this.#
|
|
3797
|
+
@click=${()=>{let t=this.systemNavItems.find(t=>t.key===e.systemKey);t&&(this._editingId=null,this.#x(t,!1))}}
|
|
3766
3798
|
>
|
|
3767
3799
|
${this.labels.remove}
|
|
3768
3800
|
</button>
|
|
@@ -3843,7 +3875,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3843
3875
|
</button>
|
|
3844
3876
|
</div>
|
|
3845
3877
|
</div>
|
|
3846
|
-
`:m:m}#
|
|
3878
|
+
`:m:m}#k(e){let t=this._editingId===e.id;return u`
|
|
3847
3879
|
<div
|
|
3848
3880
|
data-nav-id=${e.id}
|
|
3849
3881
|
class="nav-item${t?` nav-item-editing`:``}"
|
|
@@ -3875,7 +3907,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3875
3907
|
<span class="text-sm font-medium truncate"
|
|
3876
3908
|
>${e.displayLabel??e.label}</span
|
|
3877
3909
|
>
|
|
3878
|
-
${this.#
|
|
3910
|
+
${this.#D(e.type)}
|
|
3879
3911
|
</div>
|
|
3880
3912
|
<span class="text-xs text-muted-foreground truncate"
|
|
3881
3913
|
>${e.url}</span
|
|
@@ -3903,9 +3935,38 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3903
3935
|
</svg>
|
|
3904
3936
|
</button>
|
|
3905
3937
|
</div>
|
|
3906
|
-
${this.#
|
|
3938
|
+
${this.#O(e)}
|
|
3907
3939
|
</div>
|
|
3908
|
-
`}#
|
|
3940
|
+
`}#A(){let e=this.#v;return e.length===0?m:u`
|
|
3941
|
+
<section class="mt-8">
|
|
3942
|
+
<h2 class="text-lg font-semibold mb-1">
|
|
3943
|
+
${this.labels.suggestedLinks}
|
|
3944
|
+
</h2>
|
|
3945
|
+
<p class="text-sm text-muted-foreground mb-3">
|
|
3946
|
+
${this.labels.suggestedLinksDescription}
|
|
3947
|
+
</p>
|
|
3948
|
+
<div class="nav-suggestions-list">
|
|
3949
|
+
${e.map(e=>{let t=this._addingSuggestedKey===e.key;return u`
|
|
3950
|
+
<div class="nav-suggestion-item">
|
|
3951
|
+
<div class="nav-suggestion-info">
|
|
3952
|
+
<span class="nav-suggestion-title">${e.label}</span>
|
|
3953
|
+
<span class="nav-suggestion-meta">
|
|
3954
|
+
${e.url} · ${e.targetLabel}
|
|
3955
|
+
</span>
|
|
3956
|
+
</div>
|
|
3957
|
+
<button
|
|
3958
|
+
type="button"
|
|
3959
|
+
class="btn-sm"
|
|
3960
|
+
?disabled=${t||this._addingSuggestedKey!==null}
|
|
3961
|
+
@click=${()=>this.#y(e)}
|
|
3962
|
+
>
|
|
3963
|
+
${this.labels.addSuggestedLink}
|
|
3964
|
+
</button>
|
|
3965
|
+
</div>
|
|
3966
|
+
`})}
|
|
3967
|
+
</div>
|
|
3968
|
+
</section>
|
|
3969
|
+
`}#j(){return u`
|
|
3909
3970
|
<section class="mt-8">
|
|
3910
3971
|
<h2 class="text-lg font-semibold mb-3">
|
|
3911
3972
|
${this.labels.addCustomLinkToNavigation}
|
|
@@ -3982,7 +4043,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
3982
4043
|
`:m}
|
|
3983
4044
|
</div>
|
|
3984
4045
|
</section>
|
|
3985
|
-
`}#
|
|
4046
|
+
`}#M(){if(!this.collections?.length)return u`
|
|
3986
4047
|
<section class="mt-8">
|
|
3987
4048
|
<h2 class="text-lg font-semibold mb-1">
|
|
3988
4049
|
${this.labels.addCollectionToNavigation}
|
|
@@ -4076,14 +4137,14 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4076
4137
|
`:m}
|
|
4077
4138
|
</div>
|
|
4078
4139
|
</section>
|
|
4079
|
-
`}#
|
|
4140
|
+
`}#N(){return this.systemNavItems?.length?u`
|
|
4080
4141
|
<section class="mt-8">
|
|
4081
4142
|
<h2 class="text-lg font-semibold mb-1">${this.labels.systemLinks}</h2>
|
|
4082
4143
|
<p class="text-sm text-muted-foreground mb-3">
|
|
4083
4144
|
${this.labels.systemLinksDescription}
|
|
4084
4145
|
</p>
|
|
4085
4146
|
<div class="flex flex-col divide-y">
|
|
4086
|
-
${this.systemNavItems.map(e=>{let t=this.#
|
|
4147
|
+
${this.systemNavItems.map(e=>{let t=this.#b(e),n=this._togglingKeys.has(e.key);return u`
|
|
4087
4148
|
<label class=${n?`flex items-center justify-between gap-4 py-3 opacity-60 cursor-not-allowed`:`flex items-center justify-between gap-4 py-3 cursor-pointer`}>
|
|
4088
4149
|
<div>
|
|
4089
4150
|
<p class="font-medium">${e.label}</p>
|
|
@@ -4097,37 +4158,37 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4097
4158
|
class="input"
|
|
4098
4159
|
.checked=${t}
|
|
4099
4160
|
?disabled=${n}
|
|
4100
|
-
@change=${t=>{let n=t.target.checked;this.#
|
|
4161
|
+
@change=${t=>{let n=t.target.checked;this.#x(e,n)}}
|
|
4101
4162
|
/>
|
|
4102
4163
|
</label>
|
|
4103
4164
|
`})}
|
|
4104
4165
|
</div>
|
|
4105
4166
|
</section>
|
|
4106
4167
|
`:m}render(){return u`
|
|
4107
|
-
${this.#
|
|
4168
|
+
${this.#E()}
|
|
4108
4169
|
|
|
4109
4170
|
<section class="mt-8">
|
|
4110
4171
|
<h2 class="text-lg font-semibold mb-3">${this.labels.headerSection}</h2>
|
|
4111
|
-
${this.#
|
|
4172
|
+
${this.#S.length===0?u`<p class="text-sm text-muted-foreground py-4">
|
|
4112
4173
|
${this.labels.emptyState}
|
|
4113
4174
|
</p>`:m}
|
|
4114
4175
|
<div id="nav-items-header" class="nav-items-list">
|
|
4115
|
-
${
|
|
4176
|
+
${UV(this.#S,e=>e.id,e=>this.#k(e))}
|
|
4116
4177
|
</div>
|
|
4117
4178
|
</section>
|
|
4118
4179
|
|
|
4119
4180
|
<section class="mt-8">
|
|
4120
4181
|
<h2 class="text-lg font-semibold mb-3">${this.labels.moreSection}</h2>
|
|
4121
4182
|
<div id="nav-items-more" class="nav-items-list nav-items-list-drop">
|
|
4122
|
-
${this.#
|
|
4183
|
+
${this.#C.length>0?UV(this.#C,e=>e.id,e=>this.#k(e)):u`<p class="nav-items-empty-hint">
|
|
4123
4184
|
${this.labels.moreEmptyHint}
|
|
4124
4185
|
</p>`}
|
|
4125
4186
|
</div>
|
|
4126
4187
|
</section>
|
|
4127
4188
|
|
|
4128
|
-
${this.#
|
|
4129
|
-
${this.#
|
|
4130
|
-
`}};customElements.define(`jant-nav-manager`,zV),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 BV=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,VV=`M4 4 20 20`,HV=360,UV=12;function WV(e){let t=window.innerHeight-e.bottom-UV,n=e.top-UV;return t<HV&&n>t}function GV(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 KV=class extends _{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=WV(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=>{let t=e;if(!(t.isComposing||t.keyCode===229)&&t.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 De({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(),GV(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),GV(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=$x(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
|
|
4189
|
+
${this.#A()} ${this.#j()}
|
|
4190
|
+
${this.#M()} ${this.#N()}
|
|
4191
|
+
`}};customElements.define(`jant-nav-manager`,WV),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 GV=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,KV=`M4 4 20 20`,qV=360,JV=12;function YV(e){let t=window.innerHeight-e.bottom-JV,n=e.top-JV;return t<qV&&n>t}function XV(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 ZV=class extends _{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=YV(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=>{let t=e;if(!(t.isComposing||t.keyCode===229)&&t.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 De({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(),XV(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),XV(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=$x(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
|
|
4131
4192
|
xmlns="http://www.w3.org/2000/svg"
|
|
4132
4193
|
viewBox="0 0 24 24"
|
|
4133
4194
|
fill="none"
|
|
@@ -4147,7 +4208,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4147
4208
|
stroke-linecap="round"
|
|
4148
4209
|
stroke-linejoin="round"
|
|
4149
4210
|
>
|
|
4150
|
-
<path d=${
|
|
4211
|
+
<path d=${GV} />
|
|
4151
4212
|
</svg>`}#N(){return u`<svg
|
|
4152
4213
|
xmlns="http://www.w3.org/2000/svg"
|
|
4153
4214
|
viewBox="0 0 24 24"
|
|
@@ -4158,8 +4219,8 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4158
4219
|
stroke-linecap="round"
|
|
4159
4220
|
stroke-linejoin="round"
|
|
4160
4221
|
>
|
|
4161
|
-
<path d=${
|
|
4162
|
-
<path d=${
|
|
4222
|
+
<path d=${GV} />
|
|
4223
|
+
<path d=${KV} />
|
|
4163
4224
|
</svg>`}#P(){return u`<svg
|
|
4164
4225
|
xmlns="http://www.w3.org/2000/svg"
|
|
4165
4226
|
viewBox="0 0 24 24"
|
|
@@ -4604,7 +4665,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4604
4665
|
</div>
|
|
4605
4666
|
`}
|
|
4606
4667
|
${this._addCollectionPanelOpen?this.#H():m}
|
|
4607
|
-
`}};customElements.define(`jant-post-menu`,
|
|
4668
|
+
`}};customElements.define(`jant-post-menu`,ZV);var QV=e=>{if(!e)return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``};try{return JSON.parse(e)}catch{return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``}}};document.querySelectorAll(`[data-collection-page-actions]`).forEach(e=>{if(e.dataset.collectionPageActionsInitialized===`true`)return;let t=QV(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||MB(),i=e.querySelector(`[data-collection-page-action='toggle-menu']`),o=e.querySelector(`[data-collection-page-menu]`);if(!n||!i||!o)return;let s=(e=!1)=>{o.hidden||(o.hidden=!0,i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},c=(e=!1)=>{o.hidden=!1,i.setAttribute(`aria-expanded`,`true`),e&&o.querySelector(`[role='menuitem']`)?.focus()},l=async()=>{if(s(!1),await De({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);a(t.deleted),window.location.href=r}catch{a(t.saveFailed,`error`)}};i.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),o.hidden){c(!1);return}s(!1)}),i.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`)&&(e.preventDefault(),o.hidden?c(!0):s(!1)),e.key===`Escape`&&(e.preventDefault(),s(!0))}),o.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),s(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let r=n.closest(`[data-collection-page-action]`);!r||!e.contains(r)||r.dataset.collectionPageAction===`delete`&&(t.preventDefault(),l())}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||s(!1))}),e.dataset.collectionPageActionsInitialized=`true`});function $V(e=document){e.querySelectorAll(`[data-custom-url-actions]`).forEach(e=>{if(e.dataset.customUrlActionsInitialized===`true`)return;let t=e.querySelector(`[data-custom-url-action='toggle-menu']`),n=e.querySelector(`[data-custom-url-menu]`);if(!(t instanceof HTMLButtonElement)||!n)return;let r=(e=!1)=>{n.hidden||(n.hidden=!0,t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},i=(r=!1)=>{document.dispatchEvent(new CustomEvent(`jant:custom-url-menu`,{detail:{source:e}})),n.hidden=!1,t.setAttribute(`aria-expanded`,`true`),r&&n.querySelector(`[role='menuitem']`)?.focus()};t.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),n.hidden){i(!1);return}r(!1)}),t.addEventListener(`keydown`,e=>{if(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`){e.preventDefault(),n.hidden?i(!0):r(!1);return}e.key===`Escape`&&(e.preventDefault(),r(!0))}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),r(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let i=n.closest(`[data-custom-url-action]`);!i||!e.contains(i)||i.dataset.customUrlAction===`delete`&&r(!1)}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||r(!1))}),document.addEventListener(`jant:custom-url-menu`,t=>{t.detail?.source!==e&&r(!1)}),e.dataset.customUrlActionsInitialized=`true`})}$V();var eH=`xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"`,tH={post:`<svg ${eH}><path d="M8 2v4"/><path d="M12 2v4"/><path d="M16 2v4"/><rect width="16" height="18" x="4" y="4" rx="2"/><path d="M8 10h6"/><path d="M8 14h8"/><path d="M8 18h5"/></svg>`,collection:`<svg ${eH} viewBox="0 0 16 16" stroke-width="1.35"><rect x="3" y="5.05" width="10" height="8.15" rx="2.2"/><path d="M5.1 5.05V4.2a1.1 1.1 0 0 1 1.1-1.1h3.6a1.1 1.1 0 0 1 1.1 1.1v.85"/></svg>`,system:`<svg ${eH}><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>`,command:`<svg ${eH}><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg>`,path:`<svg ${eH}><polyline points="15 10 20 15 15 20"/><path d="M4 4v7a4 4 0 0 0 4 4h12"/></svg>`,search:`<svg ${eH}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`};function nH(e){let t=e.trim().replace(/^[//]+/,``);return t?`/${t}`:`/`}function rH(e){return e.trim().replace(/^[//]+/,``).trim()}var iH=5;function aH(e){try{let t=globalThis.localStorage.getItem(e);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e):[]}catch{return[]}}function oH(e,t){let n=aH(e).filter(e=>e!==t);n.unshift(t),globalThis.localStorage.setItem(e,JSON.stringify(n.slice(0,iH)))}var sH=`jant:nav-history`,cH=`jant:search-history`,lH=[{title:`Home`,path:`/`,type:`system`},{title:`Featured`,path:`/featured`,type:`system`},{title:`Latest`,path:`/latest`,type:`system`},{title:`Archive`,path:`/archive`,type:`system`},{title:`Collections`,path:`/collections`,type:`system`},{title:`Settings`,path:`/settings`,type:`system`},{title:`General`,path:`/settings/general`,type:`system`},{title:`Navigation`,path:`/settings/navigation`,type:`system`},{title:`Appearance`,path:`/settings/appearance/color-theme`,type:`system`},{title:`Custom URLs`,path:`/settings/custom-urls`,type:`system`},{title:`API Tokens`,path:`/settings/api-tokens`,type:`system`},{title:`Sessions`,path:`/settings/sessions`,type:`system`},{title:`Account`,path:`/settings/account`,type:`system`}],uH=[{label:`New Post`,icon:tH.command,action:()=>void lz()}],dH=class extends _{static properties={_open:{state:!0},_query:{state:!0},_selectedIndex:{state:!0},_loading:{state:!0}};#e=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._selectedIndex=0,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t()}async#t(){if(!this.#e)try{let e=await fetch(`/api/palette`);e.ok?this.#e=(await e.json()).items:this.#e=[]}catch{this.#e=[]}}async open(){if(this._open)return;this.#e||(this._loading=!0,await this.#t(),this._loading=!1),this._open=!0,this._query=``,this._selectedIndex=0,await this.updateComplete;let e=this.querySelector(`.command-palette`);e&&!e.open&&e.showModal(),this.querySelector(`.command-palette-input`)?.focus()}close(){let e=this.querySelector(`.command-palette`);e?.open&&e.close(),this._open=!1,this._query=``,this._selectedIndex=0}get#n(){let e=this._query.charAt(0);return e===`>`||e===`>`?`command`:e===`?`||e===`?`?`search`:e===`/`||e===`/`?`path`:`navigate`}get#r(){let e=Zx(this._query),t=[...this.#e??[],...lH];if(!e){let e=aH(sH);if(e.length===0)return t;let n=new Set(e),r=[],i=[];for(let e of t)n.has(e.path)?r.push(e):i.push(e);return r.sort((t,n)=>e.indexOf(t.path)-e.indexOf(n.path)),[...r,...i]}return t.map((t,n)=>({item:t,index:n,rank:Xx([t.title,t.path],e)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item)}get#i(){let e=Zx(this._query.slice(1));return uH.filter(t=>!e||t.label.toLowerCase().includes(e))}get#a(){let e=this.#n;if(e===`command`)return this.#i.map(e=>({label:e.label,icon:e.icon}));if(e===`search`){let e=this._query.slice(1).trim();return e?[{label:`Search for "${e}"`,icon:tH.search,searchQuery:e}]:aH(cH).map(e=>({label:e,icon:tH.search,searchQuery:e}))}if(e===`path`){let e=nH(this._query),t=rH(this._query),n=[{label:`Go to ${e}`,icon:tH.path,pathTarget:e}];return t&&n.push({label:`Search for "${t}"`,icon:tH.search,searchQuery:t}),n}let t=this.#r.map(e=>({label:e.title,secondary:(e.type,e.path),icon:tH[e.type]})),n=Zx(this._query);return t.length===0&&n&&t.push({label:`Search for "${this._query.trim()}"`,icon:tH.search,searchQuery:this._query.trim()}),t}#o(e){let t=this.#n;if(t===`command`){let t=this.#i[e];t&&(this.close(),t.action());return}if(t===`search`){let t=this.#a[e]?.searchQuery;t&&(oH(cH,t),this.close(),window.location.href=`/search?q=${encodeURIComponent(t)}`);return}if(t===`path`){let t=this.#a[e];if(t?.pathTarget){oH(sH,t.pathTarget),this.close(),window.location.href=t.pathTarget;return}if(t?.searchQuery){let e=t.searchQuery;oH(cH,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`}return}let n=this.#a[e];if(n?.searchQuery){let e=n.searchQuery;oH(cH,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`;return}let r=this.#r[e];r&&(oH(sH,r.path),this.close(),r.type===`system`?window.location.href=r.path:r.type===`collection`?window.location.href=`/collections/${r.path}`:window.location.href=`/${r.path}`)}#s=e=>{this._query=e.target.value,this._selectedIndex=0};#c=e=>{if(e.isComposing||e.keyCode===229)return;let t=this.#a;if(e.key===`ArrowDown`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex+1)%t.length:0,this.#f();return}if(e.key===`ArrowUp`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex-1+t.length)%t.length:0,this.#f();return}if(e.key===`Enter`){e.preventDefault(),this.#o(this._selectedIndex);return}if(e.key===`Tab`){e.preventDefault();return}if(e.key===`Escape`){e.preventDefault(),this.close();return}};#l=e=>{e.preventDefault(),this.close()};#u=e=>{e.target===e.currentTarget&&this.close()};#d(e){return()=>this.#o(e)}#f(){requestAnimationFrame(()=>{this.querySelector(`.command-palette-result-selected`)?.scrollIntoView({block:`nearest`})})}render(){if(!this._open)return m;let e=this.#a;return u`
|
|
4608
4669
|
<dialog
|
|
4609
4670
|
class="command-palette"
|
|
4610
4671
|
@cancel=${this.#l}
|
|
@@ -4617,7 +4678,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4617
4678
|
>
|
|
4618
4679
|
<div class="command-palette-input-wrapper">
|
|
4619
4680
|
<span class="command-palette-search-icon"
|
|
4620
|
-
>${ke(
|
|
4681
|
+
>${ke(tH.search)}</span
|
|
4621
4682
|
>
|
|
4622
4683
|
<input
|
|
4623
4684
|
type="text"
|
|
@@ -4666,4 +4727,4 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
|
|
|
4666
4727
|
`:this._query.trim()&&!this._loading?u`<div class="command-palette-empty">No results</div>`:m}
|
|
4667
4728
|
</div>
|
|
4668
4729
|
</dialog>
|
|
4669
|
-
`}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,
|
|
4730
|
+
`}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,dH),document.addEventListener(`keydown`,e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.defaultPrevented||e.isComposing)return;e.preventDefault();let t=document.querySelector(`jant-command-palette`);if(t){if(t.querySelector(`dialog[open]`)){t.close();return}document.querySelector(`dialog[open]`)||t.open()}}),document.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof globalThis.Element)||!t.closest(`.site-header-search-link`)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0||e.defaultPrevented)return;let n=document.querySelector(`jant-command-palette`);n&&(document.querySelector(`dialog[open]`)||(e.preventDefault(),n.open()))}),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),Ee(),document.querySelector(`jant-command-palette`)||document.body.appendChild(document.createElement(`jant-command-palette`));
|