@jant/core 0.3.46 → 0.3.47

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.
Files changed (109) hide show
  1. package/bin/commands/db/execute-file.js +12 -4
  2. package/bin/commands/db/rehearse.js +2 -2
  3. package/bin/commands/export.js +12 -4
  4. package/bin/commands/import-site.js +60 -267
  5. package/bin/commands/migrate.js +36 -69
  6. package/bin/commands/reset-password.js +10 -4
  7. package/bin/commands/site/export.js +59 -248
  8. package/bin/commands/site/snapshot/export.js +58 -45
  9. package/bin/commands/site/snapshot/import.js +104 -52
  10. package/bin/lib/node-env.js +100 -0
  11. package/bin/lib/runtime-target.js +64 -0
  12. package/bin/lib/site-snapshot.js +185 -54
  13. package/bin/lib/sql-export.js +19 -2
  14. package/dist/{app-DB-P66E5.js → app-3REcR-3U.js} +331 -189
  15. package/dist/app-B67XOEyo.js +6 -0
  16. package/dist/client/.vite/manifest.json +2 -2
  17. package/dist/client/_assets/{client-auth-BLCUje4M.js → client-auth-Ce5WEAVS.js} +102 -49
  18. package/dist/client/_assets/client-s71Js1Cu.css +2 -0
  19. package/dist/{github-sync-CQ1x271f.js → export-ZBlfKSKm.js} +12 -439
  20. package/dist/github-sync-C593r22F.js +4 -0
  21. package/dist/github-sync-bL1hnx3Q.js +428 -0
  22. package/dist/index.js +3 -2
  23. package/dist/node.js +5 -4
  24. package/package.json +3 -2
  25. package/src/__tests__/helpers/export-fixtures.ts +0 -1
  26. package/src/client/components/__tests__/jant-settings-avatar.test.ts +2 -0
  27. package/src/client/components/__tests__/jant-settings-general.test.ts +70 -0
  28. package/src/client/components/jant-settings-general.ts +164 -22
  29. package/src/client/components/settings-types.ts +4 -6
  30. package/src/client-auth.ts +1 -1
  31. package/src/db/__tests__/demo-canonical-snapshot.test.ts +1 -1
  32. package/src/db/__tests__/migration-rehearsal.test.ts +2 -5
  33. package/src/db/backfills/0004_register_apple_touch_media_rows.sql +65 -0
  34. package/src/db/migrations/0021_thankful_phalanx.sql +16 -0
  35. package/src/db/migrations/meta/0021_snapshot.json +2121 -0
  36. package/src/db/migrations/meta/_journal.json +7 -0
  37. package/src/db/migrations/pg/0019_gray_natasha_romanoff.sql +20 -0
  38. package/src/db/migrations/pg/meta/0019_snapshot.json +2718 -0
  39. package/src/db/migrations/pg/meta/_journal.json +7 -0
  40. package/src/db/pg/schema.ts +21 -26
  41. package/src/db/rehearsal-fixtures/demo-current.json +1 -1
  42. package/src/db/schema.ts +16 -20
  43. package/src/i18n/__tests__/middleware.test.ts +43 -1
  44. package/src/i18n/coverage.generated.ts +17 -0
  45. package/src/i18n/i18n.ts +18 -2
  46. package/src/i18n/index.ts +3 -0
  47. package/src/i18n/locales/settings/en.po +16 -11
  48. package/src/i18n/locales/settings/en.ts +1 -1
  49. package/src/i18n/locales/settings/zh-Hans.po +17 -12
  50. package/src/i18n/locales/settings/zh-Hans.ts +1 -1
  51. package/src/i18n/locales/settings/zh-Hant.po +16 -11
  52. package/src/i18n/locales/settings/zh-Hant.ts +1 -1
  53. package/src/i18n/locales.ts +84 -2
  54. package/src/i18n/middleware.ts +25 -16
  55. package/src/i18n/supported-locales.ts +153 -0
  56. package/src/lib/__tests__/csp-builder.test.ts +19 -2
  57. package/src/lib/__tests__/feed.test.ts +242 -1
  58. package/src/lib/__tests__/post-meta.test.ts +0 -1
  59. package/src/lib/__tests__/view.test.ts +0 -1
  60. package/src/lib/csp-builder.ts +28 -10
  61. package/src/lib/feed.ts +153 -3
  62. package/src/middleware/__tests__/secure-headers.test.ts +89 -0
  63. package/src/middleware/auth.ts +1 -1
  64. package/src/middleware/secure-headers.ts +47 -1
  65. package/src/node/__tests__/cli-runtime-target.test.ts +110 -2
  66. package/src/node/__tests__/cli-site-snapshot.test.ts +308 -13
  67. package/src/node/__tests__/cli-site-token-env.test.ts +2 -7
  68. package/src/node/__tests__/cli-snapshot-meta.test.ts +85 -0
  69. package/src/node/__tests__/cli-sql-export.test.ts +49 -0
  70. package/src/node/index.ts +1 -0
  71. package/src/preset.css +8 -2
  72. package/src/routes/api/__tests__/settings.test.ts +3 -2
  73. package/src/routes/api/github-sync.tsx +1 -1
  74. package/src/routes/api/settings.ts +4 -1
  75. package/src/routes/auth/signin.tsx +6 -0
  76. package/src/routes/pages/archive.tsx +4 -2
  77. package/src/services/__tests__/post.test.ts +19 -19
  78. package/src/services/__tests__/search.test.ts +0 -1
  79. package/src/services/__tests__/settings.test.ts +22 -3
  80. package/src/services/bootstrap.ts +7 -3
  81. package/src/services/collection.ts +3 -3
  82. package/src/services/export.ts +0 -3
  83. package/src/services/navigation.ts +0 -2
  84. package/src/services/path.ts +1 -38
  85. package/src/services/post.ts +32 -66
  86. package/src/services/search.ts +0 -6
  87. package/src/services/settings.ts +47 -6
  88. package/src/services/site-admin.ts +6 -1
  89. package/src/styles/ui.css +12 -23
  90. package/src/types/entities.ts +0 -1
  91. package/src/ui/color-themes.ts +1 -1
  92. package/src/ui/dash/settings/GeneralContent.tsx +17 -19
  93. package/src/ui/dash/settings/SettingsRootContent.tsx +17 -28
  94. package/src/ui/feed/NoteCard.tsx +1 -11
  95. package/src/ui/feed/__tests__/timeline-cards.test.ts +1 -1
  96. package/src/ui/pages/PostPage.tsx +2 -0
  97. package/bin/commands/collections.js +0 -268
  98. package/bin/commands/media.js +0 -302
  99. package/bin/commands/posts.js +0 -262
  100. package/bin/commands/search.js +0 -53
  101. package/bin/commands/settings.js +0 -93
  102. package/bin/lib/http-api.js +0 -223
  103. package/bin/lib/media-upload.js +0 -206
  104. package/dist/app-CM7sb3xO.js +0 -5
  105. package/dist/client/_assets/client-DDs6NzB3.css +0 -2
  106. package/src/__tests__/bin/content-cli.test.ts +0 -179
  107. package/src/__tests__/bin/media-cli.test.ts +0 -192
  108. /package/dist/{github-api-BkRWnqMx.js → github-api-Bh0PH3zr.js} +0 -0
  109. /package/dist/{github-app-WeadXMb8.js → github-app-D0GvNnqp.js} +0 -0
@@ -2163,7 +2163,70 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
2163
2163
  The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),t.includes(`flac`)&&e.push(`
2164
2164
  The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
2165
2165
  Check the discardedTracks field for more info.`)}return e}async execute(){if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
2166
- `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(e=>e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new VL;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=LO(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&Zj(l,s,c);let[u,d]=l?[l.width,l.height]:[s,c],f=u,p=d,m=f/p,h=e=>Math.ceil(e/2)*2;t.width!==void 0&&t.height===void 0?(f=h(t.width),p=h(Math.round(f/m))):t.width===void 0&&t.height!==void 0?(p=h(t.height),f=h(Math.round(p*m))):t.width!==void 0&&t.height!==void 0&&(f=h(t.width),p=h(t.height));let g=await e.getFirstTimestamp(),_=this.output.format.getSupportedVideoCodecs(),v=!!t.forceTranscode||g<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!_.includes(n)||t.codec&&t.codec!==n||f!==u||p!==d||i!==0&&!o||!!l,y=t.alpha??`discard`;if(v){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}t.codec&&(_=_.filter(e=>e===t.codec));let n=t.bitrate??_L,s=await xL(_,{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 DL(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 FL({format:new cL,target:new eL}),n=new DL(c);t.addVideoTrack(n),await t.start();let r=await new yM(e).getSample(g);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),h=!0,t.cancel()}else await t.cancel()}h?this._trackPromises.push((async()=>{await this._started;let n=new bM(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new Jj(o,{timestamp:s+n/r,duration:1/r});await this._registerVideoSample(e,t,m,i),i.close()}};for await(let{canvas:i,timestamp:a,duration:u}of n){if(this._canceled)return;let n=Math.max(a-this._startTimestamp,0);if(c=n+u,r!==void 0){let e=Math.floor(n*r)/r;if(o!==null)if(e<=s){o=i,s=e;continue}else await l(e);n=e}let d=new Jj(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(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 yM(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 wL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});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:Ck(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),i=e.map(e=>e instanceof Jj?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new Jj(e):new Jj(e,{timestamp:r.timestamp,duration:r.duration}))}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}async _processAudioTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp(),s=t.numberOfChannels??i,c=t.sampleRate??a,l=s!==i||c!==a||o<this._startTimestamp||o>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,u=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!l&&u.includes(n)&&(!t.codec||t.codec===n)&&!t.process){let t=new kL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});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??_L,a=await bL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>tA.includes(e))&&u.some(e=>tA.includes(e))&&(s!==RL||c!==zL)){let e=(await bL(u,{numberOfChannels:RL,sampleRate:zL,bitrate:i})).find(e=>tA.includes(e));e&&(l=!0,n=e,s=RL,c=zL)}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 jL({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new CM(e);for await(let r of n.samples(void 0,this._endTimestamp)){if(this._canceled){r.close();return}r.setTimestamp(r.timestamp-this._startTimestamp),await this._registerAudioSample(e,t,a,r),r.close()}a.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:Ck(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),!e.every(e=>e instanceof rM))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);i=e}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}_resampleAudio(e,t,n,r,i,a){let o=new jL({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new WL({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new CM(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=_k(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},VL=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},HL=5,UL=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<HL&&(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()>=HL}wait(e){let{promise:t,resolve:n}=ok();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},WL=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 rM({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};function GL(){return typeof AudioEncoder<`u`}async function KL(e,t){let n=new MP({source:new OP(e),formats:EP}),r=new $I,i=new FL({format:new cL({fastStart:`in-memory`}),target:r});try{let a=await BL.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:_L}});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 qL={isSupported:GL,processToFile:KL},JL=1920,YL=1080,XL=640,ZL=32;function QL(){return typeof VideoEncoder<`u`}async function $L(e){let t=new MP({source:new OP(e),formats:EP});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=s(a),c=Math.min(a*.1,3),l=await new bM(e).getCanvas(c);if(!l)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=l.canvas,d=u.width,f=u.height,p=Math.min(XL/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(ZL/d,ZL/f,1),b=Math.max(Math.round(d*y),1),x=Math.max(Math.round(f*y),1),S=document.createElement(`canvas`);S.width=b,S.height=x;let C=S.getContext(`2d`);return C?(C.drawImage(u,0,0,b,x),{poster:v,blurhash:AC(C.getImageData(0,0,b,x).data,b,x,4,3),sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o}):{poster:v,sourceWidth:n,sourceHeight:r}}catch{return{}}finally{t.dispose()}}async function eR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await $L(e),c=i||JL,l=a||YL;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(JL/e,YL/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new MP({source:new OP(e),formats:EP}),d=new $I,f=new FL({format:new cL({fastStart:`in-memory`}),target:d});try{let i=await BL.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:_L},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await iR(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&(rR(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await iR(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var tR=[65536,0,0,0,65536,0,0,0,1073741824];function nR(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`)&&nR(e,i+8,i+t,r),i+=t}}function rR(e){let t=new DataView(e);nR(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)!==tR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,tR[e])})}function iR(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=document.createElement(`video`);i.preload=`metadata`,i.onloadedmetadata=()=>{URL.revokeObjectURL(r),t({width:i.videoWidth,height:i.videoHeight})},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(`Failed to probe transcoded video dimensions`))},i.src=r})}var aR={isSupported:QL,processToFile:eR};function oR(){return document.querySelector(`jant-compose-dialog`)}function sR(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function cR(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 lR(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 uR(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}function dR(e){let t=e.dataset.format;if(t===`note`||t===`link`||t===`quote`)return t}async function fR(e){await oR()?.openNew(e)}async function pR(e){let t=e.dataset.postId;if(!t)return;let n=oR();if(!n)return;let r=e.dataset.threadRootId??t,i=dR(e);await n.openReply(t,uR(e),r,lR(e)??void 0,i?{initialFormat:i}:void 0)}function mR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function hR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function gR(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function _R(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 gR(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,y(t),!0):!1}catch{return!1}}async function vR(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await gR(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,y(e),!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);if(!r)return!1;r.outerHTML=n;let i=document.querySelector(`article[data-post-id="${e}"]`);return i&&y(i),!0}catch{return!1}}async function yR(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await gR(`/_/post-view/${encodeURIComponent(e)}`);if(!n)return!1;t.outerHTML=n;let r=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);return r&&y(r),!0}catch{return!1}}async function bR(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?_R(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?yR(e.replyRefreshId):vR(e.replyRefreshId)}var xR=new Map,SR=new Set,CR=new Map;function wR(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 TR(e,t,n){try{let r,i,o,s,c,l,u;if(e.type.startsWith(`video/`)){if(!aR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;wR(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let a=await aR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});r=a.file,i=a.width,o=a.height,s=a.durationSeconds,c=a.blurhash,u=a.poster,u&&n?.updateAttachmentPoster(t,u)}else if(e.type.startsWith(`audio/`)){if(!qL.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{l=await NC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),r=(await qL.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file}else if(e.type.startsWith(`image/`)||/\.heic$/i.test(e.name)||/\.heif$/i.test(e.name)){let s=e;try{let{isHeic:a,heicTo:c}=await kO(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(e)){n?.updateAttachmentStatus(t,`processing`,null,null);let r=await c({blob:e,type:`image/jpeg`,quality:.92});s=new File([r],e.name.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,s)}let l=await re.processToFile(s);r=l.file,i=l.width,o=l.height}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else r=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!e.type.startsWith(`video/`)){let e=await PC(r);i??=e.width,o??=e.height,c??=e.blurhash,l??=e.waveform,!u&&e.poster&&(u=e.poster,n?.updateAttachmentPoster(t,u))}let d,f;if(sS(e.type)===`text`)try{let e=await r.text(),t=e.replace(/\s+/g,` `).trim();f=e.length,d=t.length<=100?t:t.slice(0,100)+`…`}catch{}let p=await GC(r,{width:i,height:o,durationSeconds:s,blurhash:c,waveform:l,poster:u,summary:d,chars:f},e=>{n?.updateAttachmentProgress(t,e)});return n?.updateAttachmentStatus(t,`done`,p.id,null),CR.set(t,p.id),p.id}catch(e){let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),n||a(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;CR.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):SR.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=mR(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=TR(e,r,n).then(e=>SR.has(r)?(SR.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);xR.set(r,t),t.finally(()=>xR.delete(r))}}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-reply-trigger]`);if(!t)return;let n=t.closest(`article[data-post]`);n&&pR(n)});function ER(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 DR(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function OR(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??CR.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!DR(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:AT(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=hR(t.target)??document.querySelector(`jant-compose-dialog`),o=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>e.body.includes(`"blob:`)):n.body.includes(`"blob:`),u=n.pendingAttachments.length>0||l,f=s?.published??`Published!`,p=s?.view??`View`;u&&d(`compose-deferred`,c);let h=(e,t=`success`)=>{u?_(`compose-deferred`,e,t):a(e,t)},g=()=>{!o||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},v=()=>{!o||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||o)){if(te&&n.editPostId){if(typeof r.openEdit!=`function`)return;await r.openEdit(n.editPostId);return}if(n.replyToId){if(typeof r.openReply!=`function`)return;await r.openReply(n.replyToId,void 0,n.replyThreadRootId,n.replyRefreshKind&&n.replyRefreshId?{kind:n.replyRefreshKind,id:n.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:n.format});return}typeof r.openNew==`function`&&await r.openNew({restoreDraft:!0})}},x=async e=>{v(),await b(),h(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{m(e,`success`,t)},ee=()=>!o||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||i(`/`)),!0),te=!!n.editPostId,ne=!!(n.threadPosts&&n.threadPosts.length>=2),re=null;try{let e=n.pendingAttachments.map(e=>e.clientId),t=e.map(e=>xR.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!CR.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let c=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=a[t];n&&r&&c.set(n,r)}if(ne&&n.threadPosts){let e=n.threadPosts,t=re?`draft`:n.status,i=(await Promise.all(e.map(async e=>{let n=e.body;if(n.includes(`"blob:`))try{let e=await $C(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>ER(e,OR(e,c))),a={posts:i};te&&n.editPostId&&(a.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(a)});if(!l.ok){if(n.status===`published`&&!re){let e={posts:i.map(e=>({...e,status:`draft`}))};if((await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)})).ok){re=`server`,y();let e=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(e);return}}await x(w(await le(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let u=await le(l),d=w(u,`status`),m=w(u,`permalink`),_=w(u,`toast`);d===`published`?(y(),o?(await S(),g(),h(f)):(C(f,m?{label:p,href:m}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),h(_??`Draft saved.`),kR(r,`draft`));return}let u=OR(n,c);if(l)try{let e=await $C(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let d=te?`/api/posts/${n.editPostId}`:`/compose`,m=te?`PUT`:`POST`,_=ER({...n,status:re?`draft`:n.status},u),v=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!v.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await le(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(n);let r=w(e,`toast`);r&&h(r);return}}await x(w(await le(v),`error`)??`Something went wrong`);return}if(te){y();let e=await le(v),t=n.editPostId??``,r=w(e,`slug`),a=r?i(`/${r}`):null;if(o)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await yR(t)?h(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`))await yR(t)?h(`Post updated.`):(C(`Post updated.`),globalThis.location.reload());else{let e=document.querySelector(`article[data-post-id="${t}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await _R(e):await vR(t))?h(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let b=await le(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),o)await S(),g(),h(f);else if(n.replyToId){if(await S(),!await bR(n)){C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}h(f)}else C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),h(oe??`Draft saved.`),kR(r,`draft`)}catch{await x(`Something went wrong`)}});function kR(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var AR=`.compose-prompt`,jR=`.compose-prompt-trigger`,MR=`jant.composeOpenShortcutDiscovery`,NR=`/api/settings/discovery/compose-open-shortcut`,PR=350,FR=1800,IR=3,LR=`compose-prompt-discovery-visible`,RR=!1,zR=null,BR=null,VR=null;function HR(){try{return globalThis.localStorage!==void 0}catch{return!1}}function UR(){if(!HR())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(MR);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(MR),{shownCount:0,completed:!1}}}function WR(e){if(HR())try{globalThis.localStorage.setItem(MR,JSON.stringify(e))}catch{}}function GR(){zR!==null&&(clearTimeout(zR),zR=null)}function KR(){BR!==null&&(clearTimeout(BR),BR=null)}function qR(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function JR(e){return UR().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function YR(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(LR)),document.querySelectorAll(AR).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(LR)})}function XR(){let e=UR();e.completed||RR||e.shownCount>=IR||(RR=!0,WR({...e,shownCount:e.shownCount+1}))}function ZR(e){return!qR()||JR(e)?!1:UR().shownCount<IR||RR}function QR(e){GR(),KR(),e?e.classList.remove(LR):VR&&VR.classList.remove(LR),(!e||e===VR)&&(VR=null)}function $R(e){ZR(e)&&(QR(VR),VR=e,e.classList.add(LR),XR(),BR=setTimeout(()=>{QR(e)},FR))}function ez(e){ZR(e)&&(e.classList.contains(LR)||(GR(),zR=setTimeout(()=>{$R(e)},PR)))}function tz(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(jR);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{ez(e)}),t.addEventListener(`pointerleave`,()=>{QR(e)}),t.addEventListener(`focusin`,()=>{ez(e)}),t.addEventListener(`focusout`,()=>{QR(e)}))}function nz(e=document){e.querySelectorAll(AR).forEach(e=>tz(e))}function rz(){let e=UR();e.completed||WR({shownCount:Math.max(e.shownCount,IR),completed:!0}),YR(VR),QR(VR),typeof globalThis.fetch==`function`&&globalThis.fetch(NR,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{nz()}):nz();var iz=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function az(e){return e instanceof globalThis.Element&&e.closest(iz)!==null}function oz(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!oR()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return az(e.target)||t!==e.target&&az(t)}async function sz(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`||oz(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),rz();let n=sR(),r=t===`l`?`link`:t===`q`?`quote`:void 0;fR({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=cR();if(n){if(t===`r`){e.preventDefault(),pR(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=oR();r&&r.openEdit(t);return}if(t===`c`){e.preventDefault();let t=document.querySelector(`jant-post-menu`);t&&t.openCollectionsForPost(n);return}if(t===`f`){let t=n.dataset.postId;if(!t)return;e.preventDefault(),sz(t,!n.hasAttribute(`data-post-featured`),n);return}}});var cz=class extends c{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},languages:{type:Array},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},demoMode:{type:Boolean,attribute:`demo-mode`},mainFeedUrl:{type:String,attribute:`main-feed-url`},latestFeedUrl:{type:String,attribute:`latest-feed-url`},featuredFeedUrl:{type:String,attribute:`featured-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.languages=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/feed/latest`,this.featuredFeedUrl=`/feed/featured`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}disconnectedCallback(){super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=NT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=MT(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=NT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=MT(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_syncFeedDirty(){this._feedDirty=this._mainRssFeed!==this._origMainRssFeed}_saveFeeds(){this._feedLoading||!this._feedDirty||(this._feedLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/feeds`,data:{mainRssFeed:this._mainRssFeed},section:`feeds`}})))}_saveHomeToggle(e){this._homeLoading||(this._showJantBrandingOnHome=e,this._homeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/home`,data:{showJantBrandingOnHome:e},section:`home`}})))}_saveSearchToggle(e){this.demoMode||this._searchLoading||(this._noindex=!e,this._searchLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/search`,data:{allowIndexing:e},section:`search`}})))}_onKeydown(e,t,n,r){e.key===`Enter`&&!r&&n&&!(e.target instanceof HTMLTextAreaElement)&&(e.preventDefault(),t())}_renderSaveAction(e,t,n){return u`
2166
+ `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(e=>e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new VL;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=LO(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&Zj(l,s,c);let[u,d]=l?[l.width,l.height]:[s,c],f=u,p=d,m=f/p,h=e=>Math.ceil(e/2)*2;t.width!==void 0&&t.height===void 0?(f=h(t.width),p=h(Math.round(f/m))):t.width===void 0&&t.height!==void 0?(p=h(t.height),f=h(Math.round(p*m))):t.width!==void 0&&t.height!==void 0&&(f=h(t.width),p=h(t.height));let g=await e.getFirstTimestamp(),_=this.output.format.getSupportedVideoCodecs(),v=!!t.forceTranscode||g<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!_.includes(n)||t.codec&&t.codec!==n||f!==u||p!==d||i!==0&&!o||!!l,y=t.alpha??`discard`;if(v){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}t.codec&&(_=_.filter(e=>e===t.codec));let n=t.bitrate??_L,s=await xL(_,{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 DL(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 FL({format:new cL,target:new eL}),n=new DL(c);t.addVideoTrack(n),await t.start();let r=await new yM(e).getSample(g);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),h=!0,t.cancel()}else await t.cancel()}h?this._trackPromises.push((async()=>{await this._started;let n=new bM(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new Jj(o,{timestamp:s+n/r,duration:1/r});await this._registerVideoSample(e,t,m,i),i.close()}};for await(let{canvas:i,timestamp:a,duration:u}of n){if(this._canceled)return;let n=Math.max(a-this._startTimestamp,0);if(c=n+u,r!==void 0){let e=Math.floor(n*r)/r;if(o!==null)if(e<=s){o=i,s=e;continue}else await l(e);n=e}let d=new Jj(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(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 yM(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 wL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});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:Ck(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),i=e.map(e=>e instanceof Jj?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new Jj(e):new Jj(e,{timestamp:r.timestamp,duration:r.duration}))}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}async _processAudioTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp(),s=t.numberOfChannels??i,c=t.sampleRate??a,l=s!==i||c!==a||o<this._startTimestamp||o>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,u=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!l&&u.includes(n)&&(!t.codec||t.codec===n)&&!t.process){let t=new kL(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new pM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});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??_L,a=await bL(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>tA.includes(e))&&u.some(e=>tA.includes(e))&&(s!==RL||c!==zL)){let e=(await bL(u,{numberOfChannels:RL,sampleRate:zL,bitrate:i})).find(e=>tA.includes(e));e&&(l=!0,n=e,s=RL,c=zL)}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 jL({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new CM(e);for await(let r of n.samples(void 0,this._endTimestamp)){if(this._canceled){r.close();return}r.setTimestamp(r.timestamp-this._startTimestamp),await this._registerAudioSample(e,t,a,r),r.close()}a.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:Ck(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),!e.every(e=>e instanceof rM))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);i=e}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}_resampleAudio(e,t,n,r,i,a){let o=new jL({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new WL({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new CM(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=_k(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},VL=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},HL=5,UL=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<HL&&(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()>=HL}wait(e){let{promise:t,resolve:n}=ok();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},WL=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 rM({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};function GL(){return typeof AudioEncoder<`u`}async function KL(e,t){let n=new MP({source:new OP(e),formats:EP}),r=new $I,i=new FL({format:new cL({fastStart:`in-memory`}),target:r});try{let a=await BL.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:_L}});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 qL={isSupported:GL,processToFile:KL},JL=1920,YL=1080,XL=640,ZL=32;function QL(){return typeof VideoEncoder<`u`}async function $L(e){let t=new MP({source:new OP(e),formats:EP});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=s(a),c=Math.min(a*.1,3),l=await new bM(e).getCanvas(c);if(!l)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=l.canvas,d=u.width,f=u.height,p=Math.min(XL/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(ZL/d,ZL/f,1),b=Math.max(Math.round(d*y),1),x=Math.max(Math.round(f*y),1),S=document.createElement(`canvas`);S.width=b,S.height=x;let C=S.getContext(`2d`);return C?(C.drawImage(u,0,0,b,x),{poster:v,blurhash:AC(C.getImageData(0,0,b,x).data,b,x,4,3),sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o}):{poster:v,sourceWidth:n,sourceHeight:r}}catch{return{}}finally{t.dispose()}}async function eR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await $L(e),c=i||JL,l=a||YL;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(JL/e,YL/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new MP({source:new OP(e),formats:EP}),d=new $I,f=new FL({format:new cL({fastStart:`in-memory`}),target:d});try{let i=await BL.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:_L},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await iR(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&(rR(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await iR(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var tR=[65536,0,0,0,65536,0,0,0,1073741824];function nR(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`)&&nR(e,i+8,i+t,r),i+=t}}function rR(e){let t=new DataView(e);nR(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)!==tR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,tR[e])})}function iR(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=document.createElement(`video`);i.preload=`metadata`,i.onloadedmetadata=()=>{URL.revokeObjectURL(r),t({width:i.videoWidth,height:i.videoHeight})},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(`Failed to probe transcoded video dimensions`))},i.src=r})}var aR={isSupported:QL,processToFile:eR};function oR(){return document.querySelector(`jant-compose-dialog`)}function sR(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function cR(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 lR(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 uR(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}function dR(e){let t=e.dataset.format;if(t===`note`||t===`link`||t===`quote`)return t}async function fR(e){await oR()?.openNew(e)}async function pR(e){let t=e.dataset.postId;if(!t)return;let n=oR();if(!n)return;let r=e.dataset.threadRootId??t,i=dR(e);await n.openReply(t,uR(e),r,lR(e)??void 0,i?{initialFormat:i}:void 0)}function mR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function hR(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function gR(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function _R(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 gR(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,y(t),!0):!1}catch{return!1}}async function vR(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await gR(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,y(e),!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);if(!r)return!1;r.outerHTML=n;let i=document.querySelector(`article[data-post-id="${e}"]`);return i&&y(i),!0}catch{return!1}}async function yR(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await gR(`/_/post-view/${encodeURIComponent(e)}`);if(!n)return!1;t.outerHTML=n;let r=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);return r&&y(r),!0}catch{return!1}}async function bR(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?_R(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?yR(e.replyRefreshId):vR(e.replyRefreshId)}var xR=new Map,SR=new Set,CR=new Map;function wR(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 TR(e,t,n){try{let r,i,o,s,c,l,u;if(e.type.startsWith(`video/`)){if(!aR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;wR(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let a=await aR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});r=a.file,i=a.width,o=a.height,s=a.durationSeconds,c=a.blurhash,u=a.poster,u&&n?.updateAttachmentPoster(t,u)}else if(e.type.startsWith(`audio/`)){if(!qL.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{l=await NC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),r=(await qL.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file}else if(e.type.startsWith(`image/`)||/\.heic$/i.test(e.name)||/\.heif$/i.test(e.name)){let s=e;try{let{isHeic:a,heicTo:c}=await kO(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(e)){n?.updateAttachmentStatus(t,`processing`,null,null);let r=await c({blob:e,type:`image/jpeg`,quality:.92});s=new File([r],e.name.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,s)}let l=await re.processToFile(s);r=l.file,i=l.width,o=l.height}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else r=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!e.type.startsWith(`video/`)){let e=await PC(r);i??=e.width,o??=e.height,c??=e.blurhash,l??=e.waveform,!u&&e.poster&&(u=e.poster,n?.updateAttachmentPoster(t,u))}let d,f;if(sS(e.type)===`text`)try{let e=await r.text(),t=e.replace(/\s+/g,` `).trim();f=e.length,d=t.length<=100?t:t.slice(0,100)+`…`}catch{}let p=await GC(r,{width:i,height:o,durationSeconds:s,blurhash:c,waveform:l,poster:u,summary:d,chars:f},e=>{n?.updateAttachmentProgress(t,e)});return n?.updateAttachmentStatus(t,`done`,p.id,null),CR.set(t,p.id),p.id}catch(e){let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),n||a(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;CR.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):SR.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=mR(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=TR(e,r,n).then(e=>SR.has(r)?(SR.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);xR.set(r,t),t.finally(()=>xR.delete(r))}}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-reply-trigger]`);if(!t)return;let n=t.closest(`article[data-post]`);n&&pR(n)});function ER(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 DR(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function OR(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??CR.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!DR(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:AT(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=hR(t.target)??document.querySelector(`jant-compose-dialog`),o=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>e.body.includes(`"blob:`)):n.body.includes(`"blob:`),u=n.pendingAttachments.length>0||l,f=s?.published??`Published!`,p=s?.view??`View`;u&&d(`compose-deferred`,c);let h=(e,t=`success`)=>{u?_(`compose-deferred`,e,t):a(e,t)},g=()=>{!o||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},v=()=>{!o||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||o)){if(te&&n.editPostId){if(typeof r.openEdit!=`function`)return;await r.openEdit(n.editPostId);return}if(n.replyToId){if(typeof r.openReply!=`function`)return;await r.openReply(n.replyToId,void 0,n.replyThreadRootId,n.replyRefreshKind&&n.replyRefreshId?{kind:n.replyRefreshKind,id:n.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:n.format});return}typeof r.openNew==`function`&&await r.openNew({restoreDraft:!0})}},x=async e=>{v(),await b(),h(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{m(e,`success`,t)},ee=()=>!o||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||i(`/`)),!0),te=!!n.editPostId,ne=!!(n.threadPosts&&n.threadPosts.length>=2),re=null;try{let e=n.pendingAttachments.map(e=>e.clientId),t=e.map(e=>xR.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!CR.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let c=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=a[t];n&&r&&c.set(n,r)}if(ne&&n.threadPosts){let e=n.threadPosts,t=re?`draft`:n.status,i=(await Promise.all(e.map(async e=>{let n=e.body;if(n.includes(`"blob:`))try{let e=await $C(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>ER(e,OR(e,c))),a={posts:i};te&&n.editPostId&&(a.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(a)});if(!l.ok){if(n.status===`published`&&!re){let e={posts:i.map(e=>({...e,status:`draft`}))};if((await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)})).ok){re=`server`,y();let e=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(e);return}}await x(w(await le(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let u=await le(l),d=w(u,`status`),m=w(u,`permalink`),_=w(u,`toast`);d===`published`?(y(),o?(await S(),g(),h(f)):(C(f,m?{label:p,href:m}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),h(_??`Draft saved.`),kR(r,`draft`));return}let u=OR(n,c);if(l)try{let e=await $C(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let d=te?`/api/posts/${n.editPostId}`:`/compose`,m=te?`PUT`:`POST`,_=ER({...n,status:re?`draft`:n.status},u),v=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!v.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(d,{method:m,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await le(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),h(n);let r=w(e,`toast`);r&&h(r);return}}await x(w(await le(v),`error`)??`Something went wrong`);return}if(te){y();let e=await le(v),t=n.editPostId??``,r=w(e,`slug`),a=r?i(`/${r}`):null;if(o)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await yR(t)?h(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`))await yR(t)?h(`Post updated.`):(C(`Post updated.`),globalThis.location.reload());else{let e=document.querySelector(`article[data-post-id="${t}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await _R(e):await vR(t))?h(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),h(e);return}let b=await le(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),o)await S(),g(),h(f);else if(n.replyToId){if(await S(),!await bR(n)){C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}h(f)}else C(f,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),h(oe??`Draft saved.`),kR(r,`draft`)}catch{await x(`Something went wrong`)}});function kR(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var AR=`.compose-prompt`,jR=`.compose-prompt-trigger`,MR=`jant.composeOpenShortcutDiscovery`,NR=`/api/settings/discovery/compose-open-shortcut`,PR=350,FR=1800,IR=3,LR=`compose-prompt-discovery-visible`,RR=!1,zR=null,BR=null,VR=null;function HR(){try{return globalThis.localStorage!==void 0}catch{return!1}}function UR(){if(!HR())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(MR);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(MR),{shownCount:0,completed:!1}}}function WR(e){if(HR())try{globalThis.localStorage.setItem(MR,JSON.stringify(e))}catch{}}function GR(){zR!==null&&(clearTimeout(zR),zR=null)}function KR(){BR!==null&&(clearTimeout(BR),BR=null)}function qR(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function JR(e){return UR().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function YR(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(LR)),document.querySelectorAll(AR).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(LR)})}function XR(){let e=UR();e.completed||RR||e.shownCount>=IR||(RR=!0,WR({...e,shownCount:e.shownCount+1}))}function ZR(e){return!qR()||JR(e)?!1:UR().shownCount<IR||RR}function QR(e){GR(),KR(),e?e.classList.remove(LR):VR&&VR.classList.remove(LR),(!e||e===VR)&&(VR=null)}function $R(e){ZR(e)&&(QR(VR),VR=e,e.classList.add(LR),XR(),BR=setTimeout(()=>{QR(e)},FR))}function ez(e){ZR(e)&&(e.classList.contains(LR)||(GR(),zR=setTimeout(()=>{$R(e)},PR)))}function tz(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(jR);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{ez(e)}),t.addEventListener(`pointerleave`,()=>{QR(e)}),t.addEventListener(`focusin`,()=>{ez(e)}),t.addEventListener(`focusout`,()=>{QR(e)}))}function nz(e=document){e.querySelectorAll(AR).forEach(e=>tz(e))}function rz(){let e=UR();e.completed||WR({shownCount:Math.max(e.shownCount,IR),completed:!0}),YR(VR),QR(VR),typeof globalThis.fetch==`function`&&globalThis.fetch(NR,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{nz()}):nz();var iz=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function az(e){return e instanceof globalThis.Element&&e.closest(iz)!==null}function oz(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!oR()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return az(e.target)||t!==e.target&&az(t)}async function sz(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`||oz(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),rz();let n=sR(),r=t===`l`?`link`:t===`q`?`quote`:void 0;fR({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=cR();if(n){if(t===`r`){e.preventDefault(),pR(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=oR();r&&r.openEdit(t);return}if(t===`c`){e.preventDefault();let t=document.querySelector(`jant-post-menu`);t&&t.openCollectionsForPost(n);return}if(t===`f`){let t=n.dataset.postId;if(!t)return;e.preventDefault(),sz(t,!n.hasAttribute(`data-post-featured`),n);return}}});var cz=[`en`,`zh-Hans`,`zh-Hant`];function lz(e){return typeof e==`string`&&cz.includes(e)}function uz(e){let t=e.trim();if(!t)return`en`;let n;try{n=new Intl.Locale(t)}catch{return`en`}if(lz(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 dz={en:1,"zh-Hans":1,"zh-Hant":1},fz=`en.zh-Hans.zh-Hant.ja.ko.es.fr.de.it.pt.ru.ar.hi.bn.ur.tr.vi.th.id.fa.he.nl.pl.sv.da.no.fi.cs.hu.el.ro.uk.en-GB.en-US.fr-CA.pt-BR.es-MX.zh-CN.zh-TW.zh-HK`.split(`.`),pz=null;function mz(e){let t=e,n=e;try{let n=new Intl.DisplayNames([e],{type:`language`}).of(e);typeof n==`string`&&n.length>0&&(t=n)}catch{}try{let t=new Intl.DisplayNames([`en`],{type:`language`}).of(e);typeof t==`string`&&t.length>0&&(n=t)}catch{}return{tag:e,native:t,english:n,coverage:hz(e)}}function hz(e){let t=uz(e);if(t===`en`){let t;try{t=new Intl.Locale(e).language}catch{return 0}if(t!==`en`)return 0}return dz[t]}function gz(){return pz||(pz=fz.map(mz),pz)}function _z(e){let t=e.trim();return gz().find(e=>e.tag===t)||mz(t)}var vz=class extends c{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},demoMode:{type:Boolean,attribute:`demo-mode`},mainFeedUrl:{type:String,attribute:`main-feed-url`},latestFeedUrl:{type:String,attribute:`latest-feed-url`},featuredFeedUrl:{type:String,attribute:`featured-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_localeOpen:{state:!0},_localeQuery:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/feed/latest`,this.featuredFeedUrl=`/feed/featured`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._localeOpen=!1,this._localeQuery=``,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onLocalePickerDocumentClick),document.addEventListener(`keydown`,this._onLocalePickerKeydown)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this._onLocalePickerDocumentClick),document.removeEventListener(`keydown`,this._onLocalePickerKeydown),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=NT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=MT(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=NT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=MT(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_filteredLocaleEntries(){let e=gz(),t=this._localeQuery.trim().toLowerCase();return t?e.filter(e=>e.tag.toLowerCase().includes(t)||e.native.toLowerCase().includes(t)||e.english.toLowerCase().includes(t)):e}_toggleLocalePicker=()=>{this._localeOpen=!this._localeOpen,this._localeOpen?this.updateComplete.then(()=>{this.querySelector(`[data-locale-search]`)?.focus()}):this._localeQuery=``};_selectLocale(e){this._siteLanguage=e,this._localeOpen=!1,this._localeQuery=``,this._syncLocaleDirty()}_onLocalePickerDocumentClick=e=>{if(!this._localeOpen)return;let t=e.target,n=this.querySelector(`[data-locale-picker]`);n&&t&&!n.contains(t)&&(this._localeOpen=!1)};_onLocalePickerKeydown=e=>{e.key===`Escape`&&this._localeOpen&&(this._localeOpen=!1,this._localeQuery=``)};_renderLanguagePicker(){let e=_z(this._siteLanguage||`en`),t=this._filteredLocaleEntries(),n=this.labels.siteLanguageSearchPlaceholder||`Search…`,r=this.labels.siteLanguageNoMatches||`No matches.`;return u`
2167
+ <div class="relative" data-locale-picker>
2168
+ <button
2169
+ type="button"
2170
+ class="input flex w-full items-center justify-between text-left"
2171
+ aria-expanded=${this._localeOpen?`true`:`false`}
2172
+ aria-haspopup="listbox"
2173
+ aria-labelledby="site-language-label"
2174
+ @click=${this._toggleLocalePicker}
2175
+ >
2176
+ <span class="truncate">
2177
+ ${e.native}
2178
+ <span class="ml-2 text-xs text-muted-foreground">
2179
+ ${e.tag} · ${Math.round(e.coverage*100)}% translated
2180
+ </span>
2181
+ </span>
2182
+ <span class="ml-2 text-muted-foreground" aria-hidden="true">▾</span>
2183
+ </button>
2184
+
2185
+ ${this._localeOpen?u`
2186
+ <div
2187
+ class="absolute left-0 right-0 top-full z-10 mt-1 max-h-72 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md"
2188
+ >
2189
+ <div class="border-b p-2">
2190
+ <input
2191
+ type="text"
2192
+ class="input w-full"
2193
+ data-locale-search
2194
+ placeholder=${n}
2195
+ autocomplete="off"
2196
+ spellcheck="false"
2197
+ .value=${this._localeQuery}
2198
+ @input=${e=>{this._localeQuery=e.target.value}}
2199
+ />
2200
+ </div>
2201
+ <div role="listbox" class="max-h-56 overflow-auto py-1">
2202
+ ${t.length===0?u`
2203
+ <div class="px-3 py-2 text-sm text-muted-foreground">
2204
+ ${r}
2205
+ </div>
2206
+ `:t.map(e=>u`
2207
+ <button
2208
+ type="button"
2209
+ role="option"
2210
+ aria-selected=${e.tag===this._siteLanguage?`true`:`false`}
2211
+ class=${[`flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-accent`,e.tag===this._siteLanguage?`bg-accent/60`:``].join(` `)}
2212
+ @click=${()=>this._selectLocale(e.tag)}
2213
+ >
2214
+ <span class="flex flex-col">
2215
+ <span>${e.native}</span>
2216
+ <span class="text-xs text-muted-foreground">
2217
+ ${e.tag} · ${e.english}
2218
+ </span>
2219
+ </span>
2220
+ <span class="text-xs text-muted-foreground">
2221
+ ${Math.round(e.coverage*100)}% translated
2222
+ </span>
2223
+ </button>
2224
+ `)}
2225
+ </div>
2226
+ </div>
2227
+ `:g}
2228
+ </div>
2229
+ `}_syncFeedDirty(){this._feedDirty=this._mainRssFeed!==this._origMainRssFeed}_saveFeeds(){this._feedLoading||!this._feedDirty||(this._feedLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/feeds`,data:{mainRssFeed:this._mainRssFeed},section:`feeds`}})))}_saveHomeToggle(e){this._homeLoading||(this._showJantBrandingOnHome=e,this._homeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/home`,data:{showJantBrandingOnHome:e},section:`home`}})))}_saveSearchToggle(e){this.demoMode||this._searchLoading||(this._noindex=!e,this._searchLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/search`,data:{allowIndexing:e},section:`search`}})))}_onKeydown(e,t,n,r){e.key===`Enter`&&!r&&n&&!(e.target instanceof HTMLTextAreaElement)&&(e.preventDefault(),t())}_renderSaveAction(e,t,n){return u`
2167
2230
  <div class="flex mt-4">
2168
2231
  <button
2169
2232
  type="button"
@@ -2280,20 +2343,10 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2280
2343
  >
2281
2344
  ${this._renderSectionTitle(this.labels.languageAndTime)}
2282
2345
  <div class="field">
2283
- <label class="label">${this.labels.siteLanguage}</label>
2284
- <select
2285
- class="select"
2286
- @change=${e=>{this._siteLanguage=e.target.value,this._syncLocaleDirty()}}
2346
+ <label id="site-language-label" class="label"
2347
+ >${this.labels.siteLanguage}</label
2287
2348
  >
2288
- ${this.languages.map(e=>u`
2289
- <option
2290
- value=${e.value}
2291
- ?selected=${this._siteLanguage===e.value}
2292
- >
2293
- ${e.label}
2294
- </option>
2295
- `)}
2296
- </select>
2349
+ ${this._renderLanguagePicker()}
2297
2350
  <p class="text-sm text-muted-foreground mt-1">
2298
2351
  ${this.labels.siteLanguageHelp}
2299
2352
  </p>
@@ -2413,7 +2466,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2413
2466
  <div class="flex flex-col">
2414
2467
  ${this._renderGeneralForm()} ${this._renderSearchForm()}
2415
2468
  </div>
2416
- `}};customElements.define(`jant-settings-general`,cz);var lz=class extends c{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}removeError(){this._removeLoading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}async _removeAvatar(){await be({message:this.labels.confirmRemoveAvatar,confirmLabel:this.labels.remove,cancelLabel:this.labels.cancel,tone:`danger`})&&(this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}}))))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?u`
2469
+ `}};customElements.define(`jant-settings-general`,vz);var yz=class extends c{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}removeError(){this._removeLoading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}async _removeAvatar(){await be({message:this.labels.confirmRemoveAvatar,confirmLabel:this.labels.remove,cancelLabel:this.labels.cancel,tone:`danger`})&&(this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}}))))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?u`
2417
2470
  <div class=${e}>
2418
2471
  <img
2419
2472
  src=${this.avatarUrl}
@@ -2521,7 +2574,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2521
2574
  </div>
2522
2575
  </div>
2523
2576
  </div>
2524
- `}};customElements.define(`jant-settings-avatar`,lz);function uz(e){let t=w(e,`siteName`),n=w(e,`siteDescription`),r=w(e,`siteLanguage`),i=w(e,`cjkSerifFont`),a=w(e,`mainRssFeed`),o=w(e,`timeZone`),s=w(e,`siteFooter`),c=se(e,`showJantBrandingOnHome`),l=se(e,`noindex`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,cjkSerifFont:i,mainRssFeed:a,timeZone:o,siteFooter:s,showJantBrandingOnHome:c,noindex:l}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),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 le(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 le(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 dz(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=uz(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,dz):queueMicrotask(dz);var fz=300,pz=1,mz=class extends c{static properties={labels:{type:Object},apiBase:{type:String,attribute:`api-base`},connectUrl:{type:String,attribute:`connect-url`},installUrl:{type:String,attribute:`install-url`},cancelUrl:{type:String,attribute:`cancel-url`},createRepoNameHint:{type:String,attribute:`create-repo-name-hint`},_installations:{state:!0},_selectedOwner:{state:!0},_ownerOpen:{state:!0},_repos:{state:!0},_totalCount:{state:!0},_hasMore:{state:!0},_nextPage:{state:!0},_reposMode:{state:!0},_repoOpen:{state:!0},_repoSearch:{state:!0},_loadingRepos:{state:!0},_selectedRepo:{state:!0},_classification:{state:!0},_classifying:{state:!0},_confirmText:{state:!0},_connecting:{state:!0},_error:{state:!0}};#e=null;#t=0;#n=!1;#r=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.apiBase=``,this.connectUrl=``,this.installUrl=``,this.cancelUrl=``,this.createRepoNameHint=``,this._installations=[],this._selectedOwner=null,this._ownerOpen=!1,this._repos=[],this._totalCount=0,this._hasMore=!1,this._nextPage=null,this._reposMode=`list`,this._repoOpen=!1,this._repoSearch=``,this._loadingRepos=!1,this._selectedRepo=null,this._classification=null,this._classifying=!1,this._confirmText=``,this._connecting=!1,this._error=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#m),document.addEventListener(`keydown`,this.#h),window.addEventListener(`focus`,this.#g),this.#i()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#m),document.removeEventListener(`keydown`,this.#h),window.removeEventListener(`focus`,this.#g),this.#e&&clearTimeout(this.#e)}async#i(){try{let e=await fetch(`${this.apiBase}/installations`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._installations=t.installations;let n=t.installations.length===1?t.installations[0]:null;n&&this.#u(n)}catch(e){this._error=e instanceof Error?e.message:String(e)}}async#a(e,t={}){let n=++this.#t;this._loadingRepos=!0;try{let r=new URLSearchParams({installationId:e});t.q&&r.set(`q`,t.q);let i=await fetch(`${this.apiBase}/repos?${r.toString()}`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(n!==this.#t)return;if(i.status===410){this._installations=this._installations.filter(t=>t.installationId!==e),this._selectedOwner=null,this._repos=[];return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let a=await i.json();this._repos=a.repos,this._totalCount=a.totalCount,this._hasMore=a.hasMore,this._nextPage=a.nextPage,this._reposMode=a.mode}catch(e){n===this.#t&&(this._error=e instanceof Error?e.message:String(e))}finally{n===this.#t&&(this._loadingRepos=!1)}}async#o(e,t){this._classifying=!0,this._classification=null,this._confirmText=``;try{let n=await fetch(`${this.apiBase}/classify`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:e,repo:t})}),r=await n.json();if(!n.ok||!r.classification)throw Error(r.error??`HTTP ${n.status}`);this._classification=r.classification}catch(e){this._error=e instanceof Error?e.message:String(e)}finally{this._classifying=!1}}async#s(){if(!(!this._selectedOwner||!this._selectedRepo||!this._classification)){this._connecting=!0,this._error=null;try{let e=this._classification.kind===`foreign`||this._classification.kind===`owned-by-other-site`,t=await fetch(this.connectUrl,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:this._selectedOwner.installationId,repo:this._selectedRepo.fullName,confirmForeign:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw Error(n.error??`HTTP ${t.status}`);window.location.href=n.redirect??this.cancelUrl}catch(e){this._error=e instanceof Error?e.message:String(e),this._connecting=!1}}}#c(){let e=this._selectedOwner;if(!e)return;let t=this.createRepoNameHint||``,n=new URL(`https://github.com/new`);t&&n.searchParams.set(`name`,t),n.searchParams.set(`owner`,e.account.login),n.searchParams.set(`visibility`,`private`),this.#n=!0,this.#r=t||null,window.open(n.toString(),`_blank`,`noopener,noreferrer`),this._repoOpen=!1}#l(){if(!this._selectedOwner)return;let e=this._repoSearch.trim();this.#a(this._selectedOwner.installationId,e?{q:e}:{})}#u(e){if(this._selectedOwner?.installationId===e.installationId){this._ownerOpen=!1;return}this._selectedOwner=e,this._ownerOpen=!1,this._selectedRepo=null,this._classification=null,this._confirmText=``,this._repoSearch=``,this.#a(e.installationId)}#d(e){this._selectedRepo=e,this._repoOpen=!1,this._repoSearch=``,this._selectedOwner&&this.#o(this._selectedOwner.installationId,e.fullName)}#f(e){let t=e.target.value;if(this._repoSearch=t,this.#e&&clearTimeout(this.#e),!this._selectedOwner)return;let n=t.trim();if(n.length<pz){this._reposMode===`search`&&this.#a(this._selectedOwner.installationId);return}this.#e=setTimeout(()=>{this._selectedOwner&&this.#a(this._selectedOwner.installationId,{q:n})},fz)}#p(){let e=this._repoSearch.trim().toLowerCase();return!e||this._reposMode===`search`?this._repos:this._repos.filter(t=>t.name.toLowerCase().includes(e)||t.fullName.toLowerCase().includes(e))}#m=e=>{if(!this._ownerOpen&&!this._repoOpen)return;let t=e.target,n=this.querySelector(`.repo-picker-owner`),r=this.querySelector(`.repo-picker-repo`);n&&!n.contains(t)&&(this._ownerOpen=!1),r&&!r.contains(t)&&(this._repoOpen=!1)};#h=e=>{e.key===`Escape`&&(this._ownerOpen||this._repoOpen)&&(this._ownerOpen=!1,this._repoOpen=!1)};#g=()=>{if(!this.#n)return;let e=this._selectedOwner;if(!e){this.#n=!1;return}let t=this.#r;this.#n=!1,this.#r=null,(async()=>{if(this._repoSearch=``,await this.#a(e.installationId),t){let e=this._repos.find(e=>e.name===t);e&&this.#d(e)}})()};#_(){this._ownerOpen=!this._ownerOpen,this._repoOpen=!1}#v(){this._selectedOwner&&(this._repoOpen=!this._repoOpen,this._ownerOpen=!1,this._repoOpen&&queueMicrotask(()=>{this.querySelector(`.repo-picker-repo-search`)?.focus()}))}render(){return u`
2577
+ `}};customElements.define(`jant-settings-avatar`,yz);function bz(e){let t=w(e,`siteName`),n=w(e,`siteDescription`),r=w(e,`siteLanguage`),i=w(e,`cjkSerifFont`),a=w(e,`mainRssFeed`),o=w(e,`timeZone`),s=w(e,`siteFooter`),c=se(e,`showJantBrandingOnHome`),l=se(e,`noindex`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,cjkSerifFont:i,mainRssFeed:a,timeZone:o,siteFooter:s,showJantBrandingOnHome:c,noindex:l}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),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 le(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 le(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 xz(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=bz(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,xz):queueMicrotask(xz);var Sz=300,Cz=1,wz=class extends c{static properties={labels:{type:Object},apiBase:{type:String,attribute:`api-base`},connectUrl:{type:String,attribute:`connect-url`},installUrl:{type:String,attribute:`install-url`},cancelUrl:{type:String,attribute:`cancel-url`},createRepoNameHint:{type:String,attribute:`create-repo-name-hint`},_installations:{state:!0},_selectedOwner:{state:!0},_ownerOpen:{state:!0},_repos:{state:!0},_totalCount:{state:!0},_hasMore:{state:!0},_nextPage:{state:!0},_reposMode:{state:!0},_repoOpen:{state:!0},_repoSearch:{state:!0},_loadingRepos:{state:!0},_selectedRepo:{state:!0},_classification:{state:!0},_classifying:{state:!0},_confirmText:{state:!0},_connecting:{state:!0},_error:{state:!0}};#e=null;#t=0;#n=!1;#r=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.apiBase=``,this.connectUrl=``,this.installUrl=``,this.cancelUrl=``,this.createRepoNameHint=``,this._installations=[],this._selectedOwner=null,this._ownerOpen=!1,this._repos=[],this._totalCount=0,this._hasMore=!1,this._nextPage=null,this._reposMode=`list`,this._repoOpen=!1,this._repoSearch=``,this._loadingRepos=!1,this._selectedRepo=null,this._classification=null,this._classifying=!1,this._confirmText=``,this._connecting=!1,this._error=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#m),document.addEventListener(`keydown`,this.#h),window.addEventListener(`focus`,this.#g),this.#i()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#m),document.removeEventListener(`keydown`,this.#h),window.removeEventListener(`focus`,this.#g),this.#e&&clearTimeout(this.#e)}async#i(){try{let e=await fetch(`${this.apiBase}/installations`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._installations=t.installations;let n=t.installations.length===1?t.installations[0]:null;n&&this.#u(n)}catch(e){this._error=e instanceof Error?e.message:String(e)}}async#a(e,t={}){let n=++this.#t;this._loadingRepos=!0;try{let r=new URLSearchParams({installationId:e});t.q&&r.set(`q`,t.q);let i=await fetch(`${this.apiBase}/repos?${r.toString()}`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(n!==this.#t)return;if(i.status===410){this._installations=this._installations.filter(t=>t.installationId!==e),this._selectedOwner=null,this._repos=[];return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let a=await i.json();this._repos=a.repos,this._totalCount=a.totalCount,this._hasMore=a.hasMore,this._nextPage=a.nextPage,this._reposMode=a.mode}catch(e){n===this.#t&&(this._error=e instanceof Error?e.message:String(e))}finally{n===this.#t&&(this._loadingRepos=!1)}}async#o(e,t){this._classifying=!0,this._classification=null,this._confirmText=``;try{let n=await fetch(`${this.apiBase}/classify`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:e,repo:t})}),r=await n.json();if(!n.ok||!r.classification)throw Error(r.error??`HTTP ${n.status}`);this._classification=r.classification}catch(e){this._error=e instanceof Error?e.message:String(e)}finally{this._classifying=!1}}async#s(){if(!(!this._selectedOwner||!this._selectedRepo||!this._classification)){this._connecting=!0,this._error=null;try{let e=this._classification.kind===`foreign`||this._classification.kind===`owned-by-other-site`,t=await fetch(this.connectUrl,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:this._selectedOwner.installationId,repo:this._selectedRepo.fullName,confirmForeign:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw Error(n.error??`HTTP ${t.status}`);window.location.href=n.redirect??this.cancelUrl}catch(e){this._error=e instanceof Error?e.message:String(e),this._connecting=!1}}}#c(){let e=this._selectedOwner;if(!e)return;let t=this.createRepoNameHint||``,n=new URL(`https://github.com/new`);t&&n.searchParams.set(`name`,t),n.searchParams.set(`owner`,e.account.login),n.searchParams.set(`visibility`,`private`),this.#n=!0,this.#r=t||null,window.open(n.toString(),`_blank`,`noopener,noreferrer`),this._repoOpen=!1}#l(){if(!this._selectedOwner)return;let e=this._repoSearch.trim();this.#a(this._selectedOwner.installationId,e?{q:e}:{})}#u(e){if(this._selectedOwner?.installationId===e.installationId){this._ownerOpen=!1;return}this._selectedOwner=e,this._ownerOpen=!1,this._selectedRepo=null,this._classification=null,this._confirmText=``,this._repoSearch=``,this.#a(e.installationId)}#d(e){this._selectedRepo=e,this._repoOpen=!1,this._repoSearch=``,this._selectedOwner&&this.#o(this._selectedOwner.installationId,e.fullName)}#f(e){let t=e.target.value;if(this._repoSearch=t,this.#e&&clearTimeout(this.#e),!this._selectedOwner)return;let n=t.trim();if(n.length<Cz){this._reposMode===`search`&&this.#a(this._selectedOwner.installationId);return}this.#e=setTimeout(()=>{this._selectedOwner&&this.#a(this._selectedOwner.installationId,{q:n})},Sz)}#p(){let e=this._repoSearch.trim().toLowerCase();return!e||this._reposMode===`search`?this._repos:this._repos.filter(t=>t.name.toLowerCase().includes(e)||t.fullName.toLowerCase().includes(e))}#m=e=>{if(!this._ownerOpen&&!this._repoOpen)return;let t=e.target,n=this.querySelector(`.repo-picker-owner`),r=this.querySelector(`.repo-picker-repo`);n&&!n.contains(t)&&(this._ownerOpen=!1),r&&!r.contains(t)&&(this._repoOpen=!1)};#h=e=>{e.key===`Escape`&&(this._ownerOpen||this._repoOpen)&&(this._ownerOpen=!1,this._repoOpen=!1)};#g=()=>{if(!this.#n)return;let e=this._selectedOwner;if(!e){this.#n=!1;return}let t=this.#r;this.#n=!1,this.#r=null,(async()=>{if(this._repoSearch=``,await this.#a(e.installationId),t){let e=this._repos.find(e=>e.name===t);e&&this.#d(e)}})()};#_(){this._ownerOpen=!this._ownerOpen,this._repoOpen=!1}#v(){this._selectedOwner&&(this._repoOpen=!this._repoOpen,this._ownerOpen=!1,this._repoOpen&&queueMicrotask(()=>{this.querySelector(`.repo-picker-repo-search`)?.focus()}))}render(){return u`
2525
2578
  <div class="flex flex-col gap-6 max-w-lg">
2526
2579
  <div>
2527
2580
  <h2 class="text-lg font-medium mb-1">${this.labels.pageTitle}</h2>
@@ -2732,7 +2785,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2732
2785
  </button>
2733
2786
  <a href=${this.cancelUrl} class="btn-ghost">${this.labels.cancel}</a>
2734
2787
  </div>
2735
- `}};customElements.define(`jant-repo-picker`,mz);var hz=`/collections`;function gz(e){return e.includes(`+`)}function _z(){return hz}function vz(e){return`/${e}`}function yz(e){return gz(e)?`${hz}/${e}`:vz(e)}function bz(e){return`${hz}/${e}/edit`}var xz,Sz;function Cz(){return xz?Promise.resolve(xz):(Sz||=kO(()=>import(`./chunks/url-pLre2DM_.js`).then(e=>e.i).then(e=>(xz=e.slugify,e.slugify)),[]),Sz)}async function wz(e){return(await Cz())(e)}var Tz=class extends c{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;_descEditor=null;#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),this.#f(e))},this.addEventListener(`keydown`,this.#t)}disconnectedCallback(){this.#t&&=(this.removeEventListener(`keydown`,this.#t),null),super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null}update(e){(!this.#e||e.has(`initial`))&&this.#n(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#n(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`,this.variant!==`quick`&&this.updateComplete.then(()=>this.#r()))}#r(){let e=this.querySelector(`[data-collection-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=NT({element:e,placeholder:this.isEdit?void 0:this.labels.descriptionPlaceholder,content:this._description||void 0,onUpdate:e=>{this._description=e}}),this._description=MT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`5rem`)}async#i(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=gS(await wz(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#a(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#o(){let e=_S(this._slug,{maxLength:200});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#s(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#c(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#l(){let e=i(vz(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
2788
+ `}};customElements.define(`jant-repo-picker`,wz);var Tz=`/collections`;function Ez(e){return e.includes(`+`)}function Dz(){return Tz}function Oz(e){return`/${e}`}function kz(e){return Ez(e)?`${Tz}/${e}`:Oz(e)}function Az(e){return`${Tz}/${e}/edit`}var jz,Mz;function Nz(){return jz?Promise.resolve(jz):(Mz||=kO(()=>import(`./chunks/url-pLre2DM_.js`).then(e=>e.i).then(e=>(jz=e.slugify,e.slugify)),[]),Mz)}async function Pz(e){return(await Nz())(e)}var Fz=class extends c{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;_descEditor=null;#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t=e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),this.#f(e))},this.addEventListener(`keydown`,this.#t)}disconnectedCallback(){this.#t&&=(this.removeEventListener(`keydown`,this.#t),null),super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null}update(e){(!this.#e||e.has(`initial`))&&this.#n(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#n(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`,this.variant!==`quick`&&this.updateComplete.then(()=>this.#r()))}#r(){let e=this.querySelector(`[data-collection-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=NT({element:e,placeholder:this.isEdit?void 0:this.labels.descriptionPlaceholder,content:this._description||void 0,onUpdate:e=>{this._description=e}}),this._description=MT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`5rem`)}async#i(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=gS(await Pz(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#a(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#o(){let e=_S(this._slug,{maxLength:200});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#s(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#c(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#l(){let e=i(Oz(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
2736
2789
  class="text-xs text-destructive mt-1"
2737
2790
  data-collection-slug-error
2738
2791
  >
@@ -2789,7 +2842,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2789
2842
  </button>
2790
2843
  </div>
2791
2844
  </div>
2792
- `}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=gS(await wz(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`
2845
+ `}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=gS(await Pz(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`
2793
2846
  <form
2794
2847
  class=${e?`flex flex-col gap-4`:`collection-editor-form`}
2795
2848
  @submit=${e=>void this.#f(e)}
@@ -2904,20 +2957,20 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2904
2957
  </div>
2905
2958
  `}
2906
2959
  </form>
2907
- `}};customElements.define(`jant-collection-form`,Tz);function Ez(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 Dz(e){return typeof e==`string`?e:``}function Oz(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function kz(e){let n=sx(t(e.src));if(!n)return``;let r=` sandbox="${sx(e.sandbox)}"`,i=e.allow?` allow="${sx(e.allow)}"`:``;return`<iframe src="${n}"${` title="${sx(e.providerName)} embed"`}${r}${i} loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`}function Az(e){let t=e.orientation===`portrait`?`portrait`:e.orientation===`square`?`square`:e.orientation===`auto`?`auto`:`landscape`,n=[];e.heightPx&&e.heightPx>0&&n.push(`--tiptap-embed-height:${Math.round(e.heightPx)}px`);let r=n.length>0?` style="${sx(n.join(`;`))}"`:``;return` data-orientation="${sx(t)}"${r}`}function jz(e,n){let r=kz(e);if(!r)return``;let i=sx(t(e.url||e.src)),a=sx(e.providerName),o=i?`<a class="tiptap-embed-fallback" href="${i}" target="_blank" rel="noopener noreferrer">${a} →</a>`:``,s=sx(e.provider),c=n?.trim()?`<figcaption>${sx(n.trim())}</figcaption>`:``;return`<figure class="tiptap-embed-figure" data-provider="${s}"${Az(e)}><div class="tiptap-embed-frame">${r}</div>`+o+c+`</figure>`}function Mz(e){let n=e??{},r=Dz(n.url),i=Dz(n.src),a=null;if(i){let e=t(i);e&&(a={provider:Dz(n.provider)||`iframe`,providerName:Dz(n.providerName)||`Embed`,src:e,url:r||e,orientation:Dz(n.orientation)||`landscape`,heightPx:Oz(n.heightPx)??void 0,sandbox:Dz(n.sandbox)||`allow-scripts allow-same-origin allow-popups`,allow:Dz(n.allow)||void 0,cspFrameSrc:[],cspScriptSrc:[]})}if(!a&&r&&(a=RS(r)),!a){if(!r)return``;let e=sx(t(r));return e?`<p class="tiptap-embed-fallback"><a href="${e}" target="_blank" rel="noopener noreferrer">${e}</a></p>`:``}return jz(a,Dz(n.caption))}function Nz(e,t){let n=e?.[t];return typeof n==`string`?n:``}function Pz(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Fz(e){switch(e.type){case`text`:return sx(e.text??``);case`hardBreak`:return`
2908
- `;default:return(e.content??[]).map(Fz).join(``)}}function Iz(e,t,n){let r=Pz(t.attrs,`colspan`),i=Pz(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function Lz(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var Rz=null;function zz(e,t){let n=Qb(Nz(e.attrs,`label`)),r=nx(n),i=Rz?.get(n),a=i?Lz(t.renderChildren(i.content)):``;return`<label for="sn-${sx(r)}" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-${sx(r)}" class="margin-toggle"/><span class="sidenote">${a}</span>`}var Bz={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=sx(t(Nz(n.attrs,`href`))),i=Nz(n.attrs,`target`);return`<a href="${r}"${i?` target="${sx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},Vz={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=Qb(Nz(e.attrs,`label`));t&&r.set(t,e)}Rz=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{Rz=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(Pz(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=Pz(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=Nz(e.attrs,`language`);return`<pre><code${t?` class="language-${sx(t)}"`:``}>${Fz(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>Iz(`td`,e,t),tableHeader:(e,t)=>Iz(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>ux(e.attrs??{}),embed:e=>Mz(e.attrs),htmlBlock:e=>{let t=Nz(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>zz(e,t),footnoteDefinition:()=>``};function Hz(e,t=[]){let n=sx(e);for(let e of t){let t=Bz[e.type];t&&(n=t(n,e))}return n}function Uz(e=[]){return e.map(Gz).join(``)}function Wz(e,t){return e.content?t.renderChildren(e.content):``}function Gz(e){return(Vz[e.type]??Wz)(e,Kz)}var Kz={renderChildren:Uz,renderNode:Gz,renderText:Hz};function qz(e){return e.type===`doc`?Gz(ax(e)):``}function Jz(e){return e.trim()?qz(Bx(e)):``}function Yz(){return Math.floor(Date.now()/1e3)}function Xz(e){return new Date(e*1e3).toISOString()}function Zz(e,t=`UTC`){let n=Yz()-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 Qz(e,t=`UTC`){let n=Zz(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var $z=class extends c{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#b();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#y();break;case`divider`:this.#C();break;case`link`:this.#w();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#p()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(){return this._items.filter(e=>e.type===`collection`&&e.collection).length}#d(){let e=this.#u();return`${e} ${e===1?this.labels.collectionSingular:this.labels.collectionPlural}`}#f(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#p(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#m(e){return this.#r?.querySelector(e)??null}#h(){let e=this.#m(`[data-collections-count]`);e&&(e.textContent=this.#d(),e.hidden=!1);let t=this.#m(`[data-collections-action="done"]`);t&&(t.hidden=!this._reorderMode);let n=this.#m(`[data-collections-reorder-actions]`);n&&(n.hidden=!this._reorderMode);let r=this.#m(`[data-collections-toolbar]`);r&&(r.hidden=this._reorderMode);let i=this.#m(`[data-collections-hint]`);i&&(i.hidden=!this._reorderMode);let a=this.#m(`[data-collections-more-menu]`);a&&(a.hidden=!this._showMoreMenu||this._reorderMode);let o=this.#m(`[data-collections-action="toggle-menu"]`);o&&o.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#g(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#_(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#g(t)}catch{}}#v(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...vO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{SO(e,!0)},onStart:e=>{this.#n=bO(e)},onUnchoose:()=>{SO(e,!1)},onEnd:t=>{let n=yO(e,`[data-directory-item]`,`directoryItem`);xO(e,t,this.#n),this.#n=null,SO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:o}=CO(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`)})}}))}#y(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#b(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#p(),this.#h(),this._reorderMode&&this.#v(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#x()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#S()}#x(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=NT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=MT(this.#i.getJSON()))}#S(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=NT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=MT(this.#a.getJSON()))}async#C(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#_(),this._editingDividerId=t.id}catch{a(this.labels.saveFailed,`error`)}}#w(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#T(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){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.#_()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#E(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{a(this.labels.saveFailed,`error`)}}async#D(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{a(this.labels.saveFailed,`error`),await this.#_()}}async#O(e){if(await be({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(this.labels.deleted),await this.#_()}catch{a(this.labels.saveFailed,`error`)}}}#k(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#A(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){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.#_()}}async#j(e){if(await be({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{a(this.labels.saveFailed,`error`)}}}#M(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#N(e,t){let n=e.collection;if(!n)return g;let r=u`
2960
+ `}};customElements.define(`jant-collection-form`,Fz);function Iz(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 Lz(e){return typeof e==`string`?e:``}function Rz(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function zz(e){let n=sx(t(e.src));if(!n)return``;let r=` sandbox="${sx(e.sandbox)}"`,i=e.allow?` allow="${sx(e.allow)}"`:``;return`<iframe src="${n}"${` title="${sx(e.providerName)} embed"`}${r}${i} loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`}function Bz(e){let t=e.orientation===`portrait`?`portrait`:e.orientation===`square`?`square`:e.orientation===`auto`?`auto`:`landscape`,n=[];e.heightPx&&e.heightPx>0&&n.push(`--tiptap-embed-height:${Math.round(e.heightPx)}px`);let r=n.length>0?` style="${sx(n.join(`;`))}"`:``;return` data-orientation="${sx(t)}"${r}`}function Vz(e,n){let r=zz(e);if(!r)return``;let i=sx(t(e.url||e.src)),a=sx(e.providerName),o=i?`<a class="tiptap-embed-fallback" href="${i}" target="_blank" rel="noopener noreferrer">${a} →</a>`:``,s=sx(e.provider),c=n?.trim()?`<figcaption>${sx(n.trim())}</figcaption>`:``;return`<figure class="tiptap-embed-figure" data-provider="${s}"${Bz(e)}><div class="tiptap-embed-frame">${r}</div>`+o+c+`</figure>`}function Hz(e){let n=e??{},r=Lz(n.url),i=Lz(n.src),a=null;if(i){let e=t(i);e&&(a={provider:Lz(n.provider)||`iframe`,providerName:Lz(n.providerName)||`Embed`,src:e,url:r||e,orientation:Lz(n.orientation)||`landscape`,heightPx:Rz(n.heightPx)??void 0,sandbox:Lz(n.sandbox)||`allow-scripts allow-same-origin allow-popups`,allow:Lz(n.allow)||void 0,cspFrameSrc:[],cspScriptSrc:[]})}if(!a&&r&&(a=RS(r)),!a){if(!r)return``;let e=sx(t(r));return e?`<p class="tiptap-embed-fallback"><a href="${e}" target="_blank" rel="noopener noreferrer">${e}</a></p>`:``}return Vz(a,Lz(n.caption))}function Uz(e,t){let n=e?.[t];return typeof n==`string`?n:``}function Wz(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Gz(e){switch(e.type){case`text`:return sx(e.text??``);case`hardBreak`:return`
2961
+ `;default:return(e.content??[]).map(Gz).join(``)}}function Kz(e,t,n){let r=Wz(t.attrs,`colspan`),i=Wz(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function qz(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var Jz=null;function Yz(e,t){let n=Qb(Uz(e.attrs,`label`)),r=nx(n),i=Jz?.get(n),a=i?qz(t.renderChildren(i.content)):``;return`<label for="sn-${sx(r)}" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-${sx(r)}" class="margin-toggle"/><span class="sidenote">${a}</span>`}var Xz={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=sx(t(Uz(n.attrs,`href`))),i=Uz(n.attrs,`target`);return`<a href="${r}"${i?` target="${sx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},Zz={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=Qb(Uz(e.attrs,`label`));t&&r.set(t,e)}Jz=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{Jz=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(Wz(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=Wz(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=Uz(e.attrs,`language`);return`<pre><code${t?` class="language-${sx(t)}"`:``}>${Gz(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>Kz(`td`,e,t),tableHeader:(e,t)=>Kz(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>ux(e.attrs??{}),embed:e=>Hz(e.attrs),htmlBlock:e=>{let t=Uz(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>Yz(e,t),footnoteDefinition:()=>``};function Qz(e,t=[]){let n=sx(e);for(let e of t){let t=Xz[e.type];t&&(n=t(n,e))}return n}function $z(e=[]){return e.map(tB).join(``)}function eB(e,t){return e.content?t.renderChildren(e.content):``}function tB(e){return(Zz[e.type]??eB)(e,nB)}var nB={renderChildren:$z,renderNode:tB,renderText:Qz};function rB(e){return e.type===`doc`?tB(ax(e)):``}function iB(e){return e.trim()?rB(Bx(e)):``}function aB(){return Math.floor(Date.now()/1e3)}function oB(e){return new Date(e*1e3).toISOString()}function sB(e,t=`UTC`){let n=aB()-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 cB(e,t=`UTC`){let n=sB(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var lB=class extends c{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#b();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#y();break;case`divider`:this.#C();break;case`link`:this.#w();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#p()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(){return this._items.filter(e=>e.type===`collection`&&e.collection).length}#d(){let e=this.#u();return`${e} ${e===1?this.labels.collectionSingular:this.labels.collectionPlural}`}#f(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#p(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#m(e){return this.#r?.querySelector(e)??null}#h(){let e=this.#m(`[data-collections-count]`);e&&(e.textContent=this.#d(),e.hidden=!1);let t=this.#m(`[data-collections-action="done"]`);t&&(t.hidden=!this._reorderMode);let n=this.#m(`[data-collections-reorder-actions]`);n&&(n.hidden=!this._reorderMode);let r=this.#m(`[data-collections-toolbar]`);r&&(r.hidden=this._reorderMode);let i=this.#m(`[data-collections-hint]`);i&&(i.hidden=!this._reorderMode);let a=this.#m(`[data-collections-more-menu]`);a&&(a.hidden=!this._showMoreMenu||this._reorderMode);let o=this.#m(`[data-collections-action="toggle-menu"]`);o&&o.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#g(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#_(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#g(t)}catch{}}#v(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...vO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{SO(e,!0)},onStart:e=>{this.#n=bO(e)},onUnchoose:()=>{SO(e,!1)},onEnd:t=>{let n=yO(e,`[data-directory-item]`,`directoryItem`);xO(e,t,this.#n),this.#n=null,SO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:o}=CO(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`)})}}))}#y(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#b(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#p(),this.#h(),this._reorderMode&&this.#v(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#x()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#S()}#x(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=NT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=MT(this.#i.getJSON()))}#S(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=NT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=MT(this.#a.getJSON()))}async#C(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#_(),this._editingDividerId=t.id}catch{a(this.labels.saveFailed,`error`)}}#w(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#T(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){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.#_()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#E(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{a(this.labels.saveFailed,`error`)}}async#D(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{a(this.labels.saveFailed,`error`),await this.#_()}}async#O(e){if(await be({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(this.labels.deleted),await this.#_()}catch{a(this.labels.saveFailed,`error`)}}}#k(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#A(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){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.#_()}}async#j(e){if(await be({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{a(this.labels.saveFailed,`error`)}}}#M(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#N(e,t){let n=e.collection;if(!n)return g;let r=u`
2909
2962
  <div class="collection-directory-main">
2910
2963
  <span class="collection-directory-sequence" aria-hidden="true">
2911
2964
  ${t}
2912
2965
  </span>
2913
2966
  <div class="collection-directory-title-row">
2914
- <a href=${i(yz(n.slug))} class="collection-directory-title-link">
2967
+ <a href=${i(kz(n.slug))} class="collection-directory-title-link">
2915
2968
  <span class="collection-directory-title">${n.title}</span>
2916
2969
  </a>
2917
2970
  </div>
2918
2971
  ${n.description?u`
2919
2972
  <div class="collection-directory-description prose">
2920
- ${v(Jz(n.description))}
2973
+ ${v(iB(n.description))}
2921
2974
  </div>
2922
2975
  `:g}
2923
2976
  <p class="collection-directory-summary">
@@ -2929,9 +2982,9 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2929
2982
  >
2930
2983
  <time
2931
2984
  class="collection-directory-updated"
2932
- datetime=${Xz(n.recentActivityAt)}
2985
+ datetime=${oB(n.recentActivityAt)}
2933
2986
  >
2934
- ${Qz(n.recentActivityAt)}
2987
+ ${cB(n.recentActivityAt)}
2935
2988
  </time>
2936
2989
  </p>
2937
2990
  </div>
@@ -3071,7 +3124,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3071
3124
  </div>
3072
3125
  ${e.description?u`
3073
3126
  <div class="collection-directory-description prose">
3074
- ${v(Jz(e.description))}
3127
+ ${v(iB(e.description))}
3075
3128
  </div>
3076
3129
  `:u`
3077
3130
  <p class="collection-directory-summary">
@@ -3149,7 +3202,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3149
3202
  >
3150
3203
  ${t?u`
3151
3204
  <a
3152
- href=${i(`${bz(t.slug)}?returnTo=${encodeURIComponent(i(_z()))}`)}
3205
+ href=${i(`${Az(t.slug)}?returnTo=${encodeURIComponent(i(Dz()))}`)}
3153
3206
  class="collections-page-menu-item"
3154
3207
  >
3155
3208
  ${this.labels.edit}
@@ -3241,7 +3294,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3241
3294
  </svg>
3242
3295
  </button>
3243
3296
  </div>
3244
- `;let n=!!e.label,r=Ez(this._items,t);return u`
3297
+ `;let n=!!e.label,r=Iz(this._items,t);return u`
3245
3298
  <div class="collection-directory-divider">
3246
3299
  <div
3247
3300
  class="collection-directory-divider-row"
@@ -3250,7 +3303,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3250
3303
  ${n?u`
3251
3304
  ${r?u`
3252
3305
  <a
3253
- href=${i(yz(r.slugExpression))}
3306
+ href=${i(kz(r.slugExpression))}
3254
3307
  class="collection-directory-divider-link collection-directory-divider-text"
3255
3308
  >
3256
3309
  ${e.label}
@@ -3328,7 +3381,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3328
3381
  ${(()=>{let e=this.#M();return this._items.map((t,n)=>t.type===`collection`?this.#N(t,e[n]):t.type===`link`?this.#F(t,e[n]):this.#L(t,n))})()}
3329
3382
  </div>
3330
3383
  `:u`<p class="text-muted-foreground">${this.labels.emptyState}</p>`}
3331
- `}};customElements.define(`jant-collections-manager`,$z);function eB(e){try{let t=new URL(e,window.location.origin);return t.origin===window.location.origin?t:null}catch{return null}}function tB(){return document.documentElement.dataset.sitePathPrefix||``}function nB(e){let t=tB();return t?e===t?`/`:e.startsWith(`${t}/`)?e.slice(t.length)||`/`:null:e||`/`}function rB(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 iB(e,t,n){let r=t.cancelHref||i(_z());if(!e.isEdit||!n)return r;let a=eB(r);if(!a)return i(vz(n));let o=nB(a.pathname),s=t.initial?.slug?.trim()||void 0;if(s&&o===vz(s))return a.pathname=i(vz(n)),`${a.pathname}${a.search}${a.hash}`;let c=o?.match(/^\/collections\/([^/]+)$/);return c&&(a.pathname=i(yz(rB(c[1],n,s)))),`${a.pathname}${a.search}${a.hash}`}document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let a=iB(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 aB(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(sS(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return u`<svg
3384
+ `}};customElements.define(`jant-collections-manager`,lB);function uB(e){try{let t=new URL(e,window.location.origin);return t.origin===window.location.origin?t:null}catch{return null}}function dB(){return document.documentElement.dataset.sitePathPrefix||``}function fB(e){let t=dB();return t?e===t?`/`:e.startsWith(`${t}/`)?e.slice(t.length)||`/`:null:e||`/`}function pB(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 mB(e,t,n){let r=t.cancelHref||i(Dz());if(!e.isEdit||!n)return r;let a=uB(r);if(!a)return i(Oz(n));let o=fB(a.pathname),s=t.initial?.slug?.trim()||void 0;if(s&&o===Oz(s))return a.pathname=i(Oz(n)),`${a.pathname}${a.search}${a.hash}`;let c=o?.match(/^\/collections\/([^/]+)$/);return c&&(a.pathname=i(kz(pB(c[1],n,s)))),`${a.pathname}${a.search}${a.hash}`}document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let a=mB(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 hB(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(sS(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return u`<svg
3332
3385
  width="24"
3333
3386
  height="24"
3334
3387
  viewBox="0 0 24 24"
@@ -3361,7 +3414,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3361
3414
  stroke-linejoin="round"
3362
3415
  >
3363
3416
  ${Ce(`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>`+t)}
3364
- </svg>`}function oB(e){return sS(e.mimeType)===`image`?u`<img
3417
+ </svg>`}function gB(e){return sS(e.mimeType)===`image`?u`<img
3365
3418
  src=${e.thumbUrl}
3366
3419
  alt=${e.alt}
3367
3420
  class="w-full h-full object-cover rounded-lg border"
@@ -3369,15 +3422,15 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3369
3422
  />`:u`<div
3370
3423
  class="w-full h-full rounded-lg border bg-muted flex flex-col items-center justify-center gap-1 p-1 text-muted-foreground"
3371
3424
  >
3372
- ${aB(e.mimeType)}
3425
+ ${hB(e.mimeType)}
3373
3426
  <span class="text-[10px] leading-tight text-center truncate w-full px-1"
3374
3427
  >${e.originalName}</span
3375
3428
  >
3376
- </div>`}function sB(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return u`<p class="text-sm text-muted-foreground">
3429
+ </div>`}function _B(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return u`<p class="text-sm text-muted-foreground">
3377
3430
  ${n.mediaEmptyLabel}
3378
3431
  </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">
3379
3432
  ${r.map(t=>{let r=i.get(t);return r?u`<div class="relative group aspect-square" data-media-id=${t}>
3380
- ${oB(r)}
3433
+ ${gB(r)}
3381
3434
  <button
3382
3435
  type="button"
3383
3436
  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"
@@ -3399,7 +3452,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3399
3452
  &times;
3400
3453
  </button>
3401
3454
  </div>`})}
3402
- </div>`}function cB(e){return e.collections.length?u`<div class="field">
3455
+ </div>`}function vB(e){return e.collections.length?u`<div class="field">
3403
3456
  <label class="label">${e.labels.collectionsLabel}</label>
3404
3457
  <div class="flex flex-col gap-1">
3405
3458
  ${e.collections.map(t=>u`<label class="flex items-center gap-2 text-sm">
@@ -3412,7 +3465,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3412
3465
  <span>${t.title}</span>
3413
3466
  </label>`)}
3414
3467
  </div>
3415
- </div>`:g}function lB(e){return u`<form
3468
+ </div>`:g}function yB(e){return u`<form
3416
3469
  class="flex flex-col gap-4 max-w-2xl"
3417
3470
  @submit=${t=>e.handleSubmit(t)}
3418
3471
  >
@@ -3487,7 +3540,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3487
3540
 
3488
3541
  <div class="field">
3489
3542
  <label class="label">${e.labels.mediaLabel}</label>
3490
- ${sB(e)}
3543
+ ${_B(e)}
3491
3544
  <button
3492
3545
  type="button"
3493
3546
  class="btn-outline text-sm"
@@ -3533,7 +3586,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3533
3586
  ${e.labels.pinnedLabel}
3534
3587
  </label>
3535
3588
 
3536
- ${cB(e)}
3589
+ ${vB(e)}
3537
3590
 
3538
3591
  <div class="flex gap-2">
3539
3592
  <button type="submit" class="btn" ?disabled=${e._loading}>
@@ -3583,7 +3636,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3583
3636
  ${e.labels.mediaDialogLoading}
3584
3637
  </p>
3585
3638
  </div>
3586
- </dialog>`}var uB={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},dB={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 fB(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var pB=class e extends c{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...dB},this.initial={...uB},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=fB(this.labels,{...dB})),typeof this.initial==`string`&&(this.initial=fB(this.initial,{...uB})),typeof this.collections==`string`&&(this.collections=fB(this.collections,[])),typeof this.media==`string`&&(this.media=fB(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??uB;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=jT({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 lB(this)}};customElements.define(`jant-post-form`,pB);function mB(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 hB(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function gB(e){let t=e,n=t.detail;if(!n)return;let r=mB(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await le(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await le(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let o=w(t,`status`),s=w(t,`url`);if(o===`redirect`&&s){r.clearDirty(),m(i),window.location.href=s;return}a(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await le(e),i=w(t,`status`),o=w(t,`url`);if(i===`redirect`&&o){r.clearDirty(),m(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 _B(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=mB(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&&hB(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),hB(t,!1)):(r.add(n),hB(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,gB),document.addEventListener(`jant:post-load-media`,_B);var{I:vB}=l,yB=e=>e,bB=()=>document.createComment(``),xB=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new vB(r.insertBefore(bB(),i),r.insertBefore(bB(),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=yB(e).nextSibling;yB(r).insertBefore(e,i),e=t}}}return n},SB=(e,t,n=e)=>(e._$AI(t,n),e),CB={},wB=(e,t=CB)=>e._$AH=t,TB=e=>e._$AH,EB=e=>{e._$AR(),e._$AA.remove()},DB=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},OB=o(class extends f{constructor(e){if(super(e),e.type!==b.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=TB(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,m=0,h=a.length-1;for(;d<=f&&m<=h;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[m])c[m]=SB(i[d],a[m]),d++,m++;else if(s[f]===o[h])c[h]=SB(i[f],a[h]),f--,h--;else if(s[d]===o[h])c[h]=SB(i[d],a[h]),xB(e,c[h+1],i[d]),d++,h--;else if(s[f]===o[m])c[m]=SB(i[f],a[m]),xB(e,i[d],i[f]),f--,m++;else if(l===void 0&&(l=DB(o,m,h),u=DB(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=xB(e,i[d]);SB(t,a[m]),c[m]=t}else c[m]=SB(n,a[m]),xB(e,i[d],n),i[t]=null;m++}else EB(i[f]),f--;else EB(i[d]),d++;for(;m<=h;){let t=xB(e,c[h+1]);SB(t,a[m]),c[m++]=t}for(;d<=f;){let e=i[d++];e!==null&&EB(e)}return this.ut=o,wB(e,c),p}}),kB=class extends c{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#b())};#s=e=>{!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore||(e.preventDefault(),this.#b(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#y.length===0&&this.#b(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#b()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...vO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=bO(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=yO(o,`[data-nav-id]`,`navId`),u=yO(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)):xO(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:_}=CO(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 be({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){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`
3639
+ </dialog>`}var bB={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},xB={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 SB(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var CB=class e extends c{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...xB},this.initial={...bB},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=SB(this.labels,{...xB})),typeof this.initial==`string`&&(this.initial=SB(this.initial,{...bB})),typeof this.collections==`string`&&(this.collections=SB(this.collections,[])),typeof this.media==`string`&&(this.media=SB(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??bB;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=jT({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 yB(this)}};customElements.define(`jant-post-form`,CB);function wB(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 TB(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function EB(e){let t=e,n=t.detail;if(!n)return;let r=wB(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await le(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await le(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let o=w(t,`status`),s=w(t,`url`);if(o===`redirect`&&s){r.clearDirty(),m(i),window.location.href=s;return}a(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await le(e),i=w(t,`status`),o=w(t,`url`);if(i===`redirect`&&o){r.clearDirty(),m(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 DB(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=wB(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&&TB(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),TB(t,!1)):(r.add(n),TB(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,EB),document.addEventListener(`jant:post-load-media`,DB);var{I:OB}=l,kB=e=>e,AB=()=>document.createComment(``),jB=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new OB(r.insertBefore(AB(),i),r.insertBefore(AB(),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=kB(e).nextSibling;kB(r).insertBefore(e,i),e=t}}}return n},MB=(e,t,n=e)=>(e._$AI(t,n),e),NB={},PB=(e,t=NB)=>e._$AH=t,FB=e=>e._$AH,IB=e=>{e._$AR(),e._$AA.remove()},LB=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},RB=o(class extends f{constructor(e){if(super(e),e.type!==b.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=FB(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,m=0,h=a.length-1;for(;d<=f&&m<=h;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[m])c[m]=MB(i[d],a[m]),d++,m++;else if(s[f]===o[h])c[h]=MB(i[f],a[h]),f--,h--;else if(s[d]===o[h])c[h]=MB(i[d],a[h]),jB(e,c[h+1],i[d]),d++,h--;else if(s[f]===o[m])c[m]=MB(i[f],a[m]),jB(e,i[d],i[f]),f--,m++;else if(l===void 0&&(l=LB(o,m,h),u=LB(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=jB(e,i[d]);MB(t,a[m]),c[m]=t}else c[m]=MB(n,a[m]),jB(e,i[d],n),i[t]=null;m++}else IB(i[f]),f--;else IB(i[d]),d++;for(;m<=h;){let t=jB(e,c[h+1]);MB(t,a[m]),c[m++]=t}for(;d<=f;){let e=i[d++];e!==null&&IB(e)}return this.ut=o,PB(e,c),p}}),zB=class extends c{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#b())};#s=e=>{!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore||(e.preventDefault(),this.#b(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#y.length===0&&this.#b(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#b()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...vO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=bO(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=yO(o,`[data-nav-id]`,`navId`),u=yO(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)):xO(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:_}=CO(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 be({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){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`
3587
3640
  <div class="nav-preview">
3588
3641
  <div class="nav-preview-chrome">
3589
3642
  <div class="nav-preview-dots">
@@ -3595,7 +3648,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3595
3648
  <div class="site-header-top">
3596
3649
  <a href=${i(`/`)} class="site-logo">${this.siteName}</a>
3597
3650
  <nav class="site-header-nav">
3598
- ${OB(e,e=>e.id,(e,t)=>u`<a
3651
+ ${RB(e,e=>e.id,(e,t)=>u`<a
3599
3652
  class=${t===0?`site-header-link site-header-link-active`:`site-header-link`}
3600
3653
  >
3601
3654
  ${e.displayLabel??e.label}
@@ -3631,7 +3684,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3631
3684
  aria-hidden=${this._showPreviewMore?`false`:`true`}
3632
3685
  @click=${e=>e.stopPropagation()}
3633
3686
  >
3634
- ${OB(t,e=>e.id,e=>u`
3687
+ ${RB(t,e=>e.id,e=>u`
3635
3688
  <span class="site-header-more-link">
3636
3689
  ${e.displayLabel??e.label}
3637
3690
  </span>
@@ -4009,14 +4062,14 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4009
4062
  ${this.labels.emptyState}
4010
4063
  </p>`:g}
4011
4064
  <div id="nav-items-header" class="nav-items-list">
4012
- ${OB(this.#v,e=>e.id,e=>this.#T(e))}
4065
+ ${RB(this.#v,e=>e.id,e=>this.#T(e))}
4013
4066
  </div>
4014
4067
  </section>
4015
4068
 
4016
4069
  <section class="mt-8">
4017
4070
  <h2 class="text-lg font-semibold mb-3">${this.labels.moreSection}</h2>
4018
4071
  <div id="nav-items-more" class="nav-items-list nav-items-list-drop">
4019
- ${this.#y.length>0?OB(this.#y,e=>e.id,e=>this.#T(e)):u`<p class="nav-items-empty-hint">
4072
+ ${this.#y.length>0?RB(this.#y,e=>e.id,e=>this.#T(e)):u`<p class="nav-items-empty-hint">
4020
4073
  ${this.labels.moreEmptyHint}
4021
4074
  </p>`}
4022
4075
  </div>
@@ -4024,7 +4077,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4024
4077
 
4025
4078
  ${this.#E()} ${this.#D()}
4026
4079
  ${this.#O()}
4027
- `}};customElements.define(`jant-nav-manager`,kB),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 AB=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,jB=`M4 4 20 20`,MB=360,NB=12;function PB(e){let t=window.innerHeight-e.bottom-NB,n=e.top-NB;return t<MB&&n>t}function FB(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 IB=class extends c{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=PB(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{if(e.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},a({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),a(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},a(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),a(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},a(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),a(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},a(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),a(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await be({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.thread-item`),n=t?.closest(`.thread-group`);if(t&&n){if(t.remove(),n.querySelectorAll(`.thread-item:not(.thread-item-gap)`).length===0){let e=n.closest(`.feed-item`),t=e?.parentElement??null;(e??n).remove(),FB(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),FB(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=Kx(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
4080
+ `}};customElements.define(`jant-nav-manager`,zB),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 BB=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,VB=`M4 4 20 20`,HB=360,UB=12;function WB(e){let t=window.innerHeight-e.bottom-UB,n=e.top-UB;return t<HB&&n>t}function GB(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 KB=class extends c{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=WB(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{if(e.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},a({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),a(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},a(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),a(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},a(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),a(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},a(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),a(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await be({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.thread-item`),n=t?.closest(`.thread-group`);if(t&&n){if(t.remove(),n.querySelectorAll(`.thread-item:not(.thread-item-gap)`).length===0){let e=n.closest(`.feed-item`),t=e?.parentElement??null;(e??n).remove(),GB(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),GB(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=Kx(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
4028
4081
  xmlns="http://www.w3.org/2000/svg"
4029
4082
  viewBox="0 0 24 24"
4030
4083
  fill="none"
@@ -4044,7 +4097,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4044
4097
  stroke-linecap="round"
4045
4098
  stroke-linejoin="round"
4046
4099
  >
4047
- <path d=${AB} />
4100
+ <path d=${BB} />
4048
4101
  </svg>`}#N(){return u`<svg
4049
4102
  xmlns="http://www.w3.org/2000/svg"
4050
4103
  viewBox="0 0 24 24"
@@ -4055,8 +4108,8 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4055
4108
  stroke-linecap="round"
4056
4109
  stroke-linejoin="round"
4057
4110
  >
4058
- <path d=${AB} />
4059
- <path d=${jB} />
4111
+ <path d=${BB} />
4112
+ <path d=${VB} />
4060
4113
  </svg>`}#P(){return u`<svg
4061
4114
  xmlns="http://www.w3.org/2000/svg"
4062
4115
  viewBox="0 0 24 24"
@@ -4501,7 +4554,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4501
4554
  </div>
4502
4555
  `}
4503
4556
  ${this._addCollectionPanelOpen?this.#H():g}
4504
- `}};customElements.define(`jant-post-menu`,IB);var LB=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=LB(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||_z(),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 be({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);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 RB(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`})}RB();var zB=`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"`,BB={post:`<svg ${zB}><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 ${zB} 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 ${zB}><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 ${zB}><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg>`,search:`<svg ${zB}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`},VB=5;function HB(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 UB(e,t){let n=HB(e).filter(e=>e!==t);n.unshift(t),globalThis.localStorage.setItem(e,JSON.stringify(n.slice(0,VB)))}var WB=`jant:nav-history`,GB=`jant:search-history`,KB=[{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`}],qB=[{label:`New Post`,icon:BB.command,action:()=>void fR()}],JB=class extends c{static properties={_open:{state:!0},_query:{state:!0},_selectedIndex:{state:!0},_loading:{state:!0}};#e=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._selectedIndex=0,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t()}async#t(){if(!this.#e)try{let e=await fetch(`/api/palette`);e.ok?this.#e=(await e.json()).items:this.#e=[]}catch{this.#e=[]}}async open(){if(this._open)return;this.#e||(this._loading=!0,await this.#t(),this._loading=!1),this._open=!0,this._query=``,this._selectedIndex=0,await this.updateComplete;let e=this.querySelector(`.command-palette`);e&&!e.open&&e.showModal(),this.querySelector(`.command-palette-input`)?.focus()}close(){let e=this.querySelector(`.command-palette`);e?.open&&e.close(),this._open=!1,this._query=``,this._selectedIndex=0}get#n(){let e=this._query.charAt(0);return e===`>`||e===`>`?`command`:e===`?`||e===`?`?`search`:`navigate`}get#r(){let e=Wx(this._query),t=[...this.#e??[],...KB];if(!e){let e=HB(WB);if(e.length===0)return t;let n=new Set(e),r=[],i=[];for(let e of t)n.has(e.path)?r.push(e):i.push(e);return r.sort((t,n)=>e.indexOf(t.path)-e.indexOf(n.path)),[...r,...i]}return t.map((t,n)=>({item:t,index:n,rank:Ux([t.title,t.path],e)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item)}get#i(){let e=Wx(this._query.slice(1));return qB.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:BB.search,searchQuery:e}]:HB(GB).map(e=>({label:e,icon:BB.search,searchQuery:e}))}let t=this.#r.map(e=>({label:e.title,secondary:(e.type,e.path),icon:BB[e.type]})),n=Wx(this._query);return t.length===0&&n&&t.push({label:`Search for "${this._query.trim()}"`,icon:BB.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&&(UB(GB,t),this.close(),window.location.href=`/search?q=${encodeURIComponent(t)}`);return}let n=this.#a[e];if(n?.searchQuery){let e=n.searchQuery;UB(GB,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`;return}let r=this.#r[e];r&&(UB(WB,r.path),this.close(),r.type===`system`?window.location.href=r.path:r.type===`collection`?window.location.href=`/collections/${r.path}`:window.location.href=`/${r.path}`)}#s=e=>{this._query=e.target.value,this._selectedIndex=0};#c=e=>{let t=this.#a;if(e.key===`ArrowDown`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex+1)%t.length:0,this.#f();return}if(e.key===`ArrowUp`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex-1+t.length)%t.length:0,this.#f();return}if(e.key===`Enter`){e.preventDefault(),this.#o(this._selectedIndex);return}if(e.key===`Tab`){e.preventDefault();return}if(e.key===`Escape`){e.preventDefault(),this.close();return}};#l=e=>{e.preventDefault(),this.close()};#u=e=>{e.target===e.currentTarget&&this.close()};#d(e){return()=>this.#o(e)}#f(){requestAnimationFrame(()=>{this.querySelector(`.command-palette-result-selected`)?.scrollIntoView({block:`nearest`})})}render(){if(!this._open)return g;let e=this.#a;return u`
4557
+ `}};customElements.define(`jant-post-menu`,KB);var qB=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=qB(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||Dz(),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 be({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);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 JB(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`})}JB();var YB=`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"`,XB={post:`<svg ${YB}><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 ${YB} 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 ${YB}><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 ${YB}><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg>`,search:`<svg ${YB}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`},ZB=5;function QB(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 $B(e,t){let n=QB(e).filter(e=>e!==t);n.unshift(t),globalThis.localStorage.setItem(e,JSON.stringify(n.slice(0,ZB)))}var eV=`jant:nav-history`,tV=`jant:search-history`,nV=[{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`}],rV=[{label:`New Post`,icon:XB.command,action:()=>void fR()}],iV=class extends c{static properties={_open:{state:!0},_query:{state:!0},_selectedIndex:{state:!0},_loading:{state:!0}};#e=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._selectedIndex=0,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t()}async#t(){if(!this.#e)try{let e=await fetch(`/api/palette`);e.ok?this.#e=(await e.json()).items:this.#e=[]}catch{this.#e=[]}}async open(){if(this._open)return;this.#e||(this._loading=!0,await this.#t(),this._loading=!1),this._open=!0,this._query=``,this._selectedIndex=0,await this.updateComplete;let e=this.querySelector(`.command-palette`);e&&!e.open&&e.showModal(),this.querySelector(`.command-palette-input`)?.focus()}close(){let e=this.querySelector(`.command-palette`);e?.open&&e.close(),this._open=!1,this._query=``,this._selectedIndex=0}get#n(){let e=this._query.charAt(0);return e===`>`||e===`>`?`command`:e===`?`||e===`?`?`search`:`navigate`}get#r(){let e=Wx(this._query),t=[...this.#e??[],...nV];if(!e){let e=QB(eV);if(e.length===0)return t;let n=new Set(e),r=[],i=[];for(let e of t)n.has(e.path)?r.push(e):i.push(e);return r.sort((t,n)=>e.indexOf(t.path)-e.indexOf(n.path)),[...r,...i]}return t.map((t,n)=>({item:t,index:n,rank:Ux([t.title,t.path],e)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item)}get#i(){let e=Wx(this._query.slice(1));return rV.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:XB.search,searchQuery:e}]:QB(tV).map(e=>({label:e,icon:XB.search,searchQuery:e}))}let t=this.#r.map(e=>({label:e.title,secondary:(e.type,e.path),icon:XB[e.type]})),n=Wx(this._query);return t.length===0&&n&&t.push({label:`Search for "${this._query.trim()}"`,icon:XB.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&&($B(tV,t),this.close(),window.location.href=`/search?q=${encodeURIComponent(t)}`);return}let n=this.#a[e];if(n?.searchQuery){let e=n.searchQuery;$B(tV,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`;return}let r=this.#r[e];r&&($B(eV,r.path),this.close(),r.type===`system`?window.location.href=r.path:r.type===`collection`?window.location.href=`/collections/${r.path}`:window.location.href=`/${r.path}`)}#s=e=>{this._query=e.target.value,this._selectedIndex=0};#c=e=>{let t=this.#a;if(e.key===`ArrowDown`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex+1)%t.length:0,this.#f();return}if(e.key===`ArrowUp`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex-1+t.length)%t.length:0,this.#f();return}if(e.key===`Enter`){e.preventDefault(),this.#o(this._selectedIndex);return}if(e.key===`Tab`){e.preventDefault();return}if(e.key===`Escape`){e.preventDefault(),this.close();return}};#l=e=>{e.preventDefault(),this.close()};#u=e=>{e.target===e.currentTarget&&this.close()};#d(e){return()=>this.#o(e)}#f(){requestAnimationFrame(()=>{this.querySelector(`.command-palette-result-selected`)?.scrollIntoView({block:`nearest`})})}render(){if(!this._open)return g;let e=this.#a;return u`
4505
4558
  <dialog
4506
4559
  class="command-palette"
4507
4560
  @cancel=${this.#l}
@@ -4514,7 +4567,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4514
4567
  >
4515
4568
  <div class="command-palette-input-wrapper">
4516
4569
  <span class="command-palette-search-icon"
4517
- >${Ce(BB.search)}</span
4570
+ >${Ce(XB.search)}</span
4518
4571
  >
4519
4572
  <input
4520
4573
  type="text"
@@ -4563,4 +4616,4 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4563
4616
  `:this._query.trim()&&!this._loading?u`<div class="command-palette-empty">No results</div>`:g}
4564
4617
  </div>
4565
4618
  </dialog>
4566
- `}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,JB),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.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),ye(),document.querySelector(`jant-command-palette`)||document.body.appendChild(document.createElement(`jant-command-palette`));
4619
+ `}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,iV),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.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),ye(),document.querySelector(`jant-command-palette`)||document.body.appendChild(document.createElement(`jant-command-palette`));