@jant/core 1.0.1 → 1.1.0

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 (58) hide show
  1. package/dist/{app-Gt7_skt6.js → app-CKQ9PqAr.js} +791 -89
  2. package/dist/client/.vite/manifest.json +115 -75
  3. package/dist/client/_assets/chunks/{confirm-D7GrwsCN.js → confirm-CMe01lne.js} +1 -1
  4. package/dist/client/_assets/chunks/{create-editor-5Y49x7h5.js → create-editor-BQkrw8Ax.js} +4 -4
  5. package/dist/client/_assets/chunks/footnote-rail-B08scyhW.js +2 -0
  6. package/dist/client/_assets/chunks/{jant-locale-picker-DL6mIOT5.js → jant-locale-picker-2L4rkDaz.js} +1 -1
  7. package/dist/client/_assets/chunks/lit-Bw_voPoW.js +2 -0
  8. package/dist/client/_assets/chunks/preload-helper-Czpn1I53.js +1 -0
  9. package/dist/client/_assets/chunks/runtime-paths-y0_gHowM.js +1 -0
  10. package/dist/client/_assets/chunks/{settings-paths-h6RjIe3C.js → settings-paths-B0bNUaih.js} +1 -1
  11. package/dist/client/_assets/chunks/slug-format-CYmQE5ln.js +1 -0
  12. package/dist/client/_assets/chunks/{sortable-list-DWNKv782.js → sortable-list-t11Ma1Ek.js} +1 -1
  13. package/dist/client/_assets/chunks/{unsafe-html-B5ZEXaxg.js → unsafe-html-CWos3v6N.js} +1 -1
  14. package/dist/client/_assets/chunks/unsafe-svg-DZl-yjas.js +1 -0
  15. package/dist/client/_assets/client-B0-s9sqx.css +2 -0
  16. package/dist/client/_assets/client-Dp46QSht.js +354 -0
  17. package/dist/client/_assets/client-auth-CG55rWb5.js +859 -0
  18. package/dist/client/_assets/{client-compose-oxzPb3SS.js → client-compose-DkUTuavR.js} +261 -261
  19. package/dist/client/_assets/{client-manage-C1eDB1Rc.js → client-manage-DnYdQAhf.js} +176 -176
  20. package/dist/client/_assets/{client-settings-DIM44Zqh.js → client-settings-CHgsIqXJ.js} +166 -166
  21. package/dist/client/_assets/client-share-0DICJjAc.css +1 -0
  22. package/dist/client/_assets/client-share-C59mOLJ1.js +149 -0
  23. package/dist/index.js +1 -1
  24. package/dist/node.js +2 -2
  25. package/package.json +2 -1
  26. package/src/client/components/jant-post-menu.ts +80 -13
  27. package/src/client/components/jant-share-dialog.ts +422 -0
  28. package/src/client/components/jant-share-menu.ts +188 -0
  29. package/src/client/lazy-entries.ts +21 -1
  30. package/src/client/post-menu-shared.ts +100 -0
  31. package/src/client/share-capture.ts +443 -0
  32. package/src/client/share-launch.ts +133 -0
  33. package/src/client-share.ts +8 -0
  34. package/src/client.ts +1 -0
  35. package/src/lib/discover.ts +31 -0
  36. package/src/lib/share-card.ts +653 -0
  37. package/src/lib/version.ts +2 -0
  38. package/src/routes/auth/setup.tsx +37 -1
  39. package/src/routes/pages/partials.tsx +23 -0
  40. package/src/style-share.css +16 -0
  41. package/src/styles/components.css +14 -0
  42. package/src/styles/share.css +1103 -0
  43. package/src/styles/ui.css +6 -0
  44. package/src/ui/layouts/BaseLayout.tsx +7 -0
  45. package/src/ui/layouts/SiteLayout.tsx +1 -0
  46. package/src/ui/share/ShareCard.tsx +298 -0
  47. package/src/ui/shared/Icon.tsx +23 -3
  48. package/src/ui/shared/MediaGallery.tsx +12 -1
  49. package/src/ui/shared/PostFooter.tsx +20 -4
  50. package/src/ui/shared/icon-collector.ts +28 -0
  51. package/src/ui/shared/post-article-attributes.ts +3 -0
  52. package/dist/client/_assets/chunks/footnote-rail-BJwswtVQ.js +0 -1
  53. package/dist/client/_assets/chunks/lit-DW8VmJAT.js +0 -2
  54. package/dist/client/_assets/chunks/slug-format-Dsi0e9Xn.js +0 -1
  55. package/dist/client/_assets/chunks/unsafe-svg-DTZZEvLU.js +0 -2
  56. package/dist/client/_assets/client-BaqmpPQ-.css +0 -2
  57. package/dist/client/_assets/client-C6melOtG.js +0 -296
  58. package/dist/client/_assets/client-auth-Ccq8kSqq.js +0 -828
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_assets/chunks/emoji-mart-C4RpRKcU.js","_assets/chunks/rolldown-runtime-hePW80VL.js","_assets/chunks/mediabunny-DRaCQ1r-.js"])))=>i.map(i=>d[i]);
2
- import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks/lit-DW8VmJAT.js";import{r as u}from"./chunks/footnote-rail-BJwswtVQ.js";import{n as d}from"./chunks/unsafe-html-B5ZEXaxg.js";import{c as f,i as p,n as m,o as h,r as g,s as _,t as v}from"./chunks/unsafe-svg-DTZZEvLU.js";import{i as y,r as b,t as x}from"./chunks/slug-format-Dsi0e9Xn.js";import{_ as S,p as C}from"./chunks/types-D5iF3H1a.js";import{a as w,f as ee,i as te,n as T,o as E,r as D,s as ne,t as O,u as re}from"./chunks/sortable-list-DWNKv782.js";import{_ as ie,a as k,c as A,d as j,f as M,g as N,h as ae,i as oe,l as se,m as ce,n as le,o as ue,p as de,s as fe,u as pe}from"./chunks/create-editor-5Y49x7h5.js";var P=e=>e??o;function me(e){let t=e.trim().toLowerCase();if(!t)return;let n=t.split(`-`)[0];if(n===`zh`){let e=t.slice(3);return e===`hant`||e===`tw`||e===`hk`||e===`mo`?`zh-Hant`:`zh-Hans`}if(n===`ja`)return`ja`;if(n===`ko`)return`ko`}var he=`们这会说对时国学个来过现发经应关点无义与从门问间东车长马鸟鱼见贝页风飞头语话认识讲论议记让试该请读谁调谈变边达运还进远连适选递邮释钟银错锁闭开闻阅队阶阳阴陆陈险隐难静韩须顾频颜题类飘饭饮饰馆驻驾验骑骗体处备够夺奋妇妈宁宝实宽宾寻导尔尘尝尽层属岁岂岛币帅帮归当录彻忆态怀恋恶悬惊惧惨愤愿战户扩扫扬担拟挂挤挥换据摄击敌断旧显术机杀杂权条极构柜标树桥检楼欢欧残毁气汉汤沟泪洁济浏浅浆涛润涨渐渔渗湾湿满滨滤灭灯灵灾炉烦烧热营爱状犹狮独狱猎猪献猫环电画畅疗疯皱监盘矿码确础礼祸种积称稳穷窃竞笔筹简签粮紧纪纯纲纳纵纷纸线组细织终绍结绕绘给络绝统继绩绪续维综绿缓编缘缩缴网罗罚罢习联声职聪肃肠胀脑脱腊舰艰节苏药荐荡获萧蓝虏虚虽蚀蜡补装观规觉计订讨训讯词译诉诊证评诚误诸课谅谓谢谱贡财责贤败货质贩贪购贯贱贴贵贷贸费贺资赏赐赔赖赚赛赢赠赶趋践轨转轮软载较辅辈辉输辐辑辞迁迈违迟逊遗邓邻郑针钉钓钙钝钞钢钥钦钩钱钻铁铃铅铜铝铺链销锋锐锦键镇镜闪闯闲闷闹阀阁阵际隶随雾项顶预领颇颈颗颠饥饱饼馈驰驱驶骂骄鲁鲜鸡鸣鸦鸭鸽鹅鹰麦黄齐齿龄龙龟儿优传伤侦侧俭债倾偿储兰兴军农决净减凤凭则刘创剑剧劝办务动励劳势勋医华单卖卫厅历压厌厨参叶号叹吗启呐员呜响哑唤啸喷嘱团园围图圆场坏块坚坛垒垦堕墙壮壳复`,ge=`們這會說對時國學後個來過現發經應關點無義與從門問間東車長馬鳥魚見貝頁風飛頭語話認識講論議記讓試該請讀誰調談變邊達運還進遠連適選遞郵釋鐘銀錯鎖閉開聞閱隊階陽陰陸陳險隱難靜韓須顧頻顏題類飄飯飲飾館駐駕驗騎騙體處備夠奪奮婦媽寧寶實寬賓尋導爾塵嘗盡層屬歲豈島幣帥幫歸當錄徹憶態懷戀惡懸驚懼慘憤願戰戶擴掃揚擔擬掛擠揮換據攝擊敵斷舊顯術機殺雜權條極構櫃標樹橋檢樓歡歐殘毀氣漢湯溝淚潔濟瀏淺漿濤潤漲漸漁滲灣濕滿濱濾滅燈靈災爐煩燒熱營愛狀猶獅獨獄獵豬獻貓環電畫暢療瘋皺監盤礦碼確礎禮禍種積稱穩窮竊競筆籌簡簽糧緊紀純綱納縱紛紙線組細織終紹結繞繪給絡絕統繼績緒續維綜綠緩編緣縮繳網羅罰罷習聯聲職聰肅腸脹腦脫臘艦艱節蘇藥薦蕩獲蕭藍虜虛雖蝕蠟補裝觀規覺計訂討訓訊詞譯訴診證評誠誤諸課諒謂謝譜貢財責賢敗貨質販貪購貫賤貼貴貸貿費賀資賞賜賠賴賺賽贏贈趕趨踐軌轉輪軟載較輔輩輝輸輻輯辭遷邁違遲遜遺鄧鄰鄭針釘釣鈣鈍鈔鋼鑰欽鉤錢鑽鐵鈴鉛銅鋁鋪鏈銷鋒銳錦鍵鎮鏡閃闖閒悶鬧閥閣陣際隸隨霧項頂預領頗頸顆顛飢飽餅饋馳驅駛罵驕魯鮮雞鳴鴉鴨鴿鵝鷹麥黃齊齒齡龍龜兒優傳傷偵側儉債傾償儲蘭興軍農衝決淨減鳳憑劃則劉創劍劇勸辦務動勵勞勢勳醫華單賣衛廳歷壓厭廚參疊隻臺葉號嘆嗎啟吶員嗚響啞喚嘯噴囑團園圍圖圓場壞塊堅壇壘墾墮牆壯殼複`,_e=new Set(he),ve=new Set(ge);function ye(e){let t={hangul:0,kana:0,han:0,latin:0,simplified:0,traditional:0};for(let n of e){let e=n.codePointAt(0);if(e!==void 0){if(e>=44032&&e<=55203||e>=4352&&e<=4607||e>=12592&&e<=12687){t.hangul++;continue}if(e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12784&&e<=12799){t.kana++;continue}if(e>=19968&&e<=40959||e>=13312&&e<=19903||e>=63744&&e<=64255){t.han++,_e.has(n)?t.simplified++:ve.has(n)&&t.traditional++;continue}(e>=65&&e<=90||e>=97&&e<=122||e>=192&&e<=591)&&t.latin++}}return t}var be=3,xe=10;function Se(e){let t=ye(e),n=(t.hangul+t.kana+t.han)*be;return n>=t.latin&&n>=xe?t.hangul>0?`ko`:t.kana>0?`ja`:t.simplified>t.traditional?`zh-Hans`:t.traditional>t.simplified?`zh-Hant`:`han`:t.latin>=xe?`latin`:null}function Ce(e,t){let{languages:n}=t;if(n.length===0)return null;let r=Se(e);if(!r)return null;if(r===`latin`){let e=n.filter(e=>!me(e));return e.length===1?e[0]:null}if(r===`han`){let e=n.filter(e=>{let t=me(e);return t===`zh-Hans`||t===`zh-Hant`});return e.length===1?e[0]:null}return n.find(e=>me(e)===r)??null}var we=/^—\s*(.*?)(?:\s+(https?:\/\/\S+))?\s*$/;function Te(e){return e?JSON.parse(JSON.stringify(e)):null}function Ee(e){return e?typeof e.text==`string`?e.text:Array.isArray(e.content)?e.content.map(Ee).join(``):``:``}function De(e,t=2){return{type:`heading`,attrs:{level:t},content:[{type:`text`,text:e}]}}function Oe(e){return e?{type:`paragraph`,content:[{type:`text`,text:e}]}:{type:`paragraph`}}function ke(e){return{type:`paragraph`,content:[{type:`text`,text:e,marks:[{type:`link`,attrs:{href:e}}]}]}}function Ae(e){let t=we.exec(e.trim());return t?{author:t[1].trim(),url:t[2]??null}:{author:``,url:null}}function je(e){if(!e)return null;if(Array.isArray(e.marks)){let t=e.marks.find(e=>e.type===`link`)?.attrs?.href;if(typeof t==`string`&&t)return t}if(Array.isArray(e.content))for(let t of e.content){let e=je(t);if(e)return e}return null}function Me(e,t){let n=e.trim(),r=t?.trim()??``;if(!n&&!r)return null;let i=e=>({type:`text`,text:e,marks:[{type:`link`,attrs:{href:r}}]});return n&&r?{type:`paragraph`,content:[{type:`text`,text:`— `},i(n)]}:n?{type:`paragraph`,content:[{type:`text`,text:`— ${n}`}]}:{type:`paragraph`,content:[{type:`text`,text:`— `},i(r)]}}function Ne(e,t){let n=e.split(`
2
+ import{c as e,r as t}from"./chunks/runtime-paths-y0_gHowM.js";import{o as n}from"./chunks/footnote-rail-B08scyhW.js";import{c as r,f as i,i as a,l as o,n as s,s as c,t as l,u}from"./chunks/lit-Bw_voPoW.js";import{n as d}from"./chunks/unsafe-html-CWos3v6N.js";import{t as f}from"./chunks/preload-helper-Czpn1I53.js";import{c as p,i as m,n as h,o as g,r as _,s as v,t as y}from"./chunks/unsafe-svg-DZl-yjas.js";import{_ as b,p as x}from"./chunks/types-D5iF3H1a.js";import{r as S,t as C}from"./chunks/slug-format-CYmQE5ln.js";import{a as w,f as ee,i as te,n as T,o as E,r as D,s as ne,t as O,u as re}from"./chunks/sortable-list-t11Ma1Ek.js";import{_ as ie,a as k,c as A,d as j,f as M,g as N,h as ae,i as oe,l as se,m as ce,n as le,o as ue,p as de,s as fe,u as pe}from"./chunks/create-editor-BQkrw8Ax.js";var P=e=>e??s;function me(e){let t=e.trim().toLowerCase();if(!t)return;let n=t.split(`-`)[0];if(n===`zh`){let e=t.slice(3);return e===`hant`||e===`tw`||e===`hk`||e===`mo`?`zh-Hant`:`zh-Hans`}if(n===`ja`)return`ja`;if(n===`ko`)return`ko`}var he=`们这会说对时国学个来过现发经应关点无义与从门问间东车长马鸟鱼见贝页风飞头语话认识讲论议记让试该请读谁调谈变边达运还进远连适选递邮释钟银错锁闭开闻阅队阶阳阴陆陈险隐难静韩须顾频颜题类飘饭饮饰馆驻驾验骑骗体处备够夺奋妇妈宁宝实宽宾寻导尔尘尝尽层属岁岂岛币帅帮归当录彻忆态怀恋恶悬惊惧惨愤愿战户扩扫扬担拟挂挤挥换据摄击敌断旧显术机杀杂权条极构柜标树桥检楼欢欧残毁气汉汤沟泪洁济浏浅浆涛润涨渐渔渗湾湿满滨滤灭灯灵灾炉烦烧热营爱状犹狮独狱猎猪献猫环电画畅疗疯皱监盘矿码确础礼祸种积称稳穷窃竞笔筹简签粮紧纪纯纲纳纵纷纸线组细织终绍结绕绘给络绝统继绩绪续维综绿缓编缘缩缴网罗罚罢习联声职聪肃肠胀脑脱腊舰艰节苏药荐荡获萧蓝虏虚虽蚀蜡补装观规觉计订讨训讯词译诉诊证评诚误诸课谅谓谢谱贡财责贤败货质贩贪购贯贱贴贵贷贸费贺资赏赐赔赖赚赛赢赠赶趋践轨转轮软载较辅辈辉输辐辑辞迁迈违迟逊遗邓邻郑针钉钓钙钝钞钢钥钦钩钱钻铁铃铅铜铝铺链销锋锐锦键镇镜闪闯闲闷闹阀阁阵际隶随雾项顶预领颇颈颗颠饥饱饼馈驰驱驶骂骄鲁鲜鸡鸣鸦鸭鸽鹅鹰麦黄齐齿龄龙龟儿优传伤侦侧俭债倾偿储兰兴军农决净减凤凭则刘创剑剧劝办务动励劳势勋医华单卖卫厅历压厌厨参叶号叹吗启呐员呜响哑唤啸喷嘱团园围图圆场坏块坚坛垒垦堕墙壮壳复`,ge=`們這會說對時國學後個來過現發經應關點無義與從門問間東車長馬鳥魚見貝頁風飛頭語話認識講論議記讓試該請讀誰調談變邊達運還進遠連適選遞郵釋鐘銀錯鎖閉開聞閱隊階陽陰陸陳險隱難靜韓須顧頻顏題類飄飯飲飾館駐駕驗騎騙體處備夠奪奮婦媽寧寶實寬賓尋導爾塵嘗盡層屬歲豈島幣帥幫歸當錄徹憶態懷戀惡懸驚懼慘憤願戰戶擴掃揚擔擬掛擠揮換據攝擊敵斷舊顯術機殺雜權條極構櫃標樹橋檢樓歡歐殘毀氣漢湯溝淚潔濟瀏淺漿濤潤漲漸漁滲灣濕滿濱濾滅燈靈災爐煩燒熱營愛狀猶獅獨獄獵豬獻貓環電畫暢療瘋皺監盤礦碼確礎禮禍種積稱穩窮竊競筆籌簡簽糧緊紀純綱納縱紛紙線組細織終紹結繞繪給絡絕統繼績緒續維綜綠緩編緣縮繳網羅罰罷習聯聲職聰肅腸脹腦脫臘艦艱節蘇藥薦蕩獲蕭藍虜虛雖蝕蠟補裝觀規覺計訂討訓訊詞譯訴診證評誠誤諸課諒謂謝譜貢財責賢敗貨質販貪購貫賤貼貴貸貿費賀資賞賜賠賴賺賽贏贈趕趨踐軌轉輪軟載較輔輩輝輸輻輯辭遷邁違遲遜遺鄧鄰鄭針釘釣鈣鈍鈔鋼鑰欽鉤錢鑽鐵鈴鉛銅鋁鋪鏈銷鋒銳錦鍵鎮鏡閃闖閒悶鬧閥閣陣際隸隨霧項頂預領頗頸顆顛飢飽餅饋馳驅駛罵驕魯鮮雞鳴鴉鴨鴿鵝鷹麥黃齊齒齡龍龜兒優傳傷偵側儉債傾償儲蘭興軍農衝決淨減鳳憑劃則劉創劍劇勸辦務動勵勞勢勳醫華單賣衛廳歷壓厭廚參疊隻臺葉號嘆嗎啟吶員嗚響啞喚嘯噴囑團園圍圖圓場壞塊堅壇壘墾墮牆壯殼複`,_e=new Set(he),ve=new Set(ge);function ye(e){let t={hangul:0,kana:0,han:0,latin:0,simplified:0,traditional:0};for(let n of e){let e=n.codePointAt(0);if(e!==void 0){if(e>=44032&&e<=55203||e>=4352&&e<=4607||e>=12592&&e<=12687){t.hangul++;continue}if(e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12784&&e<=12799){t.kana++;continue}if(e>=19968&&e<=40959||e>=13312&&e<=19903||e>=63744&&e<=64255){t.han++,_e.has(n)?t.simplified++:ve.has(n)&&t.traditional++;continue}(e>=65&&e<=90||e>=97&&e<=122||e>=192&&e<=591)&&t.latin++}}return t}var be=3,xe=10;function Se(e){let t=ye(e),n=(t.hangul+t.kana+t.han)*be;return n>=t.latin&&n>=xe?t.hangul>0?`ko`:t.kana>0?`ja`:t.simplified>t.traditional?`zh-Hans`:t.traditional>t.simplified?`zh-Hant`:`han`:t.latin>=xe?`latin`:null}function Ce(e,t){let{languages:n}=t;if(n.length===0)return null;let r=Se(e);if(!r)return null;if(r===`latin`){let e=n.filter(e=>!me(e));return e.length===1?e[0]:null}if(r===`han`){let e=n.filter(e=>{let t=me(e);return t===`zh-Hans`||t===`zh-Hant`});return e.length===1?e[0]:null}return n.find(e=>me(e)===r)??null}var we=/^—\s*(.*?)(?:\s+(https?:\/\/\S+))?\s*$/;function Te(e){return e?JSON.parse(JSON.stringify(e)):null}function Ee(e){return e?typeof e.text==`string`?e.text:Array.isArray(e.content)?e.content.map(Ee).join(``):``:``}function De(e,t=2){return{type:`heading`,attrs:{level:t},content:[{type:`text`,text:e}]}}function Oe(e){return e?{type:`paragraph`,content:[{type:`text`,text:e}]}:{type:`paragraph`}}function ke(e){return{type:`paragraph`,content:[{type:`text`,text:e,marks:[{type:`link`,attrs:{href:e}}]}]}}function Ae(e){let t=we.exec(e.trim());return t?{author:t[1].trim(),url:t[2]??null}:{author:``,url:null}}function je(e){if(!e)return null;if(Array.isArray(e.marks)){let t=e.marks.find(e=>e.type===`link`)?.attrs?.href;if(typeof t==`string`&&t)return t}if(Array.isArray(e.content))for(let t of e.content){let e=je(t);if(e)return e}return null}function Me(e,t){let n=e.trim(),r=t?.trim()??``;if(!n&&!r)return null;let i=e=>({type:`text`,text:e,marks:[{type:`link`,attrs:{href:r}}]});return n&&r?{type:`paragraph`,content:[{type:`text`,text:`— `},i(n)]}:n?{type:`paragraph`,content:[{type:`text`,text:`— ${n}`}]}:{type:`paragraph`,content:[{type:`text`,text:`— `},i(r)]}}function Ne(e,t){let n=e.split(`
3
3
  `).map(e=>Oe(e));return t&&n.push(t),{type:`blockquote`,content:n}}function Pe(e,t,n){if(e===t)return n;let r={...n},i=Te(n.bodyJson),a=Array.isArray(i?.content)?[...i.content]:[];if(t===`link`&&r.url===``){let e=a[0],t=je(e);t&&e?.type===`paragraph`&&Array.isArray(e.content)&&e.content.length===1&&Ee(e)===t&&(r.url=t,a.shift())}if(t===`quote`&&r.quoteText===``&&a[0]?.type===`blockquote`){let e=Array.isArray(a[0].content)?[...a[0].content]:[],t=e[e.length-1],n=Ee(t);if(e.length>0&&/^—/.test(n.trim())){let i=Ae(n),a=je(t)??i.url,o=i.author===a?``:i.author;o&&(r.quoteAuthor=r.quoteAuthor||o),a&&r.url===``&&(r.url=a),e.pop()}r.quoteText=e.map(Ee).join(`
4
4
  `).trim(),a.shift()}let o=[];if(t===`quote`&&r.title.trim()!==``&&(o.push(De(r.title.trim())),r.title=``),t!==`quote`&&r.quoteText.trim()!==``){let e=t===`note`?r.url:null;o.push(Ne(r.quoteText,Me(r.quoteAuthor,e))),r.quoteText=``,r.quoteAuthor=``,t===`note`&&(r.url=``)}else t===`note`&&r.url.trim()!==``&&(o.push(ke(r.url.trim())),r.url=``);return o.length&&a.unshift(...o),r.bodyJson=a.length?{type:`doc`,content:a}:null,t===`note`&&r.title.trim().length>0&&(r.showTitle=!0),r}var Fe=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`,`image/avif`,`image/bmp`,`image/x-icon`],Ie=[`video/mp4`,`video/webm`,`video/quicktime`,`video/x-msvideo`,`video/x-matroska`,`video/mpeg`,`video/3gpp`,`video/x-flv`,`video/ogg`],Le=[`audio/mpeg`,`audio/ogg`,`audio/wav`,`audio/mp4`,`audio/x-m4a`,`audio/flac`,`audio/aac`,`audio/webm`,`audio/x-aiff`,`audio/opus`,`audio/3gpp`,`audio/midi`],Re=[`application/pdf`,`application/epub+zip`,`application/x-mobipocket-ebook`,`application/vnd.amazon.ebook`],ze=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/vnd.oasis.opendocument.presentation`,`application/vnd.apple.pages`,`application/vnd.apple.numbers`,`application/vnd.apple.keynote`],Be=[`text/plain`,`text/markdown`,`text/csv`,`text/html`,`text/css`,`text/javascript`,`text/xml`,`text/rtf`,`text/tab-separated-values`,`text/calendar`,`application/json`,`application/xml`,`application/yaml`,`application/toml`],Ve=[`application/zip`,`application/x-tar`,`application/gzip`,`application/x-bzip2`,`application/x-7z-compressed`,`application/x-rar-compressed`,`application/zstd`],He=[`font/ttf`,`font/otf`,`font/woff`,`font/woff2`],Ue=[`model/gltf+json`,`model/gltf-binary`,`model/obj`,`application/x-figma`,`image/vnd.dxf`],We=[`application/sql`,`application/wasm`,`application/x-ipynb+json`,`application/x-sh`,`application/x-python-code`],Ge=new Map([...Fe.map(e=>[e,`image`]),...Ie.map(e=>[e,`video`]),...Le.map(e=>[e,`audio`]),...Re.map(e=>[e,`document`]),...ze.map(e=>[e,`office`]),...Be.map(e=>[e,`text`]),...Ve.map(e=>[e,`archive`]),...He.map(e=>[e,`font`]),...Ue.map(e=>[e,`3d`]),...We.map(e=>[e,`code`])]);function F(e){return Ge.get(e)||(e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:e.startsWith(`font/`)?`font`:e.startsWith(`model/`)?`3d`:e.startsWith(`text/`)?`text`:`archive`)}function Ke(e){return e.startsWith(`image/`)}new Set(Fe);var qe=new Set([`heic`,`heix`,`hevc`,`hevx`,`mif1`,`msf1`]);function Je(e){if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return`image/jpeg`;if(e.length>=8&&e[0]===137&&I(e,1,3)===`PNG`)return`image/png`;if(e.length>=6&&/^GIF8[79]a$/.test(I(e,0,6)))return`image/gif`;if(e.length>=12&&I(e,0,4)===`RIFF`&&I(e,8,4)===`WEBP`)return`image/webp`;if(e.length>=12&&I(e,4,4)===`ftyp`){let t=I(e,8,4);if(t===`avif`||t===`avis`)return`image/avif`;if(qe.has(t))return`image/heic`}return e.length>=2&&e[0]===66&&e[1]===77?`image/bmp`:e.length>=4&&e[0]===0&&e[1]===0&&e[2]===1&&e[3]===0?`image/x-icon`:new TextDecoder().decode(e.subarray(0,1024)).toLowerCase().includes(`<svg`)?`image/svg+xml`:null}function Ye(e,t){return Xe(e.type,e.size,t)}function Xe(e,t,n){if(n?.imagesOnly&&!Ke(e))return`File type not allowed.`;let r=n.maxFileSizeMB;return t>r*1024*1024?`File too large (max ${r}MB).`:null}function I(e,t,n){return new TextDecoder(`ascii`).decode(e.slice(t,t+n))}var L=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),Ze=`[data-editor-floating-ui]`,Qe=`single`,$e=`(max-width: 700px), (max-height: 760px), (hover: none) and (pointer: coarse)`,et={drafts:`
5
5
  <rect x="3.85" y="3.45" width="7.85" height="8.35" rx="2.35" />
@@ -64,7 +64,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
64
64
  <circle cx="8" cy="8" r="5.7" />
65
65
  <path d="M8 5.55v4.9" />
66
66
  <path d="M5.55 8h4.9" />
67
- `};function rt(e){return i`<svg
67
+ `};function rt(e){return a`<svg
68
68
  class="compose-sheet-row-icon"
69
69
  width="18"
70
70
  height="18"
@@ -76,8 +76,8 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
76
76
  stroke-linejoin="round"
77
77
  aria-hidden="true"
78
78
  >
79
- ${v(e)}
80
- </svg>`}function it(e,t){return i`<span class=${t} aria-hidden="true">
79
+ ${y(e)}
80
+ </svg>`}function it(e,t){return a`<span class=${t} aria-hidden="true">
81
81
  <svg
82
82
  class="compose-publish-visibility-svg"
83
83
  width="16"
@@ -89,9 +89,9 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
89
89
  stroke-linecap="round"
90
90
  stroke-linejoin="round"
91
91
  >
92
- ${v(e)}
92
+ ${y(e)}
93
93
  </svg>
94
- </span>`}function B(e,t){return i`<svg
94
+ </span>`}function B(e,t){return a`<svg
95
95
  class=${t}
96
96
  width="16"
97
97
  height="16"
@@ -103,8 +103,8 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
103
103
  stroke-linejoin="round"
104
104
  aria-hidden="true"
105
105
  >
106
- ${v(e)}
107
- </svg>`}function V(e,t){return i`<svg
106
+ ${y(e)}
107
+ </svg>`}function V(e,t){return a`<svg
108
108
  class=${t}
109
109
  width="14"
110
110
  height="14"
@@ -116,8 +116,8 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
116
116
  stroke-linejoin="round"
117
117
  aria-hidden="true"
118
118
  >
119
- ${v(e)}
120
- </svg>`}function at(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=Reflect.get(e,`id`),n=Reflect.get(e,`title`),r=Reflect.get(e,`slug`);return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,title:n,slug:typeof r==`string`?r:``}]}):[]}function ot(e){return!e.content||e.content.length===0||e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}function H(e){return e?ot(e)?null:e:null}function st(e){return String(e).padStart(2,`0`)}function ct(e){let t=new Date(e*1e3);return`${t.getFullYear()}-${st(t.getMonth()+1)}-${st(t.getDate())}`}function U(e){let t=e.trim();if(!t)return null;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=new Date(r,i-1,a);return Number.isNaN(o.getTime())||o.getFullYear()!==r||o.getMonth()!==i-1||o.getDate()!==a?null:{year:r,monthIndex:i-1,day:a}}function W(e){let t=new Date(e*1e3);return t.getHours()*60+t.getMinutes()}function lt(e,t){let n=U(e);if(!n)return null;let r=Math.min(Math.max(t,0),1439),i=Math.floor(r/60),a=r%60;return Math.floor(new Date(n.year,n.monthIndex,n.day,i,a,0,0).getTime()/1e3)}async function ut(e){let t=e.filter(e=>e.type===`media`),n=e.filter(e=>e.type===`text`);return{media:t.map(e=>({id:e.id,previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,alt:e.alt,mimeType:e.mimeType,originalName:e.originalName,summary:e.summary,chars:e.chars,persisted:!0})),textAttachments:await Promise.all(n.map(async e=>{try{let t=await fetch(e.contentUrl);if(t.ok){let n=await t.json(),r=n.contentFormat===`markdown`&&n.content?n.content:``,i=r?ie(r):null;if(i)return{bodyJson:JSON.stringify(i),bodyHtml:``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:JSON.stringify({type:`doc`,content:[{type:`paragraph`}]}),bodyHtml:``,summary:e.summary??``,mediaId:e.id}})),attachmentOrder:e.map(e=>e.id)}}var dt=class e extends c{static _lastNewPostVisibility=`public`;_sourceCollectionId=null;static _collectionVisibilityKey(e){return`jant:collection-visibility:${e}`}static _getCollectionVisibility(t){try{let n=globalThis.localStorage.getItem(e._collectionVisibilityKey(t));if(n===`public`||n===`latest_hidden`||n===`private`)return n}catch{}return null}static _setCollectionVisibility(t,n){try{globalThis.localStorage.setItem(e._collectionVisibilityKey(t),n)}catch{}}static _NOTE_TITLE_KEY=`jant:compose-note-title`;static _getNoteTitleDefault(){try{return globalThis.localStorage.getItem(e._NOTE_TITLE_KEY)!==`0`}catch{return!0}}static _setNoteTitleDefault(t){try{globalThis.localStorage.setItem(e._NOTE_TITLE_KEY,t?`1`:`0`)}catch{}}static properties={collections:{type:Array},languages:{type:Array},contextLanguage:{type:String,attribute:`context-language`},labels:{type:Object},uploadMaxFileSize:{type:Number,attribute:`upload-max-file-size`},pageMode:{type:Boolean,attribute:`page-mode`},closeHref:{type:String,attribute:`close-href`},autoRestoreDraft:{type:Boolean,attribute:`auto-restore-draft`},slashCommandDiscovered:{type:Boolean,attribute:`slash-command-discovered`},_format:{state:!0},_status:{state:!0},_loading:{state:!0},_openingEdit:{state:!0},_collectionIds:{state:!0},_showCollection:{state:!0},_collectionSearch:{state:!0},_altPanelOpen:{state:!0},_altPanelIndex:{state:!0},_attachedPanelOpen:{state:!0},_attachedTextIndex:{state:!0},_confirmPanelOpen:{state:!0},_editPostId:{state:!0},_draftSourceId:{state:!0},_draftsPanelOpen:{state:!0},_drafts:{state:!0},_draftsLoading:{state:!0},_draftsError:{state:!0},_draftMenuOpenId:{state:!0},_addCollectionPanelOpen:{state:!0},_replyToId:{state:!0},_replyToData:{state:!0},_replyParentPosition:{state:!0},_replyExpanded:{state:!0},_threadItems:{state:!0},_rowStatus:{state:!0},_focusedThreadIndex:{state:!0},_slug:{state:!0},_publishedAtInput:{state:!0},_visibility:{state:!0},_showPublishPanel:{state:!0},_postMetaIndex:{state:!0},_publishPanelFullscreen:{state:!0},_suggestedSlug:{state:!0},_suggestedSlugLoading:{state:!0},_slugCheckLoading:{state:!0},_slugTaken:{state:!0},_visibilityLocked:{state:!0},_quietReply:{state:!0},_language:{state:!0},_showLanguagePicker:{state:!0},_translationOf:{state:!0},_translationCollapsed:{state:!0}};_attachedEditor=null;_attachedTextSnapshot=null;_seededFromSource=!1;_confirmForDrafts=!1;_confirmForAttachedText=!1;_draftSaveTimer=null;_draftRestored=!1;_hasOwnedContent=!1;_reportedStorageFailure=!1;_initialSnapshot=null;_pageFocusApplied=!1;_pageLeaveRequested=!1;_replyThreadRootId=null;_replyRefreshKind=null;_replyRefreshId=null;_publishedAtTimeMinutes=null;_originalPublishedAt=null;_initialPublishedAtTimeMinutes=null;_initialPublishedAtInput=``;_initialSlug=``;_slugCheckTimer=null;_slugSuggestTimer=null;_slugSuggestRequestId=0;_slugCheckRequestId=0;_slugSuggestionKey=``;_suppressBeforeUnload=!1;_dialogEl=null;_mousedownOnBackdrop=!1;_mousedownPos=null;_filePickerActive=!1;_ignoreNextEscapeClose=!1;_openEditRequestId=0;_collectionPickerOrder=[];_suppressCollectionOptionClickUntil=0;_suppressedCollectionOptionId=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.collections=[],this.languages=[],this.contextLanguage=``,this.labels={},this.uploadMaxFileSize=1024,this.pageMode=!1,this.closeHref=`/`,this.autoRestoreDraft=!1,this.slashCommandDiscovered=!1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._rowStatus=new Map,this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyParentPosition=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._publishPanelFullscreen=!1,this._postMetaIndex=null,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._visibilityLocked=!1,this._quietReply=!1,this._language=null,this._showLanguagePicker=!1,this._translationOf=null,this._translationCollapsed=!1,this._seededFromSource=!1}get _editor(){return this.querySelector(`jant-compose-editor`)}get _rowIds(){return this._threadItems.length>0?this._threadItems.map(e=>e.id):[Qe]}_handleRowStatus(e,t){let n=this._rowStatus.get(e);if(n?.hasContent===t.hasContent&&n?.publishable===t.publishable)return;let r=new Map(this._rowStatus);r.set(e,t),this._rowStatus=r}willUpdate(e){if(super.willUpdate(e),e.has(`_threadItems`)){let e=new Set(this._rowIds);[...this._rowStatus.keys()].some(t=>!e.has(t))&&(this._rowStatus=new Map([...this._rowStatus].filter(([t])=>e.has(t))))}}updated(e){super.updated(e),this._initialSnapshot===null&&this._editor&&this._captureInitialSnapshot(),this._adoptTranslationPreview(),e.has(`labels`)&&this._dialogEl&&this.labels&&this._dialogEl.setAttribute(`aria-label`,this.labels.composeDialogLabel),e.has(`_addCollectionPanelOpen`)&&this._addCollectionPanelOpen&&this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()}),e.has(`_showCollection`)&&this._showCollection&&this._scheduleCollectionPickerAutofocus(),(e.has(`_collectionIds`)||e.has(`_slug`)||e.has(`_publishedAtInput`)||e.has(`_visibility`))&&(this._draftSourceId||this._scheduleDraftSave()),this._showPublishPanel&&this._updatePublishPanelLayout(),this._showCollection&&this._updateCollectionPopoverSide(),this._postMetaIndex!==null&&this._updatePostMetaPanelLayout()}reset(){this._openEditRequestId+=1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._closeCollectionPicker(),this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._rowStatus=new Map,this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyParentPosition=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._slugSuggestionKey=``,this._visibilityLocked=!1,this._quietReply=!1,this._language=null,this._showLanguagePicker=!1,this._translationOf=null,this._translationCollapsed=!1,this._seededFromSource=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._initialSnapshot=null,this._hasOwnedContent=!1,this._reportedStorageFailure=!1,this._pageFocusApplied=!1,this._pageLeaveRequested=!1,this._slugSuggestRequestId+=1,this._slugCheckRequestId+=1,this._suppressBeforeUnload=!1,this._filePickerActive=!1,this._ignoreNextEscapeClose=!1,this._cancelSlugTimers(),this._destroyAttachedEditor(),this._editor?.reset(),this._captureInitialSnapshot()}async refreshCollections(){try{let e=await fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e.ok)return!1;let t=await e.json().catch(()=>null);return Array.isArray(t?.collections)?(this.collections=at(t.collections),!0):!1}catch{return!1}}async openEdit(e,t){this.reset();let n=++this._openEditRequestId;this._openingEdit=!0,this._editPostId=e;let r=this.closest(`dialog`);r&&!r.open&&r.showModal(),await this.updateComplete,this._focusDialogShell();try{let r=await fetch(`/api/posts/${e}`);if(!r.ok)throw Error(`Failed to load post`);let i=await r.json();if(n!==this._openEditRequestId||(this._format=i.format,this._slug=i.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=i.publishedAt?ct(i.publishedAt):``,this._publishedAtTimeMinutes=i.publishedAt?W(i.publishedAt):null,this._originalPublishedAt=i.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=i.visibility??`public`,this._visibilityLocked=!!i.replyToId,this._language=i.language??null,i.replyToId&&(this._replyToId=i.replyToId,await this._fetchReplyContext(i.replyToId),n!==this._openEditRequestId)))return;!i.replyToId&&i.collectionIds?.length&&(this._collectionIds=i.collectionIds);let{media:a,textAttachments:o,attachmentOrder:s}=await ut(i.attachments??[]);if(n!==this._openEditRequestId||(this._openingEdit=!1,await this.updateComplete,n!==this._openEditRequestId))return;this._restoreEditDraftIfAvailable(e,t?.restoreToast)||this._editor?.populate({format:i.format,title:i.format===`quote`?void 0:i.title??void 0,bodyJson:i.body??void 0,url:i.format===`quote`?i.sourceUrl??void 0:i.url??void 0,quoteText:i.quoteText??void 0,quoteAuthor:i.format===`quote`?i.sourceName??void 0:void 0,rating:i.rating??void 0,media:a,textAttachments:o,attachmentOrder:s}),globalThis.requestAnimationFrame(()=>{n===this._openEditRequestId&&(this._focusDialogShell(),this._captureInitialSnapshot())})}catch{if(n!==this._openEditRequestId)return;this._openingEdit=!1,this._closeDialog(),this.reset(),l(this.labels.loadPostFailed,`error`)}}async openDraft(e){let t=this.closest(`dialog`);t&&!t.open&&t.showModal(),await this.updateComplete,this._focusDialogShell(),await this._loadDraft(e)}async openNew(t){this.reset(),this._editor?.setTitleDefault(e._getNoteTitleDefault());let n=`none`;if(t?.restoreDraft!==!1&&(n=await this.restoreLocalDraft({notify:t?.restoreToast,extraMedia:t?.restoreMedia})),t?.initialFormat&&(this._format=t.initialFormat),t?.collectionId&&!this._collectionIds.includes(t.collectionId)&&(this._collectionIds=[t.collectionId,...this._collectionIds]),t?.collectionId){this._sourceCollectionId=t.collectionId;let r=n===`restored`?null:e._getCollectionVisibility(t.collectionId);r&&(this._visibility=r)}this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async openTranslation(t,n){this.reset(),this._editor?.setTitleDefault(e._getNoteTitleDefault()),this.languages.some(e=>e.tag===n)&&(this._language=n),this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot(),await this._loadTranslationSource(t,{seed:!0})}async openReply(e,t,n,r,i){this.reset(),this._replyToId=e,this._replyThreadRootId=n??e,this._replyRefreshKind=r?.kind??null,this._replyRefreshId=r?.id??null,this._replyToData=t??null,this._visibilityLocked=!0,this._format=i?.initialFormat??`note`,i?.restoreDraft!==!1&&await this.restoreLocalDraft({expectedReplyToId:e,notify:i?.restoreToast,extraMedia:i?.restoreMedia}),this._collectionIds=[],this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot(),this._loadReplyParentPosition(e)}async _loadReplyParentPosition(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._replyToId!==e)return;this._replyParentPosition=n.threadPosition??null}catch{}}async _fetchReplyContext(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._replyThreadRootId=n.replyToId?n.threadId:n.id,this._replyParentPosition=n.threadPosition??null;let r=n.publishedAt?new Date(n.publishedAt*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`}):``,i=(n.attachments??[]).filter(e=>e.type===`media`).map(e=>({url:e.url??e.previewUrl,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,width:e.width,height:e.height}));this._replyToData={contentHtml:n.bodyHtml??``,dateText:r,media:i.length>0?i:void 0}}catch{}}set loading(e){this._loading=e}_closeDialog(){let e=this.closest(`dialog`);if(e){e.close(),document.activeElement?.blur();return}this.pageMode&&(this._suppressBeforeUnload=!0,globalThis.location.assign(this.closeHref||r(`/`)))}requestCloseAndLeave(){this._pageLeaveRequested=!0,this.requestClose()}consumePageLeaveRequest(){let e=this._pageLeaveRequested;return this._pageLeaveRequested=!1,e}preparePageLeave(){this._suppressBeforeUnload=!0}_clearFilePickerEscapeState(){this._filePickerActive=!1,this._ignoreNextEscapeClose=!1}_shouldIgnoreEscapeClose(){return this._filePickerActive||this._ignoreNextEscapeClose?(this._clearFilePickerEscapeState(),!0):!1}_hasContent(){return this._rowIds.some(e=>this._rowStatus.get(e)?.hasContent===!0)}_hasWorkToLose(){return this._hasContent()?!this._seededFromSource||this._hasUnsavedChanges():!1}_hasWorkToLoseOnLeave(){return this._editPostId||this._draftSourceId?this._hasUnsavedChanges():this._hasWorkToLose()}_buildSnapshot(){let t=this._editor;if(!t)return null;let n=this._threadItems.length>0?Array.from(this.querySelectorAll(`jant-compose-editor`)):[];return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,language:this._language,...e._snapshotEditor(t),threadPosts:this._threadItems.flatMap((t,r)=>{let i=n[r];return i?[{format:t.format,slug:t.slug??``,publishedAtInput:t.publishedAtInput??``,publishedAtTimeMinutes:t.publishedAtTimeMinutes??null,...e._snapshotEditor(i)}]:[]})}}static _snapshotEditor(e){let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=t.rating>0&&e._showRating;return{title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,rating:t.rating,showRating:r,attachments:e._attachments.map(e=>({clientId:e.clientId,mediaId:e.mediaId,previewUrl:e.previewUrl,mimeType:e.file.type,alt:e.alt,status:e.status,summary:e.summary,chars:e.chars})),attachedTexts:n.map(e=>({clientId:e.clientId,mediaId:e.mediaId??null,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:e.getEffectiveAttachmentOrder()}}_serializeSnapshot(e){return e?JSON.stringify(e):null}_captureInitialSnapshot(){this._initialSnapshot=this._serializeSnapshot(this._buildSnapshot())}_hasUnsavedChanges(){let e=this._serializeSnapshot(this._buildSnapshot());return e===null||!this._editPostId&&!this._draftSourceId&&!this._hasContent()?!1:this._initialSnapshot===null?this._hasContent():e!==this._initialSnapshot}requestClose(){if(!this._loading){if(this._showCollection&&this._closeCollectionPicker(),this._showPublishPanel&&=!1,this._showLanguagePicker=!1,this._confirmPanelOpen){let e=this._confirmForAttachedText;this._confirmPanelOpen=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._pageLeaveRequested=!1,this.updateComplete.then(()=>{if(e){this._attachedEditor?.commands.focus();return}this._editor?.focusInput()});return}this._hasWorkToLoseOnLeave()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this._editor?.hasPendingInlineImageUploads()?this._saveDraftAndOpenDrafts():this._finishDraftSaveAndOpenDrafts()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._discardAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()):this._discardAndClose()}_buildEditorPostDetail(e,t,n,r){e.promoteLeadingH1Title({force:!0});let i=e.getData(),a=new Map((i.attachments??[]).map(e=>[e.clientId,e])),o=new Map(i.attachedTexts.map(e=>[e.clientId,e])),s=[];for(let e of i.attachmentOrder){let t=a.get(e);if(t){s.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt});continue}let n=o.get(e);n?.bodyJson&&s.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:H(n.originalBodyJson??null)})}let c=n===0;return{format:t,title:i.title,body:i.body,url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,status:r,slug:this._getPostSlug(n).trim()||void 0,publishedAt:this._getPostPublishedAtSubmitValue(n,r),visibility:c?this._visibilityLocked?void 0:this._visibility:void 0,rating:i.rating,collectionIds:c&&!this._replyToId?[...this._collectionIds]:[],attachments:s,replyToId:c?this._replyToId??void 0:void 0,quietReply:c&&this._canReplyQuietly()&&this._quietReply||void 0,replyThreadRootId:c?this._replyThreadRootId??void 0:void 0,replyRefreshKind:c?this._replyRefreshKind??void 0:void 0,replyRefreshId:c?this._replyRefreshId??void 0:void 0,language:c&&!this._replyToId?this._effectiveLanguage()??void 0:void 0,translationOfId:c?this._translationOf?.id:void 0}}_buildSubmitDetail(e){let t=this._editor;return t?{...this._buildEditorPostDetail(t,this._format,0,e),editPostId:this._editPostId??this._draftSourceId??void 0,draftSourceId:this._draftSourceId??void 0}:null}_focusBlockedSubmitField(e){if(e===`published`){let e=Math.max(1,this._threadItems.length);for(let t=0;t<e;t++)if(this._getPostPublishedAtValidationMessage(t)!==null)return this._revealPublishedAtField(t),!0}{let e=Math.max(1,this._threadItems.length);for(let t=0;t<e;t++)if(this._getPostSlugValidationMessage(t))return this._revealSlugField(t),!0}if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<this._threadItems.length;t++){let n=this._threadItems[t],r=e[t];if(r){if(r.getUrlValidationMessage())return r.revealUrlValidation(),r.focusUrlInput(`end`),!0;if(r.getLinkTitleValidationMessage())return r.revealLinkTitleValidation(),r.focusLinkTitleInput(`end`),!0;if(n.format===`quote`&&!r._quoteText.trim())return r.focusInput(`end`),!0}}return!1}let t=this._editor;return t?t.getUrlValidationMessage()?(t.revealUrlValidation(),t.focusUrlInput(`end`),!0):t.getLinkTitleValidationMessage()?(t.revealLinkTitleValidation(),t.focusLinkTitleInput(`end`),!0):this._format===`quote`&&!t._quoteText.trim()&&(t.focusInput(`end`),!0):!1}_dispatchSubmit(e){if(this._loading||this._focusBlockedSubmitField(e))return!1;if(this._draftSourceId||(this._cancelDraftSaveTimer(),this._saveDraftToStorage()),this._threadItems.length>0){if(this._threadItems.length>20)return l(this._getThreadLimitMessage(),`error`),!1;let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(t.length!==this._threadItems.length)return!1;let n=[],r=[];for(let i=0;i<this._threadItems.length;i++){let a=this._threadItems[i],o=t[i];if(!o)return!1;n.push(this._buildEditorPostDetail(o,a.format,i,e)),r.push(...(o._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`))}return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n[0],editPostId:this._editPostId??this._draftSourceId??void 0,draftSourceId:this._draftSourceId??void 0,threadPosts:n,pendingAttachments:r}})),!0}let t=this._editor;if(!t)return!1;let n=this._buildSubmitDetail(e);if(!n)return!1;let r=(t._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`);return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n,pendingAttachments:r}})),!0}_saveDraftAndOpenDrafts(){this._finishDraftSaveAndOpenDrafts()}_finishDraftSaveAndOpenDrafts(){if(!this._dispatchSubmit(`draft`))return;this.reset();let e=()=>{clearTimeout(t),this.isConnected&&this._openDraftsPanel()},t=globalThis.setTimeout(()=>{document.removeEventListener(`jant:compose-submit-complete`,e)},1e4);document.addEventListener(`jant:compose-submit-complete`,e,{once:!0})}_finishSubmit(e){if(this._dispatchSubmit(e)){if(this.pageMode){this._loading=!0;return}this._closeDialog(),this.reset()}}_submit(e){this._showPublishPanel=!1,this._finishSubmit(e)}_toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}_selectedCollectionLabel(e){let t=this._collectionIds,n=e.find(e=>e.id===t[0]);if(!n)return``;if(t.length===1)return n.title;if(t.length===2){let r=e.find(e=>e.id===t[1]);return r?`${n.title}, ${r.title}`:n.title}return this.labels.collectionCountLabel.replace(`%name%`,n.title).replace(`%count%`,String(t.length-1))}_prepareCollectionPickerOrder(){this._collectionPickerOrder=p(this.collections??[],this._collectionIds)}_focusCollectionPickerInitialTarget(){this.querySelector(`.compose-collection-search-input, .compose-collection-option, .compose-collection-add-action`)?.focus()}_focusCollectionSearchInput(){let e=this.querySelector(`.compose-collection-search-input`);if(!e)return!1;e.focus();let t=e.value.length;return e.setSelectionRange(t,t),!0}_closeCollectionPicker(e){if(this._showCollection=!1,this._collectionSearch=``,this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,e?.restoreFocus===`trigger`){this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()});return}e?.restoreFocus===`editor`&&this._restorePageEditorFocus()}_suppressNextCollectionOptionClick(e){this._suppressedCollectionOptionId=e,this._suppressCollectionOptionClickUntil=Date.now()+250}_isTouchViewport(){return globalThis.matchMedia?.(`(hover: none) and (pointer: coarse)`)?.matches??!1}_shouldAutofocusCollectionPicker(){return!this._isTouchViewport()}_shouldAutofocusFormatInput(){return!this._isTouchViewport()}_scheduleCollectionPickerAutofocus(){this._shouldAutofocusCollectionPicker()&&globalThis.requestAnimationFrame(()=>{this._showCollection&&this._focusCollectionPickerInitialTarget()})}_scheduleCollectionSearchFocus(){globalThis.requestAnimationFrame(()=>{this._showCollection&&(this._focusCollectionSearchInput()||this._focusCollectionPickerInitialTarget())})}_isPrintableCollectionSearchKey(e){return e.length===1&&e.trim().length>0}_handleCollectionTriggerKeydown=e=>{if(!(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)){if(e.key===`ArrowDown`){e.preventDefault(),this._scheduleCollectionSearchFocus();return}this._showCollection&&this._isPrintableCollectionSearchKey(e.key)&&(e.preventDefault(),this._collectionSearch+=e.key,this._scheduleCollectionSearchFocus())}};_getCollectionOptionElements(){return Array.from(this.querySelectorAll(`.compose-collection-option`))}_handleCollectionSearchKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this._closeCollectionPicker({restoreFocus:`trigger`});return}if(e.key!==`ArrowDown`)return;let[t]=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-add-action`),r=t??n;r&&(e.preventDefault(),r.focus())};_handleCollectionOptionKeydown=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this._getCollectionOptionElements(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`.compose-collection-add-action`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.compose-collection-search-input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._toggleCollection(t);return}e.key===`Enter`&&(e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._closeCollectionPicker({restoreFocus:`trigger`}))};_handleCollectionOptionClick=e=>{if(this._suppressedCollectionOptionId===e&&Date.now()<=this._suppressCollectionOptionClickUntil){this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0;return}this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,this._toggleCollection(e)};_handleCollectionAddActionKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-search-input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};_updateCollectionPopoverSide(){let e=this.querySelector(`.compose-collection-trigger`),t=this.querySelector(`.compose-collection-popover[data-popover]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=Math.max(0,i-12-a.bottom-4),s=Math.max(0,a.top-r-12-4);t.dataset.side=o>=s?`bottom`:`top`}_cancelSlugTimers(){this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null)}_currentSlugOwnerId(){return this._editPostId??this._draftSourceId??void 0}_hasManualSlug(){return this._slug.trim().length>0}_currentSuggestionTitle(){return this._editor?.getData().title.trim()??``}_canSuggestSlug(){return this._currentSuggestionTitle().length>0}_currentSuggestionKey(){return`${this._currentSlugOwnerId()??``}::${this._currentSuggestionTitle()}`}_scheduleSuggestedSlugRefresh(e=!1){if(this._postMetaIndex!==0||this._hasManualSlug())return;if(!this._canSuggestSlug()){this._slugSuggestRequestId+=1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``;return}let t=this._currentSuggestionKey();if(this._slugSuggestionKey!==t&&(this._suggestedSlug=``),!e&&!this._suggestedSlugLoading&&this._suggestedSlug&&this._slugSuggestionKey===t)return;this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null);let n=()=>void this._refreshSuggestedSlug(t);if(e){n();return}this._slugSuggestTimer=setTimeout(n,250)}async _refreshSuggestedSlug(e){if(this._slugSuggestTimer=null,this._hasManualSlug()||!this._canSuggestSlug())return;let t=++this._slugSuggestRequestId;this._suggestedSlugLoading=!0;let n=new URLSearchParams({mode:`suggest`}),r=this._currentSuggestionTitle();r&&n.set(`title`,r);let i=this._currentSlugOwnerId();i&&n.set(`postId`,i);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugSuggestRequestId||this._hasManualSlug()||this._postMetaIndex!==0)return;this._suggestedSlug=i.slug?.trim()??``,this._slugSuggestionKey=e}catch{}finally{t===this._slugSuggestRequestId&&(this._suggestedSlugLoading=!1)}}_scheduleSlugAvailabilityCheck(e=0){if(!this._hasPostManualSlug(e)){this._setPostSlugTaken(e,!1),this._slugCheckLoading=!1;return}if(this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._getPostSlugSyncValidationMessage(e)){this._setPostSlugTaken(e,!1),this._slugCheckLoading=!1;return}this._slugCheckLoading=!0;let t=this._getPostSlug(e).trim();this._slugCheckTimer=setTimeout(()=>{this._checkSlugAvailability(t,e)},250)}async _checkSlugAvailability(e,t=0){this._slugCheckTimer=null;let n=++this._slugCheckRequestId,r=new URLSearchParams({mode:`check`,slug:e}),i=t===0?this._currentSlugOwnerId():this._threadItems[t]?.sourcePostId;i&&r.set(`postId`,i);try{let i=await fetch(`/api/posts/slug?${r.toString()}`);if(!i.ok)return;let a=await i.json();if(n!==this._slugCheckRequestId||this._getPostSlug(t).trim()!==e)return;this._setPostSlugTaken(t,a.available===!1)}catch{}finally{n===this._slugCheckRequestId&&(this._slugCheckLoading=!1)}}_useSuggestedSlug(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugTaken=!1,this._slugCheckLoading=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()}))}_resetCustomSlug(e=0){this._setPostSlug(e,``),this._setPostSlugTaken(e,!1),this._slugCheckLoading=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}connectedCallback(){super.connectedCallback(),this._syncPublishPanelPresentation(),this.addEventListener(`keydown`,this._handleKeydown),this.addEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.addEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.addEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.addEventListener(`jant:compose-content-changed`,this._onContentChanged),this.addEventListener(`jant:title-toggle`,this._handleTitleToggle),this.addEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.addEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.addEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.addEventListener(`pointerdown`,this._handlePointerDown),document.addEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.addEventListener(`beforeunload`,this._onBeforeUnload),window.addEventListener(`resize`,this._handleViewportChange),window.addEventListener(`scroll`,this._handleViewportChange,{passive:!0}),document.addEventListener(`scroll`,this._handleAnyScroll,{capture:!0,passive:!0}),globalThis.visualViewport?.addEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.addEventListener(`scroll`,this._handleViewportChange),this._dialogEl=this.closest(`dialog`),this._dialogEl&&(this._dialogEl.addEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.addEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.addEventListener(`click`,this._handleDialogClick)),this.pageMode&&this.updateComplete.then(()=>this._focusPageEditorOnMount())}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener(`keydown`,this._handleKeydown),this.removeEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.removeEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.removeEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.removeEventListener(`jant:compose-content-changed`,this._onContentChanged),this.removeEventListener(`jant:title-toggle`,this._handleTitleToggle),this.removeEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.removeEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.removeEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.removeEventListener(`pointerdown`,this._handlePointerDown),document.removeEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.removeEventListener(`beforeunload`,this._onBeforeUnload),window.removeEventListener(`resize`,this._handleViewportChange),window.removeEventListener(`scroll`,this._handleViewportChange),document.removeEventListener(`scroll`,this._handleAnyScroll,{capture:!0}),globalThis.visualViewport?.removeEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`scroll`,this._handleViewportChange),this._cancelSlugTimers(),this._destroyAttachedEditor(),this._cancelDraftSaveTimer(),this._dialogEl&&=(this._dialogEl.removeEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.removeEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.removeEventListener(`click`,this._handleDialogClick),null)}_handleFilePickerOpen=()=>{this._filePickerActive=!0,this._ignoreNextEscapeClose=!1};_handleFilePickerClose=e=>{this._filePickerActive=!1,this._ignoreNextEscapeClose=!!e.detail?.cancelled};_handlePointerDown=()=>{this._clearFilePickerEscapeState()};_syncPublishPanelPresentation(){let e=globalThis.matchMedia?.($e)?.matches??!1;e!==this._publishPanelFullscreen&&(this._publishPanelFullscreen=e)}_handleViewportChange=()=>{this._syncPublishPanelPresentation(),this._showPublishPanel&&this.updateComplete.then(()=>this._updatePublishPanelLayout()),this._showCollection&&this.updateComplete.then(()=>this._updateCollectionPopoverSide()),this._postMetaIndex!==null&&this.updateComplete.then(()=>this._updatePostMetaPanelLayout())};_handleAnyScroll=()=>{this._postMetaIndex!==null&&this._updatePostMetaPanelLayout()};_handleDialogCancel=e=>{e.preventDefault();let t=e;t.isComposing||t.keyCode===229||this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay()||this.requestClose()};_pointInOpenPopover(e,t){for(let n of document.querySelectorAll(`:popover-open`)){let r=n.getBoundingClientRect();if(e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom)return!0}return!1}_handleDialogMousedown=e=>{let t=e;this._mousedownOnBackdrop=e.target===this._dialogEl&&!this._pointInOpenPopover(t.clientX,t.clientY),this._mousedownPos=this._mousedownOnBackdrop?{x:t.clientX,y:t.clientY}:null};_handleDialogClick=e=>{if(!this._dialogEl||e.target!==this._dialogEl||!this._mousedownOnBackdrop)return;let t=e;if(this._mousedownPos){let e=t.clientX-this._mousedownPos.x,n=t.clientY-this._mousedownPos.y;if(e*e+n*n>16)return}let n=document.getSelection();if(n&&!n.isCollapsed||this._pointInOpenPopover(t.clientX,t.clientY))return;let r=document.elementFromPoint(t.clientX,t.clientY);r instanceof globalThis.Element&&r.closest(Ze)||this.requestClose()};_focusDialogShell(){let e=this.querySelector(`.compose-dialog-inner`);if(e){e.focus();return}this._dialogEl?.focus()}_restorePageEditorFocus(){this.updateComplete.then(()=>this._editor?.focusInput())}_dismissEscapeOverlay(){return this._confirmPanelOpen?(this.requestClose(),!0):this._addCollectionPanelOpen?(this._closeAddCollectionPanel(),!0):this._editor?.isEmojiPickerOpen()?(this._editor.closeEmojiPicker({restoreFocus:!0}),!0):this._showLanguagePicker?(this._closeLanguagePicker(!0),!0):this._showCollection?(this._closeCollectionPicker({restoreFocus:`editor`}),!0):this._showPublishPanel?(this._closePublishPanel(!0),!0):this._postMetaIndex===null?this._altPanelOpen?(this._closeAltPanel(),this._restorePageEditorFocus(),!0):this._draftMenuOpenId?(this._draftMenuOpenId=null,!0):this._draftsPanelOpen?(this._closeDraftsPanel(),!0):this._attachedPanelOpen?(this._cancelAttachedPanel(),!0):!1:(this._closePostMeta(),!0)}_handleKeydown=t=>{let n=t;if(!(n.isComposing||n.keyCode===229)){if(n.key!==`Escape`&&this._clearFilePickerEscapeState(),n.key===`Escape`){if(n.preventDefault(),n.stopPropagation(),this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay())return;this.requestClose()}else if(n.key===`Enter`&&this._confirmPanelOpen)n.preventDefault(),this._handleConfirmSave();else if((n.metaKey||n.ctrlKey)&&n.key===`Enter`)t.preventDefault(),this._publishFromShortcut();else if((n.metaKey||n.ctrlKey)&&!n.altKey&&!n.shiftKey&&n.key>=`1`&&n.key<=String(e._FORMATS.length)){n.preventDefault();let t=e._FORMATS[Number(n.key)-1];this._threadItems.length>0?this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.dispatchEvent(new CustomEvent(`jant:format-change`,{detail:{format:t},bubbles:!0})):this._switchFormat(t)}}};_publishFromShortcut(){if(this._attachedPanelOpen){this._doneAttachedPanel();return}if(!this._canPublish()){this._focusBlockedSubmitField(`published`);return}this._submit(`published`)}_handleAltPanelOpen=e=>{let t=e.detail;this._altPanelIndex=t.index,this._altPanelOpen=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-alt-input`)?.focus()})};_handleAltPanelClose=()=>{this._altPanelOpen=!1};_getAltAttachment(){return this._editor?._attachments[this._altPanelIndex]??null}_onAltInput(e){let t=e.target.value;this._editor?.updateAlt(this._altPanelIndex,t)}_closeAltPanel(){this._altPanelOpen=!1}_handleFullscreenClose=e=>{let t=Array.from(this.querySelectorAll(`jant-compose-editor`))[e.detail.editorIndex??0]??this._editor;t&&(t.setEditorState(e.detail.json,e.detail.title,e.detail.showTitle,e.detail.selection),t.adoptPendingUploads(),e.detail.intent!==`publish`&&this.updateComplete.then(()=>t.focusSelection(e.detail.selection))),this._replyExpanded=e.detail.replyExpanded,e.detail.intent===`publish`&&this._publishFromShortcut()};_buildFullscreenReplyContext(){return!this._replyToId||!this._replyToData?null:{contentHtml:this._replyToData.contentHtml,dateText:this._replyToData.dateText,expanded:this._replyExpanded}}_handleFullscreenOpen=e=>{e.detail.replyContext=this._buildFullscreenReplyContext();let t=Array.from(this.querySelectorAll(`jant-compose-editor`)).indexOf(e.target);e.detail.editorIndex=t>=0?t:0};_handleAttachedPanelOpen=e=>{let t=e.detail;this._attachedTextIndex=t.index,this._attachedPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-attached-tiptap`);if(!e)return;let t=this._editor?._attachedTexts[this._attachedTextIndex]?.bodyJson??null;this._attachedTextSnapshot=t?JSON.parse(JSON.stringify(t)):null,this._attachedEditor=le({element:e,placeholder:this.labels.attachedTextPlaceholder,content:t,toolbarMode:`compose`,tableControlLabels:this.labels.tableControls}),this._focusAttachedEditorBoundary(t)})};_focusAttachedEditorBoundary(e){if(!this._attachedEditor)return;let t=H(e??this._attachedEditor.getJSON())?`end`:`start`;this._attachedEditor.commands.focus(t)}_isAttachedTextDirty(){return this._attachedEditor?JSON.stringify(H(this._attachedEditor.getJSON()))!==JSON.stringify(H(this._attachedTextSnapshot)):!1}_destroyAttachedEditor(){this._attachedEditor&&=(this._attachedEditor.destroy(),null),this._attachedTextSnapshot=null}_doneAttachedPanel(){if(this._attachedEditor){let e=this._attachedEditor.getJSON(),t=this._attachedEditor.getHTML();this._editor?.updateAttachedText(this._attachedTextIndex,e,t)}this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_cancelAttachedPanel(){if(this._isAttachedTextDirty()){this._confirmForDrafts=!1,this._confirmForAttachedText=!0,this._confirmPanelOpen=!0;return}this._discardAttachedPanel()}_handleAttachedEditorMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this._focusAttachedEditorBoundary())}_handleDraftButtonClick(){this._loading||(this._hasWorkToLoseOnLeave()?(this._confirmForDrafts=!0,this._confirmPanelOpen=!0):this._openDraftsPanel())}async _openDraftsPanel(){this._draftsPanelOpen=!0,this._draftsLoading=!0,this._draftsError=null,this._draftMenuOpenId=null;try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(!e.ok)throw Error(`Failed to load drafts`);let t=await e.json(),n=(Array.isArray(t)?t:t.posts??[]).map(e=>({id:e.id,slug:e.slug,format:e.format,title:(e.format===`quote`?e.sourceName:e.title)??null,bodyText:e.bodyText??null,bodyHtml:e.bodyHtml??null,url:(e.format===`quote`?e.sourceUrl:e.url)??null,quoteText:e.quoteText??null,replyToId:e.replyToId??null,updatedAt:e.updatedAt,mediaAttachments:(e.attachments??[]).filter(e=>e.type===`media`).map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt??null,mimeType:e.mimeType}))})),r=new Set(n.map(e=>e.id));this._drafts=n.filter(e=>!e.replyToId||!r.has(e.replyToId))}catch{this._draftsError=`Could not load drafts. Try again.`,this._drafts=[]}finally{this._draftsLoading=!1}}_closeDraftsPanel(){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.updateComplete.then(()=>this._editor?.focusInput())}async _populateEditorFromPost(e,t){let{media:n,textAttachments:r,attachmentOrder:i}=await ut(t.attachments??[]);e.populate({format:t.format,title:t.format===`quote`?void 0:t.title??void 0,bodyJson:t.body??void 0,url:t.format===`quote`?t.sourceUrl??void 0:t.url??void 0,quoteText:t.quoteText??void 0,quoteAuthor:t.format===`quote`?t.sourceName??void 0:void 0,rating:t.rating??void 0,media:n,textAttachments:r,attachmentOrder:i})}async _loadDraft(e){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._draftSourceId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=n.publishedAt?ct(n.publishedAt):``,this._publishedAtTimeMinutes=n.publishedAt?W(n.publishedAt):null,this._originalPublishedAt=n.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,!n.replyToId&&n.collectionIds?.length&&(this._collectionIds=n.collectionIds),n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),n.threadId===n.id||n.threadId===void 0)try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(e.ok){let t=await e.json(),r=(Array.isArray(t)?t:t.posts??[]).filter(e=>e.id!==n.id&&e.threadId===n.id&&e.status===`draft`).map(e=>({id:e.id,format:e.format,slug:e.slug??null,replyToId:e.replyToId??null,title:e.title??null,body:e.body??null,url:e.url??null,sourceUrl:e.sourceUrl??null,sourceName:e.sourceName??null,quoteText:e.quoteText??null,rating:e.rating??null,attachments:e.attachments??[],visibility:e.visibility??null}));if(r.length>0){let e=[],t=n.id;for(let n=0;n<r.length;n++){let n=r.find(e=>e.replyToId===t);if(!n)break;e.push(n),t=n.id}for(let t of r)e.includes(t)||e.push(t);this._threadItems=[{id:L(),format:n.format},...e.map(e=>({id:L(),format:e.format,slug:e.slug??``,sourcePostId:e.id}))],this._focusedThreadIndex=0,await this.updateComplete;let i=Array.from(this.querySelectorAll(`jant-compose-editor`)),a=i[0];a&&await this._populateEditorFromPost(a,n);for(let t=0;t<e.length;t++){let r=i[t+1];if(!r)continue;let a=e[t];await this._populateEditorFromPost(r,{id:a.id,threadId:n.id,format:a.format,replyToId:a.replyToId,title:a.title,body:a.body,url:a.url,sourceUrl:a.sourceUrl,sourceName:a.sourceName,quoteText:a.quoteText,rating:a.rating,attachments:a.attachments,visibility:a.visibility})}globalThis.requestAnimationFrame(()=>{i[0]?.focusInput(),this._captureInitialSnapshot()});return}}}catch{}await this.updateComplete;let r=this._editor;r&&await this._populateEditorFromPost(r,n),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async _deleteDraft(e){this._draftMenuOpenId=null,this._drafts=this._drafts.filter(t=>t.id!==e);try{if(!(await fetch(`/api/posts/${e}`,{method:`DELETE`})).ok)throw Error();l(this.labels.draftDeleted)}catch{l(`Failed to delete draft. Try again.`,`error`),this._openDraftsPanel()}}_formatDraftDate(e){let t=Date.now()/1e3-e;return t<60?`now`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:t<604800?`${Math.floor(t/86400)}d`:new Date(e*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}_getDraftPreview(e){return e.format===`quote`&&e.quoteText?e.quoteText:e.title?e.title:e.bodyText?e.bodyText:e.url?e.url:null}_getThreadLimitMessage(){return this.labels.threadLimitReached||`Threads can include up to 20 posts.`}static _DRAFT_KEY=`jant:compose-draft`;static _EDIT_DRAFT_KEY_PREFIX=`jant:compose-edit:`;static _DRAFT_MAX_AGE=6048e5;_currentDraftStorageKey(){return this._editPostId?e._EDIT_DRAFT_KEY_PREFIX+this._editPostId:e._DRAFT_KEY}_onContentChanged=()=>{this.requestUpdate(),this._hasManualSlug()||this._scheduleSuggestedSlugRefresh(),this._draftSourceId||this._scheduleDraftSave()};_handleTitleToggle=t=>{this._editPostId||this._draftSourceId||this._replyToId||t.target?.threadItem||e._setNoteTitleDefault(t.detail.showTitle)};_cancelDraftSaveTimer(){this._draftSaveTimer!==null&&(clearTimeout(this._draftSaveTimer),this._draftSaveTimer=null)}_scheduleDraftSave(){this._cancelDraftSaveTimer(),this._draftSaveTimer=setTimeout(()=>this._saveDraftToStorage(),1e3)}_onBeforeUnload=e=>{if(this._suppressBeforeUnload)return;this._draftSaveTimer!==null&&(this._cancelDraftSaveTimer(),this._saveDraftToStorage());let t=this.closest(`dialog`);this._hasUnsavedChanges()&&(this.pageMode||t?.open===!0)&&(e.preventDefault(),e.returnValue=``)};_saveDraftToStorage(){if(this._threadItems.length>0){let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(!t.some(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.rating>0||t.attachedTexts.length>0||t.attachments.length>0})){this._releaseStoredDraft();return}let n=this._threadItems.map((n,r)=>{let i=t[r];if(!i)return null;let a=i.getData();return{format:n.format,publishedAtInput:n.publishedAtInput,publishedAtTimeMinutes:n.publishedAtTimeMinutes,slug:n.slug,title:a.title,bodyJson:i.getNormalizedBodyJson(),url:a.url,quoteText:a.quoteText,quoteAuthor:a.quoteAuthor,rating:a.rating,showTitle:n.format===`note`&&i._showTitle,showRating:a.rating>0&&i._showRating,attachedTexts:a.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...a.attachmentOrder],mediaAttachments:e._mediaSnapshotFromAttachments(a.attachments)}}).filter(e=>e!==null),r={format:this._threadItems[0]?.format??this._format,title:``,bodyJson:null,url:``,quoteText:``,quoteAuthor:``,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:0,showTitle:!1,showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,language:this._language,translationOfId:this._translationOf?.id??null,attachedTexts:[],attachmentOrder:[],threadItems:n,savedAt:Date.now()};this._writeStoredDraft(r);return}let t=this._editor;if(!t)return;if(!this._hasUnsavedChanges()){this._releaseStoredDraft();return}let n=t.getData();if(!(n.body||n.title.trim()||n.url.trim()||n.quoteText.trim()||n.quoteAuthor.trim()||n.rating>0||n.attachments.length>0||n.attachedTexts.length>0)){this._releaseStoredDraft();return}let r={format:this._format,title:n.title,bodyJson:t.getNormalizedBodyJson(),url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:n.rating,showTitle:this._format===`note`&&t._showTitle,showRating:n.rating>0&&t._showRating,collectionIds:[...this._collectionIds],replyToId:this._replyToId,language:this._language,translationOfId:this._translationOf?.id??null,attachedTexts:n.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary,mediaId:e.mediaId,originalBodyJson:e.mediaId?e.originalBodyJson??null:void 0})),attachmentOrder:[...n.attachmentOrder],mediaAttachments:e._mediaSnapshotFromAttachments(n.attachments),savedAt:Date.now()};this._writeStoredDraft(r)}_writeStoredDraft(e){try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(e)),this._hasOwnedContent=!0}catch(e){console.warn(`[jant] compose draft could not be stored`,e),this._reportedStorageFailure||(this._reportedStorageFailure=!0,l(this.labels.draftStoreFailed,`error`))}}_releaseStoredDraft(){this._hasOwnedContent&&(this._hasOwnedContent=!1,globalThis.localStorage.removeItem(this._currentDraftStorageKey()))}_clearDraftFromStorage(){this._cancelDraftSaveTimer(),this._hasOwnedContent=!1,globalThis.localStorage.removeItem(this._currentDraftStorageKey())}clearLocalDraftFromStorage(){this._clearDraftFromStorage()}clearEditDraftFromStorage(t){globalThis.localStorage.removeItem(e._EDIT_DRAFT_KEY_PREFIX+t)}static _mediaSnapshotFromAttachments(e){return e.flatMap(e=>e.status===`done`&&e.mediaId&&e.remoteUrl?[{clientId:e.clientId,mediaId:e.mediaId,url:e.remoteUrl,mimeType:e.file.type,name:e.file.name||void 0,alt:e.alt||void 0,summary:e.summary,chars:e.chars,persisted:e.persisted||void 0}]:[])}static _restoredMediaToPopulate(e){return e.map(e=>({id:e.mediaId,clientId:e.clientId,previewUrl:e.url,mimeType:e.mimeType,originalName:e.name,alt:e.alt,summary:e.summary??void 0,chars:e.chars??void 0,persisted:e.persisted??!1}))}static _mergeRestoredMedia(e,t){let n=new Map;for(let t of e??[])n.set(t.clientId,t);for(let e of t??[])n.set(e.clientId,e);return n}async restoreLocalDraft(t){let n=e._DRAFT_KEY;if(this._editPostId||this._draftSourceId)return this._reportRestoreOutcome(`composer-busy`,n);if(this._hasContent())return this._reportRestoreOutcome(`composer-has-content`,n);let r;try{r=globalThis.localStorage.getItem(n)}catch{return`none`}if(!r)return`none`;let i;try{i=JSON.parse(r)}catch{return this._reportRestoreOutcome(`unreadable`,n,r)}if(Date.now()-i.savedAt>e._DRAFT_MAX_AGE)return this._reportRestoreOutcome(`expired`,n,r,i);if(t?.expectedReplyToId!==void 0&&i.replyToId!==t.expectedReplyToId)return this._reportRestoreOutcome(`other-reply`,n,r,i);if(this._collectionIds=i.replyToId?[]:[...i.collectionIds??[]],this._slug=i.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=i.publishedAtInput??``,this._publishedAtTimeMinutes=i.publishedAtTimeMinutes??null,this._visibility=i.visibility??`public`,this._language=i.language??null,i.translationOfId&&await this._loadTranslationSource(i.translationOfId),i.replyToId&&(this._replyToId=i.replyToId,this._visibilityLocked=!0,await this._fetchReplyContext(i.replyToId)),i.threadItems&&i.threadItems.length>=2){this._format=i.threadItems[0].format,this._threadItems=i.threadItems.map(e=>({id:L(),format:e.format,publishedAtInput:e.publishedAtInput,publishedAtTimeMinutes:e.publishedAtTimeMinutes,slug:e.slug})),this._focusedThreadIndex=0,await this.updateComplete;let n=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let r=0;r<i.threadItems.length;r++){let a=i.threadItems[r],o=n[r];if(!o)continue;let s=a.attachedTexts?.flatMap(e=>{let t=H(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]}),c=t?.extraMedia?.filter(e=>a.attachmentOrder?.includes(e.clientId)),l=[...e._mergeRestoredMedia(a.mediaAttachments,c).values()];o.populate({format:a.format,title:a.title||void 0,bodyJson:a.bodyJson?JSON.stringify(a.bodyJson):void 0,url:a.url||void 0,quoteText:a.quoteText||void 0,quoteAuthor:a.quoteAuthor||void 0,rating:a.rating||void 0,showTitle:a.showTitle,showRating:a.showRating,media:l.length?e._restoredMediaToPopulate(l):void 0,textAttachments:s?.length?s:void 0,attachmentOrder:a.attachmentOrder})}return this._draftRestored=!0,this._hasOwnedContent=!0,t?.notify!==!1&&l(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()}),`restored`}this._format=i.format,await this.updateComplete;let a=i.attachedTexts?.flatMap(e=>{let t=H(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]}),o=[...e._mergeRestoredMedia(i.mediaAttachments,t?.extraMedia).values()];return this._editor?.populate({format:i.format,title:i.title||void 0,bodyJson:i.bodyJson?JSON.stringify(i.bodyJson):void 0,url:i.url||void 0,quoteText:i.quoteText||void 0,quoteAuthor:i.quoteAuthor||void 0,rating:i.rating||void 0,showTitle:i.showTitle,showRating:i.showRating,media:o.length?e._restoredMediaToPopulate(o):void 0,textAttachments:a?.length?a:void 0,attachmentOrder:i.attachmentOrder}),this._draftRestored=!0,this._hasOwnedContent=!0,t?.notify!==!1&&l(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()}),`restored`}_reportRestoreOutcome(e,t,n,r){if(e===`restored`||e===`none`)return e;let i=n;if(i===void 0)try{i=globalThis.localStorage.getItem(t)}catch{i=null}return i?(console.warn(`[jant] compose draft not restored: ${e}`,{key:t,bytes:i.length,savedAt:r?.savedAt?new Date(r.savedAt).toISOString():null,thread:r?.threadItems?.length??null}),e):`none`}_restoreEditDraftIfAvailable(t,n){let r=e._EDIT_DRAFT_KEY_PREFIX+t,i;try{i=globalThis.localStorage.getItem(r)}catch{return!1}if(!i)return!1;let a;try{a=JSON.parse(i)}catch{return this._reportRestoreOutcome(`unreadable`,r,i),!1}if(Date.now()-a.savedAt>e._DRAFT_MAX_AGE)return this._reportRestoreOutcome(`expired`,r,i,a),!1;this._format=a.format,this._collectionIds=this._replyToId?[]:[...a.collectionIds??[]],this._slug=a.slug??``,this._publishedAtInput=a.publishedAtInput??``,this._publishedAtTimeMinutes=a.publishedAtTimeMinutes??null,this._visibility=a.visibility??`public`,this._language=a.language??null;let o=a.attachedTexts?.flatMap(e=>{let t=H(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary,mediaId:e.mediaId,originalBodyJson:e.mediaId?JSON.stringify(e.originalBodyJson??null):void 0}]:[]}),s=a.mediaAttachments??[];return this._editor?.populate({format:a.format,title:a.title||void 0,bodyJson:a.bodyJson?JSON.stringify(a.bodyJson):void 0,url:a.url||void 0,quoteText:a.quoteText||void 0,quoteAuthor:a.quoteAuthor||void 0,rating:a.rating||void 0,showTitle:a.showTitle,showRating:a.showRating,media:s.length?e._restoredMediaToPopulate(s):void 0,textAttachments:o?.length?o:void 0,attachmentOrder:a.attachmentOrder}),this._draftRestored=!0,this._hasOwnedContent=!0,n!==!1&&l(this.labels.draftRestored),!0}async _applyTranslationRequestFromUrl(){let e=new URLSearchParams(globalThis.location?.search??``),t=e.get(`translationOf`);if(!t)return;let n=e.get(`lang`);n&&this.languages.some(e=>e.tag===n)&&(this._language=n),this._translationOf||await this._loadTranslationSource(t,{seed:!0})}async _focusPageEditorOnMount(){this._pageFocusApplied||(this.autoRestoreDraft&&await this.restoreLocalDraft(),await this._applyTranslationRequestFromUrl(),await this.updateComplete,globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._pageFocusApplied=!0}))}_renderDraftsPanel(){return this._draftsPanelOpen?i`
119
+ ${y(e)}
120
+ </svg>`}function at(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=Reflect.get(e,`id`),n=Reflect.get(e,`title`),r=Reflect.get(e,`slug`);return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,title:n,slug:typeof r==`string`?r:``}]}):[]}function ot(e){return!e.content||e.content.length===0||e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}function H(e){return e?ot(e)?null:e:null}function st(e){return String(e).padStart(2,`0`)}function ct(e){let t=new Date(e*1e3);return`${t.getFullYear()}-${st(t.getMonth()+1)}-${st(t.getDate())}`}function U(e){let t=e.trim();if(!t)return null;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=new Date(r,i-1,a);return Number.isNaN(o.getTime())||o.getFullYear()!==r||o.getMonth()!==i-1||o.getDate()!==a?null:{year:r,monthIndex:i-1,day:a}}function W(e){let t=new Date(e*1e3);return t.getHours()*60+t.getMinutes()}function lt(e,t){let n=U(e);if(!n)return null;let r=Math.min(Math.max(t,0),1439),i=Math.floor(r/60),a=r%60;return Math.floor(new Date(n.year,n.monthIndex,n.day,i,a,0,0).getTime()/1e3)}async function ut(e){let t=e.filter(e=>e.type===`media`),n=e.filter(e=>e.type===`text`);return{media:t.map(e=>({id:e.id,previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,alt:e.alt,mimeType:e.mimeType,originalName:e.originalName,summary:e.summary,chars:e.chars,persisted:!0})),textAttachments:await Promise.all(n.map(async e=>{try{let t=await fetch(e.contentUrl);if(t.ok){let n=await t.json(),r=n.contentFormat===`markdown`&&n.content?n.content:``,i=r?ie(r):null;if(i)return{bodyJson:JSON.stringify(i),bodyHtml:``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:JSON.stringify({type:`doc`,content:[{type:`paragraph`}]}),bodyHtml:``,summary:e.summary??``,mediaId:e.id}})),attachmentOrder:e.map(e=>e.id)}}var dt=class e extends l{static _lastNewPostVisibility=`public`;_sourceCollectionId=null;static _collectionVisibilityKey(e){return`jant:collection-visibility:${e}`}static _getCollectionVisibility(t){try{let n=globalThis.localStorage.getItem(e._collectionVisibilityKey(t));if(n===`public`||n===`latest_hidden`||n===`private`)return n}catch{}return null}static _setCollectionVisibility(t,n){try{globalThis.localStorage.setItem(e._collectionVisibilityKey(t),n)}catch{}}static _NOTE_TITLE_KEY=`jant:compose-note-title`;static _getNoteTitleDefault(){try{return globalThis.localStorage.getItem(e._NOTE_TITLE_KEY)!==`0`}catch{return!0}}static _setNoteTitleDefault(t){try{globalThis.localStorage.setItem(e._NOTE_TITLE_KEY,t?`1`:`0`)}catch{}}static properties={collections:{type:Array},languages:{type:Array},contextLanguage:{type:String,attribute:`context-language`},labels:{type:Object},uploadMaxFileSize:{type:Number,attribute:`upload-max-file-size`},pageMode:{type:Boolean,attribute:`page-mode`},closeHref:{type:String,attribute:`close-href`},autoRestoreDraft:{type:Boolean,attribute:`auto-restore-draft`},slashCommandDiscovered:{type:Boolean,attribute:`slash-command-discovered`},_format:{state:!0},_status:{state:!0},_loading:{state:!0},_openingEdit:{state:!0},_collectionIds:{state:!0},_showCollection:{state:!0},_collectionSearch:{state:!0},_altPanelOpen:{state:!0},_altPanelIndex:{state:!0},_attachedPanelOpen:{state:!0},_attachedTextIndex:{state:!0},_confirmPanelOpen:{state:!0},_editPostId:{state:!0},_draftSourceId:{state:!0},_draftsPanelOpen:{state:!0},_drafts:{state:!0},_draftsLoading:{state:!0},_draftsError:{state:!0},_draftMenuOpenId:{state:!0},_addCollectionPanelOpen:{state:!0},_replyToId:{state:!0},_replyToData:{state:!0},_replyParentPosition:{state:!0},_replyExpanded:{state:!0},_threadItems:{state:!0},_rowStatus:{state:!0},_focusedThreadIndex:{state:!0},_slug:{state:!0},_publishedAtInput:{state:!0},_visibility:{state:!0},_showPublishPanel:{state:!0},_postMetaIndex:{state:!0},_publishPanelFullscreen:{state:!0},_suggestedSlug:{state:!0},_suggestedSlugLoading:{state:!0},_slugCheckLoading:{state:!0},_slugTaken:{state:!0},_visibilityLocked:{state:!0},_quietReply:{state:!0},_language:{state:!0},_showLanguagePicker:{state:!0},_translationOf:{state:!0},_translationCollapsed:{state:!0}};_attachedEditor=null;_attachedTextSnapshot=null;_seededFromSource=!1;_confirmForDrafts=!1;_confirmForAttachedText=!1;_draftSaveTimer=null;_draftRestored=!1;_hasOwnedContent=!1;_reportedStorageFailure=!1;_initialSnapshot=null;_pageFocusApplied=!1;_pageLeaveRequested=!1;_replyThreadRootId=null;_replyRefreshKind=null;_replyRefreshId=null;_publishedAtTimeMinutes=null;_originalPublishedAt=null;_initialPublishedAtTimeMinutes=null;_initialPublishedAtInput=``;_initialSlug=``;_slugCheckTimer=null;_slugSuggestTimer=null;_slugSuggestRequestId=0;_slugCheckRequestId=0;_slugSuggestionKey=``;_suppressBeforeUnload=!1;_dialogEl=null;_mousedownOnBackdrop=!1;_mousedownPos=null;_filePickerActive=!1;_ignoreNextEscapeClose=!1;_openEditRequestId=0;_collectionPickerOrder=[];_suppressCollectionOptionClickUntil=0;_suppressedCollectionOptionId=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.collections=[],this.languages=[],this.contextLanguage=``,this.labels={},this.uploadMaxFileSize=1024,this.pageMode=!1,this.closeHref=`/`,this.autoRestoreDraft=!1,this.slashCommandDiscovered=!1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._rowStatus=new Map,this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyParentPosition=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._publishPanelFullscreen=!1,this._postMetaIndex=null,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._visibilityLocked=!1,this._quietReply=!1,this._language=null,this._showLanguagePicker=!1,this._translationOf=null,this._translationCollapsed=!1,this._seededFromSource=!1}get _editor(){return this.querySelector(`jant-compose-editor`)}get _rowIds(){return this._threadItems.length>0?this._threadItems.map(e=>e.id):[Qe]}_handleRowStatus(e,t){let n=this._rowStatus.get(e);if(n?.hasContent===t.hasContent&&n?.publishable===t.publishable)return;let r=new Map(this._rowStatus);r.set(e,t),this._rowStatus=r}willUpdate(e){if(super.willUpdate(e),e.has(`_threadItems`)){let e=new Set(this._rowIds);[...this._rowStatus.keys()].some(t=>!e.has(t))&&(this._rowStatus=new Map([...this._rowStatus].filter(([t])=>e.has(t))))}}updated(e){super.updated(e),this._initialSnapshot===null&&this._editor&&this._captureInitialSnapshot(),this._adoptTranslationPreview(),e.has(`labels`)&&this._dialogEl&&this.labels&&this._dialogEl.setAttribute(`aria-label`,this.labels.composeDialogLabel),e.has(`_addCollectionPanelOpen`)&&this._addCollectionPanelOpen&&this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()}),e.has(`_showCollection`)&&this._showCollection&&this._scheduleCollectionPickerAutofocus(),(e.has(`_collectionIds`)||e.has(`_slug`)||e.has(`_publishedAtInput`)||e.has(`_visibility`))&&(this._draftSourceId||this._scheduleDraftSave()),this._showPublishPanel&&this._updatePublishPanelLayout(),this._showCollection&&this._updateCollectionPopoverSide(),this._postMetaIndex!==null&&this._updatePostMetaPanelLayout()}reset(){this._openEditRequestId+=1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._closeCollectionPicker(),this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._rowStatus=new Map,this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyParentPosition=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._slugSuggestionKey=``,this._visibilityLocked=!1,this._quietReply=!1,this._language=null,this._showLanguagePicker=!1,this._translationOf=null,this._translationCollapsed=!1,this._seededFromSource=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._initialSnapshot=null,this._hasOwnedContent=!1,this._reportedStorageFailure=!1,this._pageFocusApplied=!1,this._pageLeaveRequested=!1,this._slugSuggestRequestId+=1,this._slugCheckRequestId+=1,this._suppressBeforeUnload=!1,this._filePickerActive=!1,this._ignoreNextEscapeClose=!1,this._cancelSlugTimers(),this._destroyAttachedEditor(),this._editor?.reset(),this._captureInitialSnapshot()}async refreshCollections(){try{let e=await fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e.ok)return!1;let t=await e.json().catch(()=>null);return Array.isArray(t?.collections)?(this.collections=at(t.collections),!0):!1}catch{return!1}}async openEdit(e,t){this.reset();let n=++this._openEditRequestId;this._openingEdit=!0,this._editPostId=e;let r=this.closest(`dialog`);r&&!r.open&&r.showModal(),await this.updateComplete,this._focusDialogShell();try{let r=await fetch(`/api/posts/${e}`);if(!r.ok)throw Error(`Failed to load post`);let i=await r.json();if(n!==this._openEditRequestId||(this._format=i.format,this._slug=i.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=i.publishedAt?ct(i.publishedAt):``,this._publishedAtTimeMinutes=i.publishedAt?W(i.publishedAt):null,this._originalPublishedAt=i.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=i.visibility??`public`,this._visibilityLocked=!!i.replyToId,this._language=i.language??null,i.replyToId&&(this._replyToId=i.replyToId,await this._fetchReplyContext(i.replyToId),n!==this._openEditRequestId)))return;!i.replyToId&&i.collectionIds?.length&&(this._collectionIds=i.collectionIds);let{media:a,textAttachments:o,attachmentOrder:s}=await ut(i.attachments??[]);if(n!==this._openEditRequestId||(this._openingEdit=!1,await this.updateComplete,n!==this._openEditRequestId))return;this._restoreEditDraftIfAvailable(e,t?.restoreToast)||this._editor?.populate({format:i.format,title:i.format===`quote`?void 0:i.title??void 0,bodyJson:i.body??void 0,url:i.format===`quote`?i.sourceUrl??void 0:i.url??void 0,quoteText:i.quoteText??void 0,quoteAuthor:i.format===`quote`?i.sourceName??void 0:void 0,rating:i.rating??void 0,media:a,textAttachments:o,attachmentOrder:s}),globalThis.requestAnimationFrame(()=>{n===this._openEditRequestId&&(this._focusDialogShell(),this._captureInitialSnapshot())})}catch{if(n!==this._openEditRequestId)return;this._openingEdit=!1,this._closeDialog(),this.reset(),u(this.labels.loadPostFailed,`error`)}}async openDraft(e){let t=this.closest(`dialog`);t&&!t.open&&t.showModal(),await this.updateComplete,this._focusDialogShell(),await this._loadDraft(e)}async openNew(t){this.reset(),this._editor?.setTitleDefault(e._getNoteTitleDefault());let n=`none`;if(t?.restoreDraft!==!1&&(n=await this.restoreLocalDraft({notify:t?.restoreToast,extraMedia:t?.restoreMedia})),t?.initialFormat&&(this._format=t.initialFormat),t?.collectionId&&!this._collectionIds.includes(t.collectionId)&&(this._collectionIds=[t.collectionId,...this._collectionIds]),t?.collectionId){this._sourceCollectionId=t.collectionId;let r=n===`restored`?null:e._getCollectionVisibility(t.collectionId);r&&(this._visibility=r)}this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async openTranslation(t,n){this.reset(),this._editor?.setTitleDefault(e._getNoteTitleDefault()),this.languages.some(e=>e.tag===n)&&(this._language=n),this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot(),await this._loadTranslationSource(t,{seed:!0})}async openReply(e,t,n,r,i){this.reset(),this._replyToId=e,this._replyThreadRootId=n??e,this._replyRefreshKind=r?.kind??null,this._replyRefreshId=r?.id??null,this._replyToData=t??null,this._visibilityLocked=!0,this._format=i?.initialFormat??`note`,i?.restoreDraft!==!1&&await this.restoreLocalDraft({expectedReplyToId:e,notify:i?.restoreToast,extraMedia:i?.restoreMedia}),this._collectionIds=[],this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot(),this._loadReplyParentPosition(e)}async _loadReplyParentPosition(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._replyToId!==e)return;this._replyParentPosition=n.threadPosition??null}catch{}}async _fetchReplyContext(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._replyThreadRootId=n.replyToId?n.threadId:n.id,this._replyParentPosition=n.threadPosition??null;let r=n.publishedAt?new Date(n.publishedAt*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`}):``,i=(n.attachments??[]).filter(e=>e.type===`media`).map(e=>({url:e.url??e.previewUrl,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,width:e.width,height:e.height}));this._replyToData={contentHtml:n.bodyHtml??``,dateText:r,media:i.length>0?i:void 0}}catch{}}set loading(e){this._loading=e}_closeDialog(){let e=this.closest(`dialog`);if(e){e.close(),document.activeElement?.blur();return}this.pageMode&&(this._suppressBeforeUnload=!0,globalThis.location.assign(this.closeHref||t(`/`)))}requestCloseAndLeave(){this._pageLeaveRequested=!0,this.requestClose()}consumePageLeaveRequest(){let e=this._pageLeaveRequested;return this._pageLeaveRequested=!1,e}preparePageLeave(){this._suppressBeforeUnload=!0}_clearFilePickerEscapeState(){this._filePickerActive=!1,this._ignoreNextEscapeClose=!1}_shouldIgnoreEscapeClose(){return this._filePickerActive||this._ignoreNextEscapeClose?(this._clearFilePickerEscapeState(),!0):!1}_hasContent(){return this._rowIds.some(e=>this._rowStatus.get(e)?.hasContent===!0)}_hasWorkToLose(){return this._hasContent()?!this._seededFromSource||this._hasUnsavedChanges():!1}_hasWorkToLoseOnLeave(){return this._editPostId||this._draftSourceId?this._hasUnsavedChanges():this._hasWorkToLose()}_buildSnapshot(){let t=this._editor;if(!t)return null;let n=this._threadItems.length>0?Array.from(this.querySelectorAll(`jant-compose-editor`)):[];return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,language:this._language,...e._snapshotEditor(t),threadPosts:this._threadItems.flatMap((t,r)=>{let i=n[r];return i?[{format:t.format,slug:t.slug??``,publishedAtInput:t.publishedAtInput??``,publishedAtTimeMinutes:t.publishedAtTimeMinutes??null,...e._snapshotEditor(i)}]:[]})}}static _snapshotEditor(e){let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=t.rating>0&&e._showRating;return{title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,rating:t.rating,showRating:r,attachments:e._attachments.map(e=>({clientId:e.clientId,mediaId:e.mediaId,previewUrl:e.previewUrl,mimeType:e.file.type,alt:e.alt,status:e.status,summary:e.summary,chars:e.chars})),attachedTexts:n.map(e=>({clientId:e.clientId,mediaId:e.mediaId??null,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:e.getEffectiveAttachmentOrder()}}_serializeSnapshot(e){return e?JSON.stringify(e):null}_captureInitialSnapshot(){this._initialSnapshot=this._serializeSnapshot(this._buildSnapshot())}_hasUnsavedChanges(){let e=this._serializeSnapshot(this._buildSnapshot());return e===null||!this._editPostId&&!this._draftSourceId&&!this._hasContent()?!1:this._initialSnapshot===null?this._hasContent():e!==this._initialSnapshot}requestClose(){if(!this._loading){if(this._showCollection&&this._closeCollectionPicker(),this._showPublishPanel&&=!1,this._showLanguagePicker=!1,this._confirmPanelOpen){let e=this._confirmForAttachedText;this._confirmPanelOpen=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._pageLeaveRequested=!1,this.updateComplete.then(()=>{if(e){this._attachedEditor?.commands.focus();return}this._editor?.focusInput()});return}this._hasWorkToLoseOnLeave()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this._editor?.hasPendingInlineImageUploads()?this._saveDraftAndOpenDrafts():this._finishDraftSaveAndOpenDrafts()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._discardAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()):this._discardAndClose()}_buildEditorPostDetail(e,t,n,r){e.promoteLeadingH1Title({force:!0});let i=e.getData(),a=new Map((i.attachments??[]).map(e=>[e.clientId,e])),o=new Map(i.attachedTexts.map(e=>[e.clientId,e])),s=[];for(let e of i.attachmentOrder){let t=a.get(e);if(t){s.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt});continue}let n=o.get(e);n?.bodyJson&&s.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:H(n.originalBodyJson??null)})}let c=n===0;return{format:t,title:i.title,body:i.body,url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,status:r,slug:this._getPostSlug(n).trim()||void 0,publishedAt:this._getPostPublishedAtSubmitValue(n,r),visibility:c?this._visibilityLocked?void 0:this._visibility:void 0,rating:i.rating,collectionIds:c&&!this._replyToId?[...this._collectionIds]:[],attachments:s,replyToId:c?this._replyToId??void 0:void 0,quietReply:c&&this._canReplyQuietly()&&this._quietReply||void 0,replyThreadRootId:c?this._replyThreadRootId??void 0:void 0,replyRefreshKind:c?this._replyRefreshKind??void 0:void 0,replyRefreshId:c?this._replyRefreshId??void 0:void 0,language:c&&!this._replyToId?this._effectiveLanguage()??void 0:void 0,translationOfId:c?this._translationOf?.id:void 0}}_buildSubmitDetail(e){let t=this._editor;return t?{...this._buildEditorPostDetail(t,this._format,0,e),editPostId:this._editPostId??this._draftSourceId??void 0,draftSourceId:this._draftSourceId??void 0}:null}_focusBlockedSubmitField(e){if(e===`published`){let e=Math.max(1,this._threadItems.length);for(let t=0;t<e;t++)if(this._getPostPublishedAtValidationMessage(t)!==null)return this._revealPublishedAtField(t),!0}{let e=Math.max(1,this._threadItems.length);for(let t=0;t<e;t++)if(this._getPostSlugValidationMessage(t))return this._revealSlugField(t),!0}if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<this._threadItems.length;t++){let n=this._threadItems[t],r=e[t];if(r){if(r.getUrlValidationMessage())return r.revealUrlValidation(),r.focusUrlInput(`end`),!0;if(r.getLinkTitleValidationMessage())return r.revealLinkTitleValidation(),r.focusLinkTitleInput(`end`),!0;if(n.format===`quote`&&!r._quoteText.trim())return r.focusInput(`end`),!0}}return!1}let t=this._editor;return t?t.getUrlValidationMessage()?(t.revealUrlValidation(),t.focusUrlInput(`end`),!0):t.getLinkTitleValidationMessage()?(t.revealLinkTitleValidation(),t.focusLinkTitleInput(`end`),!0):this._format===`quote`&&!t._quoteText.trim()&&(t.focusInput(`end`),!0):!1}_dispatchSubmit(e){if(this._loading||this._focusBlockedSubmitField(e))return!1;if(this._draftSourceId||(this._cancelDraftSaveTimer(),this._saveDraftToStorage()),this._threadItems.length>0){if(this._threadItems.length>20)return u(this._getThreadLimitMessage(),`error`),!1;let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(t.length!==this._threadItems.length)return!1;let n=[],r=[];for(let i=0;i<this._threadItems.length;i++){let a=this._threadItems[i],o=t[i];if(!o)return!1;n.push(this._buildEditorPostDetail(o,a.format,i,e)),r.push(...(o._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`))}return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n[0],editPostId:this._editPostId??this._draftSourceId??void 0,draftSourceId:this._draftSourceId??void 0,threadPosts:n,pendingAttachments:r}})),!0}let t=this._editor;if(!t)return!1;let n=this._buildSubmitDetail(e);if(!n)return!1;let r=(t._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`);return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n,pendingAttachments:r}})),!0}_saveDraftAndOpenDrafts(){this._finishDraftSaveAndOpenDrafts()}_finishDraftSaveAndOpenDrafts(){if(!this._dispatchSubmit(`draft`))return;this.reset();let e=()=>{clearTimeout(t),this.isConnected&&this._openDraftsPanel()},t=globalThis.setTimeout(()=>{document.removeEventListener(`jant:compose-submit-complete`,e)},1e4);document.addEventListener(`jant:compose-submit-complete`,e,{once:!0})}_finishSubmit(e){if(this._dispatchSubmit(e)){if(this.pageMode){this._loading=!0;return}this._closeDialog(),this.reset()}}_submit(e){this._showPublishPanel=!1,this._finishSubmit(e)}_toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}_selectedCollectionLabel(e){let t=this._collectionIds,n=e.find(e=>e.id===t[0]);if(!n)return``;if(t.length===1)return n.title;if(t.length===2){let r=e.find(e=>e.id===t[1]);return r?`${n.title}, ${r.title}`:n.title}return this.labels.collectionCountLabel.replace(`%name%`,n.title).replace(`%count%`,String(t.length-1))}_prepareCollectionPickerOrder(){this._collectionPickerOrder=m(this.collections??[],this._collectionIds)}_focusCollectionPickerInitialTarget(){this.querySelector(`.compose-collection-search-input, .compose-collection-option, .compose-collection-add-action`)?.focus()}_focusCollectionSearchInput(){let e=this.querySelector(`.compose-collection-search-input`);if(!e)return!1;e.focus();let t=e.value.length;return e.setSelectionRange(t,t),!0}_closeCollectionPicker(e){if(this._showCollection=!1,this._collectionSearch=``,this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,e?.restoreFocus===`trigger`){this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()});return}e?.restoreFocus===`editor`&&this._restorePageEditorFocus()}_suppressNextCollectionOptionClick(e){this._suppressedCollectionOptionId=e,this._suppressCollectionOptionClickUntil=Date.now()+250}_isTouchViewport(){return globalThis.matchMedia?.(`(hover: none) and (pointer: coarse)`)?.matches??!1}_shouldAutofocusCollectionPicker(){return!this._isTouchViewport()}_shouldAutofocusFormatInput(){return!this._isTouchViewport()}_scheduleCollectionPickerAutofocus(){this._shouldAutofocusCollectionPicker()&&globalThis.requestAnimationFrame(()=>{this._showCollection&&this._focusCollectionPickerInitialTarget()})}_scheduleCollectionSearchFocus(){globalThis.requestAnimationFrame(()=>{this._showCollection&&(this._focusCollectionSearchInput()||this._focusCollectionPickerInitialTarget())})}_isPrintableCollectionSearchKey(e){return e.length===1&&e.trim().length>0}_handleCollectionTriggerKeydown=e=>{if(!(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)){if(e.key===`ArrowDown`){e.preventDefault(),this._scheduleCollectionSearchFocus();return}this._showCollection&&this._isPrintableCollectionSearchKey(e.key)&&(e.preventDefault(),this._collectionSearch+=e.key,this._scheduleCollectionSearchFocus())}};_getCollectionOptionElements(){return Array.from(this.querySelectorAll(`.compose-collection-option`))}_handleCollectionSearchKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this._closeCollectionPicker({restoreFocus:`trigger`});return}if(e.key!==`ArrowDown`)return;let[t]=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-add-action`),r=t??n;r&&(e.preventDefault(),r.focus())};_handleCollectionOptionKeydown=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this._getCollectionOptionElements(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`.compose-collection-add-action`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.compose-collection-search-input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._toggleCollection(t);return}e.key===`Enter`&&(e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._closeCollectionPicker({restoreFocus:`trigger`}))};_handleCollectionOptionClick=e=>{if(this._suppressedCollectionOptionId===e&&Date.now()<=this._suppressCollectionOptionClickUntil){this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0;return}this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,this._toggleCollection(e)};_handleCollectionAddActionKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-search-input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};_updateCollectionPopoverSide(){let e=this.querySelector(`.compose-collection-trigger`),t=this.querySelector(`.compose-collection-popover[data-popover]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=Math.max(0,i-12-a.bottom-4),s=Math.max(0,a.top-r-12-4);t.dataset.side=o>=s?`bottom`:`top`}_cancelSlugTimers(){this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null)}_currentSlugOwnerId(){return this._editPostId??this._draftSourceId??void 0}_hasManualSlug(){return this._slug.trim().length>0}_currentSuggestionTitle(){return this._editor?.getData().title.trim()??``}_canSuggestSlug(){return this._currentSuggestionTitle().length>0}_currentSuggestionKey(){return`${this._currentSlugOwnerId()??``}::${this._currentSuggestionTitle()}`}_scheduleSuggestedSlugRefresh(e=!1){if(this._postMetaIndex!==0||this._hasManualSlug())return;if(!this._canSuggestSlug()){this._slugSuggestRequestId+=1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``;return}let t=this._currentSuggestionKey();if(this._slugSuggestionKey!==t&&(this._suggestedSlug=``),!e&&!this._suggestedSlugLoading&&this._suggestedSlug&&this._slugSuggestionKey===t)return;this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null);let n=()=>void this._refreshSuggestedSlug(t);if(e){n();return}this._slugSuggestTimer=setTimeout(n,250)}async _refreshSuggestedSlug(e){if(this._slugSuggestTimer=null,this._hasManualSlug()||!this._canSuggestSlug())return;let t=++this._slugSuggestRequestId;this._suggestedSlugLoading=!0;let n=new URLSearchParams({mode:`suggest`}),r=this._currentSuggestionTitle();r&&n.set(`title`,r);let i=this._currentSlugOwnerId();i&&n.set(`postId`,i);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugSuggestRequestId||this._hasManualSlug()||this._postMetaIndex!==0)return;this._suggestedSlug=i.slug?.trim()??``,this._slugSuggestionKey=e}catch{}finally{t===this._slugSuggestRequestId&&(this._suggestedSlugLoading=!1)}}_scheduleSlugAvailabilityCheck(e=0){if(!this._hasPostManualSlug(e)){this._setPostSlugTaken(e,!1),this._slugCheckLoading=!1;return}if(this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._getPostSlugSyncValidationMessage(e)){this._setPostSlugTaken(e,!1),this._slugCheckLoading=!1;return}this._slugCheckLoading=!0;let t=this._getPostSlug(e).trim();this._slugCheckTimer=setTimeout(()=>{this._checkSlugAvailability(t,e)},250)}async _checkSlugAvailability(e,t=0){this._slugCheckTimer=null;let n=++this._slugCheckRequestId,r=new URLSearchParams({mode:`check`,slug:e}),i=t===0?this._currentSlugOwnerId():this._threadItems[t]?.sourcePostId;i&&r.set(`postId`,i);try{let i=await fetch(`/api/posts/slug?${r.toString()}`);if(!i.ok)return;let a=await i.json();if(n!==this._slugCheckRequestId||this._getPostSlug(t).trim()!==e)return;this._setPostSlugTaken(t,a.available===!1)}catch{}finally{n===this._slugCheckRequestId&&(this._slugCheckLoading=!1)}}_useSuggestedSlug(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugTaken=!1,this._slugCheckLoading=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()}))}_resetCustomSlug(e=0){this._setPostSlug(e,``),this._setPostSlugTaken(e,!1),this._slugCheckLoading=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}connectedCallback(){super.connectedCallback(),this._syncPublishPanelPresentation(),this.addEventListener(`keydown`,this._handleKeydown),this.addEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.addEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.addEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.addEventListener(`jant:compose-content-changed`,this._onContentChanged),this.addEventListener(`jant:title-toggle`,this._handleTitleToggle),this.addEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.addEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.addEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.addEventListener(`pointerdown`,this._handlePointerDown),document.addEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.addEventListener(`beforeunload`,this._onBeforeUnload),window.addEventListener(`resize`,this._handleViewportChange),window.addEventListener(`scroll`,this._handleViewportChange,{passive:!0}),document.addEventListener(`scroll`,this._handleAnyScroll,{capture:!0,passive:!0}),globalThis.visualViewport?.addEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.addEventListener(`scroll`,this._handleViewportChange),this._dialogEl=this.closest(`dialog`),this._dialogEl&&(this._dialogEl.addEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.addEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.addEventListener(`click`,this._handleDialogClick)),this.pageMode&&this.updateComplete.then(()=>this._focusPageEditorOnMount())}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener(`keydown`,this._handleKeydown),this.removeEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.removeEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.removeEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.removeEventListener(`jant:compose-content-changed`,this._onContentChanged),this.removeEventListener(`jant:title-toggle`,this._handleTitleToggle),this.removeEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.removeEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.removeEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.removeEventListener(`pointerdown`,this._handlePointerDown),document.removeEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.removeEventListener(`beforeunload`,this._onBeforeUnload),window.removeEventListener(`resize`,this._handleViewportChange),window.removeEventListener(`scroll`,this._handleViewportChange),document.removeEventListener(`scroll`,this._handleAnyScroll,{capture:!0}),globalThis.visualViewport?.removeEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`scroll`,this._handleViewportChange),this._cancelSlugTimers(),this._destroyAttachedEditor(),this._cancelDraftSaveTimer(),this._dialogEl&&=(this._dialogEl.removeEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.removeEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.removeEventListener(`click`,this._handleDialogClick),null)}_handleFilePickerOpen=()=>{this._filePickerActive=!0,this._ignoreNextEscapeClose=!1};_handleFilePickerClose=e=>{this._filePickerActive=!1,this._ignoreNextEscapeClose=!!e.detail?.cancelled};_handlePointerDown=()=>{this._clearFilePickerEscapeState()};_syncPublishPanelPresentation(){let e=globalThis.matchMedia?.($e)?.matches??!1;e!==this._publishPanelFullscreen&&(this._publishPanelFullscreen=e)}_handleViewportChange=()=>{this._syncPublishPanelPresentation(),this._showPublishPanel&&this.updateComplete.then(()=>this._updatePublishPanelLayout()),this._showCollection&&this.updateComplete.then(()=>this._updateCollectionPopoverSide()),this._postMetaIndex!==null&&this.updateComplete.then(()=>this._updatePostMetaPanelLayout())};_handleAnyScroll=()=>{this._postMetaIndex!==null&&this._updatePostMetaPanelLayout()};_handleDialogCancel=e=>{e.preventDefault();let t=e;t.isComposing||t.keyCode===229||this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay()||this.requestClose()};_pointInOpenPopover(e,t){for(let n of document.querySelectorAll(`:popover-open`)){let r=n.getBoundingClientRect();if(e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom)return!0}return!1}_handleDialogMousedown=e=>{let t=e;this._mousedownOnBackdrop=e.target===this._dialogEl&&!this._pointInOpenPopover(t.clientX,t.clientY),this._mousedownPos=this._mousedownOnBackdrop?{x:t.clientX,y:t.clientY}:null};_handleDialogClick=e=>{if(!this._dialogEl||e.target!==this._dialogEl||!this._mousedownOnBackdrop)return;let t=e;if(this._mousedownPos){let e=t.clientX-this._mousedownPos.x,n=t.clientY-this._mousedownPos.y;if(e*e+n*n>16)return}let n=document.getSelection();if(n&&!n.isCollapsed||this._pointInOpenPopover(t.clientX,t.clientY))return;let r=document.elementFromPoint(t.clientX,t.clientY);r instanceof globalThis.Element&&r.closest(Ze)||this.requestClose()};_focusDialogShell(){let e=this.querySelector(`.compose-dialog-inner`);if(e){e.focus();return}this._dialogEl?.focus()}_restorePageEditorFocus(){this.updateComplete.then(()=>this._editor?.focusInput())}_dismissEscapeOverlay(){return this._confirmPanelOpen?(this.requestClose(),!0):this._addCollectionPanelOpen?(this._closeAddCollectionPanel(),!0):this._editor?.isEmojiPickerOpen()?(this._editor.closeEmojiPicker({restoreFocus:!0}),!0):this._showLanguagePicker?(this._closeLanguagePicker(!0),!0):this._showCollection?(this._closeCollectionPicker({restoreFocus:`editor`}),!0):this._showPublishPanel?(this._closePublishPanel(!0),!0):this._postMetaIndex===null?this._altPanelOpen?(this._closeAltPanel(),this._restorePageEditorFocus(),!0):this._draftMenuOpenId?(this._draftMenuOpenId=null,!0):this._draftsPanelOpen?(this._closeDraftsPanel(),!0):this._attachedPanelOpen?(this._cancelAttachedPanel(),!0):!1:(this._closePostMeta(),!0)}_handleKeydown=t=>{let n=t;if(!(n.isComposing||n.keyCode===229)){if(n.key!==`Escape`&&this._clearFilePickerEscapeState(),n.key===`Escape`){if(n.preventDefault(),n.stopPropagation(),this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay())return;this.requestClose()}else if(n.key===`Enter`&&this._confirmPanelOpen)n.preventDefault(),this._handleConfirmSave();else if((n.metaKey||n.ctrlKey)&&n.key===`Enter`)t.preventDefault(),this._publishFromShortcut();else if((n.metaKey||n.ctrlKey)&&!n.altKey&&!n.shiftKey&&n.key>=`1`&&n.key<=String(e._FORMATS.length)){n.preventDefault();let t=e._FORMATS[Number(n.key)-1];this._threadItems.length>0?this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.dispatchEvent(new CustomEvent(`jant:format-change`,{detail:{format:t},bubbles:!0})):this._switchFormat(t)}}};_publishFromShortcut(){if(this._attachedPanelOpen){this._doneAttachedPanel();return}if(!this._canPublish()){this._focusBlockedSubmitField(`published`);return}this._submit(`published`)}_handleAltPanelOpen=e=>{let t=e.detail;this._altPanelIndex=t.index,this._altPanelOpen=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-alt-input`)?.focus()})};_handleAltPanelClose=()=>{this._altPanelOpen=!1};_getAltAttachment(){return this._editor?._attachments[this._altPanelIndex]??null}_onAltInput(e){let t=e.target.value;this._editor?.updateAlt(this._altPanelIndex,t)}_closeAltPanel(){this._altPanelOpen=!1}_handleFullscreenClose=e=>{let t=Array.from(this.querySelectorAll(`jant-compose-editor`))[e.detail.editorIndex??0]??this._editor;t&&(t.setEditorState(e.detail.json,e.detail.title,e.detail.showTitle,e.detail.selection),t.adoptPendingUploads(),e.detail.intent!==`publish`&&this.updateComplete.then(()=>t.focusSelection(e.detail.selection))),this._replyExpanded=e.detail.replyExpanded,e.detail.intent===`publish`&&this._publishFromShortcut()};_buildFullscreenReplyContext(){return!this._replyToId||!this._replyToData?null:{contentHtml:this._replyToData.contentHtml,dateText:this._replyToData.dateText,expanded:this._replyExpanded}}_handleFullscreenOpen=e=>{e.detail.replyContext=this._buildFullscreenReplyContext();let t=Array.from(this.querySelectorAll(`jant-compose-editor`)).indexOf(e.target);e.detail.editorIndex=t>=0?t:0};_handleAttachedPanelOpen=e=>{let t=e.detail;this._attachedTextIndex=t.index,this._attachedPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-attached-tiptap`);if(!e)return;let t=this._editor?._attachedTexts[this._attachedTextIndex]?.bodyJson??null;this._attachedTextSnapshot=t?JSON.parse(JSON.stringify(t)):null,this._attachedEditor=le({element:e,placeholder:this.labels.attachedTextPlaceholder,content:t,toolbarMode:`compose`,tableControlLabels:this.labels.tableControls}),this._focusAttachedEditorBoundary(t)})};_focusAttachedEditorBoundary(e){if(!this._attachedEditor)return;let t=H(e??this._attachedEditor.getJSON())?`end`:`start`;this._attachedEditor.commands.focus(t)}_isAttachedTextDirty(){return this._attachedEditor?JSON.stringify(H(this._attachedEditor.getJSON()))!==JSON.stringify(H(this._attachedTextSnapshot)):!1}_destroyAttachedEditor(){this._attachedEditor&&=(this._attachedEditor.destroy(),null),this._attachedTextSnapshot=null}_doneAttachedPanel(){if(this._attachedEditor){let e=this._attachedEditor.getJSON(),t=this._attachedEditor.getHTML();this._editor?.updateAttachedText(this._attachedTextIndex,e,t)}this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_cancelAttachedPanel(){if(this._isAttachedTextDirty()){this._confirmForDrafts=!1,this._confirmForAttachedText=!0,this._confirmPanelOpen=!0;return}this._discardAttachedPanel()}_handleAttachedEditorMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this._focusAttachedEditorBoundary())}_handleDraftButtonClick(){this._loading||(this._hasWorkToLoseOnLeave()?(this._confirmForDrafts=!0,this._confirmPanelOpen=!0):this._openDraftsPanel())}async _openDraftsPanel(){this._draftsPanelOpen=!0,this._draftsLoading=!0,this._draftsError=null,this._draftMenuOpenId=null;try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(!e.ok)throw Error(`Failed to load drafts`);let t=await e.json(),n=(Array.isArray(t)?t:t.posts??[]).map(e=>({id:e.id,slug:e.slug,format:e.format,title:(e.format===`quote`?e.sourceName:e.title)??null,bodyText:e.bodyText??null,bodyHtml:e.bodyHtml??null,url:(e.format===`quote`?e.sourceUrl:e.url)??null,quoteText:e.quoteText??null,replyToId:e.replyToId??null,updatedAt:e.updatedAt,mediaAttachments:(e.attachments??[]).filter(e=>e.type===`media`).map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt??null,mimeType:e.mimeType}))})),r=new Set(n.map(e=>e.id));this._drafts=n.filter(e=>!e.replyToId||!r.has(e.replyToId))}catch{this._draftsError=`Could not load drafts. Try again.`,this._drafts=[]}finally{this._draftsLoading=!1}}_closeDraftsPanel(){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.updateComplete.then(()=>this._editor?.focusInput())}async _populateEditorFromPost(e,t){let{media:n,textAttachments:r,attachmentOrder:i}=await ut(t.attachments??[]);e.populate({format:t.format,title:t.format===`quote`?void 0:t.title??void 0,bodyJson:t.body??void 0,url:t.format===`quote`?t.sourceUrl??void 0:t.url??void 0,quoteText:t.quoteText??void 0,quoteAuthor:t.format===`quote`?t.sourceName??void 0:void 0,rating:t.rating??void 0,media:n,textAttachments:r,attachmentOrder:i})}async _loadDraft(e){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._draftSourceId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=n.publishedAt?ct(n.publishedAt):``,this._publishedAtTimeMinutes=n.publishedAt?W(n.publishedAt):null,this._originalPublishedAt=n.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,!n.replyToId&&n.collectionIds?.length&&(this._collectionIds=n.collectionIds),n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),n.threadId===n.id||n.threadId===void 0)try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(e.ok){let t=await e.json(),r=(Array.isArray(t)?t:t.posts??[]).filter(e=>e.id!==n.id&&e.threadId===n.id&&e.status===`draft`).map(e=>({id:e.id,format:e.format,slug:e.slug??null,replyToId:e.replyToId??null,title:e.title??null,body:e.body??null,url:e.url??null,sourceUrl:e.sourceUrl??null,sourceName:e.sourceName??null,quoteText:e.quoteText??null,rating:e.rating??null,attachments:e.attachments??[],visibility:e.visibility??null}));if(r.length>0){let e=[],t=n.id;for(let n=0;n<r.length;n++){let n=r.find(e=>e.replyToId===t);if(!n)break;e.push(n),t=n.id}for(let t of r)e.includes(t)||e.push(t);this._threadItems=[{id:L(),format:n.format},...e.map(e=>({id:L(),format:e.format,slug:e.slug??``,sourcePostId:e.id}))],this._focusedThreadIndex=0,await this.updateComplete;let i=Array.from(this.querySelectorAll(`jant-compose-editor`)),a=i[0];a&&await this._populateEditorFromPost(a,n);for(let t=0;t<e.length;t++){let r=i[t+1];if(!r)continue;let a=e[t];await this._populateEditorFromPost(r,{id:a.id,threadId:n.id,format:a.format,replyToId:a.replyToId,title:a.title,body:a.body,url:a.url,sourceUrl:a.sourceUrl,sourceName:a.sourceName,quoteText:a.quoteText,rating:a.rating,attachments:a.attachments,visibility:a.visibility})}globalThis.requestAnimationFrame(()=>{i[0]?.focusInput(),this._captureInitialSnapshot()});return}}}catch{}await this.updateComplete;let r=this._editor;r&&await this._populateEditorFromPost(r,n),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async _deleteDraft(e){this._draftMenuOpenId=null,this._drafts=this._drafts.filter(t=>t.id!==e);try{if(!(await fetch(`/api/posts/${e}`,{method:`DELETE`})).ok)throw Error();u(this.labels.draftDeleted)}catch{u(`Failed to delete draft. Try again.`,`error`),this._openDraftsPanel()}}_formatDraftDate(e){let t=Date.now()/1e3-e;return t<60?`now`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:t<604800?`${Math.floor(t/86400)}d`:new Date(e*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}_getDraftPreview(e){return e.format===`quote`&&e.quoteText?e.quoteText:e.title?e.title:e.bodyText?e.bodyText:e.url?e.url:null}_getThreadLimitMessage(){return this.labels.threadLimitReached||`Threads can include up to 20 posts.`}static _DRAFT_KEY=`jant:compose-draft`;static _EDIT_DRAFT_KEY_PREFIX=`jant:compose-edit:`;static _DRAFT_MAX_AGE=6048e5;_currentDraftStorageKey(){return this._editPostId?e._EDIT_DRAFT_KEY_PREFIX+this._editPostId:e._DRAFT_KEY}_onContentChanged=()=>{this.requestUpdate(),this._hasManualSlug()||this._scheduleSuggestedSlugRefresh(),this._draftSourceId||this._scheduleDraftSave()};_handleTitleToggle=t=>{this._editPostId||this._draftSourceId||this._replyToId||t.target?.threadItem||e._setNoteTitleDefault(t.detail.showTitle)};_cancelDraftSaveTimer(){this._draftSaveTimer!==null&&(clearTimeout(this._draftSaveTimer),this._draftSaveTimer=null)}_scheduleDraftSave(){this._cancelDraftSaveTimer(),this._draftSaveTimer=setTimeout(()=>this._saveDraftToStorage(),1e3)}_onBeforeUnload=e=>{if(this._suppressBeforeUnload)return;this._draftSaveTimer!==null&&(this._cancelDraftSaveTimer(),this._saveDraftToStorage());let t=this.closest(`dialog`);this._hasUnsavedChanges()&&(this.pageMode||t?.open===!0)&&(e.preventDefault(),e.returnValue=``)};_saveDraftToStorage(){if(this._threadItems.length>0){let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(!t.some(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.rating>0||t.attachedTexts.length>0||t.attachments.length>0})){this._releaseStoredDraft();return}let n=this._threadItems.map((n,r)=>{let i=t[r];if(!i)return null;let a=i.getData();return{format:n.format,publishedAtInput:n.publishedAtInput,publishedAtTimeMinutes:n.publishedAtTimeMinutes,slug:n.slug,title:a.title,bodyJson:i.getNormalizedBodyJson(),url:a.url,quoteText:a.quoteText,quoteAuthor:a.quoteAuthor,rating:a.rating,showTitle:n.format===`note`&&i._showTitle,showRating:a.rating>0&&i._showRating,attachedTexts:a.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...a.attachmentOrder],mediaAttachments:e._mediaSnapshotFromAttachments(a.attachments)}}).filter(e=>e!==null),r={format:this._threadItems[0]?.format??this._format,title:``,bodyJson:null,url:``,quoteText:``,quoteAuthor:``,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:0,showTitle:!1,showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,language:this._language,translationOfId:this._translationOf?.id??null,attachedTexts:[],attachmentOrder:[],threadItems:n,savedAt:Date.now()};this._writeStoredDraft(r);return}let t=this._editor;if(!t)return;if(!this._hasUnsavedChanges()){this._releaseStoredDraft();return}let n=t.getData();if(!(n.body||n.title.trim()||n.url.trim()||n.quoteText.trim()||n.quoteAuthor.trim()||n.rating>0||n.attachments.length>0||n.attachedTexts.length>0)){this._releaseStoredDraft();return}let r={format:this._format,title:n.title,bodyJson:t.getNormalizedBodyJson(),url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:n.rating,showTitle:this._format===`note`&&t._showTitle,showRating:n.rating>0&&t._showRating,collectionIds:[...this._collectionIds],replyToId:this._replyToId,language:this._language,translationOfId:this._translationOf?.id??null,attachedTexts:n.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary,mediaId:e.mediaId,originalBodyJson:e.mediaId?e.originalBodyJson??null:void 0})),attachmentOrder:[...n.attachmentOrder],mediaAttachments:e._mediaSnapshotFromAttachments(n.attachments),savedAt:Date.now()};this._writeStoredDraft(r)}_writeStoredDraft(e){try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(e)),this._hasOwnedContent=!0}catch(e){console.warn(`[jant] compose draft could not be stored`,e),this._reportedStorageFailure||(this._reportedStorageFailure=!0,u(this.labels.draftStoreFailed,`error`))}}_releaseStoredDraft(){this._hasOwnedContent&&(this._hasOwnedContent=!1,globalThis.localStorage.removeItem(this._currentDraftStorageKey()))}_clearDraftFromStorage(){this._cancelDraftSaveTimer(),this._hasOwnedContent=!1,globalThis.localStorage.removeItem(this._currentDraftStorageKey())}clearLocalDraftFromStorage(){this._clearDraftFromStorage()}clearEditDraftFromStorage(t){globalThis.localStorage.removeItem(e._EDIT_DRAFT_KEY_PREFIX+t)}static _mediaSnapshotFromAttachments(e){return e.flatMap(e=>e.status===`done`&&e.mediaId&&e.remoteUrl?[{clientId:e.clientId,mediaId:e.mediaId,url:e.remoteUrl,mimeType:e.file.type,name:e.file.name||void 0,alt:e.alt||void 0,summary:e.summary,chars:e.chars,persisted:e.persisted||void 0}]:[])}static _restoredMediaToPopulate(e){return e.map(e=>({id:e.mediaId,clientId:e.clientId,previewUrl:e.url,mimeType:e.mimeType,originalName:e.name,alt:e.alt,summary:e.summary??void 0,chars:e.chars??void 0,persisted:e.persisted??!1}))}static _mergeRestoredMedia(e,t){let n=new Map;for(let t of e??[])n.set(t.clientId,t);for(let e of t??[])n.set(e.clientId,e);return n}async restoreLocalDraft(t){let n=e._DRAFT_KEY;if(this._editPostId||this._draftSourceId)return this._reportRestoreOutcome(`composer-busy`,n);if(this._hasContent())return this._reportRestoreOutcome(`composer-has-content`,n);let r;try{r=globalThis.localStorage.getItem(n)}catch{return`none`}if(!r)return`none`;let i;try{i=JSON.parse(r)}catch{return this._reportRestoreOutcome(`unreadable`,n,r)}if(Date.now()-i.savedAt>e._DRAFT_MAX_AGE)return this._reportRestoreOutcome(`expired`,n,r,i);if(t?.expectedReplyToId!==void 0&&i.replyToId!==t.expectedReplyToId)return this._reportRestoreOutcome(`other-reply`,n,r,i);if(this._collectionIds=i.replyToId?[]:[...i.collectionIds??[]],this._slug=i.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=i.publishedAtInput??``,this._publishedAtTimeMinutes=i.publishedAtTimeMinutes??null,this._visibility=i.visibility??`public`,this._language=i.language??null,i.translationOfId&&await this._loadTranslationSource(i.translationOfId),i.replyToId&&(this._replyToId=i.replyToId,this._visibilityLocked=!0,await this._fetchReplyContext(i.replyToId)),i.threadItems&&i.threadItems.length>=2){this._format=i.threadItems[0].format,this._threadItems=i.threadItems.map(e=>({id:L(),format:e.format,publishedAtInput:e.publishedAtInput,publishedAtTimeMinutes:e.publishedAtTimeMinutes,slug:e.slug})),this._focusedThreadIndex=0,await this.updateComplete;let n=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let r=0;r<i.threadItems.length;r++){let a=i.threadItems[r],o=n[r];if(!o)continue;let s=a.attachedTexts?.flatMap(e=>{let t=H(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]}),c=t?.extraMedia?.filter(e=>a.attachmentOrder?.includes(e.clientId)),l=[...e._mergeRestoredMedia(a.mediaAttachments,c).values()];o.populate({format:a.format,title:a.title||void 0,bodyJson:a.bodyJson?JSON.stringify(a.bodyJson):void 0,url:a.url||void 0,quoteText:a.quoteText||void 0,quoteAuthor:a.quoteAuthor||void 0,rating:a.rating||void 0,showTitle:a.showTitle,showRating:a.showRating,media:l.length?e._restoredMediaToPopulate(l):void 0,textAttachments:s?.length?s:void 0,attachmentOrder:a.attachmentOrder})}return this._draftRestored=!0,this._hasOwnedContent=!0,t?.notify!==!1&&u(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()}),`restored`}this._format=i.format,await this.updateComplete;let a=i.attachedTexts?.flatMap(e=>{let t=H(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]}),o=[...e._mergeRestoredMedia(i.mediaAttachments,t?.extraMedia).values()];return this._editor?.populate({format:i.format,title:i.title||void 0,bodyJson:i.bodyJson?JSON.stringify(i.bodyJson):void 0,url:i.url||void 0,quoteText:i.quoteText||void 0,quoteAuthor:i.quoteAuthor||void 0,rating:i.rating||void 0,showTitle:i.showTitle,showRating:i.showRating,media:o.length?e._restoredMediaToPopulate(o):void 0,textAttachments:a?.length?a:void 0,attachmentOrder:i.attachmentOrder}),this._draftRestored=!0,this._hasOwnedContent=!0,t?.notify!==!1&&u(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()}),`restored`}_reportRestoreOutcome(e,t,n,r){if(e===`restored`||e===`none`)return e;let i=n;if(i===void 0)try{i=globalThis.localStorage.getItem(t)}catch{i=null}return i?(console.warn(`[jant] compose draft not restored: ${e}`,{key:t,bytes:i.length,savedAt:r?.savedAt?new Date(r.savedAt).toISOString():null,thread:r?.threadItems?.length??null}),e):`none`}_restoreEditDraftIfAvailable(t,n){let r=e._EDIT_DRAFT_KEY_PREFIX+t,i;try{i=globalThis.localStorage.getItem(r)}catch{return!1}if(!i)return!1;let a;try{a=JSON.parse(i)}catch{return this._reportRestoreOutcome(`unreadable`,r,i),!1}if(Date.now()-a.savedAt>e._DRAFT_MAX_AGE)return this._reportRestoreOutcome(`expired`,r,i,a),!1;this._format=a.format,this._collectionIds=this._replyToId?[]:[...a.collectionIds??[]],this._slug=a.slug??``,this._publishedAtInput=a.publishedAtInput??``,this._publishedAtTimeMinutes=a.publishedAtTimeMinutes??null,this._visibility=a.visibility??`public`,this._language=a.language??null;let o=a.attachedTexts?.flatMap(e=>{let t=H(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary,mediaId:e.mediaId,originalBodyJson:e.mediaId?JSON.stringify(e.originalBodyJson??null):void 0}]:[]}),s=a.mediaAttachments??[];return this._editor?.populate({format:a.format,title:a.title||void 0,bodyJson:a.bodyJson?JSON.stringify(a.bodyJson):void 0,url:a.url||void 0,quoteText:a.quoteText||void 0,quoteAuthor:a.quoteAuthor||void 0,rating:a.rating||void 0,showTitle:a.showTitle,showRating:a.showRating,media:s.length?e._restoredMediaToPopulate(s):void 0,textAttachments:o?.length?o:void 0,attachmentOrder:a.attachmentOrder}),this._draftRestored=!0,this._hasOwnedContent=!0,n!==!1&&u(this.labels.draftRestored),!0}async _applyTranslationRequestFromUrl(){let e=new URLSearchParams(globalThis.location?.search??``),t=e.get(`translationOf`);if(!t)return;let n=e.get(`lang`);n&&this.languages.some(e=>e.tag===n)&&(this._language=n),this._translationOf||await this._loadTranslationSource(t,{seed:!0})}async _focusPageEditorOnMount(){this._pageFocusApplied||(this.autoRestoreDraft&&await this.restoreLocalDraft(),await this._applyTranslationRequestFromUrl(),await this.updateComplete,globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._pageFocusApplied=!0}))}_renderDraftsPanel(){return this._draftsPanelOpen?a`
121
121
  <div class="compose-drafts-panel">
122
122
  <div class="compose-alt-header">
123
123
  <button
@@ -141,7 +141,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
141
141
  </button>
142
142
  <span class="compose-alt-title">${this.labels.drafts}</span>
143
143
  </div>
144
- ${this._draftsLoading?i`<div class="compose-drafts-loading">
144
+ ${this._draftsLoading?a`<div class="compose-drafts-loading">
145
145
  <svg
146
146
  class="animate-spin size-5"
147
147
  xmlns="http://www.w3.org/2000/svg"
@@ -154,43 +154,43 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
154
154
  >
155
155
  <path d="M21 12a9 9 0 1 1-6.219-8.56" />
156
156
  </svg>
157
- </div>`:this._draftsError?i`<div class="compose-drafts-empty">
157
+ </div>`:this._draftsError?a`<div class="compose-drafts-empty">
158
158
  ${this._draftsError}
159
- </div>`:this._drafts.length===0?i`<div class="compose-drafts-empty">
159
+ </div>`:this._drafts.length===0?a`<div class="compose-drafts-empty">
160
160
  ${this.labels.draftsEmpty}
161
- </div>`:i`<div class="compose-drafts-list">
162
- ${this._drafts.map((e,t)=>i`
163
- ${t>0?i`<div class="compose-drafts-divider"></div>`:o}
161
+ </div>`:a`<div class="compose-drafts-list">
162
+ ${this._drafts.map((e,t)=>a`
163
+ ${t>0?a`<div class="compose-drafts-divider"></div>`:s}
164
164
  ${this._renderDraftItem(e)}
165
165
  `)}
166
166
  </div>`}
167
167
  </div>
168
- `:o}_renderDraftItem(e){let t=this._getDraftPreview(e),n=this.labels[e.format],a=`draft-actions-${e.id}`,s=this._draftMenuOpenId===e.id;return i`
168
+ `:s}_renderDraftItem(e){let n=this._getDraftPreview(e),r=this.labels[e.format],i=`draft-actions-${e.id}`,o=this._draftMenuOpenId===e.id;return a`
169
169
  <div class="compose-draft-item" @click=${()=>this.openDraft(e.id)}>
170
170
  <div class="compose-draft-content">
171
- ${t?i`<div class="compose-draft-preview">${t}</div>`:i`<div
171
+ ${n?a`<div class="compose-draft-preview">${n}</div>`:a`<div
172
172
  class="compose-draft-preview compose-draft-preview-empty"
173
173
  >
174
174
  Empty draft
175
175
  </div>`}
176
176
  <div class="compose-draft-meta">
177
- <span class="compose-draft-format">${n}</span>
177
+ <span class="compose-draft-format">${r}</span>
178
178
  <span aria-hidden="true">·</span>
179
179
  ${this._formatDraftDate(e.updatedAt)}
180
180
  </div>
181
181
  </div>
182
182
  <div class="relative">
183
- ${s?i`<div
183
+ ${o?a`<div
184
184
  class="compose-dropdown-backdrop"
185
185
  @click=${e=>{e.stopPropagation(),this._draftMenuOpenId=null}}
186
- ></div>`:o}
186
+ ></div>`:s}
187
187
  <button
188
188
  type="button"
189
189
  class="compose-draft-more"
190
190
  aria-label=${this.labels.draftActions}
191
191
  aria-haspopup="menu"
192
- aria-expanded=${s?`true`:`false`}
193
- aria-controls=${a}
192
+ aria-expanded=${o?`true`:`false`}
193
+ aria-controls=${i}
194
194
  @click=${t=>{t.stopPropagation(),this._draftMenuOpenId=this._draftMenuOpenId===e.id?null:e.id}}
195
195
  >
196
196
  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
@@ -199,15 +199,15 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
199
199
  <circle cx="12" cy="8" r="1.2" />
200
200
  </svg>
201
201
  </button>
202
- ${s?i`
202
+ ${o?a`
203
203
  <div
204
- id=${a}
204
+ id=${i}
205
205
  class="compose-dropdown compose-dropdown-right"
206
206
  role="menu"
207
207
  >
208
208
  <a
209
209
  class="compose-dropdown-item"
210
- href=${r(`/preview/${e.slug}`)}
210
+ href=${t(`/preview/${e.slug}`)}
211
211
  target="_blank"
212
212
  rel="noopener noreferrer"
213
213
  role="menuitem"
@@ -228,12 +228,12 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
228
228
  ${this.labels.deleteDraft}
229
229
  </button>
230
230
  </div>
231
- `:o}
231
+ `:s}
232
232
  </div>
233
233
  </div>
234
- `}_renderTranslationContext(){let e=this._translationOf;if(!e)return o;let t=this.languages.find(e=>e.tag===this._language)?.label??``,n=t?this.labels.translationContextInLanguage.replace(`{language}`,t):this.labels.translationContext,r=this._translationCollapsed;return i`
234
+ `}_renderTranslationContext(){let e=this._translationOf;if(!e)return s;let t=this.languages.find(e=>e.tag===this._language)?.label??``,n=t?this.labels.translationContextInLanguage.replace(`{language}`,t):this.labels.translationContext,r=this._translationCollapsed;return a`
235
235
  <div class="compose-translation-context">
236
- ${r?o:e.previewHtml?i`<div
236
+ ${r?s:e.previewHtml?a`<div
237
237
  class="compose-translation-original"
238
238
  tabindex="0"
239
239
  role="region"
@@ -242,8 +242,8 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
242
242
  <div class="compose-translation-preview">
243
243
  ${d(e.previewHtml)}
244
244
  </div>
245
- </div>`:i`<p class="compose-translation-fallback">
246
- ${e.href?i`<a
245
+ </div>`:a`<p class="compose-translation-fallback">
246
+ ${e.href?a`<a
247
247
  href=${e.href}
248
248
  target="_blank"
249
249
  rel="noopener noreferrer"
@@ -267,7 +267,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
267
267
  </button>
268
268
  </div>
269
269
  </div>
270
- `}_adoptTranslationPreview(){let e=this.querySelector(`.compose-translation-preview:not([data-preview-adopted])`);if(e){e.dataset.previewAdopted=``;for(let t of e.querySelectorAll(`a[href]`))t.setAttribute(`target`,`_blank`),t.setAttribute(`rel`,`noopener noreferrer`);for(let t of e.querySelectorAll(`[data-post-id]`))delete t.dataset.postId,delete t.dataset.post,delete t.dataset.threadRootId,delete t.dataset.postMenuTarget,t.classList.remove(`post-menu-target`);for(let t of e.querySelectorAll(`[data-post-menu-trigger], [data-reply-trigger], [data-timeline-item]`))t.remove()}}_iconArrowDown(){return i`<svg
270
+ `}_adoptTranslationPreview(){let e=this.querySelector(`.compose-translation-preview:not([data-preview-adopted])`);if(e){e.dataset.previewAdopted=``;for(let t of e.querySelectorAll(`a[href]`))t.setAttribute(`target`,`_blank`),t.setAttribute(`rel`,`noopener noreferrer`);for(let t of e.querySelectorAll(`[data-post-id]`))delete t.dataset.postId,delete t.dataset.post,delete t.dataset.threadRootId,delete t.dataset.postMenuTarget,t.classList.remove(`post-menu-target`);for(let t of e.querySelectorAll(`[data-post-menu-trigger], [data-reply-trigger], [data-timeline-item]`))t.remove()}}_iconArrowDown(){return a`<svg
271
271
  class="compose-translation-seam-icon"
272
272
  xmlns="http://www.w3.org/2000/svg"
273
273
  viewBox="0 0 24 24"
@@ -280,20 +280,20 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
280
280
  >
281
281
  <path d="M12 5v14" />
282
282
  <path d="m19 12-7 7-7-7" />
283
- </svg>`}_renderReplyContext(){if(!this._replyToId||!this._replyToData)return o;let{contentHtml:e,dateText:t,media:n}=this._replyToData,r=this._replyExpanded;return i`
283
+ </svg>`}_renderReplyContext(){if(!this._replyToId||!this._replyToData)return s;let{contentHtml:e,dateText:t,media:n}=this._replyToData,r=this._replyExpanded;return a`
284
284
  <div class="compose-reply-row">
285
285
  <div class="compose-thread-dot"></div>
286
286
  <div
287
- class=${b({"compose-reply-context":!0,expanded:r})}
287
+ class=${S({"compose-reply-context":!0,expanded:r})}
288
288
  >
289
289
  <div class="compose-reply-context-body">
290
290
  ${d(e)}
291
- ${n?.length?i`<div
291
+ ${n?.length?a`<div
292
292
  class="compose-reply-context-media"
293
293
  data-post-media
294
294
  data-lightbox-group=${JSON.stringify(n.map(e=>({url:e.url,alt:e.alt??``,width:e.width,height:e.height,mimeType:e.mimeType})))}
295
295
  >
296
- ${n.map((e,t)=>i`
296
+ ${n.map((e,t)=>a`
297
297
  <a
298
298
  href=${e.url}
299
299
  data-lightbox-index=${t}
@@ -307,13 +307,13 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
307
307
  />
308
308
  </a>
309
309
  `)}
310
- </div>`:o}
310
+ </div>`:s}
311
311
  </div>
312
- ${r?o:i`<div class="compose-reply-fade"></div>`}
312
+ ${r?s:a`<div class="compose-reply-fade"></div>`}
313
313
  </div>
314
314
  </div>
315
315
  <div class="compose-reply-meta">
316
- ${t?i`<span>${t}</span><span>·</span>`:o}
316
+ ${t?a`<span>${t}</span><span>·</span>`:s}
317
317
  <button
318
318
  type="button"
319
319
  class="compose-reply-toggle"
@@ -322,7 +322,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
322
322
  ${r?this.labels.showLess:this.labels.showMore}
323
323
  </button>
324
324
  </div>
325
- `}static _FORMATS=[`note`,`link`,`quote`];_shouldConvertOnFormatSwitch(){return!!(this._editPostId||this._draftSourceId)}_convertForFormatSwitch(e,t,n){e&&t!==n&&this._shouldConvertOnFormatSwitch()&&e.applyConvertedFields(Pe(t,n,e.getConvertibleFields()))}_switchFormat(e){this._format!==e&&(this._convertForFormatSwitch(this._editor,this._format,e),this._cancelDraftSaveTimer(),this._format=e,this._showPublishPanel=!1,this._shouldAutofocusFormatInput()&&globalThis.requestAnimationFrame(()=>this._editor?.focusInput()))}_renderCloseComposeControl(){return this.pageMode||this._threadItems.length>0?o:i`
325
+ `}static _FORMATS=[`note`,`link`,`quote`];_shouldConvertOnFormatSwitch(){return!!(this._editPostId||this._draftSourceId)}_convertForFormatSwitch(e,t,n){e&&t!==n&&this._shouldConvertOnFormatSwitch()&&e.applyConvertedFields(Pe(t,n,e.getConvertibleFields()))}_switchFormat(e){this._format!==e&&(this._convertForFormatSwitch(this._editor,this._format,e),this._cancelDraftSaveTimer(),this._format=e,this._showPublishPanel=!1,this._shouldAutofocusFormatInput()&&globalThis.requestAnimationFrame(()=>this._editor?.focusInput()))}_renderCloseComposeControl(){return this.pageMode||this._threadItems.length>0?s:a`
326
326
  <button
327
327
  type="button"
328
328
  class="compose-close-btn"
@@ -343,38 +343,38 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
343
343
  <path d="M4.5 4.5 11.5 11.5M11.5 4.5 4.5 11.5" />
344
344
  </svg>
345
345
  </button>
346
- `}_renderCollectionSelector(){let e=this.collections??[],t=m(e,this._collectionPickerOrder),n=this._collectionSearch.trim().length>0,r=g(t,this._collectionSearch),a=this._collectionIds.length,s=a>0?this._selectedCollectionLabel(e):this.labels.collection,c=n?this.labels.noCollections:this.labels.emptyCollections;return i`
346
+ `}_renderCollectionSelector(){let e=this.collections??[],t=h(e,this._collectionPickerOrder),n=this._collectionSearch.trim().length>0,r=_(t,this._collectionSearch),i=this._collectionIds.length,o=i>0?this._selectedCollectionLabel(e):this.labels.collection,c=n?this.labels.noCollections:this.labels.emptyCollections;return a`
347
347
  <div class="flex-1 min-w-0">
348
- ${this._showCollection?i`<div
348
+ ${this._showCollection?a`<div
349
349
  class="compose-dropdown-backdrop"
350
350
  @click=${()=>this._closeCollectionPicker()}
351
- ></div>`:o}
351
+ ></div>`:s}
352
352
  <div
353
353
  class="select compose-collection-select"
354
354
  data-select-initialized
355
- data-open=${this._showCollection?`true`:o}
355
+ data-open=${this._showCollection?`true`:s}
356
356
  >
357
357
  <button
358
358
  type="button"
359
359
  class="compose-collection-trigger"
360
360
  aria-haspopup="listbox"
361
361
  aria-expanded=${this._showCollection?`true`:`false`}
362
- data-open=${this._showCollection?`true`:o}
363
- data-selected=${a>0?`true`:o}
362
+ data-open=${this._showCollection?`true`:s}
363
+ data-selected=${i>0?`true`:s}
364
364
  @keydown=${this._handleCollectionTriggerKeydown}
365
365
  @click=${()=>{let e=!this._showCollection;this._showPublishPanel=!1,this._showLanguagePicker=!1,e&&this._prepareCollectionPickerOrder(),this._showCollection=e,e||this._closeCollectionPicker()}}
366
366
  >
367
367
  <!-- No chevron: the glyph already says "picker", and a second one
368
368
  pointing down only made the control wider. -->
369
369
  ${B(z.collection,`compose-collection-trigger-svg`)}
370
- <span class="compose-collection-label">${s}</span>
370
+ <span class="compose-collection-label">${o}</span>
371
371
  </button>
372
372
  <div
373
373
  class="compose-collection-popover"
374
374
  data-popover
375
375
  aria-hidden=${this._showCollection?`false`:`true`}
376
376
  >
377
- ${e.length>0?i`<div class="compose-collection-popover-header">
377
+ ${e.length>0?a`<div class="compose-collection-popover-header">
378
378
  <label class="compose-collection-search-shell">
379
379
  ${B(z.search,`compose-collection-search-icon`)}
380
380
  <input
@@ -390,16 +390,16 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
390
390
  @input=${e=>{this._collectionSearch=e.target.value}}
391
391
  />
392
392
  </label>
393
- </div>`:o}
393
+ </div>`:s}
394
394
  <div
395
395
  role="listbox"
396
396
  class="compose-collection-options"
397
397
  aria-multiselectable="true"
398
398
  >
399
- ${r.length>0?r.map(e=>{let t=this._collectionIds.includes(e.id);return i`
399
+ ${r.length>0?r.map(e=>{let t=this._collectionIds.includes(e.id);return a`
400
400
  <button
401
401
  type="button"
402
- class=${b({"compose-collection-option":!0,"compose-collection-option-selected":t})}
402
+ class=${S({"compose-collection-option":!0,"compose-collection-option-selected":t})}
403
403
  role="option"
404
404
  data-value=${e.id}
405
405
  aria-selected=${t?`true`:`false`}
@@ -410,9 +410,9 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
410
410
  >${e.title}</span
411
411
  >
412
412
  <span
413
- class=${b({"compose-collection-option-marker":!0,"compose-collection-option-marker-selected":t,"compose-collection-option-marker-add":!t})}
413
+ class=${S({"compose-collection-option-marker":!0,"compose-collection-option-marker-selected":t,"compose-collection-option-marker-add":!t})}
414
414
  >
415
- ${t?i`<svg
415
+ ${t?a`<svg
416
416
  xmlns="http://www.w3.org/2000/svg"
417
417
  class="compose-collection-option-check-circle"
418
418
  viewBox="0 0 24 24"
@@ -435,7 +435,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
435
435
  </svg>`:B(z.plusCircle,`compose-collection-option-plus-circle`)}
436
436
  </span>
437
437
  </button>
438
- `}):i`<div class="compose-collection-empty">
438
+ `}):a`<div class="compose-collection-empty">
439
439
  ${c}
440
440
  </div>`}
441
441
  </div>
@@ -455,7 +455,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
455
455
  </div>
456
456
  </div>
457
457
  </div>
458
- `}_closeAddCollectionPanel(){this._addCollectionPanelOpen=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()})}async _handleAddCollectionSubmit(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||`Couldn't create collection. Try again.`);if(!t?.id||!t.title)throw Error(`Couldn't create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug??``};(!await this.refreshCollections()||!this.collections.some(e=>e.id===t.id))&&(this.collections=[...this.collections,r]),this._collectionIds=[...this._collectionIds,t.id],this._closeAddCollectionPanel(),l(this.labels.collectionFormLabels.createdLabel)}catch(e){l(e instanceof Error?e.message:`Couldn't create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}_submitAddCollectionForm(){let e=this.querySelector(`[data-collection-quick-dialog] form`);e&&e.requestSubmit()}_renderAddCollectionPanel(){return this._addCollectionPanelOpen?i`
458
+ `}_closeAddCollectionPanel(){this._addCollectionPanelOpen=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()})}async _handleAddCollectionSubmit(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||`Couldn't create collection. Try again.`);if(!t?.id||!t.title)throw Error(`Couldn't create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug??``};(!await this.refreshCollections()||!this.collections.some(e=>e.id===t.id))&&(this.collections=[...this.collections,r]),this._collectionIds=[...this._collectionIds,t.id],this._closeAddCollectionPanel(),u(this.labels.collectionFormLabels.createdLabel)}catch(e){u(e instanceof Error?e.message:`Couldn't create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}_submitAddCollectionForm(){let e=this.querySelector(`[data-collection-quick-dialog] form`);e&&e.requestSubmit()}_renderAddCollectionPanel(){return this._addCollectionPanelOpen?a`
459
459
  <div
460
460
  class="collection-quick-dialog-backdrop"
461
461
  @click=${()=>this._closeAddCollectionPanel()}
@@ -489,7 +489,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
489
489
  <jant-collection-form
490
490
  .labels=${this.labels.collectionFormLabels}
491
491
  .initial=${{title:``,slug:``}}
492
- action=${r(`/api/collections`)}
492
+ action=${t(`/api/collections`)}
493
493
  @jant:collection-submit=${e=>this._handleAddCollectionSubmit(e)}
494
494
  ></jant-collection-form>
495
495
  </div>
@@ -503,7 +503,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
503
503
  </button>
504
504
  </div>
505
505
  </div>
506
- `:o}_renderAttachedPanel(){return this._attachedPanelOpen?i`
506
+ `:s}_renderAttachedPanel(){return this._attachedPanelOpen?a`
507
507
  <div class="compose-attached-panel">
508
508
  <div class="compose-alt-header">
509
509
  <button
@@ -529,7 +529,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
529
529
  ></div>
530
530
  </div>
531
531
  </div>
532
- `:o}_renderAltPanel(){if(!this._altPanelOpen)return o;let e=this._getAltAttachment();if(!e)return o;let t=F(e.file.type);return i`
532
+ `:s}_renderAltPanel(){if(!this._altPanelOpen)return s;let e=this._getAltAttachment();if(!e)return s;let t=F(e.file.type);return a`
533
533
  <div class="compose-alt-panel">
534
534
  <div class="compose-alt-header">
535
535
  <button
@@ -554,16 +554,16 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
554
554
  <span class="compose-alt-title">${this.labels.addAltTitle}</span>
555
555
  </div>
556
556
  <div class="compose-alt-preview">
557
- ${t===`image`?i`<img
557
+ ${t===`image`?a`<img
558
558
  src=${e.previewUrl}
559
559
  alt=""
560
560
  class="compose-alt-preview-img"
561
- />`:t===`video`?i`<video
561
+ />`:t===`video`?a`<video
562
562
  src=${e.previewUrl}
563
563
  class="compose-alt-preview-img"
564
564
  preload="metadata"
565
565
  muted
566
- ></video>`:i`<span class="text-sm text-muted-foreground"
566
+ ></video>`:a`<span class="text-sm text-muted-foreground"
567
567
  >${e.file.name}</span
568
568
  >`}
569
569
  </div>
@@ -589,7 +589,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
589
589
  </button>
590
590
  </div>
591
591
  </div>
592
- `}_renderConfirmPanel(){if(!this._confirmPanelOpen)return o;let e=!!this._editPostId,t=this._confirmForAttachedText?this.labels.confirmAttachedTitle:e?this.labels.confirmEditTitle:this.labels.confirmCloseTitle,n=this._confirmForAttachedText?this.labels.confirmAttachedSubtitle:e?this.labels.confirmEditSubtitle:this.labels.confirmCloseSubtitle,r=this._confirmForAttachedText?this.labels.confirmAttachedSave:e?this.labels.confirmEditPublish:this.labels.confirmCloseSave,a=this._confirmForAttachedText?this.labels.confirmAttachedDiscard:e?this.labels.confirmEditDiscard:this.labels.confirmCloseDiscard;return i`
592
+ `}_renderConfirmPanel(){if(!this._confirmPanelOpen)return s;let e=!!this._editPostId,t=this._confirmForAttachedText?this.labels.confirmAttachedTitle:e?this.labels.confirmEditTitle:this.labels.confirmCloseTitle,n=this._confirmForAttachedText?this.labels.confirmAttachedSubtitle:e?this.labels.confirmEditSubtitle:this.labels.confirmCloseSubtitle,r=this._confirmForAttachedText?this.labels.confirmAttachedSave:e?this.labels.confirmEditPublish:this.labels.confirmCloseSave,i=this._confirmForAttachedText?this.labels.confirmAttachedDiscard:e?this.labels.confirmEditDiscard:this.labels.confirmCloseDiscard;return a`
593
593
  <div class="compose-confirm-panel">
594
594
  <div class="compose-confirm-sheet">
595
595
  <div class="compose-confirm-header">
@@ -608,7 +608,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
608
608
  class="compose-confirm-action compose-confirm-discard"
609
609
  @click=${()=>this._handleConfirmDiscard()}
610
610
  >
611
- ${a}
611
+ ${i}
612
612
  </button>
613
613
  <button
614
614
  type="button"
@@ -619,10 +619,10 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
619
619
  </button>
620
620
  </div>
621
621
  </div>
622
- `}_getSubmitLabel(){return this._editPostId?this.labels.update:this._replyToId?this._quietReply?this.labels.quietReplyLabel:this.labels.reply:this._visibility===`latest_hidden`?this.labels.postHiddenFromLatest:this._visibility===`private`?this.labels.postPrivately:this.labels.post}_getSlugSyncValidationMessage(){let e=x(this._slug);return e===`invalid`?this.labels.publishSlugInvalid:e===`reserved`?this.labels.publishSlugReserved:null}_getSlugValidationMessage(){return this._getSlugSyncValidationMessage()||(this._hasManualSlug()&&this._slugTaken?this.labels.publishSlugTaken:null)}_getSlugPreviewUrl(){if(!this._hasManualSlug()||this._getSlugValidationMessage())return null;let e=r(`/${this._slug.trim()}`),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}_getSlugPreviewParts(){let e=this._getSlugPreviewUrl();if(!e)return null;let t=new URL(e);return{full:e,origin:t.origin,path:`${t.pathname}${t.search}${t.hash}`}}_getSlugStatusMessage(){return this._hasManualSlug()?this._getSlugValidationMessage()?this._getSlugValidationMessage():null:this._suggestedSlugLoading?this.labels.publishSlugGenerating:null}_getCurrentTimestamp(){return Math.floor(Date.now()/1e3)}_getPublishedAtMaxInput(){return ct(this._getCurrentTimestamp())}_getPublishedAtTimeMinutes(){return this._publishedAtTimeMinutes??W(this._getCurrentTimestamp())}_hasPublishedAtValue(){return this._publishedAtInput.trim().length>0}_getPublishedAtValidationMessage(){return this._hasPublishedAtValue()?U(this._publishedAtInput)===null?this.labels.publishDateInvalid:this._publishedAtInput>this._getPublishedAtMaxInput()?this.labels.publishDateFutureError:null:null}_getPublishedAtSummary(){if(this._editPostId||this._draftSourceId){if(this._publishedAtInput===this._initialPublishedAtInput)return null;if(!this._hasPublishedAtValue())return{input:``,text:this.labels.publishDateSummaryNow}}if(this._getPublishedAtValidationMessage()!==null)return null;let e=U(this._publishedAtInput);return e===null?null:{input:this._publishedAtInput,text:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(e.year,e.monthIndex,e.day))}}_getPostPublishedAtSubmitValue(e,t){if(e===0)return this._getPublishedAtSubmitValue(t);if(t===`draft`)return;let n=this._threadItems[e],r=n?.publishedAtInput??``;if(!r.trim())return;let i=lt(r,n?.publishedAtTimeMinutes??W(this._getCurrentTimestamp()));if(i!==null)return Math.min(i,this._getCurrentTimestamp())}_getPublishedAtSubmitValue(e){if(e===`draft`)return;let t=lt(this._publishedAtInput,this._getPublishedAtTimeMinutes());if(t!==null)return this._originalPublishedAt!==null&&this._publishedAtInput===this._initialPublishedAtInput&&this._publishedAtTimeMinutes===this._initialPublishedAtTimeMinutes?Math.min(this._originalPublishedAt,this._getCurrentTimestamp()):Math.min(t,this._getCurrentTimestamp());if(!(this._publishedAtInput.trim().length>0)&&this._editPostId)return this._getCurrentTimestamp()}_openPublishPanelAndFocus(e,t=0){this._showCollection=!1,this._collectionSearch=``,this._showPublishPanel=!1,this._showLanguagePicker=!1,this._postMetaIndex=t,this._confirmPanelOpen=!1,this._scheduleSuggestedSlugRefresh(!0),this._placeAndFocusPostMetaPanel(e)}_revealSlugField(e=0){this._openPublishPanelAndFocus(`.compose-publish-slug-input`,e)}_revealPublishedAtField(e=0){this._openPublishPanelAndFocus(`.compose-publish-date-input`,e)}_canPublish(){if(this._loading)return!1;let e=this._rowIds;for(let t=0;t<e.length;t++)if(this._getPostPublishedAtValidationMessage(t)||this._getPostSlugValidationMessage(t))return!1;return e.every(e=>this._rowStatus.get(e)?.publishable===!0)}_focusPublishPanelInitialField(){let e=this._visibilityLocked?`.compose-publish-date-input`:`.compose-publish-option[role='radio']`;this.querySelector(e)?.focus()}_closePublishPanel(e=!1){this._showPublishPanel&&(this._showPublishPanel=!1,e&&this.updateComplete.then(()=>this._restorePageEditorFocus()))}_togglePublishPanel(){this._showCollection=!1,this._collectionSearch=``,this._showLanguagePicker=!1;let e=!this._showPublishPanel;this._showPublishPanel=e,e&&(this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>this._focusPublishPanelInitialField()))}_setVisibility(t){this._visibilityLocked||(this._visibility=t,this._showPublishPanel&&this._closePublishPanel(!0),!this._editPostId&&!this._draftSourceId&&!this._replyToId&&(e._lastNewPostVisibility=t,this._sourceCollectionId&&e._setCollectionVisibility(this._sourceCollectionId,t)))}_onSlugInput(e,t=0){let n=e.target.value;if(this._setPostSlug(t,n.toLowerCase()),this._setPostSlugTaken(t,!1),this._slugCheckLoading=!1,this._hasPostManualSlug(t)){this._scheduleSlugAvailabilityCheck(t);return}this._scheduleSuggestedSlugRefresh()}_resetPublishedAt(e=0){let t=this._getCurrentTimestamp();this._setPostPublishedAtInput(e,ct(t)),this._setPostPublishedAtTimeMinutes(e,W(t)),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-date-input`)?.focus()})}_renderVisibilityIcon(e,t=`menu`){let n=b({"compose-publish-visibility-icon":!0,"compose-publish-visibility-icon-toggle":t===`toggle`,"compose-publish-visibility-icon-public":e===`public`,"compose-publish-visibility-icon-latest_hidden":e===`latest_hidden`,"compose-publish-visibility-icon-private":e===`private`});return it(tt[e],n)}_renderVisibilityRow(e,t,n){let r=this._visibility===e;return i`
622
+ `}_getSubmitLabel(){return this._editPostId?this.labels.update:this._replyToId?this._quietReply?this.labels.quietReplyLabel:this.labels.reply:this._visibility===`latest_hidden`?this.labels.postHiddenFromLatest:this._visibility===`private`?this.labels.postPrivately:this.labels.post}_getSlugSyncValidationMessage(){let e=C(this._slug);return e===`invalid`?this.labels.publishSlugInvalid:e===`reserved`?this.labels.publishSlugReserved:null}_getSlugValidationMessage(){return this._getSlugSyncValidationMessage()||(this._hasManualSlug()&&this._slugTaken?this.labels.publishSlugTaken:null)}_getSlugPreviewUrl(){if(!this._hasManualSlug()||this._getSlugValidationMessage())return null;let e=t(`/${this._slug.trim()}`),n=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${n}/`).toString()}_getSlugPreviewParts(){let e=this._getSlugPreviewUrl();if(!e)return null;let t=new URL(e);return{full:e,origin:t.origin,path:`${t.pathname}${t.search}${t.hash}`}}_getSlugStatusMessage(){return this._hasManualSlug()?this._getSlugValidationMessage()?this._getSlugValidationMessage():null:this._suggestedSlugLoading?this.labels.publishSlugGenerating:null}_getCurrentTimestamp(){return Math.floor(Date.now()/1e3)}_getPublishedAtMaxInput(){return ct(this._getCurrentTimestamp())}_getPublishedAtTimeMinutes(){return this._publishedAtTimeMinutes??W(this._getCurrentTimestamp())}_hasPublishedAtValue(){return this._publishedAtInput.trim().length>0}_getPublishedAtValidationMessage(){return this._hasPublishedAtValue()?U(this._publishedAtInput)===null?this.labels.publishDateInvalid:this._publishedAtInput>this._getPublishedAtMaxInput()?this.labels.publishDateFutureError:null:null}_getPublishedAtSummary(){if(this._editPostId||this._draftSourceId){if(this._publishedAtInput===this._initialPublishedAtInput)return null;if(!this._hasPublishedAtValue())return{input:``,text:this.labels.publishDateSummaryNow}}if(this._getPublishedAtValidationMessage()!==null)return null;let e=U(this._publishedAtInput);return e===null?null:{input:this._publishedAtInput,text:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(e.year,e.monthIndex,e.day))}}_getPostPublishedAtSubmitValue(e,t){if(e===0)return this._getPublishedAtSubmitValue(t);if(t===`draft`)return;let n=this._threadItems[e],r=n?.publishedAtInput??``;if(!r.trim())return;let i=lt(r,n?.publishedAtTimeMinutes??W(this._getCurrentTimestamp()));if(i!==null)return Math.min(i,this._getCurrentTimestamp())}_getPublishedAtSubmitValue(e){if(e===`draft`)return;let t=lt(this._publishedAtInput,this._getPublishedAtTimeMinutes());if(t!==null)return this._originalPublishedAt!==null&&this._publishedAtInput===this._initialPublishedAtInput&&this._publishedAtTimeMinutes===this._initialPublishedAtTimeMinutes?Math.min(this._originalPublishedAt,this._getCurrentTimestamp()):Math.min(t,this._getCurrentTimestamp());if(!(this._publishedAtInput.trim().length>0)&&this._editPostId)return this._getCurrentTimestamp()}_openPublishPanelAndFocus(e,t=0){this._showCollection=!1,this._collectionSearch=``,this._showPublishPanel=!1,this._showLanguagePicker=!1,this._postMetaIndex=t,this._confirmPanelOpen=!1,this._scheduleSuggestedSlugRefresh(!0),this._placeAndFocusPostMetaPanel(e)}_revealSlugField(e=0){this._openPublishPanelAndFocus(`.compose-publish-slug-input`,e)}_revealPublishedAtField(e=0){this._openPublishPanelAndFocus(`.compose-publish-date-input`,e)}_canPublish(){if(this._loading)return!1;let e=this._rowIds;for(let t=0;t<e.length;t++)if(this._getPostPublishedAtValidationMessage(t)||this._getPostSlugValidationMessage(t))return!1;return e.every(e=>this._rowStatus.get(e)?.publishable===!0)}_focusPublishPanelInitialField(){let e=this._visibilityLocked?`.compose-publish-date-input`:`.compose-publish-option[role='radio']`;this.querySelector(e)?.focus()}_closePublishPanel(e=!1){this._showPublishPanel&&(this._showPublishPanel=!1,e&&this.updateComplete.then(()=>this._restorePageEditorFocus()))}_togglePublishPanel(){this._showCollection=!1,this._collectionSearch=``,this._showLanguagePicker=!1;let e=!this._showPublishPanel;this._showPublishPanel=e,e&&(this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>this._focusPublishPanelInitialField()))}_setVisibility(t){this._visibilityLocked||(this._visibility=t,this._showPublishPanel&&this._closePublishPanel(!0),!this._editPostId&&!this._draftSourceId&&!this._replyToId&&(e._lastNewPostVisibility=t,this._sourceCollectionId&&e._setCollectionVisibility(this._sourceCollectionId,t)))}_onSlugInput(e,t=0){let n=e.target.value;if(this._setPostSlug(t,n.toLowerCase()),this._setPostSlugTaken(t,!1),this._slugCheckLoading=!1,this._hasPostManualSlug(t)){this._scheduleSlugAvailabilityCheck(t);return}this._scheduleSuggestedSlugRefresh()}_resetPublishedAt(e=0){let t=this._getCurrentTimestamp();this._setPostPublishedAtInput(e,ct(t)),this._setPostPublishedAtTimeMinutes(e,W(t)),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-date-input`)?.focus()})}_renderVisibilityIcon(e,t=`menu`){let n=S({"compose-publish-visibility-icon":!0,"compose-publish-visibility-icon-toggle":t===`toggle`,"compose-publish-visibility-icon-public":e===`public`,"compose-publish-visibility-icon-latest_hidden":e===`latest_hidden`,"compose-publish-visibility-icon-private":e===`private`});return it(tt[e],n)}_renderVisibilityRow(e,t,n){let r=this._visibility===e;return a`
623
623
  <button
624
624
  type="button"
625
- class=${b({"compose-sheet-row":!0,"compose-sheet-row-selected":r})}
625
+ class=${S({"compose-sheet-row":!0,"compose-sheet-row-selected":r})}
626
626
  role="radio"
627
627
  aria-checked=${r?`true`:`false`}
628
628
  ?disabled=${this._visibilityLocked}
@@ -633,14 +633,14 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
633
633
  <span class="compose-sheet-title">${t}</span>
634
634
  <span class="compose-sheet-sub">${n}</span>
635
635
  </span>
636
- ${r?i`<span class="compose-sheet-check" aria-hidden="true">
636
+ ${r?a`<span class="compose-sheet-check" aria-hidden="true">
637
637
  ${V(R.check,`compose-sheet-check-icon`)}
638
- </span>`:o}
638
+ </span>`:s}
639
639
  </button>
640
- `}async _loadTranslationSource(e,t={}){try{let n=await fetch(r(`/api/posts/${e}`),{credentials:`same-origin`});if(!n.ok)return;let i=await n.json();this._translationOf={id:i.id,title:i.displayTitle||i.slug||``,href:i.slug?r(`/${i.slug}`):``,previewHtml:await this._fetchTranslationPreview(i.id)},t.seed&&await this._seedFromTranslationSource(i)}catch{}}async _fetchTranslationPreview(e){try{let t=await fetch(r(`/_/post-preview/${encodeURIComponent(e)}`),{headers:{Accept:`text/html`},credentials:`same-origin`});return t.ok?await t.text():``}catch{return``}}async _seedFromTranslationSource(e){if(this._hasContent()||this._editPostId||this._draftSourceId)return;let t=e.format;this._format=t,e.collectionIds?.length&&(this._collectionIds=[...e.collectionIds]),e.visibility&&(this._visibility=e.visibility),await this.updateComplete,this._editor?.populate({format:t,url:t===`quote`?e.sourceUrl??void 0:e.url??void 0,quoteAuthor:t===`quote`?e.sourceName??void 0:void 0,rating:e.rating??void 0}),await this.updateComplete,this._seededFromSource=!0,this._captureInitialSnapshot()}_composeTextForDetection(){let e=this._editor;if(!e)return``;let t=e.getData(),n=t.body?re(t.body)??``:``;return[t.title,t.quoteText,n].filter(Boolean).join(` `)}_contextLanguageTag(){let e=this.languages.map(e=>e.tag);return e.length===0?null:e.includes(this.contextLanguage)?this.contextLanguage:e[0]}_readLanguage(){return Ce(this._composeTextForDetection(),{languages:this.languages.map(e=>e.tag)})}_effectiveLanguage(){return this._language??this._readLanguage()??this._contextLanguageTag()}_renderLanguageRow(e,t,n){let r=this._language===e;return i`
640
+ `}async _loadTranslationSource(e,n={}){try{let r=await fetch(t(`/api/posts/${e}`),{credentials:`same-origin`});if(!r.ok)return;let i=await r.json();this._translationOf={id:i.id,title:i.displayTitle||i.slug||``,href:i.slug?t(`/${i.slug}`):``,previewHtml:await this._fetchTranslationPreview(i.id)},n.seed&&await this._seedFromTranslationSource(i)}catch{}}async _fetchTranslationPreview(e){try{let n=await fetch(t(`/_/post-preview/${encodeURIComponent(e)}`),{headers:{Accept:`text/html`},credentials:`same-origin`});return n.ok?await n.text():``}catch{return``}}async _seedFromTranslationSource(e){if(this._hasContent()||this._editPostId||this._draftSourceId)return;let t=e.format;this._format=t,e.collectionIds?.length&&(this._collectionIds=[...e.collectionIds]),e.visibility&&(this._visibility=e.visibility),await this.updateComplete,this._editor?.populate({format:t,url:t===`quote`?e.sourceUrl??void 0:e.url??void 0,quoteAuthor:t===`quote`?e.sourceName??void 0:void 0,rating:e.rating??void 0}),await this.updateComplete,this._seededFromSource=!0,this._captureInitialSnapshot()}_composeTextForDetection(){let e=this._editor;if(!e)return``;let t=e.getData(),n=t.body?re(t.body)??``:``;return[t.title,t.quoteText,n].filter(Boolean).join(` `)}_contextLanguageTag(){let e=this.languages.map(e=>e.tag);return e.length===0?null:e.includes(this.contextLanguage)?this.contextLanguage:e[0]}_readLanguage(){return Ce(this._composeTextForDetection(),{languages:this.languages.map(e=>e.tag)})}_effectiveLanguage(){return this._language??this._readLanguage()??this._contextLanguageTag()}_renderLanguageRow(e,t,n){let r=this._language===e;return a`
641
641
  <button
642
642
  type="button"
643
- class=${b({"compose-sheet-row":!0,"compose-sheet-row-selected":r})}
643
+ class=${S({"compose-sheet-row":!0,"compose-sheet-row-selected":r})}
644
644
  role="radio"
645
645
  aria-checked=${r?`true`:`false`}
646
646
  lang=${P(e??void 0)}
@@ -649,31 +649,31 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
649
649
  >
650
650
  <span class="compose-sheet-main">
651
651
  <span class="compose-sheet-title">${t}</span>
652
- ${n?i`<span class="compose-sheet-sub">${n}</span>`:o}
652
+ ${n?a`<span class="compose-sheet-sub">${n}</span>`:s}
653
653
  </span>
654
- ${r?i`<span class="compose-sheet-check" aria-hidden="true">
654
+ ${r?a`<span class="compose-sheet-check" aria-hidden="true">
655
655
  ${V(R.check,`compose-sheet-check-icon`)}
656
- </span>`:o}
656
+ </span>`:s}
657
657
  </button>
658
- `}_closeLanguagePicker(e=!1){this._showLanguagePicker&&(this._showLanguagePicker=!1,e&&this.updateComplete.then(()=>{this.querySelector(`[data-compose-language-trigger]`)?.focus()}))}_toggleLanguagePicker(){if(this._showLanguagePicker){this._closeLanguagePicker(!0);return}this._showCollection=!1,this._collectionSearch=``,this._showPublishPanel=!1,this._postMetaIndex=null,this._showLanguagePicker=!0,this.updateComplete.then(()=>{let e=this.querySelectorAll(`[data-compose-language-row]`);(Array.from(e).find(e=>e.getAttribute(`aria-checked`)===`true`)??e[0])?.focus()})}_renderLanguageControl(){if(this._replyToId||this.languages.length<2)return o;let e=this._effectiveLanguage(),t=this.languages.find(t=>t.tag===e)?.label??``,n=this._language!==null,r=n||e!==this._contextLanguageTag(),a=this._showLanguagePicker,s=this.labels.languageTriggerLabel.replace(`{language}`,t);return i`
658
+ `}_closeLanguagePicker(e=!1){this._showLanguagePicker&&(this._showLanguagePicker=!1,e&&this.updateComplete.then(()=>{this.querySelector(`[data-compose-language-trigger]`)?.focus()}))}_toggleLanguagePicker(){if(this._showLanguagePicker){this._closeLanguagePicker(!0);return}this._showCollection=!1,this._collectionSearch=``,this._showPublishPanel=!1,this._postMetaIndex=null,this._showLanguagePicker=!0,this.updateComplete.then(()=>{let e=this.querySelectorAll(`[data-compose-language-row]`);(Array.from(e).find(e=>e.getAttribute(`aria-checked`)===`true`)??e[0])?.focus()})}_renderLanguageControl(){if(this._replyToId||this.languages.length<2)return s;let e=this._effectiveLanguage(),t=this.languages.find(t=>t.tag===e)?.label??``,n=this._language!==null,r=n||e!==this._contextLanguageTag(),i=this._showLanguagePicker,o=this.labels.languageTriggerLabel.replace(`{language}`,t);return a`
659
659
  <div
660
- class=${b({"compose-language":!0,"compose-language-open":a})}
660
+ class=${S({"compose-language":!0,"compose-language-open":i})}
661
661
  >
662
- ${a?i`<div
662
+ ${i?a`<div
663
663
  class="compose-dropdown-backdrop"
664
664
  @click=${()=>this._closeLanguagePicker(!0)}
665
- ></div>`:o}
665
+ ></div>`:s}
666
666
  <button
667
667
  type="button"
668
- class=${b({"compose-language-trigger":!0,"compose-language-trigger-bare":!r})}
668
+ class=${S({"compose-language-trigger":!0,"compose-language-trigger-bare":!r})}
669
669
  data-compose-language-trigger
670
- data-open=${a?`true`:o}
671
- data-chosen=${n?`true`:o}
670
+ data-open=${i?`true`:s}
671
+ data-chosen=${n?`true`:s}
672
672
  ?disabled=${this._loading}
673
673
  aria-haspopup="dialog"
674
- aria-expanded=${a?`true`:`false`}
675
- aria-label=${s}
676
- title=${s}
674
+ aria-expanded=${i?`true`:`false`}
675
+ aria-label=${o}
676
+ title=${o}
677
677
  @click=${()=>this._toggleLanguagePicker()}
678
678
  >
679
679
  <svg
@@ -688,49 +688,49 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
688
688
  stroke-linejoin="round"
689
689
  aria-hidden="true"
690
690
  >
691
- ${v(nt)}
691
+ ${y(nt)}
692
692
  </svg>
693
- ${r?i`<span
693
+ ${r?a`<span
694
694
  class="compose-language-label"
695
695
  lang=${P(e??void 0)}
696
696
  >${t}</span
697
- >`:o}
697
+ >`:s}
698
698
  </button>
699
- ${a?this._renderLanguagePicker():o}
699
+ ${i?this._renderLanguagePicker():s}
700
700
  </div>
701
- `}_renderLanguagePicker(){let e=e=>this.languages.find(t=>t.tag===e)?.label??``,t=this._readLanguage(),n=e(this._contextLanguageTag()),r=t?this.labels.languageAutoDetected.replace(`{language}`,e(t)):n?this.labels.languageAutoPending.replace(`{language}`,n):this.labels.languageAutoHint;return i`
701
+ `}_renderLanguagePicker(){let e=e=>this.languages.find(t=>t.tag===e)?.label??``,t=this._readLanguage(),n=e(this._contextLanguageTag()),r=t?this.labels.languageAutoDetected.replace(`{language}`,e(t)):n?this.labels.languageAutoPending.replace(`{language}`,n):this.labels.languageAutoHint;return a`
702
702
  <div
703
703
  class="compose-language-popover"
704
704
  role="dialog"
705
705
  aria-label=${this.labels.languageLabel}
706
706
  >
707
707
  <p class="compose-sheet-label">${this.labels.languageLabel}</p>
708
- ${this._translationOf?i`<p class="compose-sheet-note">
708
+ ${this._translationOf?a`<p class="compose-sheet-note">
709
709
  ${this.labels.translationOf.replace(`{title}`,this._translationOf.title)}
710
- </p>`:o}
710
+ </p>`:s}
711
711
  <div role="radiogroup" aria-label=${this.labels.languageLabel}>
712
712
  ${this._renderLanguageRow(null,this.labels.languageAuto,r)}
713
713
  ${this.languages.map(e=>this._renderLanguageRow(e.tag,e.label,``))}
714
714
  </div>
715
715
  </div>
716
- `}_renderMetaFieldHead(e,t){return i`
716
+ `}_renderMetaFieldHead(e,t){return a`
717
717
  <div class="compose-meta-field-head">
718
718
  <span class="compose-meta-label">${e}</span>
719
719
  ${t}
720
720
  </div>
721
- `}_openDatePicker(e){let t=this.querySelectorAll(`.compose-publish-date-input`),n=t[e]??t[0];if(n){n.focus();try{n.showPicker()}catch{}}}_renderPublishDateSection(e){let t=this._getPostPublishedAtValidationMessage(e),n=this._hasPostPublishedAtValue(e);return i`
721
+ `}_openDatePicker(e){let t=this.querySelectorAll(`.compose-publish-date-input`),n=t[e]??t[0];if(n){n.focus();try{n.showPicker()}catch{}}}_renderPublishDateSection(e){let t=this._getPostPublishedAtValidationMessage(e),n=this._hasPostPublishedAtValue(e);return a`
722
722
  <div class="compose-meta-field compose-publish-date-field">
723
- ${this._renderMetaFieldHead(this.labels.publishDateLabel,n?i`<button
723
+ ${this._renderMetaFieldHead(this.labels.publishDateLabel,n?a`<button
724
724
  type="button"
725
725
  class="compose-publish-section-action"
726
726
  @click=${()=>this._resetPublishedAt(e)}
727
727
  >
728
728
  ${this.labels.publishDateReset}
729
- </button>`:o)}
729
+ </button>`:s)}
730
730
  <div class="compose-publish-date-input-wrap">
731
731
  <input
732
732
  type="date"
733
- class=${b({"compose-input":!0,"compose-publish-date-input":!0,"compose-publish-date-input-empty":!n})}
733
+ class=${S({"compose-input":!0,"compose-publish-date-input":!0,"compose-publish-date-input-empty":!n})}
734
734
  .value=${this._getPostPublishedAtInput(e)}
735
735
  max=${this._getPublishedAtMaxInput()}
736
736
  aria-label=${this.labels.publishDateLabel}
@@ -747,23 +747,23 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
747
747
  ${V(R.calendar,`compose-publish-date-picker-icon`)}
748
748
  </button>
749
749
  </div>
750
- ${t?i`<p
750
+ ${t?a`<p
751
751
  class="compose-publish-date-status compose-publish-date-status-error"
752
752
  >
753
753
  ${t}
754
- </p>`:n?o:i`<p class="compose-sheet-hint">
754
+ </p>`:n?s:a`<p class="compose-sheet-hint">
755
755
  ${this.labels.publishDateHint}
756
756
  </p>`}
757
757
  </div>
758
- `}_renderPublishSlugSection(e){let t=e===0,n=this._getPostSlugValidationMessage(e),r=t?this._getSlugStatusMessage():n,a=t?this._getSlugPreviewParts():null,s=t&&!this._hasManualSlug()&&!this._suggestedSlugLoading&&!!this._suggestedSlug;return i`
758
+ `}_renderPublishSlugSection(e){let t=e===0,n=this._getPostSlugValidationMessage(e),r=t?this._getSlugStatusMessage():n,i=t?this._getSlugPreviewParts():null,o=t&&!this._hasManualSlug()&&!this._suggestedSlugLoading&&!!this._suggestedSlug;return a`
759
759
  <div class="compose-meta-field compose-publish-slug-field">
760
- ${this._renderMetaFieldHead(this.labels.publishSlugLabel,this._hasManualSlug()?i`<button
760
+ ${this._renderMetaFieldHead(this.labels.publishSlugLabel,this._hasManualSlug()?a`<button
761
761
  type="button"
762
762
  class="compose-publish-section-action"
763
763
  @click=${()=>this._resetCustomSlug()}
764
764
  >
765
765
  ${this.labels.publishSlugReset}
766
- </button>`:o)}
766
+ </button>`:s)}
767
767
  <div class="compose-publish-slug-input-wrap">
768
768
  <span class="compose-publish-slug-prefix" aria-hidden="true">/</span>
769
769
  <input
@@ -779,7 +779,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
779
779
  @input=${t=>this._onSlugInput(t,e)}
780
780
  />
781
781
  </div>
782
- ${s?i`
782
+ ${o?a`
783
783
  <button
784
784
  type="button"
785
785
  class="compose-slug-suggestion"
@@ -807,27 +807,27 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
807
807
  </svg>
808
808
  </span>
809
809
  </button>
810
- `:o}
811
- ${r?i`<p
812
- class=${b({"compose-publish-slug-status":!0,"compose-publish-slug-status-error":!!n})}
813
- data-compose-slug-error=${n?`true`:o}
810
+ `:s}
811
+ ${r?a`<p
812
+ class=${S({"compose-publish-slug-status":!0,"compose-publish-slug-status-error":!!n})}
813
+ data-compose-slug-error=${n?`true`:s}
814
814
  >
815
815
  ${r}
816
- </p>`:a?i`<p
816
+ </p>`:i?a`<p
817
817
  class="compose-publish-slug-preview"
818
818
  data-compose-slug-preview
819
- title=${a.full}
819
+ title=${i.full}
820
820
  >
821
821
  <span class="compose-publish-slug-preview-origin"
822
- >${a.origin}</span
822
+ >${i.origin}</span
823
823
  ><span class="compose-publish-slug-preview-path"
824
- >${a.path}</span
824
+ >${i.path}</span
825
825
  >
826
- </p>`:this._hasPostManualSlug(e)?o:i`<p class="compose-sheet-hint">
826
+ </p>`:this._hasPostManualSlug(e)?s:a`<p class="compose-sheet-hint">
827
827
  ${this.labels.publishSlugHint}
828
828
  </p>`}
829
829
  </div>
830
- `}_canReplyQuietly(){return this._replyToId?!(this._editPostId||this._draftSourceId)||this._threadItems.length>=2:!1}_renderQuietReplySection(){return this._canReplyQuietly()?i`
830
+ `}_canReplyQuietly(){return this._replyToId?!(this._editPostId||this._draftSourceId)||this._threadItems.length>=2:!1}_renderQuietReplySection(){return this._canReplyQuietly()?a`
831
831
  <label class="compose-sheet-row compose-sheet-row-switch">
832
832
  <span class="compose-sheet-main">
833
833
  <span class="compose-sheet-title"
@@ -843,14 +843,14 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
843
843
  @change=${e=>{this._quietReply=e.target.checked}}
844
844
  />
845
845
  </label>
846
- `:o}_getPublishedAtRowValue(){let e=U(this._publishedAtInput);return e===null?this.labels.publishDateSummaryNow:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(e.year,e.monthIndex,e.day))}_getPostSlugRowValue(e){let t=this._getPostSlug(e).trim();return t?`/${t}`:this.labels.publishSlugSummaryAuto}_getPostSlug(e){return e===0?this._slug:this._threadItems[e]?.slug??``}_setPostSlug(e,t){if(e===0){this._slug=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,slug:t}:n)}_setPostSlugTaken(e,t){if(e===0){this._slugTaken=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,slugTaken:t}:n)}_hasPostManualSlug(e){return this._getPostSlug(e).trim().length>0}_getPostSlugSyncValidationMessage(e){let t=x(this._getPostSlug(e));return t===`invalid`?this.labels.publishSlugInvalid:t===`reserved`?this.labels.publishSlugReserved:null}_getPostSlugValidationMessage(e){let t=this._getPostSlugSyncValidationMessage(e);if(t)return t;let n=e===0?this._slugTaken:this._threadItems[e]?.slugTaken;return this._hasPostManualSlug(e)&&n?this.labels.publishSlugTaken:null}_getPostPublishedAtInput(e){return e===0?this._publishedAtInput:this._threadItems[e]?.publishedAtInput??``}_setPostPublishedAtInput(e,t){if(e===0){this._publishedAtInput=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,publishedAtInput:t}:n)}_setPostPublishedAtTimeMinutes(e,t){if(e===0){this._publishedAtTimeMinutes=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,publishedAtTimeMinutes:t}:n)}_hasPostPublishedAtValue(e){return this._getPostPublishedAtInput(e).trim().length>0}_getPostPublishedAtValidationMessage(e){let t=this._getPostPublishedAtInput(e);return t.trim()?U(t)===null?this.labels.publishDateInvalid:t>this._getPublishedAtMaxInput()?this.labels.publishDateFutureError:null:null}_getPostPublishedAtRowValue(e){let t=U(this._getPostPublishedAtInput(e));return t===null?e>0&&this._hasPublishedAtValue()?this._getPublishedAtRowValue():this.labels.publishDateSummaryNow:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(t.year,t.monthIndex,t.day))}_renderPostMetaControl(e){if(this._openingEdit)return o;let t=e===0,n=this._postMetaIndex===e,r=this._hasPostPublishedAtValue(e)||this._hasPostManualSlug(e);return i`
846
+ `:s}_getPublishedAtRowValue(){let e=U(this._publishedAtInput);return e===null?this.labels.publishDateSummaryNow:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(e.year,e.monthIndex,e.day))}_getPostSlugRowValue(e){let t=this._getPostSlug(e).trim();return t?`/${t}`:this.labels.publishSlugSummaryAuto}_getPostSlug(e){return e===0?this._slug:this._threadItems[e]?.slug??``}_setPostSlug(e,t){if(e===0){this._slug=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,slug:t}:n)}_setPostSlugTaken(e,t){if(e===0){this._slugTaken=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,slugTaken:t}:n)}_hasPostManualSlug(e){return this._getPostSlug(e).trim().length>0}_getPostSlugSyncValidationMessage(e){let t=C(this._getPostSlug(e));return t===`invalid`?this.labels.publishSlugInvalid:t===`reserved`?this.labels.publishSlugReserved:null}_getPostSlugValidationMessage(e){let t=this._getPostSlugSyncValidationMessage(e);if(t)return t;let n=e===0?this._slugTaken:this._threadItems[e]?.slugTaken;return this._hasPostManualSlug(e)&&n?this.labels.publishSlugTaken:null}_getPostPublishedAtInput(e){return e===0?this._publishedAtInput:this._threadItems[e]?.publishedAtInput??``}_setPostPublishedAtInput(e,t){if(e===0){this._publishedAtInput=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,publishedAtInput:t}:n)}_setPostPublishedAtTimeMinutes(e,t){if(e===0){this._publishedAtTimeMinutes=t;return}this._threadItems=this._threadItems.map((n,r)=>r===e?{...n,publishedAtTimeMinutes:t}:n)}_hasPostPublishedAtValue(e){return this._getPostPublishedAtInput(e).trim().length>0}_getPostPublishedAtValidationMessage(e){let t=this._getPostPublishedAtInput(e);return t.trim()?U(t)===null?this.labels.publishDateInvalid:t>this._getPublishedAtMaxInput()?this.labels.publishDateFutureError:null:null}_getPostPublishedAtRowValue(e){let t=U(this._getPostPublishedAtInput(e));return t===null?e>0&&this._hasPublishedAtValue()?this._getPublishedAtRowValue():this.labels.publishDateSummaryNow:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(t.year,t.monthIndex,t.day))}_renderPostMetaControl(e){if(this._openingEdit)return s;let t=e===0,n=this._postMetaIndex===e,r=this._hasPostPublishedAtValue(e)||this._hasPostManualSlug(e);return a`
847
847
  <div
848
- class=${b({"compose-post-meta":!0,"compose-post-meta-set":r,"compose-post-meta-open":n})}
848
+ class=${S({"compose-post-meta":!0,"compose-post-meta-set":r,"compose-post-meta-open":n})}
849
849
  >
850
- ${n?i`<div
850
+ ${n?a`<div
851
851
  class="compose-dropdown-backdrop"
852
852
  @click=${()=>this._closePostMeta()}
853
- ></div>`:o}
853
+ ></div>`:s}
854
854
  <button
855
855
  type="button"
856
856
  class="compose-post-meta-pill"
@@ -871,7 +871,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
871
871
  >${this._getPostSlugRowValue(e)}</span
872
872
  >
873
873
  </button>
874
- ${n?i`<div
874
+ ${n?a`<div
875
875
  class="compose-post-meta-panel"
876
876
  role="dialog"
877
877
  aria-label=${this.labels.publishSettings}
@@ -890,14 +890,14 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
890
890
  ${this.labels.done}
891
891
  </button>
892
892
  </div>
893
- </div>`:o}
893
+ </div>`:s}
894
894
  </div>
895
- `}_placeAndFocusPostMetaPanel(e){this.updateComplete.then(()=>{this._updatePostMetaPanelLayout(),this.querySelector(e??`[data-compose-post-meta-panel]`)?.focus({preventScroll:!0})})}_updatePostMetaPanelLayout(){let e=this._postMetaIndex;if(e===null)return;let t=this.querySelector(`[data-compose-post-meta-panel]`),n=this.querySelector(`[data-compose-post-meta-pill][data-post-index="${e}"]`);if(!t||!n)return;let r=globalThis.visualViewport,i=r?.offsetTop??0,a=r?.offsetLeft??0,o=i+(r?.height??globalThis.innerHeight),s=a+(r?.width??globalThis.innerWidth),c=n.getBoundingClientRect(),l=Math.max(0,c.top-(i+12)-6),u=Math.max(0,o-12-c.bottom-6),d=u>=l?`down`:`up`,f=Math.max(1,Math.floor(d===`up`?l:u));t.style.top=`0px`,t.style.left=`0px`;let p=t.getBoundingClientRect(),m=p.width/(t.offsetWidth||p.width||1)||1;t.style.setProperty(`--compose-post-meta-panel-max-height`,`${f/m}px`);let h=t.offsetHeight*m,g=d===`down`?c.bottom+6:c.top-6-h,_=Math.min(Math.max(c.right-p.width,a+12),Math.max(s-12-p.width,a));t.style.top=`${(g-p.top)/m}px`,t.style.left=`${(_-p.left)/m}px`}_closePostMeta(){let e=this._postMetaIndex;if(e===null)return;let t=this.querySelector(`[data-compose-post-meta-panel]`)?.contains(document.activeElement)??!1;this._postMetaIndex=null,t&&this.updateComplete.then(()=>{let t=this.querySelectorAll(`jant-compose-editor`);(t[e]??t[0])?.focusInput()})}_hasPublishPanelContent(){return!this._visibilityLocked||this._replyToId&&this._renderQuietReplySection()!==o?!0:this._renderSaveDraftRow()!==o||this._renderDraftsRow()!==o}_renderPublishPanelSections(){let e=i`<div
895
+ `}_placeAndFocusPostMetaPanel(e){this.updateComplete.then(()=>{this._updatePostMetaPanelLayout(),this.querySelector(e??`[data-compose-post-meta-panel]`)?.focus({preventScroll:!0})})}_updatePostMetaPanelLayout(){let e=this._postMetaIndex;if(e===null)return;let t=this.querySelector(`[data-compose-post-meta-panel]`),n=this.querySelector(`[data-compose-post-meta-pill][data-post-index="${e}"]`);if(!t||!n)return;let r=globalThis.visualViewport,i=r?.offsetTop??0,a=r?.offsetLeft??0,o=i+(r?.height??globalThis.innerHeight),s=a+(r?.width??globalThis.innerWidth),c=n.getBoundingClientRect(),l=Math.max(0,c.top-(i+12)-6),u=Math.max(0,o-12-c.bottom-6),d=u>=l?`down`:`up`,f=Math.max(1,Math.floor(d===`up`?l:u));t.style.top=`0px`,t.style.left=`0px`;let p=t.getBoundingClientRect(),m=p.width/(t.offsetWidth||p.width||1)||1;t.style.setProperty(`--compose-post-meta-panel-max-height`,`${f/m}px`);let h=t.offsetHeight*m,g=d===`down`?c.bottom+6:c.top-6-h,_=Math.min(Math.max(c.right-p.width,a+12),Math.max(s-12-p.width,a));t.style.top=`${(g-p.top)/m}px`,t.style.left=`${(_-p.left)/m}px`}_closePostMeta(){let e=this._postMetaIndex;if(e===null)return;let t=this.querySelector(`[data-compose-post-meta-panel]`)?.contains(document.activeElement)??!1;this._postMetaIndex=null,t&&this.updateComplete.then(()=>{let t=this.querySelectorAll(`jant-compose-editor`);(t[e]??t[0])?.focusInput()})}_hasPublishPanelContent(){return!this._visibilityLocked||this._replyToId&&this._renderQuietReplySection()!==s?!0:this._renderSaveDraftRow()!==s||this._renderDraftsRow()!==s}_renderPublishPanelSections(){let e=a`<div
896
896
  class="compose-sheet-divider"
897
897
  aria-hidden="true"
898
- ></div>`,t=this._renderSaveDraftRow(),n=this._renderDraftsRow(),r=t!==o||n!==o;return i`
898
+ ></div>`,t=this._renderSaveDraftRow(),n=this._renderDraftsRow(),r=t!==s||n!==s;return a`
899
899
  <div class="compose-sheet">
900
- ${this._visibilityLocked?o:i`
900
+ ${this._visibilityLocked?s:a`
901
901
  <p class="compose-sheet-label">
902
902
  ${this.labels.publishVisibilityLabel}
903
903
  </p>
@@ -910,11 +910,11 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
910
910
  ${this._renderVisibilityRow(`private`,this.labels.publishVisibilityPrivate,this.labels.publishVisibilityPrivateHint)}
911
911
  </div>
912
912
  `}
913
- ${this._replyToId?i`${this._visibilityLocked?o:e}
914
- ${this._renderQuietReplySection()}`:o}
915
- ${r?i`${e} ${t} ${n}`:o}
913
+ ${this._replyToId?a`${this._visibilityLocked?s:e}
914
+ ${this._renderQuietReplySection()}`:s}
915
+ ${r?a`${e} ${t} ${n}`:s}
916
916
  </div>
917
- `}_renderSaveDraftRow(){return this._editPostId||!this._hasWorkToLose()?o:i`
917
+ `}_renderSaveDraftRow(){return this._editPostId||!this._hasWorkToLose()?s:a`
918
918
  <button
919
919
  type="button"
920
920
  class="compose-sheet-row"
@@ -926,7 +926,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
926
926
  <span class="compose-sheet-title">${this.labels.saveAsDraft}</span>
927
927
  </span>
928
928
  </button>
929
- `}_renderDraftsRow(){return this._editPostId?o:i`
929
+ `}_renderDraftsRow(){return this._editPostId?s:a`
930
930
  <button
931
931
  type="button"
932
932
  class="compose-sheet-row"
@@ -939,7 +939,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
939
939
  </span>
940
940
  ${V(R.caretRight,`compose-sheet-caret`)}
941
941
  </button>
942
- `}_renderCloseComposeQuickAction(){return this.pageMode||this._threadItems.length===0?o:i`
942
+ `}_renderCloseComposeQuickAction(){return this.pageMode||this._threadItems.length===0?s:a`
943
943
  <button
944
944
  type="button"
945
945
  class="compose-quick-actions-close"
@@ -948,7 +948,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
948
948
  >
949
949
  ${this.labels.close}
950
950
  </button>
951
- `}_renderDesktopPublishPanel(){return!this._showPublishPanel||this._publishPanelFullscreen?o:i`
951
+ `}_renderDesktopPublishPanel(){return!this._showPublishPanel||this._publishPanelFullscreen?s:a`
952
952
  <div
953
953
  class="compose-publish-panel compose-publish-panel-desktop"
954
954
  role="dialog"
@@ -959,7 +959,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
959
959
  >
960
960
  ${this._renderPublishPanelSections()}
961
961
  </div>
962
- `}_renderMobilePublishPanel(){return!this._showPublishPanel||!this._publishPanelFullscreen?o:i`
962
+ `}_renderMobilePublishPanel(){return!this._showPublishPanel||!this._publishPanelFullscreen?s:a`
963
963
  <div
964
964
  class="compose-publish-panel compose-publish-panel-mobile"
965
965
  role="dialog"
@@ -1001,7 +1001,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1001
1001
  ${this._renderPublishPanelSections()}
1002
1002
  </div>
1003
1003
  </div>
1004
- `}_updatePublishPanelLayout(){if(this._publishPanelFullscreen)return;let e=this.querySelector(`.compose-publish-group`),t=this.querySelector(`[data-compose-publish-panel-desktop]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=r+12,s=i-12,c=Math.max(0,a.top-o-10),l=Math.max(0,s-a.bottom-10),u=l>=c?`down`:`up`,d=Math.max(1,Math.floor(u===`up`?c:l));t.dataset.position=u,t.style.setProperty(`--compose-publish-panel-max-height`,`${d}px`)}_renderPublishButton(){let e=i`<svg
1004
+ `}_updatePublishPanelLayout(){if(this._publishPanelFullscreen)return;let e=this.querySelector(`.compose-publish-group`),t=this.querySelector(`[data-compose-publish-panel-desktop]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=r+12,s=i-12,c=Math.max(0,a.top-o-10),l=Math.max(0,s-a.bottom-10),u=l>=c?`down`:`up`,d=Math.max(1,Math.floor(u===`up`?c:l));t.dataset.position=u,t.style.setProperty(`--compose-publish-panel-max-height`,`${d}px`)}_renderPublishButton(){let e=a`<svg
1005
1005
  class="animate-spin size-4"
1006
1006
  xmlns="http://www.w3.org/2000/svg"
1007
1007
  viewBox="0 0 24 24"
@@ -1013,34 +1013,34 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1013
1013
  role="status"
1014
1014
  >
1015
1015
  <path d="M21 12a9 9 0 1 1-6.219-8.56" />
1016
- </svg>`,t=this._canPublish();return i`
1016
+ </svg>`,t=this._canPublish();return a`
1017
1017
  <div class="compose-publish-shell">
1018
1018
  <div
1019
- class=${b({"compose-publish-group":!0,"compose-publish-group-open":this._showPublishPanel})}
1019
+ class=${S({"compose-publish-group":!0,"compose-publish-group-open":this._showPublishPanel})}
1020
1020
  >
1021
- ${this._showPublishPanel&&!this._publishPanelFullscreen?i`<div
1021
+ ${this._showPublishPanel&&!this._publishPanelFullscreen?a`<div
1022
1022
  class="compose-dropdown-backdrop"
1023
1023
  @click=${()=>this._closePublishPanel(!0)}
1024
- ></div>`:o}
1024
+ ></div>`:s}
1025
1025
  <div
1026
1026
  role="group"
1027
- class=${b({"compose-publish-buttons":!0,"compose-publish-buttons-inactive":!t&&!this._loading})}
1027
+ class=${S({"compose-publish-buttons":!0,"compose-publish-buttons-inactive":!t&&!this._loading})}
1028
1028
  >
1029
1029
  <button
1030
1030
  type="button"
1031
- class=${b({"compose-publish-main":!0,"compose-publish-main-loading":this._loading})}
1031
+ class=${S({"compose-publish-main":!0,"compose-publish-main-loading":this._loading})}
1032
1032
  ?disabled=${!t}
1033
1033
  @click=${()=>void this._submit(`published`)}
1034
1034
  >
1035
- ${this._loading?e:o} ${this._getSubmitLabel()}
1035
+ ${this._loading?e:s} ${this._getSubmitLabel()}
1036
1036
  </button>
1037
1037
  </div>
1038
1038
  <!-- Options sits past Publish as its own control rather than a
1039
1039
  chevron welded to it: a split button reads as one button, which
1040
1040
  is why nobody found the settings. -->
1041
- ${this._hasPublishPanelContent()?i`<button
1041
+ ${this._hasPublishPanelContent()?a`<button
1042
1042
  type="button"
1043
- class=${b({"compose-options-trigger":!0,"compose-options-trigger-open":this._showPublishPanel})}
1043
+ class=${S({"compose-options-trigger":!0,"compose-options-trigger-open":this._showPublishPanel})}
1044
1044
  ?disabled=${this._loading}
1045
1045
  aria-haspopup="dialog"
1046
1046
  aria-expanded=${this._showPublishPanel?`true`:`false`}
@@ -1059,17 +1059,17 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1059
1059
  stroke-linejoin="round"
1060
1060
  aria-hidden="true"
1061
1061
  >
1062
- ${v(R.options)}
1062
+ ${y(R.options)}
1063
1063
  </svg>
1064
- </button>`:o}
1064
+ </button>`:s}
1065
1065
  ${this._renderDesktopPublishPanel()}
1066
1066
  </div>
1067
1067
  </div>
1068
- `}_renderQuickActionsRow(){let e=this._renderCloseComposeQuickAction(),t=this._renderHideFromLatestQuickToggle(),n=this._renderQuietReplyQuickToggle();return e===o&&t===o&&n===o?o:i`
1068
+ `}_renderQuickActionsRow(){let e=this._renderCloseComposeQuickAction(),t=this._renderHideFromLatestQuickToggle(),n=this._renderQuietReplyQuickToggle();return e===s&&t===s&&n===s?s:a`
1069
1069
  <div class="compose-quick-actions-row">
1070
1070
  ${e} ${t} ${n}
1071
1071
  </div>
1072
- `}_renderQuietReplyQuickToggle(){return this._canReplyQuietly()?i`
1072
+ `}_renderQuietReplyQuickToggle(){return this._canReplyQuietly()?a`
1073
1073
  <label class="compose-publish-quick-toggle">
1074
1074
  <input
1075
1075
  type="checkbox"
@@ -1080,7 +1080,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1080
1080
  />
1081
1081
  <span>${this.labels.quietReplyLabel}</span>
1082
1082
  </label>
1083
- `:o}_renderHideFromLatestQuickToggle(){if(this._visibilityLocked||this._visibility===`private`)return o;let e=this._visibility===`latest_hidden`;return i`
1083
+ `:s}_renderHideFromLatestQuickToggle(){if(this._visibilityLocked||this._visibility===`private`)return s;let e=this._visibility===`latest_hidden`;return a`
1084
1084
  <label class="compose-publish-quick-toggle">
1085
1085
  <input
1086
1086
  type="checkbox"
@@ -1091,7 +1091,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1091
1091
  />
1092
1092
  <span>${this.labels.publishHideFromLatest}</span>
1093
1093
  </label>
1094
- `}_renderEditLoadingState(){return i`
1094
+ `}_renderEditLoadingState(){return a`
1095
1095
  <div
1096
1096
  class="compose-edit-loading"
1097
1097
  role="status"
@@ -1129,9 +1129,9 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1129
1129
  </div>
1130
1130
  </div>
1131
1131
  </div>
1132
- `}_addThreadItem(){if((this._threadItems.length===0?2:this._threadItems.length+1)>20){l(this._getThreadLimitMessage(),`error`);return}let e=this._threadItems.length>0?this._threadItems[this._threadItems.length-1].format:this._format;if(this._threadItems.length===0){let t=this._editor;this._threadItems=[{id:L(),format:this._format},{id:L(),format:e}],this.updateComplete.then(()=>{let e=this.querySelector(`jant-compose-editor`);t&&e&&e.takeOver(t)})}else this._threadItems=[...this._threadItems,{id:L(),format:e}];this._focusedThreadIndex=this._threadItems.length-1,this.updateComplete.then(()=>{this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.focusInput();let e=this.querySelector(`.compose-scroll`);e&&(e.scrollTop=e.scrollHeight)})}_removeThreadItem(e){if(this._threadItems.length<=1)return;let t=this._threadItems.filter((t,n)=>n!==e);if(e===0){let e=t[0];this._slug=e.slug??``,this._slugTaken=e.slugTaken??!1,this._publishedAtInput=e.publishedAtInput??``,this._publishedAtTimeMinutes=e.publishedAtTimeMinutes??null}if(t.length===1){let e=this.querySelector(`jant-compose-editor[data-thread-id="${t[0].id}"]`);this._threadItems=[],this._focusedThreadIndex=0,this._format=t[0].format,this.updateComplete.then(()=>{let t=this._editor;t&&(e&&t.takeOver(e),t.focusInput())})}else this._threadItems=t,this._focusedThreadIndex=Math.min(this._focusedThreadIndex,t.length-1)}_positionLabel(e){if(this._editPostId)return``;let t=!!(this._replyToId&&this._replyToData);if(t&&this._replyParentPosition===null)return``;let n=t?this._replyParentPosition??0:0,r=n+(this._threadItems.length||1);return r<2?``:`${n+e+1}/${r}`}_renderThreadPost(e,t,n,r){return i`
1132
+ `}_addThreadItem(){if((this._threadItems.length===0?2:this._threadItems.length+1)>20){u(this._getThreadLimitMessage(),`error`);return}let e=this._threadItems.length>0?this._threadItems[this._threadItems.length-1].format:this._format;if(this._threadItems.length===0){let t=this._editor;this._threadItems=[{id:L(),format:this._format},{id:L(),format:e}],this.updateComplete.then(()=>{let e=this.querySelector(`jant-compose-editor`);t&&e&&e.takeOver(t)})}else this._threadItems=[...this._threadItems,{id:L(),format:e}];this._focusedThreadIndex=this._threadItems.length-1,this.updateComplete.then(()=>{this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.focusInput();let e=this.querySelector(`.compose-scroll`);e&&(e.scrollTop=e.scrollHeight)})}_removeThreadItem(e){if(this._threadItems.length<=1)return;let t=this._threadItems.filter((t,n)=>n!==e);if(e===0){let e=t[0];this._slug=e.slug??``,this._slugTaken=e.slugTaken??!1,this._publishedAtInput=e.publishedAtInput??``,this._publishedAtTimeMinutes=e.publishedAtTimeMinutes??null}if(t.length===1){let e=this.querySelector(`jant-compose-editor[data-thread-id="${t[0].id}"]`);this._threadItems=[],this._focusedThreadIndex=0,this._format=t[0].format,this.updateComplete.then(()=>{let t=this._editor;t&&(e&&t.takeOver(e),t.focusInput())})}else this._threadItems=t,this._focusedThreadIndex=Math.min(this._focusedThreadIndex,t.length-1)}_positionLabel(e){if(this._editPostId)return``;let t=!!(this._replyToId&&this._replyToData);if(t&&this._replyParentPosition===null)return``;let n=t?this._replyParentPosition??0:0,r=n+(this._threadItems.length||1);return r<2?``:`${n+e+1}/${r}`}_renderThreadPost(e,t,n,r){return a`
1133
1133
  <div
1134
- class=${b({"compose-editor-row":!0,"compose-thread-post":!0,"is-current":t===this._focusedThreadIndex})}
1134
+ class=${S({"compose-editor-row":!0,"compose-thread-post":!0,"is-current":t===this._focusedThreadIndex})}
1135
1135
  data-thread-index=${t}
1136
1136
  @focusin=${()=>{this._focusedThreadIndex=t}}
1137
1137
  @jant:format-change=${n=>{n.stopPropagation(),this._convertForFormatSwitch(n.target,e.format,n.detail.format),this._threadItems=this._threadItems.map((e,r)=>r===t?{...e,format:n.detail.format}:e),this._format=n.detail.format,this._shouldAutofocusFormatInput()&&this.updateComplete.then(()=>{let e=this.querySelectorAll(`jant-compose-editor`)[t];e?.updateComplete.then(()=>e.focusInput())})}}
@@ -1152,7 +1152,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1152
1152
  data-thread-id=${e.id}
1153
1153
  ></jant-compose-editor>
1154
1154
  </div>
1155
- `}_renderAddToThreadRow(){let e=this._rowIds,t=e[e.length-1],n=!this._rowStatus.get(t)?.hasContent,r=this._threadItems.length>=20;return i`
1155
+ `}_renderAddToThreadRow(){let e=this._rowIds,t=e[e.length-1],n=!this._rowStatus.get(t)?.hasContent,r=this._threadItems.length>=20;return a`
1156
1156
  <div class="compose-thread-add-row">
1157
1157
  <div class="compose-thread-add-dot"></div>
1158
1158
  <button
@@ -1164,9 +1164,9 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1164
1164
  Add to thread
1165
1165
  </button>
1166
1166
  </div>
1167
- `}_renderThreadComposeLayout(){let e=!!(this._replyToId&&this._replyToData),t=this._threadItems,n=t.length>1;return i`
1167
+ `}_renderThreadComposeLayout(){let e=!!(this._replyToId&&this._replyToData),t=this._threadItems,n=t.length>1;return a`
1168
1168
  <div
1169
- class=${b({"compose-thread-layout":!0,"compose-thread-compose-layout":!0,"compose-reply-compose-layout":e})}
1169
+ class=${S({"compose-thread-layout":!0,"compose-thread-compose-layout":!0,"compose-reply-compose-layout":e})}
1170
1170
  @jant:compose-content-changed=${()=>this._scheduleDraftSave()}
1171
1171
  >
1172
1172
  ${e?this._renderReplyContext():this._renderTranslationContext()}
@@ -1178,7 +1178,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1178
1178
  ${ee(t,e=>e.id,(t,r)=>this._renderThreadPost(t,r,n,r===0&&!e))}
1179
1179
  ${this._renderAddToThreadRow()}
1180
1180
  </div>
1181
- `}_renderAddThreadTrigger(e){let t=!this._hasWorkToLose(),n=i`
1181
+ `}_renderAddThreadTrigger(e){let t=!this._hasWorkToLose(),n=a`
1182
1182
  <button
1183
1183
  type="button"
1184
1184
  class="compose-thread-add-btn"
@@ -1187,12 +1187,12 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1187
1187
  >
1188
1188
  Add to thread
1189
1189
  </button>
1190
- `;return e?i`
1190
+ `;return e?a`
1191
1191
  <div class="compose-thread-add-row">
1192
1192
  <div class="compose-thread-add-dot"></div>
1193
1193
  ${n}
1194
1194
  </div>
1195
- `:i`<div class="compose-add-thread-trigger">${n}</div>`}render(){let t=!!(this._replyToId&&this._replyToData),n=this._threadItems.length>0,r=this._openingEdit,a=i`<jant-compose-editor
1195
+ `:a`<div class="compose-add-thread-trigger">${n}</div>`}render(){let t=!!(this._replyToId&&this._replyToData),n=this._threadItems.length>0,r=this._openingEdit,i=a`<jant-compose-editor
1196
1196
  .format=${this._format}
1197
1197
  .labels=${this.labels}
1198
1198
  .uploadMaxFileSize=${this.uploadMaxFileSize}
@@ -1200,36 +1200,36 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1200
1200
  .titleByDefault=${!t&&e._getNoteTitleDefault()}
1201
1201
  .positionLabel=${this._positionLabel(0)}
1202
1202
  .badgeLabel=${this._editPostId?this.labels.editing:``}
1203
- .headerExtra=${i`${this._renderPostMetaControl(0)}
1203
+ .headerExtra=${a`${this._renderPostMetaControl(0)}
1204
1204
  ${this._renderCloseComposeControl()}`}
1205
1205
  .slashCommandDiscovered=${this.slashCommandDiscovered}
1206
1206
  @jant:format-change=${e=>{e.stopPropagation(),this._switchFormat(e.detail.format)}}
1207
1207
  @jant:compose-status=${e=>{e.stopPropagation(),this._handleRowStatus(Qe,e.detail)}}
1208
- ></jant-compose-editor>`,s=r||n||this._editPostId?o:this._renderAddThreadTrigger(t);return i`
1208
+ ></jant-compose-editor>`,o=r||n||this._editPostId?s:this._renderAddThreadTrigger(t);return a`
1209
1209
  <div
1210
- class=${b({"compose-dialog-inner":!0,"compose-dialog-inner-page":this.pageMode,"compose-dialog-inner-suspended":this._addCollectionPanelOpen})}
1210
+ class=${S({"compose-dialog-inner":!0,"compose-dialog-inner-page":this.pageMode,"compose-dialog-inner-suspended":this._addCollectionPanelOpen})}
1211
1211
  tabindex="-1"
1212
1212
  aria-hidden=${this._addCollectionPanelOpen?`true`:`false`}
1213
1213
  ?inert=${this._addCollectionPanelOpen}
1214
1214
  >
1215
1215
  <div class="compose-scroll">
1216
- ${r?this._renderEditLoadingState():n?this._renderThreadComposeLayout():t?i`
1216
+ ${r?this._renderEditLoadingState():n?this._renderThreadComposeLayout():t?a`
1217
1217
  <div
1218
1218
  class="compose-thread-layout compose-reply-compose-layout"
1219
1219
  >
1220
1220
  ${this._renderReplyContext()}
1221
1221
  <div class="compose-editor-row is-current">
1222
1222
  <div class="compose-thread-dot"></div>
1223
- ${a}
1223
+ ${i}
1224
1224
  </div>
1225
- ${s}
1225
+ ${o}
1226
1226
  </div>
1227
- `:i`${this._renderTranslationContext()}${a}${s}`}
1227
+ `:a`${this._renderTranslationContext()}${i}${o}`}
1228
1228
  </div>
1229
- ${r?o:i`<div
1230
- class=${b({"compose-action-row":!0,"compose-action-row-without-collection":!!this._replyToId,"compose-action-row-overlay-open":this._showPublishPanel||this._showCollection||this._showLanguagePicker})}
1229
+ ${r?s:a`<div
1230
+ class=${S({"compose-action-row":!0,"compose-action-row-without-collection":!!this._replyToId,"compose-action-row-overlay-open":this._showPublishPanel||this._showCollection||this._showLanguagePicker})}
1231
1231
  >
1232
- ${this._replyToId?o:this._renderCollectionSelector()}
1232
+ ${this._replyToId?s:this._renderCollectionSelector()}
1233
1233
  ${this._renderLanguageControl()}
1234
1234
  ${this._renderPublishButton()}
1235
1235
  </div>
@@ -1297,7 +1297,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1297
1297
  <path d="M12.15 3H15v2.85" />
1298
1298
  <path d="M3 12.15V15h2.85" />
1299
1299
  <path d="M15 12.15V15h-2.85" />
1300
- `};function J(e){return i`<svg
1300
+ `};function J(e){return a`<svg
1301
1301
  class="compose-tool-icon"
1302
1302
  width="18"
1303
1303
  height="18"
@@ -1308,8 +1308,8 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1308
1308
  stroke-linejoin="round"
1309
1309
  aria-hidden="true"
1310
1310
  >
1311
- ${v(e)}
1312
- </svg>`}function zt(e){return i`<span
1311
+ ${y(e)}
1312
+ </svg>`}function zt(e){return a`<span
1313
1313
  class=${`decorative-quote-mark ${e}`}
1314
1314
  aria-hidden="true"
1315
1315
  >
@@ -1318,9 +1318,9 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1318
1318
  role="presentation"
1319
1319
  focusable="false"
1320
1320
  >
1321
- ${v(vt)}
1321
+ ${y(vt)}
1322
1322
  </svg>
1323
- </span>`}function Bt(e,t){let n=e.state.doc.content.size,r=Math.max(1,Math.min(t.from,n));return{from:r,to:Math.max(r,Math.min(t.to,n))}}var Vt=class t extends c{static properties={format:{type:String},labels:{type:Object},uploadMaxFileSize:{type:Number},threadItem:{type:Boolean,attribute:`thread-item`},removable:{type:Boolean},inlineFormat:{type:Boolean,attribute:`inline-format`},titleByDefault:{type:Boolean,attribute:`title-by-default`},positionLabel:{type:String,attribute:`position-label`},badgeLabel:{type:String,attribute:`badge-label`},headerExtra:{attribute:!1},slashCommandDiscovered:{type:Boolean},_title:{state:!0},_bodyJson:{state:!0},_url:{state:!0},_quoteText:{state:!0},_quoteAuthor:{state:!0},_rating:{state:!0},_showTitle:{state:!0},_showRating:{state:!0},_attachedTexts:{state:!0},_attachments:{state:!0},_attachmentOrder:{state:!0},_failedAttachmentPreviews:{state:!0},_showAltPanel:{state:!0},_altPanelIndex:{state:!0},_showEmojiPicker:{state:!0},_showUrlValidation:{state:!0},_showLinkTitleValidation:{state:!0}};_editor=null;_fileInput=null;_lastFocusedField=null;_lastEditorSelection=null;_emojiPickerEl=null;_emojiContainer=null;_urlStatusId=`compose-url-status-${L()}`;_onDocClickBound=this._onDocumentClick.bind(this);_filePickerCleanup=null;_suppressAttachedTextOpenUntil=0;_suppressContentChangedOnce=!1;#e=!1;#t=0;#n=new Set;#r=0;#i;#a=null;#o=null;#s=null;#c;createRenderRoot(){return this}constructor(){super(),this.format=`note`,this.labels={},this.uploadMaxFileSize=1024,this.threadItem=!1,this.removable=!1,this.inlineFormat=!1,this.titleByDefault=!0,this.positionLabel=``,this.badgeLabel=``,this.headerExtra=null,this.slashCommandDiscovered=!1,this._title=``,this._bodyJson=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!0,this._showRating=!1,this._attachedTexts=[],this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showEmojiPicker=!1,this._showUrlValidation=!1,this._showLinkTitleValidation=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),this.addEventListener(`dragenter`,this._onDragEnter),this.addEventListener(`dragover`,this._onDragOver,!0),this.addEventListener(`dragleave`,this._onDragLeave),this.addEventListener(`drop`,this._onDrop),this.#b()?.addEventListener(`change`,this._onPointerTypeChange)}disconnectedCallback(){super.disconnectedCallback(),this.#h(),this._editor?.destroy(),this._editor=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),document.removeEventListener(`click`,this._onDocClickBound),this.removeEventListener(`dragenter`,this._onDragEnter),this.removeEventListener(`dragover`,this._onDragOver,!0),this.removeEventListener(`dragleave`,this._onDragLeave),this.removeEventListener(`drop`,this._onDrop),Pt(this),this._emojiContainer?.remove(),this._emojiPickerEl=null,this._filePickerCleanup?.(),this._filePickerCleanup=null,this.#b()?.removeEventListener(`change`,this._onPointerTypeChange)}#l=0;#u(e){let t=e.dataTransfer?.types;return t?Array.from(t).includes(`Files`):!1}_onDragEnter=e=>{this.#u(e)&&(this.#l+=1,this.classList.add(`compose-editor-dragover`))};_onDragOver=e=>{this.#u(e)&&(e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`))};_onDragLeave=e=>{this.#u(e)&&(this.#l=Math.max(0,this.#l-1),this.#l===0&&this.classList.remove(`compose-editor-dragover`))};_onDrop=e=>{if(this.#l=0,this.classList.remove(`compose-editor-dragover`),e.defaultPrevented)return;let t=ue(e.dataTransfer);if(t.length===0)return;e.preventDefault();let n=[],r=[];for(let e of t)this._editor&&this._shouldPasteInlineImage(e)?n.push(e):r.push(e);for(let e of n)this._uploadAndInsertImage(e);r.length>0&&this.addFiles(r)};_onSlashCommandDiscovered=()=>{Lt()};_onSlashImage=()=>{document.querySelector(`.compose-fullscreen-dialog[open]`)||this._editor&&this._triggerSlashImagePicker()};_slashImageInput=null;_triggerSlashImagePicker(){this._slashImageInput||(this._slashImageInput=document.createElement(`input`),this._slashImageInput.type=`file`,this._slashImageInput.accept=`image/*`,this._slashImageInput.style.display=`none`,this._slashImageInput.addEventListener(`change`,()=>{let e=this._slashImageInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._slashImageInput&&(this._slashImageInput.value=``)}),document.body.appendChild(this._slashImageInput)),this._trackFilePickerSession(this._slashImageInput),this._slashImageInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=this.#t,r=M(t,e).finally(()=>{n===this.#t&&this.#n.delete(r)});return this.#n.add(r),r}#d(e){if(e.startsWith(`data:`))return!0;if(!/^https?:\/\//i.test(e))return!1;let t;try{t=new URL(e).origin}catch{return!1}if(t===window.location.origin)return!1;let n=document.documentElement.dataset.mediaBase;return!(n&&e.startsWith(n))}#f(e){let t=this._editor;if(!t){k(e);return}let n=e.startsWith(`data:`)?async()=>{let t=await(await fetch(e)).blob(),n=new File([t],`pasted-image`,{type:t.type||`image/png`});return(await de(n)).url}:async()=>(await j(e)).url,r=async()=>{try{return await n()}catch(e){throw this.#p(),e}},i=this.#t,a=se(t,e,r).finally(()=>{k(e),i===this.#t&&this.#n.delete(a)});this.#n.add(a)}#p(){this.#r+=1,this.#i===void 0&&(this.#i=setTimeout(()=>{this.#m()},800))}#m(){this.#i=void 0;let e=this.#r;if(this.#r=0,e<=0||!this.isConnected)return;let t=e===1?this.labels.imageNotRehosted??`An image couldn't be saved to your library — its original link was kept.`:(this.labels.imagesNotRehosted??`{count} images couldn't be saved to your library — their original links were kept.`).replace(`{count}`,String(e));l(t,`error`)}hasPendingInlineImageUploads(){return this.#n.size>0}async waitForPendingInlineImageUploads(){let e=this.#t;for(;e===this.#t&&this.#n.size>0;)await Promise.allSettled(Array.from(this.#n))}#h(){this.#t+=1,this.#n.clear(),this.#i!==void 0&&(clearTimeout(this.#i),this.#i=void 0),this.#r=0}adoptPendingUploads(){if(!this._editor)return;let e=this.#t,t=fe(this._editor);for(let n of t){let t=n.finally(()=>{e===this.#t&&this.#n.delete(t)});this.#n.add(t)}}_dispatchFilePickerEvent(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_trackFilePickerSession(e){this._filePickerCleanup?.();let t=!1,n=e=>{t||(t=!0,o(),this._dispatchFilePickerEvent(`jant:file-picker-close`,{cancelled:e}))},r=()=>n(!1),i=()=>n(!0),a=()=>{globalThis.setTimeout(()=>{n(!(e.files&&e.files.length>0))},0)},o=()=>{e.removeEventListener(`change`,r),e.removeEventListener(`cancel`,i),window.removeEventListener(`focus`,a),this._filePickerCleanup===o&&(this._filePickerCleanup=null)};this._filePickerCleanup=o,e.addEventListener(`change`,r,{once:!0}),e.addEventListener(`cancel`,i,{once:!0}),window.addEventListener(`focus`,a,{once:!0}),this._dispatchFilePickerEvent(`jant:file-picker-open`)}_isEmptyDoc(e){return!e.content||e.content.length===0||e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0||e.content.every(e=>e.type===`hardBreak`)))}_normalizeDocJson(e){return e?this._isEmptyDoc(e)?null:e:null}_isSelectionInsideTopLevelBlock(e){let t=this._editor;return t?t.state.selection.$from.index(0)===e:!1}_removedTopLevelSize(e){let t=this._editor?.state.doc;if(!t)return 0;let n=0;for(let r=0;r<=e.headingIndex;r+=1)n+=t.child(r)?.nodeSize??0;return n}promoteLeadingH1Title(e={}){if(this.format!==`note`||this._title.trim())return!1;let t=gt(this._editor?.getJSON()??this._bodyJson);if(!t||!e.force&&this._isSelectionInsideTopLevelBlock(t.headingIndex))return!1;let n=this._editor,r=!!n?.isFocused,i=n?.state.selection.from??null,a=this._removedTopLevelSize(t);if(this._title=t.title,this._showTitle=!0,this._bodyJson=t.bodyJson,n&&(t.bodyJson?n.commands.setContent(t.bodyJson):n.commands.clearContent(),r&&i!==null)){let e=n.state.doc.content.size;e>0&&(n.commands.setTextSelection(Math.max(1,Math.min(i-a,e))),n.commands.focus())}return!0}getNormalizedBodyJson(){return this._normalizeDocJson(this._bodyJson)}getEffectiveAttachedTexts(){return this._attachedTexts.flatMap(e=>{let t=this._normalizeDocJson(e.bodyJson);return t?[{...e,bodyJson:t,originalBodyJson:this._normalizeDocJson(e.originalBodyJson??null)}]:[]})}getEffectiveAttachmentOrder(){let e=new Set(this.getEffectiveAttachedTexts().map(e=>e.clientId)),t=new Set(this._attachments.map(e=>e.clientId));return this._attachmentOrder.filter(n=>t.has(n)||e.has(n))}_getEffectiveRating(){return this._showRating?this._rating:0}getData(){let e=this.getNormalizedBodyJson(),t=this.getEffectiveAttachedTexts(),n=this.getEffectiveAttachmentOrder(),r=e?JSON.stringify(e):``,i={rating:this._getEffectiveRating(),attachedTexts:t,attachments:this._attachments,attachmentOrder:n};switch(this.format){case`link`:return{...i,title:this._title,body:r,url:this._url,quoteText:``,quoteAuthor:``};case`quote`:return{...i,title:``,body:r,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor};default:return{...i,title:this._showTitle?this._title:``,body:r,url:``,quoteText:``,quoteAuthor:``}}}getStatus(){let e=this.getData(),t=!!e.body||!!e.title.trim()||!!e.url.trim()||!!e.quoteText.trim()||!!e.quoteAuthor.trim()||e.rating>0||e.attachments.length>0||e.attachedTexts.length>0,n=!this.getUrlValidationMessage()&&!this.getLinkTitleValidationMessage(),r;switch(this.format){case`link`:r=n;break;case`quote`:r=n&&!!e.quoteText.trim();break;default:r=n&&t}return{hasContent:t,publishable:r}}#g=null;#_(){let e=this.getStatus();(this.#g?.hasContent!==e.hasContent||this.#g?.publishable!==e.publishable)&&(this.#g=e,this.dispatchEvent(new CustomEvent(`jant:compose-status`,{bubbles:!0,detail:e})))}setTitleDefault(e){this.titleByDefault=e,this._showTitle=e}reset(){this.#h(),this._title=``,this._showTitle=this.titleByDefault,this._bodyJson=null,this._editor?.commands.clearContent(),this._lastEditorSelection=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showRating=!1,this._attachedTexts=[];for(let e of this._attachments)URL.revokeObjectURL(e.previewUrl),e.posterUrl&&URL.revokeObjectURL(e.posterUrl);this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.closeEmojiPicker()}updateAttachmentStatus(e,t,n,r,i){this._attachments=this._attachments.map(a=>a.clientId===e?{...a,status:t,mediaId:n,error:r,remoteUrl:i??a.remoteUrl}:a)}updateAttachmentPreview(e,t){this._setAttachmentPreviewFailure(e,!1),this._attachments=this._attachments.map(n=>n.clientId===e?(URL.revokeObjectURL(n.previewUrl),n.posterUrl&&URL.revokeObjectURL(n.posterUrl),{...n,file:t,previewUrl:URL.createObjectURL(t),posterUrl:null}):n)}updateAttachmentPoster(e,t){let n=URL.createObjectURL(t);this._attachments=this._attachments.map(t=>t.clientId===e?{...t,posterUrl:n}:t)}updateAttachmentProgress(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?{...n,progress:t}:n)}focusInput(e){if(this.format===`link`){this.focusUrlInput(e);return}if(this.format===`quote`){this._focusTextControl(this.querySelector(`.compose-quote-text`),e);return}if(e){this._editor?.commands.focus(e);return}this._editor?.commands.focus()}focusSelection(e){if(this.format!==`note`||!this._editor){this.focusInput();return}let t=e??this.getEditorSelection();if(!t){this.focusInput();return}let n=Bt(this._editor,t);this._lastEditorSelection=n,this._editor.chain().focus().setTextSelection(n).run()}focusUrlInput(e){this._focusTextControl(this.querySelector(`.compose-url-input`),e)}focusLinkTitleInput(e){this._focusTextControl(this.querySelector(`.compose-link-title`),e)}getUrlValidationMessage(){return this.format===`note`?null:this._url.trim()?e(this._url)?null:this.labels.urlInvalid:this.format===`link`?this.labels.linkUrlRequired:null}getLinkTitleValidationMessage(){return this.format===`link`?this._title.trim()?null:this.labels.linkTitleRequired:null}revealUrlValidation(){return this._showUrlValidation=!0,this.getUrlValidationMessage()}revealLinkTitleValidation(){return this._showLinkTitleValidation=!0,this.getLinkTitleValidationMessage()}getEditorSelection(){return this._readEditorSelection()??this._lastEditorSelection}isEmojiPickerOpen(){return this._showEmojiPicker}_readEditorSelection(){if(!this._editor)return null;let{from:e,to:t}=this._editor.state.selection;return{from:e,to:t}}_focusTextControl(e,t){if(!e||(e.focus(),!t))return;let n=t===`end`?e.value.length:0;e.setSelectionRange(n,n)}_initEditor(){let e=this.querySelector(`.compose-tiptap-body`);e&&!this._editor&&(this.dataset.slashCommandDiscovered=this.slashCommandDiscovered?`true`:`false`,this._editor=le({element:e,placeholder:this.format===`note`?this.labels.bodyPlaceholder:this.labels.thoughtsPlaceholder,content:this._bodyJson,toolbarMode:`compose`,onUpdate:e=>{this._bodyJson=e,this.promoteLeadingH1Title(),Pt(this)},onFocus:()=>{this._lastFocusedField=null,this._editor?.isEmpty&&It(this)},onBlur:()=>{this.promoteLeadingH1Title({force:!0})},onSelectionUpdate:e=>{this._lastEditorSelection=e},pasteMedia:{shouldInsertInline:e=>this._shouldPasteInlineImage(e),uploadInlineImage:e=>this._uploadAndInsertImage(e),onPasteFiles:e=>{this.addFiles(e)}},rehostImages:{shouldRehost:e=>this.#d(e),rehost:e=>this.#f(e)},imageNodeLabels:Rt(this.labels),tableControlLabels:this.labels.tableControls}),this._lastEditorSelection=this._readEditorSelection(),this.adoptPendingUploads())}_destroyEditor(){this.#h(),this._editor?.destroy(),this._editor=null}static _CONTENT_PROPS=new Set([`_title`,`_bodyJson`,`_url`,`_quoteText`,`_quoteAuthor`,`_rating`,`_showTitle`,`_showRating`,`_attachedTexts`,`_attachmentOrder`]);willUpdate(e){super.willUpdate(e),!this.hasUpdated&&!this.#e&&(this._showTitle=this.titleByDefault)}updated(e){if(super.updated(e),this._editor||this._initEditor(),e.has(`format`)&&e.get(`format`)!==void 0&&(this._showUrlValidation&&=!1,this._showLinkTitleValidation&&=!1,this._destroyEditor(),this.updateComplete.then(()=>this._initEditor())),(e.has(`_attachmentOrder`)||e.has(`_attachments`)||e.has(`_attachedTexts`))&&(e.has(`_attachments`)&&this._syncFailedAttachmentPreviews(),this._attachmentOrder.length>1?this.#x():(this.#a?.destroy(),this.#a=null),this.#v()),this.#_(),this._suppressContentChangedOnce)this._suppressContentChangedOnce=!1;else for(let n of e.keys())if(t._CONTENT_PROPS.has(n)){this.dispatchEvent(new Event(`jant:compose-content-changed`,{bubbles:!0}));break}}getEditorState(){return{json:this._editor?.getJSON()??this._bodyJson,title:this._title,showTitle:this._showTitle,selection:this.getEditorSelection()}}getConvertibleFields(){return{title:this._title,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor,showTitle:this._showTitle,bodyJson:this._normalizeDocJson(this._editor?.getJSON()??this._bodyJson)}}applyConvertedFields(e){this._suppressContentChangedOnce=!0,this._title=e.title,this._url=e.url,this._quoteText=e.quoteText,this._quoteAuthor=e.quoteAuthor,this._showTitle=e.showTitle,this._bodyJson=e.bodyJson}takeOver(e){this._title=e._title,this._showTitle=e._showTitle,this.#e=!0,this._bodyJson=e._editor?.getJSON()??e._bodyJson,this._url=e._url,this._quoteText=e._quoteText,this._quoteAuthor=e._quoteAuthor,this._rating=e._rating,this._showRating=e._showRating,this._attachedTexts=[...e._attachedTexts],this._attachments=[...e._attachments],this._attachmentOrder=[...e._attachmentOrder],this._lastEditorSelection=e.getEditorSelection(),this._editor&&(this._editor.commands.setContent(this._bodyJson??{type:`doc`,content:[{type:`paragraph`}]}),this.adoptPendingUploads()),this.#_()}hasAttachment(e){return this._attachments.some(t=>t.clientId===e)}populate(e){if(e.title&&(this._title=e.title),e.url&&(this._url=e.url),e.quoteText&&(this._quoteText=e.quoteText),e.quoteAuthor&&(this._quoteAuthor=e.quoteAuthor),e.rating&&e.rating>0&&(this._rating=e.rating,this._showRating=!0),e.showTitle===void 0?e.title&&e.format===`note`&&(this._showTitle=!0):this._showTitle=e.showTitle,e.showRating!==void 0&&(this._showRating=e.showRating),this._failedAttachmentPreviews=[],e.bodyJson)try{let t=JSON.parse(e.bodyJson);this._bodyJson=t,this._editor&&this._editor.commands.setContent(t)}catch{}if(e.media?.length){let t=e.media.map(e=>({clientId:e.clientId??L(),file:new File([],e.originalName??`existing`,{type:e.mimeType}),previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,status:`done`,progress:null,mediaId:e.id,persisted:e.persisted??!1,remoteUrl:e.previewUrl,alt:e.alt??``,error:null,summary:e.summary??null,chars:e.chars??null}));this._attachments=t,this._attachmentOrder=t.map(e=>e.clientId)}if(e.textAttachments?.length){let t=e=>{try{return JSON.parse(e)}catch{return null}},n=e.textAttachments.map(e=>{let n=t(e.bodyJson);return{clientId:e.clientId??L(),bodyJson:n,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:e.originalBodyJson===void 0?n:t(e.originalBodyJson)}});this._attachedTexts=n,this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)]}if(e.attachmentOrder?.length){let t=e.attachmentOrder.map(e=>this._attachments.find(t=>t.mediaId===e||t.clientId===e)?.clientId||this._attachedTexts.find(t=>t.mediaId===e||t.clientId===e)?.clientId).filter(e=>e!==void 0),n=this._attachmentOrder.filter(e=>!t.includes(e));this._attachmentOrder=[...t,...n]}this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.#_()}setEditorState(e,t,n,r){this._bodyJson=e,this._title=t,this.format===`note`&&(this._showTitle=n||t.length>0),this._editor&&this._editor.commands.setContent(e??{type:`doc`,content:[{type:`paragraph`}]}),this._lastEditorSelection=r??this._readEditorSelection(),this.#_()}static SUMMARY_LENGTH=100;_computeSummary(e){let n=e.replace(/\s+/g,` `).trim();return n.length<=t.SUMMARY_LENGTH?n:n.slice(0,t.SUMMARY_LENGTH)+`…`}_openAttachedText(){let e={clientId:L(),bodyJson:null,bodyHtml:``,summary:``};this._attachedTexts=[...this._attachedTexts,e],this._attachmentOrder=[...this._attachmentOrder,e.clientId];let t=this._attachedTexts.length-1;this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:t}}))}_moveAttachment(e,t,n=`handle`){let r=this._attachmentOrder.indexOf(e),i=r+t;if(r===-1||i<0||i>=this._attachmentOrder.length)return;let a=[...this._attachmentOrder],[o]=a.splice(r,1);o&&(a.splice(i,0,o),this._attachmentOrder=a,this.#s={clientId:e,direction:t,focusTarget:n},this.#S(e))}#v(){let e=this.#s;if(!e)return;this.#s=null;let t=this.querySelector(`[data-attachment-id="${e.clientId}"]`);if(t){if(e.focusTarget===`handle`){t.querySelector(`[data-attachment-sortable]`)?.focus({preventScroll:!0});return}(this.#y(t,e.direction)??this.#y(t,e.direction===1?-1:1))?.focus({preventScroll:!0})}}#y(e,t){let n=e.querySelector(`[data-attachment-move="${t===-1?`earlier`:`later`}"]`);return n&&!n.disabled?n:null}_handleAttachmentKeydown(e,t,n){if(t.key===`ArrowLeft`||t.key===`ArrowUp`){t.preventDefault(),this._moveAttachment(e,-1);return}if(t.key===`ArrowRight`||t.key===`ArrowDown`){t.preventDefault(),this._moveAttachment(e,1);return}n&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n())}#b(){return this.#c===void 0&&(this.#c=typeof window.matchMedia==`function`?window.matchMedia(`(pointer: coarse)`):null),this.#c}_onPointerTypeChange=()=>{this.#a?.destroy(),this.#a=null,this.#x()};#x(){let e=this.querySelector(`[data-attachment-list]`);!e||this.#a||this._attachmentOrder.length<=1||this.#b()?.matches||(this.#a=ne.create(e,{...te,chosenClass:`compose-attachment-chosen`,delay:250,direction:`horizontal`,dragClass:`compose-attachment-drag`,filter:`button, a, input, textarea, select, option, [contenteditable='true']`,ghostClass:`compose-attachment-ghost`,handle:`[data-attachment-sortable]`,preventOnFilter:!1,scroll:e,onChoose:()=>{E(e,!0)},onStart:e=>{this.#o=O(e)},onUnchoose:()=>{E(e,!1)},onEnd:t=>{let n=D(e,`[data-attachment-id]`,`attachmentId`);if(w(e,t,this.#o),this.#o=null,E(e,!1),this.#a?.destroy(),this.#a=null,n.length===this._attachmentOrder.length){this._attachmentOrder=n;let{movedId:e}=T(n,t.newIndex);e&&(this._suppressAttachedTextOpenUntil=Date.now()+250,this.#S(e))}}}))}#S(e){this.updateComplete.then(()=>{this.querySelector(`[data-attachment-id="${e}"]`)?.scrollIntoView({behavior:`smooth`,block:`nearest`,inline:`nearest`})})}_maybeEditAttachedText(e){Date.now()<this._suppressAttachedTextOpenUntil||this._editAttachedText(e)}_editAttachedText(e){this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:e}}))}_removeAttachedText(e){let t=this._attachedTexts[e];this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}updateAttachedText(e,t,n){let r=this._normalizeDocJson(t),i=this._extractPlainText(r);this._attachedTexts=this._attachedTexts.map((t,a)=>a===e?{...t,bodyJson:r,bodyHtml:r?n??``:``,summary:this._computeSummary(i)}:t)}closeAttachedPanel(e){let t=this._attachedTexts[e];t&&(t.mediaId||this._hasAttachedTextContent(t.bodyJson)||(this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)))}_hasAttachedTextContent(e){let t=this._normalizeDocJson(e);return t?this._extractPlainText(t).trim().length>0:!1}_extractPlainText(e){if(!e)return``;let t=``,n=e=>{e.text&&(t+=e.text),e.content&&e.content.forEach(n)};return n(e),t}_onInput(e,t){let n=t.target;this[e]=n.value,n.tagName===`TEXTAREA`&&this._autoResize(n)}_autoResize(e){e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`}#C=null;#w=null;_recordBodyPress=e=>{this.#C=e.target,this.#w=null};_recordBodyRelease=e=>{this.#w=e.target};_focusBodyFromBlankSpace=e=>{let t=this.#C,n=this.#w;if(this.#C=null,this.#w=null,t!==e.target||n!==e.target)return;let r=e.target;r&&(r.classList.contains(`compose-body`)||r.classList.contains(`compose-field-enter`)||r.classList.contains(`compose-tiptap-wrap`))&&this._editor?.commands.focus(`end`)};_setRating(e){this._rating=this._rating===e?0:e}_shouldPasteInlineImage(e){return!e.type.startsWith(`image/`)||this.format!==`note`||!this._showTitle?!1:this._title.trim().length>0}_openFilePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.multiple=!0,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>this._handleFilesSelected()),this.appendChild(this._fileInput)),this._fileInput.value=``,this._trackFilePickerSession(this._fileInput),this._fileInput.click()}_handleFilesSelected(){let e=this._fileInput?.files;e&&e.length!==0&&this.addFiles(e)}addFiles(e){let t=Array.from(e);if(t.length===0)return;let n=[],r=[];for(let e of t){let t=Ye(e,{maxFileSizeMB:this.uploadMaxFileSize});if(t){l(t,`error`);continue}let i=L(),a=URL.createObjectURL(e);n.push({clientId:i,file:e,previewUrl:a,posterUrl:null,status:`pending`,progress:null,mediaId:null,persisted:!1,remoteUrl:null,alt:``,error:null,summary:null,chars:null}),r.push({file:e,clientId:i})}if(n.length!==0){this._attachments=[...this._attachments,...n],this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)];for(let e of n)F(e.file.type)===`text`&&e.file.text().then(t=>{let n=this._computeSummary(t),r=t.length;this._attachments=this._attachments.map(t=>t.clientId===e.clientId?{...t,summary:n,chars:r}:t)});this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:r}}))}}removeAttachment(e){let t=this._attachments.findIndex(t=>t.clientId===e);t!==-1&&this._removeAttachment(t)}_removeAttachment(e){let t=this._attachments[e];t&&(this._setAttachmentPreviewFailure(t.clientId,!1),URL.revokeObjectURL(t.previewUrl),t.posterUrl&&URL.revokeObjectURL(t.posterUrl),this.dispatchEvent(new CustomEvent(`jant:attachment-removed`,{bubbles:!0,detail:{clientId:t.clientId,mediaId:t.mediaId,persisted:t.persisted}}))),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)),this._attachments=this._attachments.filter((t,n)=>n!==e),this._showAltPanel&&this._altPanelIndex===e?(this._showAltPanel=!1,this.dispatchEvent(new CustomEvent(`jant:alt-panel-close`,{bubbles:!0}))):this._showAltPanel&&this._altPanelIndex>e&&--this._altPanelIndex}_retryAllFailed(){let e=this._attachments.filter(e=>e.status===`error`);e.length!==0&&(this._attachments=this._attachments.map(e=>e.status===`error`?{...e,status:`pending`,progress:null,error:null}:e),this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:e.map(e=>({file:e.file,clientId:e.clientId}))}})))}_openAltPanel(e){this._altPanelIndex=e,this._showAltPanel=!0,this.dispatchEvent(new CustomEvent(`jant:alt-panel-open`,{bubbles:!0,detail:{index:e}}))}updateAlt(e,t){this._attachments=this._attachments.map((n,r)=>r===e?{...n,alt:t}:n)}_onFieldFocus(e){let t=e.target;this._lastFocusedField=t}_handleTitleKeydown(e){e.isComposing||e.keyCode===229||e.key!==`Enter`||e.metaKey||e.ctrlKey||e.altKey||(e.preventDefault(),this._editor?.commands.focus(`start`))}_toggleEmojiPicker(){this._showEmojiPicker?this.closeEmojiPicker():(this._showEmojiPicker=!0,this._mountEmojiPicker(),globalThis.setTimeout(()=>{document.addEventListener(`click`,this._onDocClickBound)},0))}closeEmojiPicker(e){if(!this._showEmojiPicker){e?.restoreFocus&&this._restoreEmojiFocus();return}this._showEmojiPicker=!1,this._emojiContainer?.remove(),this._emojiPickerEl=null,document.removeEventListener(`click`,this._onDocClickBound),e?.restoreFocus&&this._restoreEmojiFocus()}_restoreEmojiFocus(){let e=this._lastFocusedField;if(e&&this.contains(e)&&!e.disabled){e.focus();return}this.focusSelection()}_onDocumentClick(e){let t=e.target;this.querySelector(`.compose-emoji-btn`)?.contains(t)||this._emojiContainer?.contains(t)||this.closeEmojiPicker()}async _mountEmojiPicker(){let e=this.closest(`dialog`);if(this._emojiContainer||(this._emojiContainer=document.createElement(`div`),this._emojiContainer.className=`compose-emoji-picker`),(e??document.body).appendChild(this._emojiContainer),!this._emojiPickerEl){let[{default:e},{Picker:t}]=await Promise.all([y(()=>import(`./chunks/emoji-mart-C4RpRKcU.js`).then(e=>e.n),__vite__mapDeps([0,1])),y(()=>import(`./chunks/emoji-mart-C4RpRKcU.js`).then(e=>e.t),__vite__mapDeps([0,1]))]);if(!this._showEmojiPicker)return;let n=new t({data:e,onEmojiSelect:e=>{this._insertEmoji(e.native),this.closeEmojiPicker()},theme:`auto`,previewPosition:`none`,skinTonePosition:`none`});this._emojiPickerEl=n}this._emojiContainer.innerHTML=``,this._emojiContainer.appendChild(this._emojiPickerEl);let t=this.querySelector(`.compose-emoji-btn`);if(t&&e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=n.left-r.left,a=n.top-r.top,o=i+n.width/2-176;o=Math.max(-r.left+8,Math.min(o,r.width-8));let s=a-435-8;r.top+s<8&&(s=a+n.height+8),this._emojiContainer.style.left=`${o}px`,this._emojiContainer.style.top=`${s}px`}}_insertEmoji(e){let t=this._lastFocusedField;if(!t){this._editor&&this._editor.chain().focus().insertContent(e).run();return}let n=t.selectionStart??t.value.length,r=t.selectionEnd??n,i=t.value.slice(0,n),a=t.value.slice(r);t.value=i+e+a,t.dispatchEvent(new Event(`input`,{bubbles:!0}));let o=n+e.length;globalThis.requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(o,o)})}_getCategory(e){return F(e.file.type)}_formatSize(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}_formatChars(e){return e<1e3?`${e} chars`:e<1e6?`${parseFloat((e/1e3).toFixed(1))}k chars`:`${parseFloat((e/1e6).toFixed(1))}M chars`}_renderFileIcon(e,t){let n;return n=e===`application/pdf`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`:e===`text/markdown`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`:e===`text/csv`?`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`:F(e)===`archive`?`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`:e===`text/html; charset=utf-8`?`<line x1="16" y1="11" x2="8" y2="11"/><line x1="16" y1="14" x2="8" y2="14"/><line x1="12" y1="17" x2="8" y2="17"/>`:`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`,i`<svg
1323
+ </span>`}function Bt(e,t){let n=e.state.doc.content.size,r=Math.max(1,Math.min(t.from,n));return{from:r,to:Math.max(r,Math.min(t.to,n))}}var Vt=class t extends l{static properties={format:{type:String},labels:{type:Object},uploadMaxFileSize:{type:Number},threadItem:{type:Boolean,attribute:`thread-item`},removable:{type:Boolean},inlineFormat:{type:Boolean,attribute:`inline-format`},titleByDefault:{type:Boolean,attribute:`title-by-default`},positionLabel:{type:String,attribute:`position-label`},badgeLabel:{type:String,attribute:`badge-label`},headerExtra:{attribute:!1},slashCommandDiscovered:{type:Boolean},_title:{state:!0},_bodyJson:{state:!0},_url:{state:!0},_quoteText:{state:!0},_quoteAuthor:{state:!0},_rating:{state:!0},_showTitle:{state:!0},_showRating:{state:!0},_attachedTexts:{state:!0},_attachments:{state:!0},_attachmentOrder:{state:!0},_failedAttachmentPreviews:{state:!0},_showAltPanel:{state:!0},_altPanelIndex:{state:!0},_showEmojiPicker:{state:!0},_showUrlValidation:{state:!0},_showLinkTitleValidation:{state:!0}};_editor=null;_fileInput=null;_lastFocusedField=null;_lastEditorSelection=null;_emojiPickerEl=null;_emojiContainer=null;_urlStatusId=`compose-url-status-${L()}`;_onDocClickBound=this._onDocumentClick.bind(this);_filePickerCleanup=null;_suppressAttachedTextOpenUntil=0;_suppressContentChangedOnce=!1;#e=!1;#t=0;#n=new Set;#r=0;#i;#a=null;#o=null;#s=null;#c;createRenderRoot(){return this}constructor(){super(),this.format=`note`,this.labels={},this.uploadMaxFileSize=1024,this.threadItem=!1,this.removable=!1,this.inlineFormat=!1,this.titleByDefault=!0,this.positionLabel=``,this.badgeLabel=``,this.headerExtra=null,this.slashCommandDiscovered=!1,this._title=``,this._bodyJson=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!0,this._showRating=!1,this._attachedTexts=[],this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showEmojiPicker=!1,this._showUrlValidation=!1,this._showLinkTitleValidation=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),this.addEventListener(`dragenter`,this._onDragEnter),this.addEventListener(`dragover`,this._onDragOver,!0),this.addEventListener(`dragleave`,this._onDragLeave),this.addEventListener(`drop`,this._onDrop),this.#b()?.addEventListener(`change`,this._onPointerTypeChange)}disconnectedCallback(){super.disconnectedCallback(),this.#h(),this._editor?.destroy(),this._editor=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),document.removeEventListener(`click`,this._onDocClickBound),this.removeEventListener(`dragenter`,this._onDragEnter),this.removeEventListener(`dragover`,this._onDragOver,!0),this.removeEventListener(`dragleave`,this._onDragLeave),this.removeEventListener(`drop`,this._onDrop),Pt(this),this._emojiContainer?.remove(),this._emojiPickerEl=null,this._filePickerCleanup?.(),this._filePickerCleanup=null,this.#b()?.removeEventListener(`change`,this._onPointerTypeChange)}#l=0;#u(e){let t=e.dataTransfer?.types;return t?Array.from(t).includes(`Files`):!1}_onDragEnter=e=>{this.#u(e)&&(this.#l+=1,this.classList.add(`compose-editor-dragover`))};_onDragOver=e=>{this.#u(e)&&(e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`))};_onDragLeave=e=>{this.#u(e)&&(this.#l=Math.max(0,this.#l-1),this.#l===0&&this.classList.remove(`compose-editor-dragover`))};_onDrop=e=>{if(this.#l=0,this.classList.remove(`compose-editor-dragover`),e.defaultPrevented)return;let t=ue(e.dataTransfer);if(t.length===0)return;e.preventDefault();let n=[],r=[];for(let e of t)this._editor&&this._shouldPasteInlineImage(e)?n.push(e):r.push(e);for(let e of n)this._uploadAndInsertImage(e);r.length>0&&this.addFiles(r)};_onSlashCommandDiscovered=()=>{Lt()};_onSlashImage=()=>{document.querySelector(`.compose-fullscreen-dialog[open]`)||this._editor&&this._triggerSlashImagePicker()};_slashImageInput=null;_triggerSlashImagePicker(){this._slashImageInput||(this._slashImageInput=document.createElement(`input`),this._slashImageInput.type=`file`,this._slashImageInput.accept=`image/*`,this._slashImageInput.style.display=`none`,this._slashImageInput.addEventListener(`change`,()=>{let e=this._slashImageInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._slashImageInput&&(this._slashImageInput.value=``)}),document.body.appendChild(this._slashImageInput)),this._trackFilePickerSession(this._slashImageInput),this._slashImageInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=this.#t,r=M(t,e).finally(()=>{n===this.#t&&this.#n.delete(r)});return this.#n.add(r),r}#d(e){if(e.startsWith(`data:`))return!0;if(!/^https?:\/\//i.test(e))return!1;let t;try{t=new URL(e).origin}catch{return!1}if(t===window.location.origin)return!1;let n=document.documentElement.dataset.mediaBase;return!(n&&e.startsWith(n))}#f(e){let t=this._editor;if(!t){k(e);return}let n=e.startsWith(`data:`)?async()=>{let t=await(await fetch(e)).blob(),n=new File([t],`pasted-image`,{type:t.type||`image/png`});return(await de(n)).url}:async()=>(await j(e)).url,r=async()=>{try{return await n()}catch(e){throw this.#p(),e}},i=this.#t,a=se(t,e,r).finally(()=>{k(e),i===this.#t&&this.#n.delete(a)});this.#n.add(a)}#p(){this.#r+=1,this.#i===void 0&&(this.#i=setTimeout(()=>{this.#m()},800))}#m(){this.#i=void 0;let e=this.#r;if(this.#r=0,e<=0||!this.isConnected)return;let t=e===1?this.labels.imageNotRehosted??`An image couldn't be saved to your library — its original link was kept.`:(this.labels.imagesNotRehosted??`{count} images couldn't be saved to your library — their original links were kept.`).replace(`{count}`,String(e));u(t,`error`)}hasPendingInlineImageUploads(){return this.#n.size>0}async waitForPendingInlineImageUploads(){let e=this.#t;for(;e===this.#t&&this.#n.size>0;)await Promise.allSettled(Array.from(this.#n))}#h(){this.#t+=1,this.#n.clear(),this.#i!==void 0&&(clearTimeout(this.#i),this.#i=void 0),this.#r=0}adoptPendingUploads(){if(!this._editor)return;let e=this.#t,t=fe(this._editor);for(let n of t){let t=n.finally(()=>{e===this.#t&&this.#n.delete(t)});this.#n.add(t)}}_dispatchFilePickerEvent(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_trackFilePickerSession(e){this._filePickerCleanup?.();let t=!1,n=e=>{t||(t=!0,o(),this._dispatchFilePickerEvent(`jant:file-picker-close`,{cancelled:e}))},r=()=>n(!1),i=()=>n(!0),a=()=>{globalThis.setTimeout(()=>{n(!(e.files&&e.files.length>0))},0)},o=()=>{e.removeEventListener(`change`,r),e.removeEventListener(`cancel`,i),window.removeEventListener(`focus`,a),this._filePickerCleanup===o&&(this._filePickerCleanup=null)};this._filePickerCleanup=o,e.addEventListener(`change`,r,{once:!0}),e.addEventListener(`cancel`,i,{once:!0}),window.addEventListener(`focus`,a,{once:!0}),this._dispatchFilePickerEvent(`jant:file-picker-open`)}_isEmptyDoc(e){return!e.content||e.content.length===0||e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0||e.content.every(e=>e.type===`hardBreak`)))}_normalizeDocJson(e){return e?this._isEmptyDoc(e)?null:e:null}_isSelectionInsideTopLevelBlock(e){let t=this._editor;return t?t.state.selection.$from.index(0)===e:!1}_removedTopLevelSize(e){let t=this._editor?.state.doc;if(!t)return 0;let n=0;for(let r=0;r<=e.headingIndex;r+=1)n+=t.child(r)?.nodeSize??0;return n}promoteLeadingH1Title(e={}){if(this.format!==`note`||this._title.trim())return!1;let t=gt(this._editor?.getJSON()??this._bodyJson);if(!t||!e.force&&this._isSelectionInsideTopLevelBlock(t.headingIndex))return!1;let n=this._editor,r=!!n?.isFocused,i=n?.state.selection.from??null,a=this._removedTopLevelSize(t);if(this._title=t.title,this._showTitle=!0,this._bodyJson=t.bodyJson,n&&(t.bodyJson?n.commands.setContent(t.bodyJson):n.commands.clearContent(),r&&i!==null)){let e=n.state.doc.content.size;e>0&&(n.commands.setTextSelection(Math.max(1,Math.min(i-a,e))),n.commands.focus())}return!0}getNormalizedBodyJson(){return this._normalizeDocJson(this._bodyJson)}getEffectiveAttachedTexts(){return this._attachedTexts.flatMap(e=>{let t=this._normalizeDocJson(e.bodyJson);return t?[{...e,bodyJson:t,originalBodyJson:this._normalizeDocJson(e.originalBodyJson??null)}]:[]})}getEffectiveAttachmentOrder(){let e=new Set(this.getEffectiveAttachedTexts().map(e=>e.clientId)),t=new Set(this._attachments.map(e=>e.clientId));return this._attachmentOrder.filter(n=>t.has(n)||e.has(n))}_getEffectiveRating(){return this._showRating?this._rating:0}getData(){let e=this.getNormalizedBodyJson(),t=this.getEffectiveAttachedTexts(),n=this.getEffectiveAttachmentOrder(),r=e?JSON.stringify(e):``,i={rating:this._getEffectiveRating(),attachedTexts:t,attachments:this._attachments,attachmentOrder:n};switch(this.format){case`link`:return{...i,title:this._title,body:r,url:this._url,quoteText:``,quoteAuthor:``};case`quote`:return{...i,title:``,body:r,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor};default:return{...i,title:this._showTitle?this._title:``,body:r,url:``,quoteText:``,quoteAuthor:``}}}getStatus(){let e=this.getData(),t=!!e.body||!!e.title.trim()||!!e.url.trim()||!!e.quoteText.trim()||!!e.quoteAuthor.trim()||e.rating>0||e.attachments.length>0||e.attachedTexts.length>0,n=!this.getUrlValidationMessage()&&!this.getLinkTitleValidationMessage(),r;switch(this.format){case`link`:r=n;break;case`quote`:r=n&&!!e.quoteText.trim();break;default:r=n&&t}return{hasContent:t,publishable:r}}#g=null;#_(){let e=this.getStatus();(this.#g?.hasContent!==e.hasContent||this.#g?.publishable!==e.publishable)&&(this.#g=e,this.dispatchEvent(new CustomEvent(`jant:compose-status`,{bubbles:!0,detail:e})))}setTitleDefault(e){this.titleByDefault=e,this._showTitle=e}reset(){this.#h(),this._title=``,this._showTitle=this.titleByDefault,this._bodyJson=null,this._editor?.commands.clearContent(),this._lastEditorSelection=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showRating=!1,this._attachedTexts=[];for(let e of this._attachments)URL.revokeObjectURL(e.previewUrl),e.posterUrl&&URL.revokeObjectURL(e.posterUrl);this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.closeEmojiPicker()}updateAttachmentStatus(e,t,n,r,i){this._attachments=this._attachments.map(a=>a.clientId===e?{...a,status:t,mediaId:n,error:r,remoteUrl:i??a.remoteUrl}:a)}updateAttachmentPreview(e,t){this._setAttachmentPreviewFailure(e,!1),this._attachments=this._attachments.map(n=>n.clientId===e?(URL.revokeObjectURL(n.previewUrl),n.posterUrl&&URL.revokeObjectURL(n.posterUrl),{...n,file:t,previewUrl:URL.createObjectURL(t),posterUrl:null}):n)}updateAttachmentPoster(e,t){let n=URL.createObjectURL(t);this._attachments=this._attachments.map(t=>t.clientId===e?{...t,posterUrl:n}:t)}updateAttachmentProgress(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?{...n,progress:t}:n)}focusInput(e){if(this.format===`link`){this.focusUrlInput(e);return}if(this.format===`quote`){this._focusTextControl(this.querySelector(`.compose-quote-text`),e);return}if(e){this._editor?.commands.focus(e);return}this._editor?.commands.focus()}focusSelection(e){if(this.format!==`note`||!this._editor){this.focusInput();return}let t=e??this.getEditorSelection();if(!t){this.focusInput();return}let n=Bt(this._editor,t);this._lastEditorSelection=n,this._editor.chain().focus().setTextSelection(n).run()}focusUrlInput(e){this._focusTextControl(this.querySelector(`.compose-url-input`),e)}focusLinkTitleInput(e){this._focusTextControl(this.querySelector(`.compose-link-title`),e)}getUrlValidationMessage(){return this.format===`note`?null:this._url.trim()?e(this._url)?null:this.labels.urlInvalid:this.format===`link`?this.labels.linkUrlRequired:null}getLinkTitleValidationMessage(){return this.format===`link`?this._title.trim()?null:this.labels.linkTitleRequired:null}revealUrlValidation(){return this._showUrlValidation=!0,this.getUrlValidationMessage()}revealLinkTitleValidation(){return this._showLinkTitleValidation=!0,this.getLinkTitleValidationMessage()}getEditorSelection(){return this._readEditorSelection()??this._lastEditorSelection}isEmojiPickerOpen(){return this._showEmojiPicker}_readEditorSelection(){if(!this._editor)return null;let{from:e,to:t}=this._editor.state.selection;return{from:e,to:t}}_focusTextControl(e,t){if(!e||(e.focus(),!t))return;let n=t===`end`?e.value.length:0;e.setSelectionRange(n,n)}_initEditor(){let e=this.querySelector(`.compose-tiptap-body`);e&&!this._editor&&(this.dataset.slashCommandDiscovered=this.slashCommandDiscovered?`true`:`false`,this._editor=le({element:e,placeholder:this.format===`note`?this.labels.bodyPlaceholder:this.labels.thoughtsPlaceholder,content:this._bodyJson,toolbarMode:`compose`,onUpdate:e=>{this._bodyJson=e,this.promoteLeadingH1Title(),Pt(this)},onFocus:()=>{this._lastFocusedField=null,this._editor?.isEmpty&&It(this)},onBlur:()=>{this.promoteLeadingH1Title({force:!0})},onSelectionUpdate:e=>{this._lastEditorSelection=e},pasteMedia:{shouldInsertInline:e=>this._shouldPasteInlineImage(e),uploadInlineImage:e=>this._uploadAndInsertImage(e),onPasteFiles:e=>{this.addFiles(e)}},rehostImages:{shouldRehost:e=>this.#d(e),rehost:e=>this.#f(e)},imageNodeLabels:Rt(this.labels),tableControlLabels:this.labels.tableControls}),this._lastEditorSelection=this._readEditorSelection(),this.adoptPendingUploads())}_destroyEditor(){this.#h(),this._editor?.destroy(),this._editor=null}static _CONTENT_PROPS=new Set([`_title`,`_bodyJson`,`_url`,`_quoteText`,`_quoteAuthor`,`_rating`,`_showTitle`,`_showRating`,`_attachedTexts`,`_attachmentOrder`]);willUpdate(e){super.willUpdate(e),!this.hasUpdated&&!this.#e&&(this._showTitle=this.titleByDefault)}updated(e){if(super.updated(e),this._editor||this._initEditor(),e.has(`format`)&&e.get(`format`)!==void 0&&(this._showUrlValidation&&=!1,this._showLinkTitleValidation&&=!1,this._destroyEditor(),this.updateComplete.then(()=>this._initEditor())),(e.has(`_attachmentOrder`)||e.has(`_attachments`)||e.has(`_attachedTexts`))&&(e.has(`_attachments`)&&this._syncFailedAttachmentPreviews(),this._attachmentOrder.length>1?this.#x():(this.#a?.destroy(),this.#a=null),this.#v()),this.#_(),this._suppressContentChangedOnce)this._suppressContentChangedOnce=!1;else for(let n of e.keys())if(t._CONTENT_PROPS.has(n)){this.dispatchEvent(new Event(`jant:compose-content-changed`,{bubbles:!0}));break}}getEditorState(){return{json:this._editor?.getJSON()??this._bodyJson,title:this._title,showTitle:this._showTitle,selection:this.getEditorSelection()}}getConvertibleFields(){return{title:this._title,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor,showTitle:this._showTitle,bodyJson:this._normalizeDocJson(this._editor?.getJSON()??this._bodyJson)}}applyConvertedFields(e){this._suppressContentChangedOnce=!0,this._title=e.title,this._url=e.url,this._quoteText=e.quoteText,this._quoteAuthor=e.quoteAuthor,this._showTitle=e.showTitle,this._bodyJson=e.bodyJson}takeOver(e){this._title=e._title,this._showTitle=e._showTitle,this.#e=!0,this._bodyJson=e._editor?.getJSON()??e._bodyJson,this._url=e._url,this._quoteText=e._quoteText,this._quoteAuthor=e._quoteAuthor,this._rating=e._rating,this._showRating=e._showRating,this._attachedTexts=[...e._attachedTexts],this._attachments=[...e._attachments],this._attachmentOrder=[...e._attachmentOrder],this._lastEditorSelection=e.getEditorSelection(),this._editor&&(this._editor.commands.setContent(this._bodyJson??{type:`doc`,content:[{type:`paragraph`}]}),this.adoptPendingUploads()),this.#_()}hasAttachment(e){return this._attachments.some(t=>t.clientId===e)}populate(e){if(e.title&&(this._title=e.title),e.url&&(this._url=e.url),e.quoteText&&(this._quoteText=e.quoteText),e.quoteAuthor&&(this._quoteAuthor=e.quoteAuthor),e.rating&&e.rating>0&&(this._rating=e.rating,this._showRating=!0),e.showTitle===void 0?e.title&&e.format===`note`&&(this._showTitle=!0):this._showTitle=e.showTitle,e.showRating!==void 0&&(this._showRating=e.showRating),this._failedAttachmentPreviews=[],e.bodyJson)try{let t=JSON.parse(e.bodyJson);this._bodyJson=t,this._editor&&this._editor.commands.setContent(t)}catch{}if(e.media?.length){let t=e.media.map(e=>({clientId:e.clientId??L(),file:new File([],e.originalName??`existing`,{type:e.mimeType}),previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,status:`done`,progress:null,mediaId:e.id,persisted:e.persisted??!1,remoteUrl:e.previewUrl,alt:e.alt??``,error:null,summary:e.summary??null,chars:e.chars??null}));this._attachments=t,this._attachmentOrder=t.map(e=>e.clientId)}if(e.textAttachments?.length){let t=e=>{try{return JSON.parse(e)}catch{return null}},n=e.textAttachments.map(e=>{let n=t(e.bodyJson);return{clientId:e.clientId??L(),bodyJson:n,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:e.originalBodyJson===void 0?n:t(e.originalBodyJson)}});this._attachedTexts=n,this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)]}if(e.attachmentOrder?.length){let t=e.attachmentOrder.map(e=>this._attachments.find(t=>t.mediaId===e||t.clientId===e)?.clientId||this._attachedTexts.find(t=>t.mediaId===e||t.clientId===e)?.clientId).filter(e=>e!==void 0),n=this._attachmentOrder.filter(e=>!t.includes(e));this._attachmentOrder=[...t,...n]}this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.#_()}setEditorState(e,t,n,r){this._bodyJson=e,this._title=t,this.format===`note`&&(this._showTitle=n||t.length>0),this._editor&&this._editor.commands.setContent(e??{type:`doc`,content:[{type:`paragraph`}]}),this._lastEditorSelection=r??this._readEditorSelection(),this.#_()}static SUMMARY_LENGTH=100;_computeSummary(e){let n=e.replace(/\s+/g,` `).trim();return n.length<=t.SUMMARY_LENGTH?n:n.slice(0,t.SUMMARY_LENGTH)+`…`}_openAttachedText(){let e={clientId:L(),bodyJson:null,bodyHtml:``,summary:``};this._attachedTexts=[...this._attachedTexts,e],this._attachmentOrder=[...this._attachmentOrder,e.clientId];let t=this._attachedTexts.length-1;this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:t}}))}_moveAttachment(e,t,n=`handle`){let r=this._attachmentOrder.indexOf(e),i=r+t;if(r===-1||i<0||i>=this._attachmentOrder.length)return;let a=[...this._attachmentOrder],[o]=a.splice(r,1);o&&(a.splice(i,0,o),this._attachmentOrder=a,this.#s={clientId:e,direction:t,focusTarget:n},this.#S(e))}#v(){let e=this.#s;if(!e)return;this.#s=null;let t=this.querySelector(`[data-attachment-id="${e.clientId}"]`);if(t){if(e.focusTarget===`handle`){t.querySelector(`[data-attachment-sortable]`)?.focus({preventScroll:!0});return}(this.#y(t,e.direction)??this.#y(t,e.direction===1?-1:1))?.focus({preventScroll:!0})}}#y(e,t){let n=e.querySelector(`[data-attachment-move="${t===-1?`earlier`:`later`}"]`);return n&&!n.disabled?n:null}_handleAttachmentKeydown(e,t,n){if(t.key===`ArrowLeft`||t.key===`ArrowUp`){t.preventDefault(),this._moveAttachment(e,-1);return}if(t.key===`ArrowRight`||t.key===`ArrowDown`){t.preventDefault(),this._moveAttachment(e,1);return}n&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n())}#b(){return this.#c===void 0&&(this.#c=typeof window.matchMedia==`function`?window.matchMedia(`(pointer: coarse)`):null),this.#c}_onPointerTypeChange=()=>{this.#a?.destroy(),this.#a=null,this.#x()};#x(){let e=this.querySelector(`[data-attachment-list]`);!e||this.#a||this._attachmentOrder.length<=1||this.#b()?.matches||(this.#a=ne.create(e,{...te,chosenClass:`compose-attachment-chosen`,delay:250,direction:`horizontal`,dragClass:`compose-attachment-drag`,filter:`button, a, input, textarea, select, option, [contenteditable='true']`,ghostClass:`compose-attachment-ghost`,handle:`[data-attachment-sortable]`,preventOnFilter:!1,scroll:e,onChoose:()=>{E(e,!0)},onStart:e=>{this.#o=O(e)},onUnchoose:()=>{E(e,!1)},onEnd:t=>{let n=D(e,`[data-attachment-id]`,`attachmentId`);if(w(e,t,this.#o),this.#o=null,E(e,!1),this.#a?.destroy(),this.#a=null,n.length===this._attachmentOrder.length){this._attachmentOrder=n;let{movedId:e}=T(n,t.newIndex);e&&(this._suppressAttachedTextOpenUntil=Date.now()+250,this.#S(e))}}}))}#S(e){this.updateComplete.then(()=>{this.querySelector(`[data-attachment-id="${e}"]`)?.scrollIntoView({behavior:`smooth`,block:`nearest`,inline:`nearest`})})}_maybeEditAttachedText(e){Date.now()<this._suppressAttachedTextOpenUntil||this._editAttachedText(e)}_editAttachedText(e){this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:e}}))}_removeAttachedText(e){let t=this._attachedTexts[e];this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}updateAttachedText(e,t,n){let r=this._normalizeDocJson(t),i=this._extractPlainText(r);this._attachedTexts=this._attachedTexts.map((t,a)=>a===e?{...t,bodyJson:r,bodyHtml:r?n??``:``,summary:this._computeSummary(i)}:t)}closeAttachedPanel(e){let t=this._attachedTexts[e];t&&(t.mediaId||this._hasAttachedTextContent(t.bodyJson)||(this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)))}_hasAttachedTextContent(e){let t=this._normalizeDocJson(e);return t?this._extractPlainText(t).trim().length>0:!1}_extractPlainText(e){if(!e)return``;let t=``,n=e=>{e.text&&(t+=e.text),e.content&&e.content.forEach(n)};return n(e),t}_onInput(e,t){let n=t.target;this[e]=n.value,n.tagName===`TEXTAREA`&&this._autoResize(n)}_autoResize(e){e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`}#C=null;#w=null;_recordBodyPress=e=>{this.#C=e.target,this.#w=null};_recordBodyRelease=e=>{this.#w=e.target};_focusBodyFromBlankSpace=e=>{let t=this.#C,n=this.#w;if(this.#C=null,this.#w=null,t!==e.target||n!==e.target)return;let r=e.target;r&&(r.classList.contains(`compose-body`)||r.classList.contains(`compose-field-enter`)||r.classList.contains(`compose-tiptap-wrap`))&&this._editor?.commands.focus(`end`)};_setRating(e){this._rating=this._rating===e?0:e}_shouldPasteInlineImage(e){return!e.type.startsWith(`image/`)||this.format!==`note`||!this._showTitle?!1:this._title.trim().length>0}_openFilePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.multiple=!0,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>this._handleFilesSelected()),this.appendChild(this._fileInput)),this._fileInput.value=``,this._trackFilePickerSession(this._fileInput),this._fileInput.click()}_handleFilesSelected(){let e=this._fileInput?.files;e&&e.length!==0&&this.addFiles(e)}addFiles(e){let t=Array.from(e);if(t.length===0)return;let n=[],r=[];for(let e of t){let t=Ye(e,{maxFileSizeMB:this.uploadMaxFileSize});if(t){u(t,`error`);continue}let i=L(),a=URL.createObjectURL(e);n.push({clientId:i,file:e,previewUrl:a,posterUrl:null,status:`pending`,progress:null,mediaId:null,persisted:!1,remoteUrl:null,alt:``,error:null,summary:null,chars:null}),r.push({file:e,clientId:i})}if(n.length!==0){this._attachments=[...this._attachments,...n],this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)];for(let e of n)F(e.file.type)===`text`&&e.file.text().then(t=>{let n=this._computeSummary(t),r=t.length;this._attachments=this._attachments.map(t=>t.clientId===e.clientId?{...t,summary:n,chars:r}:t)});this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:r}}))}}removeAttachment(e){let t=this._attachments.findIndex(t=>t.clientId===e);t!==-1&&this._removeAttachment(t)}_removeAttachment(e){let t=this._attachments[e];t&&(this._setAttachmentPreviewFailure(t.clientId,!1),URL.revokeObjectURL(t.previewUrl),t.posterUrl&&URL.revokeObjectURL(t.posterUrl),this.dispatchEvent(new CustomEvent(`jant:attachment-removed`,{bubbles:!0,detail:{clientId:t.clientId,mediaId:t.mediaId,persisted:t.persisted}}))),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)),this._attachments=this._attachments.filter((t,n)=>n!==e),this._showAltPanel&&this._altPanelIndex===e?(this._showAltPanel=!1,this.dispatchEvent(new CustomEvent(`jant:alt-panel-close`,{bubbles:!0}))):this._showAltPanel&&this._altPanelIndex>e&&--this._altPanelIndex}_retryAllFailed(){let e=this._attachments.filter(e=>e.status===`error`);e.length!==0&&(this._attachments=this._attachments.map(e=>e.status===`error`?{...e,status:`pending`,progress:null,error:null}:e),this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:e.map(e=>({file:e.file,clientId:e.clientId}))}})))}_openAltPanel(e){this._altPanelIndex=e,this._showAltPanel=!0,this.dispatchEvent(new CustomEvent(`jant:alt-panel-open`,{bubbles:!0,detail:{index:e}}))}updateAlt(e,t){this._attachments=this._attachments.map((n,r)=>r===e?{...n,alt:t}:n)}_onFieldFocus(e){let t=e.target;this._lastFocusedField=t}_handleTitleKeydown(e){e.isComposing||e.keyCode===229||e.key!==`Enter`||e.metaKey||e.ctrlKey||e.altKey||(e.preventDefault(),this._editor?.commands.focus(`start`))}_toggleEmojiPicker(){this._showEmojiPicker?this.closeEmojiPicker():(this._showEmojiPicker=!0,this._mountEmojiPicker(),globalThis.setTimeout(()=>{document.addEventListener(`click`,this._onDocClickBound)},0))}closeEmojiPicker(e){if(!this._showEmojiPicker){e?.restoreFocus&&this._restoreEmojiFocus();return}this._showEmojiPicker=!1,this._emojiContainer?.remove(),this._emojiPickerEl=null,document.removeEventListener(`click`,this._onDocClickBound),e?.restoreFocus&&this._restoreEmojiFocus()}_restoreEmojiFocus(){let e=this._lastFocusedField;if(e&&this.contains(e)&&!e.disabled){e.focus();return}this.focusSelection()}_onDocumentClick(e){let t=e.target;this.querySelector(`.compose-emoji-btn`)?.contains(t)||this._emojiContainer?.contains(t)||this.closeEmojiPicker()}async _mountEmojiPicker(){let e=this.closest(`dialog`);if(this._emojiContainer||(this._emojiContainer=document.createElement(`div`),this._emojiContainer.className=`compose-emoji-picker`),(e??document.body).appendChild(this._emojiContainer),!this._emojiPickerEl){let[{default:e},{Picker:t}]=await Promise.all([f(()=>import(`./chunks/emoji-mart-C4RpRKcU.js`).then(e=>e.n),__vite__mapDeps([0,1])),f(()=>import(`./chunks/emoji-mart-C4RpRKcU.js`).then(e=>e.t),__vite__mapDeps([0,1]))]);if(!this._showEmojiPicker)return;let n=new t({data:e,onEmojiSelect:e=>{this._insertEmoji(e.native),this.closeEmojiPicker()},theme:`auto`,previewPosition:`none`,skinTonePosition:`none`});this._emojiPickerEl=n}this._emojiContainer.innerHTML=``,this._emojiContainer.appendChild(this._emojiPickerEl);let t=this.querySelector(`.compose-emoji-btn`);if(t&&e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=n.left-r.left,a=n.top-r.top,o=i+n.width/2-176;o=Math.max(-r.left+8,Math.min(o,r.width-8));let s=a-435-8;r.top+s<8&&(s=a+n.height+8),this._emojiContainer.style.left=`${o}px`,this._emojiContainer.style.top=`${s}px`}}_insertEmoji(e){let t=this._lastFocusedField;if(!t){this._editor&&this._editor.chain().focus().insertContent(e).run();return}let n=t.selectionStart??t.value.length,r=t.selectionEnd??n,i=t.value.slice(0,n),a=t.value.slice(r);t.value=i+e+a,t.dispatchEvent(new Event(`input`,{bubbles:!0}));let o=n+e.length;globalThis.requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(o,o)})}_getCategory(e){return F(e.file.type)}_formatSize(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}_formatChars(e){return e<1e3?`${e} chars`:e<1e6?`${parseFloat((e/1e3).toFixed(1))}k chars`:`${parseFloat((e/1e6).toFixed(1))}M chars`}_renderFileIcon(e,t){let n;return n=e===`application/pdf`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`:e===`text/markdown`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`:e===`text/csv`?`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`:F(e)===`archive`?`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`:e===`text/html; charset=utf-8`?`<line x1="16" y1="11" x2="8" y2="11"/><line x1="16" y1="14" x2="8" y2="14"/><line x1="12" y1="17" x2="8" y2="17"/>`:`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`,a`<svg
1324
1324
  width="${t}"
1325
1325
  height="${t}"
1326
1326
  viewBox="0 0 24 24"
@@ -1330,8 +1330,8 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1330
1330
  stroke-linecap="round"
1331
1331
  stroke-linejoin="round"
1332
1332
  >
1333
- ${v(`<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"/>`+n)}
1334
- </svg>`}_hasFailedAttachmentPreview(e){return this._failedAttachmentPreviews.includes(e)}_setAttachmentPreviewFailure(e,t){t!==this._failedAttachmentPreviews.includes(e)&&(this._failedAttachmentPreviews=t?[...this._failedAttachmentPreviews,e]:this._failedAttachmentPreviews.filter(t=>t!==e))}_syncFailedAttachmentPreviews(){let e=new Set(this._attachments.map(e=>e.clientId)),t=this._failedAttachmentPreviews.filter(t=>e.has(t));t.length!==this._failedAttachmentPreviews.length&&(this._failedAttachmentPreviews=t)}_renderAttachmentPreviewFallback(e){let t=this.labels.brokenImageUnavailable??`Image unavailable`;return i`
1333
+ ${y(`<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"/>`+n)}
1334
+ </svg>`}_hasFailedAttachmentPreview(e){return this._failedAttachmentPreviews.includes(e)}_setAttachmentPreviewFailure(e,t){t!==this._failedAttachmentPreviews.includes(e)&&(this._failedAttachmentPreviews=t?[...this._failedAttachmentPreviews,e]:this._failedAttachmentPreviews.filter(t=>t!==e))}_syncFailedAttachmentPreviews(){let e=new Set(this._attachments.map(e=>e.clientId)),t=this._failedAttachmentPreviews.filter(t=>e.has(t));t.length!==this._failedAttachmentPreviews.length&&(this._failedAttachmentPreviews=t)}_renderAttachmentPreviewFallback(e){let t=this.labels.brokenImageUnavailable??`Image unavailable`;return a`
1335
1335
  <div
1336
1336
  class="compose-attachment-preview-fallback"
1337
1337
  data-preview-failed=${e}
@@ -1354,17 +1354,17 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1354
1354
  <span class="compose-attachment-preview-fallback-label">
1355
1355
  ${t}
1356
1356
  </span>
1357
- ${e===`video`?i`
1357
+ ${e===`video`?a`
1358
1358
  <div class="compose-attachment-play-icon">
1359
1359
  <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
1360
1360
  <path d="M8 5v14l11-7z" />
1361
1361
  </svg>
1362
1362
  </div>
1363
- `:o}
1363
+ `:s}
1364
1364
  </div>
1365
- `}_renderNoteFields(){return i`
1365
+ `}_renderNoteFields(){return a`
1366
1366
  <div class="compose-field-enter">
1367
- ${this._showTitle?i`<input
1367
+ ${this._showTitle?a`<input
1368
1368
  type="text"
1369
1369
  .value=${this._title}
1370
1370
  @input=${e=>this._onInput(`_title`,e)}
@@ -1372,7 +1372,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1372
1372
  @keydown=${this._handleTitleKeydown}
1373
1373
  class="compose-input compose-note-title"
1374
1374
  placeholder=${this.labels.titlePlaceholder}
1375
- />`:o}
1375
+ />`:s}
1376
1376
  <div class="compose-tiptap-wrap">
1377
1377
  <div class="compose-tiptap-body"></div>
1378
1378
  <span class="compose-slash-discovery-hint" aria-hidden="true">
@@ -1380,10 +1380,10 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1380
1380
  </span>
1381
1381
  </div>
1382
1382
  </div>
1383
- `}_renderLinkFields(){let e=this._showUrlValidation?this.getUrlValidationMessage():null,t=this._showLinkTitleValidation?this.getLinkTitleValidationMessage():null;return i`
1383
+ `}_renderLinkFields(){let e=this._showUrlValidation?this.getUrlValidationMessage():null,t=this._showLinkTitleValidation?this.getLinkTitleValidationMessage():null;return a`
1384
1384
  <div class="compose-field-enter">
1385
1385
  <div
1386
- class=${b({"compose-link-url-wrap":!0,"compose-link-url-wrap-invalid":!!e})}
1386
+ class=${S({"compose-link-url-wrap":!0,"compose-link-url-wrap-invalid":!!e})}
1387
1387
  >
1388
1388
  <span class="text-base opacity-50 shrink-0">🔗</span>
1389
1389
  <input
@@ -1398,13 +1398,13 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1398
1398
  aria-describedby=${P(e?this._urlStatusId:void 0)}
1399
1399
  />
1400
1400
  </div>
1401
- ${e?i`<p
1401
+ ${e?a`<p
1402
1402
  id=${this._urlStatusId}
1403
1403
  class="compose-url-status compose-url-status-error"
1404
1404
  data-compose-url-status="error"
1405
1405
  >
1406
1406
  ${e}
1407
- </p>`:o}
1407
+ </p>`:s}
1408
1408
  <input
1409
1409
  type="text"
1410
1410
  .value=${this._title}
@@ -1416,12 +1416,12 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1416
1416
  placeholder=${this.labels.linkTitlePlaceholder}
1417
1417
  aria-invalid=${t?`true`:`false`}
1418
1418
  />
1419
- ${t?i`<p
1419
+ ${t?a`<p
1420
1420
  class="compose-url-status compose-url-status-error"
1421
1421
  data-compose-link-title-error="error"
1422
1422
  >
1423
1423
  ${t}
1424
- </p>`:o}
1424
+ </p>`:s}
1425
1425
  <div class="compose-divider"></div>
1426
1426
  <div class="compose-tiptap-wrap">
1427
1427
  <div class="compose-tiptap-body compose-tiptap-link"></div>
@@ -1430,7 +1430,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1430
1430
  </span>
1431
1431
  </div>
1432
1432
  </div>
1433
- `}_renderQuoteFields(){let e=this._showUrlValidation?this.getUrlValidationMessage():null;return i`
1433
+ `}_renderQuoteFields(){let e=this._showUrlValidation?this.getUrlValidationMessage():null;return a`
1434
1434
  <div class="compose-field-enter">
1435
1435
  <div class="compose-quote-wrap">
1436
1436
  ${zt(`compose-quote-mark`)}
@@ -1466,13 +1466,13 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1466
1466
  aria-invalid=${e?`true`:`false`}
1467
1467
  aria-describedby=${P(e?this._urlStatusId:void 0)}
1468
1468
  />
1469
- ${e?i`<p
1469
+ ${e?a`<p
1470
1470
  id=${this._urlStatusId}
1471
1471
  class="compose-url-status compose-url-status-error"
1472
1472
  data-compose-url-status="error"
1473
1473
  >
1474
1474
  ${e}
1475
- </p>`:o}
1475
+ </p>`:s}
1476
1476
  </div>
1477
1477
  <div
1478
1478
  class="compose-divider compose-divider-quote"
@@ -1485,20 +1485,20 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1485
1485
  </span>
1486
1486
  </div>
1487
1487
  </div>
1488
- `}_renderStarRating(){return this._showRating?i`
1488
+ `}_renderStarRating(){return this._showRating?a`
1489
1489
  <div class="compose-star-rating">
1490
- ${[1,2,3,4,5].map(e=>i`
1490
+ ${[1,2,3,4,5].map(e=>a`
1491
1491
  <button
1492
1492
  type="button"
1493
- class=${b({"compose-star":!0,"compose-star-filled":this._rating>=e})}
1493
+ class=${S({"compose-star":!0,"compose-star-filled":this._rating>=e})}
1494
1494
  @click=${()=>this._setRating(e)}
1495
1495
  >
1496
1496
  ★
1497
1497
  </button>
1498
1498
  `)}
1499
- ${this._rating>0?i`<span class="compose-star-label">${this._rating}/5</span>`:o}
1499
+ ${this._rating>0?a`<span class="compose-star-label">${this._rating}/5</span>`:s}
1500
1500
  </div>
1501
- `:o}_renderAttachmentPreview(e){let t=this._getCategory(e);return t===`video`?i`
1501
+ `:s}_renderAttachmentPreview(e){let t=this._getCategory(e);return t===`video`?a`
1502
1502
  <div class="compose-attachment-thumb">
1503
1503
  <video
1504
1504
  src=${e.previewUrl}
@@ -1512,7 +1512,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1512
1512
  </svg>
1513
1513
  </div>
1514
1514
  </div>
1515
- `:t===`audio`?i`
1515
+ `:t===`audio`?a`
1516
1516
  <div class="compose-attachment-file-card">
1517
1517
  <div class="compose-attachment-file-icon">
1518
1518
  <svg
@@ -1535,7 +1535,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1535
1535
  >${this._formatSize(e.file.size)}</span
1536
1536
  >
1537
1537
  </div>
1538
- `:t===`document`?i`
1538
+ `:t===`document`?a`
1539
1539
  <div class="compose-attachment-file-card">
1540
1540
  <div class="compose-attachment-file-icon">
1541
1541
  ${this._renderFileIcon(e.file.type,20)}
@@ -1545,24 +1545,24 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1545
1545
  >${this._formatSize(e.file.size)}</span
1546
1546
  >
1547
1547
  </div>
1548
- `:t===`text`?i`
1548
+ `:t===`text`?a`
1549
1549
  <div class="compose-attachment-file-card">
1550
1550
  <div class="compose-attachment-file-icon">
1551
1551
  ${this._renderFileIcon(e.file.type,20)}
1552
1552
  </div>
1553
1553
  <span class="compose-attachment-file-name">${e.file.name}</span>
1554
- ${e.summary?i`<span class="compose-attachment-text-summary"
1554
+ ${e.summary?a`<span class="compose-attachment-text-summary"
1555
1555
  >${e.summary}</span
1556
- >`:o}
1557
- ${typeof e.chars==`number`&&e.chars>0?i`<span class="compose-attachment-file-size"
1556
+ >`:s}
1557
+ ${typeof e.chars==`number`&&e.chars>0?a`<span class="compose-attachment-file-size"
1558
1558
  >${this._formatChars(e.chars)}</span
1559
- >`:o}
1559
+ >`:s}
1560
1560
  </div>
1561
- `:t===`image`?i`
1561
+ `:t===`image`?a`
1562
1562
  <div class="compose-attachment-thumb">
1563
1563
  <img src=${e.previewUrl} alt="" class="compose-attachment-img" />
1564
1564
  </div>
1565
- `:i`
1565
+ `:a`
1566
1566
  <div class="compose-attachment-file-card">
1567
1567
  <div class="compose-attachment-file-icon">
1568
1568
  ${this._renderFileIcon(e.file.type,20)}
@@ -1572,8 +1572,8 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1572
1572
  >${this._formatSize(e.file.size)}</span
1573
1573
  >
1574
1574
  </div>
1575
- `}_renderAttachmentOverlay(e,t){return i`
1576
- ${e.status===`error`?i`
1575
+ `}_renderAttachmentOverlay(e,t){return a`
1576
+ ${e.status===`error`?a`
1577
1577
  <button
1578
1578
  type="button"
1579
1579
  class="compose-attachment-overlay compose-attachment-retry"
@@ -1603,13 +1603,13 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1603
1603
  >${this.labels.retryAll}</span
1604
1604
  >
1605
1605
  </span>
1606
- ${e.error?i`<span class="compose-attachment-error-msg"
1606
+ ${e.error?a`<span class="compose-attachment-error-msg"
1607
1607
  >${e.error}</span
1608
- >`:o}
1608
+ >`:s}
1609
1609
  </button>
1610
- `:o}
1610
+ `:s}
1611
1611
  ${this._renderAttachmentRemoveButton(e=>{e.stopPropagation(),this._removeAttachment(t)})}
1612
- `}_renderAttachmentRemoveButton(e){return i`
1612
+ `}_renderAttachmentRemoveButton(e){return a`
1613
1613
  <button
1614
1614
  type="button"
1615
1615
  class="compose-attachment-remove"
@@ -1629,14 +1629,14 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1629
1629
  <path d="M10.5 3.5 3.5 10.5" />
1630
1630
  </svg>
1631
1631
  </button>
1632
- `}_renderAttachmentMoveButton(e,t,n){let r=t===-1,a=r?this.labels.moveAttachmentEarlier:this.labels.moveAttachmentLater;return i`
1632
+ `}_renderAttachmentMoveButton(e,t,n){let r=t===-1,i=r?this.labels.moveAttachmentEarlier:this.labels.moveAttachmentLater;return a`
1633
1633
  <button
1634
1634
  type="button"
1635
1635
  class="compose-attachment-move"
1636
1636
  data-attachment-move=${r?`earlier`:`later`}
1637
1637
  ?disabled=${n}
1638
- aria-label=${a}
1639
- title=${a}
1638
+ aria-label=${i}
1639
+ title=${i}
1640
1640
  @click=${n=>{n.stopPropagation(),this._moveAttachment(e,t,`move`)}}
1641
1641
  >
1642
1642
  <svg
@@ -1654,17 +1654,17 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1654
1654
  />
1655
1655
  </svg>
1656
1656
  </button>
1657
- `}_renderAttachmentActions(e,t=o){let n=this._attachmentOrder.length,r=this._attachmentOrder.indexOf(e),a=n>1&&r!==-1;return!a&&t===o?o:i`
1657
+ `}_renderAttachmentActions(e,t=s){let n=this._attachmentOrder.length,r=this._attachmentOrder.indexOf(e),i=n>1&&r!==-1;return!i&&t===s?s:a`
1658
1658
  <div class="compose-attachment-actions">
1659
- ${a?i`
1659
+ ${i?a`
1660
1660
  <div class="compose-attachment-move-group">
1661
1661
  ${this._renderAttachmentMoveButton(e,-1,r===0)}
1662
1662
  ${this._renderAttachmentMoveButton(e,1,r===n-1)}
1663
1663
  </div>
1664
- `:o}
1664
+ `:s}
1665
1665
  ${t}
1666
1666
  </div>
1667
- `}_renderAttachedTextCard(e,t){return i`
1667
+ `}_renderAttachedTextCard(e,t){return a`
1668
1668
  <div class="compose-attachment" data-attachment-id=${e.clientId}>
1669
1669
  <div
1670
1670
  class="compose-attachment-thumb compose-attachment-sortable"
@@ -1678,17 +1678,17 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1678
1678
  ${this._renderFileIcon(`text/html; charset=utf-8`,20)}
1679
1679
  </div>
1680
1680
  <span class="compose-attachment-text-summary">${e.summary}</span>
1681
- ${e.bodyJson?i`<span class="compose-attachment-file-size"
1681
+ ${e.bodyJson?a`<span class="compose-attachment-file-size"
1682
1682
  >${this._formatChars(this._extractPlainText(e.bodyJson).length)}</span
1683
- >`:o}
1683
+ >`:s}
1684
1684
  </div>
1685
1685
  ${this._renderAttachmentRemoveButton(e=>{e.stopPropagation(),this._removeAttachedText(t)})}
1686
1686
  </div>
1687
1687
  ${this._renderAttachmentActions(e.clientId)}
1688
1688
  </div>
1689
- `}_renderMediaAttachment(e,t){let n=this._getCategory(e),r=n!==`image`&&n!==`video`,a=n===`video`?`video`:`image`,s=this._hasFailedAttachmentPreview(e.clientId);return i`
1689
+ `}_renderMediaAttachment(e,t){let n=this._getCategory(e),r=n!==`image`&&n!==`video`,i=n===`video`?`video`:`image`,o=this._hasFailedAttachmentPreview(e.clientId);return a`
1690
1690
  <div class="compose-attachment" data-attachment-id=${e.clientId}>
1691
- ${r?i`
1691
+ ${r?a`
1692
1692
  <div class="compose-attachment-thumb">
1693
1693
  <div
1694
1694
  class="compose-attachment-sortable"
@@ -1700,7 +1700,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1700
1700
  </div>
1701
1701
  ${this._renderAttachmentOverlay(e,t)}
1702
1702
  </div>
1703
- `:i`
1703
+ `:a`
1704
1704
  <div class="compose-attachment-thumb">
1705
1705
  <div
1706
1706
  class="compose-attachment-sortable"
@@ -1708,10 +1708,10 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1708
1708
  tabindex="0"
1709
1709
  @keydown=${t=>this._handleAttachmentKeydown(e.clientId,t)}
1710
1710
  >
1711
- ${s?this._renderAttachmentPreviewFallback(a):n===`video`?i`
1711
+ ${o?this._renderAttachmentPreviewFallback(i):n===`video`?a`
1712
1712
  <video
1713
1713
  src=${e.previewUrl}
1714
- poster=${e.posterUrl??o}
1714
+ poster=${e.posterUrl??s}
1715
1715
  class="compose-attachment-img"
1716
1716
  preload="metadata"
1717
1717
  .playsInline=${!0}
@@ -1729,7 +1729,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1729
1729
  <path d="M8 5v14l11-7z" />
1730
1730
  </svg>
1731
1731
  </div>
1732
- `:e.status===`processing`?i`
1732
+ `:e.status===`processing`?a`
1733
1733
  <div class="compose-attachment-processing">
1734
1734
  <svg
1735
1735
  class="animate-spin size-5"
@@ -1744,7 +1744,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1744
1744
  />
1745
1745
  </svg>
1746
1746
  </div>
1747
- `:i`
1747
+ `:a`
1748
1748
  <img
1749
1749
  src=${e.previewUrl}
1750
1750
  alt=""
@@ -1757,51 +1757,51 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1757
1757
  ${this._renderAttachmentOverlay(e,t)}
1758
1758
  </div>
1759
1759
  `}
1760
- ${this._renderAttachmentActions(e.clientId,n===`image`?i`
1760
+ ${this._renderAttachmentActions(e.clientId,n===`image`?a`
1761
1761
  <button
1762
1762
  type="button"
1763
- class=${b({"compose-attachment-alt":!0,"compose-attachment-alt-set":e.alt.length>0})}
1763
+ class=${S({"compose-attachment-alt":!0,"compose-attachment-alt-set":e.alt.length>0})}
1764
1764
  @click=${()=>this._openAltPanel(t)}
1765
1765
  >
1766
1766
  ${e.alt.length>0?`ALT`:`+ ALT`}
1767
1767
  </button>
1768
- `:o)}
1768
+ `:s)}
1769
1769
  </div>
1770
- `}_renderAttachments(){return this._attachments.length===0&&this._attachedTexts.length===0?o:i`
1770
+ `}_renderAttachments(){return this._attachments.length===0&&this._attachedTexts.length===0?s:a`
1771
1771
  <div class="compose-attachments" data-attachment-list>
1772
- ${this._attachmentOrder.map(e=>{let t=this._attachments.findIndex(t=>t.clientId===e);if(t!==-1)return this._renderMediaAttachment(this._attachments[t],t);let n=this._attachedTexts.findIndex(t=>t.clientId===e);return n===-1?o:this._renderAttachedTextCard(this._attachedTexts[n],n)})}
1772
+ ${this._attachmentOrder.map(e=>{let t=this._attachments.findIndex(t=>t.clientId===e);if(t!==-1)return this._renderMediaAttachment(this._attachments[t],t);let n=this._attachedTexts.findIndex(t=>t.clientId===e);return n===-1?s:this._renderAttachedTextCard(this._attachedTexts[n],n)})}
1773
1773
  </div>
1774
- `}_renderAttachmentDock(){return this._attachments.length===0&&this._attachedTexts.length===0?o:i`
1774
+ `}_renderAttachmentDock(){return this._attachments.length===0&&this._attachedTexts.length===0?s:a`
1775
1775
  <div class="compose-attachments-dock">${this._renderAttachments()}</div>
1776
- `}_renderToolsRow(){let e=this._attachedTexts.length>0;return i`
1776
+ `}_renderToolsRow(){let e=this._attachedTexts.length>0;return a`
1777
1777
  <div class="compose-tools-row">
1778
1778
  <button
1779
1779
  type="button"
1780
- class=${b({"compose-tool-btn":!0,"compose-tool-btn-add":this._attachments.length>0})}
1780
+ class=${S({"compose-tool-btn":!0,"compose-tool-btn-add":this._attachments.length>0})}
1781
1781
  title=${this._attachments.length>0?``:this.labels.media}
1782
1782
  @click=${()=>this._openFilePicker()}
1783
1783
  >
1784
1784
  ${J(q.media)}
1785
- ${this._attachments.length>0?i`<span class="compose-tool-label"
1785
+ ${this._attachments.length>0?a`<span class="compose-tool-label"
1786
1786
  >${this.labels.addMore}</span
1787
- >`:o}
1787
+ >`:s}
1788
1788
  </button>
1789
1789
 
1790
1790
  <button
1791
1791
  type="button"
1792
- class=${b({"compose-tool-btn":!0,"compose-tool-btn-add":e})}
1792
+ class=${S({"compose-tool-btn":!0,"compose-tool-btn-add":e})}
1793
1793
  title=${e?``:this.labels.attachedText}
1794
1794
  @click=${()=>this._openAttachedText()}
1795
1795
  >
1796
1796
  ${J(q.attachedText)}
1797
- ${e?i`<span class="compose-tool-label"
1797
+ ${e?a`<span class="compose-tool-label"
1798
1798
  >${this.labels.addMore}</span
1799
- >`:o}
1799
+ >`:s}
1800
1800
  </button>
1801
1801
 
1802
1802
  <button
1803
1803
  type="button"
1804
- class=${b({"compose-tool-btn":!0,"compose-emoji-btn":!0,"compose-tool-btn-active":this._showEmojiPicker})}
1804
+ class=${S({"compose-tool-btn":!0,"compose-emoji-btn":!0,"compose-tool-btn-active":this._showEmojiPicker})}
1805
1805
  title=${this.labels.emoji}
1806
1806
  aria-pressed=${this._showEmojiPicker?`true`:`false`}
1807
1807
  @click=${()=>this._toggleEmojiPicker()}
@@ -1813,7 +1813,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1813
1813
 
1814
1814
  <button
1815
1815
  type="button"
1816
- class=${b({"compose-tool-btn":!0,"compose-tool-btn-active":this._showRating})}
1816
+ class=${S({"compose-tool-btn":!0,"compose-tool-btn-active":this._showRating})}
1817
1817
  title=${this.labels.rate}
1818
1818
  aria-pressed=${this._showRating?`true`:`false`}
1819
1819
  @click=${()=>{let e=!this._showRating;this._showRating=e,e&&this.updateComplete.then(()=>{this.querySelector(`.compose-star-rating`)?.scrollIntoView({block:`nearest`,behavior:`smooth`})})}}
@@ -1821,18 +1821,18 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1821
1821
  ${J(q.rate)}
1822
1822
  </button>
1823
1823
 
1824
- ${this.format===`note`?i`
1824
+ ${this.format===`note`?a`
1825
1825
  <button
1826
1826
  type="button"
1827
- class=${b({"compose-tool-btn":!0,"compose-tool-btn-active":this._showTitle})}
1827
+ class=${S({"compose-tool-btn":!0,"compose-tool-btn-active":this._showTitle})}
1828
1828
  title=${this.labels.title}
1829
1829
  aria-pressed=${this._showTitle?`true`:`false`}
1830
1830
  @click=${()=>{let e=!this._showTitle;this._showTitle=e,this.dispatchEvent(new CustomEvent(`jant:title-toggle`,{bubbles:!0,detail:{showTitle:e}})),e&&this.updateComplete.then(()=>{this.querySelector(`.compose-note-title`)?.focus()})}}
1831
1831
  >
1832
1832
  ${J(q.title)}
1833
1833
  </button>
1834
- `:o}
1835
- ${this.format===`note`?i`
1834
+ `:s}
1835
+ ${this.format===`note`?a`
1836
1836
  <div class="compose-tool-view-group">
1837
1837
  <button
1838
1838
  type="button"
@@ -1844,32 +1844,32 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1844
1844
  ${J(q.fullscreen)}
1845
1845
  </button>
1846
1846
  </div>
1847
- `:o}
1847
+ `:s}
1848
1848
  </div>
1849
- `}_renderFormatHeader(){let e={note:this.labels.note,link:this.labels.link,quote:this.labels.quote};return i`
1849
+ `}_renderFormatHeader(){let e={note:this.labels.note,link:this.labels.link,quote:this.labels.quote};return a`
1850
1850
  <div class="compose-thread-post-header">
1851
1851
  <div class="compose-segmented">
1852
1852
  <!-- No sliding indicator: the items size to their labels now, so a
1853
1853
  thirds-based pill would not line up. The active item carries its
1854
1854
  own background instead. -->
1855
- ${[`note`,`link`,`quote`].map(t=>i`
1855
+ ${[`note`,`link`,`quote`].map(t=>a`
1856
1856
  <button
1857
1857
  type="button"
1858
- class=${b({"compose-segmented-item":!0,"compose-segmented-item-active":this.format===t})}
1858
+ class=${S({"compose-segmented-item":!0,"compose-segmented-item-active":this.format===t})}
1859
1859
  @click=${()=>{this.format!==t&&this.dispatchEvent(new CustomEvent(`jant:format-change`,{bubbles:!0,detail:{format:t}}))}}
1860
1860
  >
1861
1861
  ${e[t]}
1862
1862
  </button>
1863
1863
  `)}
1864
1864
  </div>
1865
- ${this.positionLabel?i`<span class="compose-post-position"
1865
+ ${this.positionLabel?a`<span class="compose-post-position"
1866
1866
  >${this.positionLabel}</span
1867
- >`:o}
1868
- ${this.badgeLabel?i`<span class="compose-post-position compose-post-badge"
1867
+ >`:s}
1868
+ ${this.badgeLabel?a`<span class="compose-post-position compose-post-badge"
1869
1869
  >${this.badgeLabel}</span
1870
- >`:o}
1871
- ${this.headerExtra??o}
1872
- ${this.removable?i`<button
1870
+ >`:s}
1871
+ ${this.headerExtra??s}
1872
+ ${this.removable?a`<button
1873
1873
  type="button"
1874
1874
  class="compose-thread-post-remove"
1875
1875
  title="Remove post"
@@ -1885,11 +1885,11 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1885
1885
  stroke-linecap="round"
1886
1886
  aria-hidden="true"
1887
1887
  >
1888
- ${v(`<path d="M4.5 4.5 11.5 11.5M11.5 4.5 4.5 11.5"/>`)}
1888
+ ${y(`<path d="M4.5 4.5 11.5 11.5M11.5 4.5 4.5 11.5"/>`)}
1889
1889
  </svg>
1890
- </button>`:o}
1890
+ </button>`:s}
1891
1891
  </div>
1892
- `}openFullscreen(){if(this.format!==`note`)return;let e=this.getEditorState();this.dispatchEvent(new CustomEvent(`jant:fullscreen-open`,{bubbles:!0,detail:{...e,labels:this.labels}}))}render(){return i`
1892
+ `}openFullscreen(){if(this.format!==`note`)return;let e=this.getEditorState();this.dispatchEvent(new CustomEvent(`jant:fullscreen-open`,{bubbles:!0,detail:{...e,labels:this.labels}}))}render(){return a`
1893
1893
  ${this._renderFormatHeader()}
1894
1894
  <section
1895
1895
  class="compose-body"
@@ -1901,7 +1901,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1901
1901
  </section>
1902
1902
  ${this._renderAttachmentDock()} ${this._renderStarRating()}
1903
1903
  ${this._renderToolsRow()}
1904
- `}};customElements.define(`jant-compose-editor`,Vt);var Ht=`.tiptap-slash-menu, .tiptap-link-input, .tiptap-table-size-picker, .tiptap-table-options:not([hidden])`,Ut=class extends c{static properties={labels:{type:Object},_open:{state:!0},_title:{state:!0},_showTitle:{state:!0},_replyContext:{state:!0},_replyExpanded:{state:!0}};_editor=null;_content=null;_selection=null;_editorIndex=0;_fileInput=null;#e=new Set;createRenderRoot(){return this}constructor(){super(),this.labels={},this._open=!1,this._title=``,this._showTitle=!0,this._replyContext=null,this._replyExpanded=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:fullscreen-open`,this._onOpen),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`keydown`,this._onDocumentKeydown,!0)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`jant:fullscreen-open`,this._onOpen),document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`keydown`,this._onDocumentKeydown,!0),this._fileInput?.remove(),this._destroyEditor()}_onSlashImage=()=>{this._open&&this._editor&&this._triggerImagePicker()};_triggerImagePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`image/*`,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>{let e=this._fileInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._fileInput&&(this._fileInput.value=``)}),document.body.appendChild(this._fileInput)),this._fileInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=M(t,e).finally(()=>{this.#e.delete(n)});return this.#e.add(n),n}_onOpen=e=>{this._content=e.detail.json,this._selection=e.detail.selection??null,this._title=e.detail.title,e.detail.labels&&(this.labels=e.detail.labels),this._showTitle=e.detail.showTitle||e.detail.title.trim().length>0,this._replyContext=e.detail.replyContext??null,this._replyExpanded=e.detail.replyContext?.expanded??!1,this._editorIndex=e.detail.editorIndex??0,this._open=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-fullscreen-dialog`);e&&!e.open&&e.showModal(),this._initEditor()})};_initEditor(){let e=this.querySelector(`.compose-fullscreen .compose-tiptap-body`);if(!e||this._editor)return;this._editor=le({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._content,toolbarMode:`compose`,onUpdate:e=>{this._content=e},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`),uploadInlineImage:e=>this._uploadAndInsertImage(e)},imageNodeLabels:Rt(this.labels),tableControlLabels:this.labels.tableControls});let t=this._selection;if(t){let e=this._editor.state.doc.content.size,n=Math.max(1,Math.min(t.from,e)),r=Math.max(n,Math.min(t.to,e));this._selection={from:n,to:r},this._editor.chain().focus().setTextSelection({from:n,to:r}).run();return}this._editor.commands.focus()}_destroyEditor(){this.#e.clear(),this._editor?.destroy(),this._editor=null}_onDialogCancel=e=>{e.preventDefault(),this._close()};_onDocumentKeydown=e=>{if(this._open&&!(e.isComposing||e.keyCode===229)){if((e.metaKey||e.ctrlKey)&&e.key===`Enter`){e.preventDefault(),e.stopPropagation(),this._publish();return}e.key===`Escape`&&(this._hasActiveEscapeOverlay()||(e.preventDefault(),e.stopPropagation(),this._close()))}};_hasActiveEscapeOverlay(){let e=this.querySelector(`.compose-fullscreen-dialog[open]`);return e?Array.from(e.querySelectorAll(Ht)).some(e=>getComputedStyle(e).display!==`none`):!1}_finishClose(e){let t=this._editor?.getJSON()??this._content,n=this._editor?{from:this._editor.state.selection.from,to:this._editor.state.selection.to}:this._selection;this._destroyEditor(),this.querySelector(`.compose-fullscreen-dialog`)?.close(),this._open=!1,this._replyContext=null,document.dispatchEvent(new CustomEvent(`jant:fullscreen-close`,{bubbles:!0,detail:{json:t,title:this._title,showTitle:this._showTitle||this._title.trim().length>0,selection:n,replyExpanded:this._replyExpanded,intent:e,editorIndex:this._editorIndex}}))}_close(){this._open&&this._finishClose()}_publish(){this._open&&this._finishClose(`publish`)}_revealTitle(){this._showTitle=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-fullscreen-title`)?.focus()})}_renderTitleField(e){let t=b({"compose-fullscreen-title":!0,"compose-fullscreen-title-reply":e===`reply`}),n=b({"compose-fullscreen-title-placeholder":!0,"compose-fullscreen-title-placeholder-reply":e===`reply`});return this._showTitle?i`
1904
+ `}};customElements.define(`jant-compose-editor`,Vt);var Ht=`.tiptap-slash-menu, .tiptap-link-input, .tiptap-table-size-picker, .tiptap-table-options:not([hidden])`,Ut=class extends l{static properties={labels:{type:Object},_open:{state:!0},_title:{state:!0},_showTitle:{state:!0},_replyContext:{state:!0},_replyExpanded:{state:!0}};_editor=null;_content=null;_selection=null;_editorIndex=0;_fileInput=null;#e=new Set;createRenderRoot(){return this}constructor(){super(),this.labels={},this._open=!1,this._title=``,this._showTitle=!0,this._replyContext=null,this._replyExpanded=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:fullscreen-open`,this._onOpen),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`keydown`,this._onDocumentKeydown,!0)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`jant:fullscreen-open`,this._onOpen),document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`keydown`,this._onDocumentKeydown,!0),this._fileInput?.remove(),this._destroyEditor()}_onSlashImage=()=>{this._open&&this._editor&&this._triggerImagePicker()};_triggerImagePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`image/*`,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>{let e=this._fileInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._fileInput&&(this._fileInput.value=``)}),document.body.appendChild(this._fileInput)),this._fileInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=M(t,e).finally(()=>{this.#e.delete(n)});return this.#e.add(n),n}_onOpen=e=>{this._content=e.detail.json,this._selection=e.detail.selection??null,this._title=e.detail.title,e.detail.labels&&(this.labels=e.detail.labels),this._showTitle=e.detail.showTitle||e.detail.title.trim().length>0,this._replyContext=e.detail.replyContext??null,this._replyExpanded=e.detail.replyContext?.expanded??!1,this._editorIndex=e.detail.editorIndex??0,this._open=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-fullscreen-dialog`);e&&!e.open&&e.showModal(),this._initEditor()})};_initEditor(){let e=this.querySelector(`.compose-fullscreen .compose-tiptap-body`);if(!e||this._editor)return;this._editor=le({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._content,toolbarMode:`compose`,onUpdate:e=>{this._content=e},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`),uploadInlineImage:e=>this._uploadAndInsertImage(e)},imageNodeLabels:Rt(this.labels),tableControlLabels:this.labels.tableControls});let t=this._selection;if(t){let e=this._editor.state.doc.content.size,n=Math.max(1,Math.min(t.from,e)),r=Math.max(n,Math.min(t.to,e));this._selection={from:n,to:r},this._editor.chain().focus().setTextSelection({from:n,to:r}).run();return}this._editor.commands.focus()}_destroyEditor(){this.#e.clear(),this._editor?.destroy(),this._editor=null}_onDialogCancel=e=>{e.preventDefault(),this._close()};_onDocumentKeydown=e=>{if(this._open&&!(e.isComposing||e.keyCode===229)){if((e.metaKey||e.ctrlKey)&&e.key===`Enter`){e.preventDefault(),e.stopPropagation(),this._publish();return}e.key===`Escape`&&(this._hasActiveEscapeOverlay()||(e.preventDefault(),e.stopPropagation(),this._close()))}};_hasActiveEscapeOverlay(){let e=this.querySelector(`.compose-fullscreen-dialog[open]`);return e?Array.from(e.querySelectorAll(Ht)).some(e=>getComputedStyle(e).display!==`none`):!1}_finishClose(e){let t=this._editor?.getJSON()??this._content,n=this._editor?{from:this._editor.state.selection.from,to:this._editor.state.selection.to}:this._selection;this._destroyEditor(),this.querySelector(`.compose-fullscreen-dialog`)?.close(),this._open=!1,this._replyContext=null,document.dispatchEvent(new CustomEvent(`jant:fullscreen-close`,{bubbles:!0,detail:{json:t,title:this._title,showTitle:this._showTitle||this._title.trim().length>0,selection:n,replyExpanded:this._replyExpanded,intent:e,editorIndex:this._editorIndex}}))}_close(){this._open&&this._finishClose()}_publish(){this._open&&this._finishClose(`publish`)}_revealTitle(){this._showTitle=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-fullscreen-title`)?.focus()})}_renderTitleField(e){let t=S({"compose-fullscreen-title":!0,"compose-fullscreen-title-reply":e===`reply`}),n=S({"compose-fullscreen-title-placeholder":!0,"compose-fullscreen-title-placeholder-reply":e===`reply`});return this._showTitle?a`
1905
1905
  <div class="compose-fullscreen-title-shell">
1906
1906
  <input
1907
1907
  type="text"
@@ -1912,7 +1912,7 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1912
1912
  placeholder=${this.labels.titlePlaceholder??`Title`}
1913
1913
  />
1914
1914
  </div>
1915
- `:i`
1915
+ `:a`
1916
1916
  <button
1917
1917
  type="button"
1918
1918
  class=${n}
@@ -1920,14 +1920,14 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1920
1920
  >
1921
1921
  ${this.labels.titlePlaceholder||this.labels.title||`Title`}
1922
1922
  </button>
1923
- `}render(){if(!this._open)return o;let e=this._replyContext,t=e=>i`
1923
+ `}render(){if(!this._open)return s;let e=this._replyContext,t=e=>a`
1924
1924
  <div
1925
- class=${b({"compose-fullscreen-editor-surface":!0,"compose-fullscreen-editor-surface-reply":e===`reply`})}
1925
+ class=${S({"compose-fullscreen-editor-surface":!0,"compose-fullscreen-editor-surface-reply":e===`reply`})}
1926
1926
  >
1927
1927
  ${this._renderTitleField(e)}
1928
1928
  <div class="compose-tiptap-body"></div>
1929
1929
  </div>
1930
- `;return i`
1930
+ `;return a`
1931
1931
  <dialog
1932
1932
  class="compose-fullscreen-dialog"
1933
1933
  aria-label=${this.labels.fullscreen||this.labels.note||`Fullscreen`}
@@ -1963,24 +1963,24 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
1963
1963
  </header>
1964
1964
  <div class="compose-fullscreen-content">
1965
1965
  <div class="compose-fullscreen-inner">
1966
- ${e?i`
1966
+ ${e?a`
1967
1967
  <div
1968
1968
  class="compose-thread-layout compose-fullscreen-thread-layout"
1969
1969
  >
1970
1970
  <div class="compose-reply-row">
1971
1971
  <div class="compose-thread-dot"></div>
1972
1972
  <div
1973
- class=${b({"compose-reply-context":!0,expanded:this._replyExpanded})}
1973
+ class=${S({"compose-reply-context":!0,expanded:this._replyExpanded})}
1974
1974
  >
1975
1975
  <div class="compose-reply-context-body">
1976
1976
  ${d(e.contentHtml)}
1977
1977
  </div>
1978
- ${this._replyExpanded?o:i`<div class="compose-reply-fade"></div>`}
1978
+ ${this._replyExpanded?s:a`<div class="compose-reply-fade"></div>`}
1979
1979
  </div>
1980
1980
  </div>
1981
1981
  <div class="compose-reply-meta">
1982
- ${e.dateText?i`<span>${e.dateText}</span
1983
- ><span>·</span>`:o}
1982
+ ${e.dateText?a`<span>${e.dateText}</span
1983
+ ><span>·</span>`:s}
1984
1984
  <button
1985
1985
  type="button"
1986
1986
  class="compose-reply-toggle"
@@ -2001,4 +2001,4 @@ import{b as e,c as t,f as n,h as r,i,l as a,n as o,s,t as c,u as l}from"./chunks
2001
2001
  </div>
2002
2002
  </div>
2003
2003
  </dialog>
2004
- `}};customElements.define(`jant-compose-fullscreen`,Ut);var Wt;function Gt(){return Wt??=y(()=>import(`./chunks/mediabunny-DRaCQ1r-.js`).then(e=>e.t),__vite__mapDeps([2,1])),Wt}function Kt(){return typeof AudioEncoder<`u`}async function qt(e,t){let{Input:n,Output:r,Mp4OutputFormat:i,BufferTarget:a,BlobSource:o,Conversion:s,ALL_FORMATS:c}=await Gt(),l=new n({source:new o(e),formats:c}),u=new a,d=new r({format:new i({fastStart:`in-memory`}),target:u});try{let n=await s.init({input:l,output:d,video:{discard:!0},audio:{codec:`aac`}});t&&(n.onProgress=t),await n.execute();let r=u.buffer;if(!r)throw Error(`Audio processing produced no output`);let i=e.name.replace(/\.[^.]+$/,``);return{file:new File([r],`${i}.m4a`,{type:`audio/mp4`})}}finally{l.dispose()}}var Jt={isSupported:Kt,processToFile:qt},Yt=new Set([`moov`,`trak`]);function Xt(e){return 12+(e===1?32:20)+8+2}function Zt(e){let t=new DataView(e),n=(e,r)=>{let i=e;for(;i+8<=r;){let e=t.getUint32(i),a=String.fromCharCode(t.getUint8(i+4),t.getUint8(i+5),t.getUint8(i+6),t.getUint8(i+7));if(e===0&&(e=r-i),e<8||i+e>r)break;if(a===`tkhd`){let n=t.getUint8(i+8),r=i+Xt(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else Yt.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var Qt=1920,$t=1080,en=640,tn=32,nn=79e5,rn=2073600,an=.95,on={avc:1,hevc:1/.6,vp9:1/.6,av1:1/.4,vp8:1/1.2};function sn(e,t){let n=nn*(t/rn)**an;if(!e.bitrate||!e.pixels)return Math.round(n);let r=(e.codec&&on[e.codec])??1,i=e.bitrate*r*(t/e.pixels)**an;return Math.round(Math.min(n,i))}function cn(){return typeof VideoEncoder<`u`}function ln(e,t){console.warn(`[jant] video probe: ${e} failed`,t)}async function Y(e,t){try{return await t()}catch(t){ln(e,t);return}}function un(e,t,n){let r=document.createElement(`canvas`);r.width=t,r.height=n;let i=r.getContext(`2d`);return i?(i.drawImage(e,0,0,t,n),{canvas:r,ctx:i}):null}async function dn(e){let{Input:t,BlobSource:n,ALL_FORMATS:r,CanvasSink:i}=await Gt(),a=new t({source:new n(e),formats:r});try{let e=await Y(`open video track`,()=>a.getPrimaryVideoTrack());if(!e)return{};let t=await Y(`read codec`,()=>e.getCodec()),n=await Y(`compute bitrate`,async()=>(await e.computePacketStats()).averageBitrate),r=await Y(`compute duration`,()=>a.computeDuration()),o={sourceWidth:e.displayWidth,sourceHeight:e.displayHeight,rotation:e.rotation,durationSeconds:r===void 0?void 0:u(r),videoCodec:t,videoBitrate:n},s=r===void 0?0:Math.min(r*.1,1),c=await Y(`capture frame`,()=>new i(e).getCanvas(s));if(!c)return o;let l=c.canvas,d=l.width,f=l.height,p=Math.min(en/d,1),m=un(l,Math.round(d*p),Math.round(f*p)),h=m?await Y(`encode poster`,()=>new Promise(e=>{m.canvas.toBlob(t=>e(t??void 0),`image/webp`,.8)})):void 0,g=Math.min(tn/d,tn/f,1),_=Math.max(Math.round(d*g),1),v=Math.max(Math.round(f*g),1),y=un(l,_,v),b=y?await Y(`encode blurhash`,async()=>N(y.ctx.getImageData(0,0,_,v).data,_,v,4,3)):void 0;return{...o,poster:h,blurhash:b}}finally{a.dispose()}}function fn(e,t){let{width:n,height:r}=e,i=n||t.maxLongEdge,a=r||t.maxShortEdge,o=!1;if(n&&r){let e=Math.max(n,r),s=Math.min(n,r),c=Math.min(t.maxLongEdge/e,t.maxShortEdge/s,1);o=c<1,o&&(i=Math.round(n*c),a=Math.round(r*c),i+=i%2,a+=a%2)}let s=o||e.videoCodec!==`avc`;return{needsResize:o,width:i,height:a,videoNeedsReencode:s,videoBitrate:s?sn({pixels:(n??0)*(r??0),bitrate:e.videoBitrate,codec:e.videoCodec},i*a):void 0}}async function pn(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s,videoCodec:c,videoBitrate:l}=await dn(e),{needsResize:u,width:d,height:f,videoBitrate:p}=fn({width:i,height:a,videoCodec:c,videoBitrate:l},{maxLongEdge:Qt,maxShortEdge:$t}),{Input:m,Output:h,Mp4OutputFormat:g,BufferTarget:_,BlobSource:v,Conversion:y,Quality:b,ALL_FORMATS:x}=await Gt(),S=new m({source:new v(e),formats:x}),C=new _,w=new h({format:new g({fastStart:`in-memory`}),target:C});try{let i=await y.init({input:S,output:w,video:{codec:`avc`,...u?{width:d,height:f,fit:`contain`}:{},...p===void 0?{}:{quality:new b({bitrate:p})}},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=C.buffer;if(!a)throw Error(`Video processing produced no output`);Zt(a);let c=e.name.replace(/\.[^.]+$/,``),l=new File([a],`${c}.mp4`,{type:`video/mp4`}),m=await _n(l),h=Math.abs(m.width-d)<=2&&Math.abs(m.height-f)<=2;return o&&!h&&(gn(a),l=new File([a],`${c}.mp4`,{type:`video/mp4`}),m=await _n(l)),{file:l,width:m.width,height:m.height,durationSeconds:s,poster:n,blurhash:r}}finally{S.dispose()}}var mn=[65536,0,0,0,65536,0,0,0,1073741824];function hn(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`)&&hn(e,i+8,i+t,r),i+=t}}function gn(e){let t=new DataView(e);hn(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)!==mn[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,mn[e])})}function _n(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 vn={isSupported:cn,processToFile:pn};async function yn(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function bn(e,t,n=`POST`){try{return await fetch(e,{method:n,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:t})}catch{return null}}async function xn(e,t){if(!e)return t?.publishFailedOffline??`Couldn't reach the server. Try again.`;let n=await S(e);return C(n,`error`)??t?.publishFailed??`Couldn't publish. Try again.`}function Sn(e){try{return A(JSON.parse(e))}catch{return!1}}function Cn(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function wn(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function Tn(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?f(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?_(e.replyRefreshId):h(e.replyRefreshId)}var En=new Map,Dn=new Set,X=new Map,Z=null;function Q(){if(!Z)return;let{clientIds:e,baseMsg:t}=Z;if(e.length===0)return;let r=0,i=0;for(let t of e){let e=X.get(t)??0;r+=Math.min(1,Math.max(0,e)),e>=1&&(i+=1)}let a=e.length,o=Math.floor(r/a*100),s=Math.min(i+1,a),c=a===1?`${t} ${o}%`:`${t} ${o}% ${s}/${a}`;n(`compose-deferred`,c)}var $=new Map;function On(e,t){if(!e||e.isConnected)return e;let n=document.querySelectorAll(`jant-compose-editor`);for(let e of n)if(e.hasAttachment(t))return e;return e}function kn(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})}var An=12;async function jn(e){let t=await e.slice(0,An).arrayBuffer();return Je(new Uint8Array(t))===`image/heic`}async function Mn(e,t,n){let r=()=>On(n,t),i=e.type,a=e.name;try{let n,o,s,c,u,d,f;if(i.startsWith(`video/`)){if(!vn.isSupported())return r()?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;let i=kn(e).then(e=>(e&&r()?.updateAttachmentPoster(t,e),e)).catch(()=>null);r()?.updateAttachmentStatus(t,`processing`,null,null);let a=await vn.processToFile(e,e=>{r()?.updateAttachmentProgress(t,e)});n=a.file,e=null,o=a.width,s=a.height,c=a.durationSeconds,u=a.blurhash,f=a.poster??await i??void 0,f&&r()?.updateAttachmentPoster(t,f)}else if(i.startsWith(`audio/`)){if(!Jt.isSupported())return r()?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{d=await yn(e)}catch{}r()?.updateAttachmentStatus(t,`processing`,null,null),n=(await Jt.processToFile(e,e=>{r()?.updateAttachmentProgress(t,e)})).file,e=null}else if(i.startsWith(`image/`)||/\.heic$/i.test(a)||/\.heif$/i.test(a)){let i=e;try{if(await jn(i)){let{heicTo:e}=await y(async()=>{let{heicTo:e}=await import(`./chunks/heic-to-CuP2Qlsw.js`);return{heicTo:e}},[]);r()?.updateAttachmentStatus(t,`processing`,null,null);let n=await e({blob:i,type:`image/jpeg`,quality:.92});i=new File([n],a.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),r()?.updateAttachmentPreview(t,i)}let c=await ae.processToFile(i);n=c.file,o=c.width,s=c.height,u=c.blurhash,e=null,i=null}catch{return r()?.removeAttachment(t),l(`Image format not supported.`,`error`),null}}else n=e;r()?.updateAttachmentStatus(t,`uploading`,null,null);let p,m;if(F(i)===`text`)try{let e=await n.text(),t=e.replace(/\s+/g,` `).trim();m=e.length,p=t.length<=100?t:t.slice(0,100)+`…`}catch{}X.set(t,0),Q();let h=await ce(n,{width:o,height:s,durationSeconds:c,blurhash:u,waveform:d,poster:f,summary:p,chars:m},e=>{r()?.updateAttachmentProgress(t,e),X.set(t,e),Q()});return X.set(t,1),Q(),r()?.updateAttachmentStatus(t,`done`,h.id,null,h.url),$.set(t,h),h.id}catch(e){X.delete(t),Q();let i=e instanceof Error?e.message:`Upload failed`;return r()?.updateAttachmentStatus(t,`error`,null,i),n||l(i,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n,persisted:i}=e.detail;$.delete(t),!i&&(n?fetch(r(`/api/media/${n}`),{method:`DELETE`}).catch(()=>{}):Dn.add(t))}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=Cn(t.target);for(let{file:e,clientId:i}of t.detail.files){let t=Mn(e,i,n).then(e=>Dn.has(i)?(Dn.delete(i),e&&fetch(r(`/api/media/${e}`),{method:`DELETE`}).catch(()=>{}),null):e);En.set(i,t),t.finally(()=>En.delete(i))}});function Nn(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.replyToId?void 0:e.collectionIds,attachments:i||t.length>0?t:void 0,replyToId:e.replyToId||void 0,quietReply:e.quietReply||void 0,language:e.language||void 0,translationOfId:i?void 0:e.translationOfId||void 0}}function Pn(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function Fn(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??$.get(r.clientId)?.id;if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!Pn(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:oe(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let n=e,i=n.detail,o=wn(n.target)??document.querySelector(`jant-compose-dialog`),c=!!o?.pageMode,u=!!document.querySelector(`[data-preview-status]`),d=o?.labels,p=d?.uploading??`Uploading...`,m=d?.publishing??`Publishing...`,g=d?.saving??`Saving...`,v=i.threadPosts?i.threadPosts.some(e=>Sn(e.body)):Sn(i.body),y=i.pendingAttachments.length>0||v,b=d?.published??`Published!`,x=d?.view??`View`,w=!!i.editPostId,ee=!!(i.threadPosts&&i.threadPosts.length>=2),te=i.status===`published`&&(!w||!!i.draftSourceId),T=!0;a(`compose-deferred`,y?p:te?m:g),i.pendingAttachments.length>0&&(Z={clientIds:i.pendingAttachments.map(e=>e.clientId),baseMsg:p},Q());let E=(e,n=`success`)=>{if(Z){for(let e of Z.clientIds)X.delete(e);Z=null}T?(T=!1,t(`compose-deferred`,e,n)):l(e,n)},D=()=>{c&&o&&(o.reset(),o.updateComplete.then(()=>{o.querySelector(`jant-compose-editor`)?.focusInput()}))},ne=()=>{c&&o&&(o.loading=!1)},O=()=>{if(w){i.editPostId&&o?.clearEditDraftFromStorage?.(i.editPostId);return}o?.clearLocalDraftFromStorage?.()},re=()=>{let e=i.threadPosts?.length?i.threadPosts:[i],t=[],n=new Set;for(let r of e)for(let e of r.attachments){if(e.type!==`media`||n.has(e.clientId))continue;n.add(e.clientId);let r=$.get(e.clientId);r&&t.push({clientId:e.clientId,mediaId:r.id,url:r.url,mimeType:r.mimeType,name:r.originalName||void 0,alt:e.alt||void 0})}return t},ie=async()=>{if(o&&!c){if(i.draftSourceId){if(typeof o.openDraft!=`function`)return;await o.openDraft(i.draftSourceId);return}if(w&&i.editPostId){if(typeof o.openEdit!=`function`)return;await o.openEdit(i.editPostId,{restoreToast:!1});return}if(i.replyToId){if(typeof o.openReply!=`function`)return;await o.openReply(i.replyToId,void 0,i.replyThreadRootId,i.replyRefreshKind&&i.replyRefreshId?{kind:i.replyRefreshKind,id:i.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:i.format,restoreToast:!1,restoreMedia:re()});return}typeof o.openNew==`function`&&await o.openNew({restoreDraft:!0,restoreToast:!1,restoreMedia:re()})}},k=async e=>{ne(),await ie(),E(e,`error`)},A=async()=>{await o?.refreshCollections()},j=(e,t)=>{s(e,`success`,t)},M=()=>!c||!o||!o.consumePageLeaveRequest()?!1:(o.preparePageLeave(),globalThis.location.assign(o.closeHref||r(`/`)),!0),N=null;try{let e=i.pendingAttachments.map(e=>e.clientId),t=e.map(e=>En.get(e)??Promise.resolve(null)),n=await Promise.all(t);if(n.filter((t,n)=>t===null&&!$.has(e[n]??``)).length>0){if(i.status===`published`&&!w)N=`upload`;else{await k(`Upload failed. Post not created.`);return}}let a=new Map;for(let t=0;t<e.length;t++){let r=e[t],i=n[t];r&&i&&a.set(r,i)}if(ee&&i.threadPosts){let e=i.threadPosts,t=N?`draft`:i.status,n=(await Promise.all(e.map(async e=>{let n=e.body;if(Sn(n))try{let e=JSON.parse(n),t=await pe(e);n=t?JSON.stringify(t):``}catch{}return{...e,body:n,status:t}}))).map(e=>Nn(e,Fn(e,a))),r={posts:n};w&&i.editPostId&&(r.replaceThreadId=i.editPostId);let s=await bn(`/compose/thread`,JSON.stringify(r));if(!s?.ok){if(i.status===`published`&&!N){let e={posts:n.map(e=>({...e,status:`draft`}))};if((await bn(`/compose/thread`,JSON.stringify(e)))?.ok){N=`server`,O();let e=d?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await A(),M()||D(),E(e);return}}await k(await xn(s,d));return}if(N===`upload`){O();let e=d?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await A(),D(),E(e);return}let l=await S(s),f=C(l,`status`),p=C(l,`permalink`),m=C(l,`toast`);if(f===`published`)O(),u&&i.draftSourceId?(j(b),globalThis.location.assign(p??globalThis.location.pathname)):c?(await A(),D(),E(b)):(j(b,p?{label:x,href:p}:void 0),globalThis.location.reload());else{if(O(),u&&i.draftSourceId){j(m??`Draft saved.`),globalThis.location.assign(globalThis.location.pathname);return}await A(),M()||D(),E(m??`Draft saved.`),In(o,`draft`)}return}let s=Fn(i,a);if(v)try{let e=JSON.parse(i.body),t=await pe(e);i.body=t?JSON.stringify(t):``}catch{}let l=w?`/api/posts/${i.editPostId}`:`/compose`,p=w?`PUT`:`POST`,m=Nn({...i,status:N?`draft`:i.status},s),g=await bn(l,JSON.stringify(m),p);if(!g?.ok){if(i.status===`published`&&!w&&!N){let e={...m,status:`draft`},t=await bn(l,JSON.stringify(e),p);if(t?.ok){N=`server`,O();let e=await S(t),n=d?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await A(),M()||D(),E(n);let r=C(e,`toast`);r&&E(r);return}}await k(await xn(g,d));return}if(w){O();let e=await S(g),t=i.editPostId??``,n=C(e,`slug`),a=C(e,`status`)??i.status,s=n?r(a===`draft`?`/preview/${n}`:`/${n}`):null,l=a===`draft`?`Draft saved.`:i.draftSourceId?b:`Post updated.`;if(a===`draft`){if(u){j(l),globalThis.location.assign(s??globalThis.location.pathname);return}await A(),E(l),In(o,`draft`);return}if(c)s&&s!==globalThis.location.pathname?(j(l),globalThis.location.assign(s)):t&&await _(t)?E(l):(j(l),globalThis.location.assign(globalThis.location.pathname));else if(t){if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`)){if(s&&s!==globalThis.location.pathname){j(l),globalThis.location.assign(s);return}await _(t)?E(l):(j(l),globalThis.location.reload())}else{let e=document.querySelector(`article[data-post-id="${t}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await f(e):await h(t))?E(l):(j(l),globalThis.location.reload())}}else j(l),globalThis.location.reload();return}if(N===`upload`){O();let e=d?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await A(),D(),E(e);return}let y=await S(g),te=C(y,`status`),T=C(y,`permalink`),ne=C(y,`toast`);if(te===`published`){if(O(),c)await A(),D(),E(b);else if(i.replyToId){if(await A(),!await Tn(i)){j(b,T?{label:x,href:T}:void 0),globalThis.location.reload();return}E(b)}else j(b,T?{label:x,href:T}:void 0),globalThis.location.reload();return}O(),await A(),M()||D(),E(ne??`Draft saved.`),In(o,`draft`)}catch{await k(await xn(null,d))}});function In(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{}),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`));
2004
+ `}};customElements.define(`jant-compose-fullscreen`,Ut);var Wt;function Gt(){return Wt??=f(()=>import(`./chunks/mediabunny-DRaCQ1r-.js`).then(e=>e.t),__vite__mapDeps([2,1])),Wt}function Kt(){return typeof AudioEncoder<`u`}async function qt(e,t){let{Input:n,Output:r,Mp4OutputFormat:i,BufferTarget:a,BlobSource:o,Conversion:s,ALL_FORMATS:c}=await Gt(),l=new n({source:new o(e),formats:c}),u=new a,d=new r({format:new i({fastStart:`in-memory`}),target:u});try{let n=await s.init({input:l,output:d,video:{discard:!0},audio:{codec:`aac`}});t&&(n.onProgress=t),await n.execute();let r=u.buffer;if(!r)throw Error(`Audio processing produced no output`);let i=e.name.replace(/\.[^.]+$/,``);return{file:new File([r],`${i}.m4a`,{type:`audio/mp4`})}}finally{l.dispose()}}var Jt={isSupported:Kt,processToFile:qt},Yt=new Set([`moov`,`trak`]);function Xt(e){return 12+(e===1?32:20)+8+2}function Zt(e){let t=new DataView(e),n=(e,r)=>{let i=e;for(;i+8<=r;){let e=t.getUint32(i),a=String.fromCharCode(t.getUint8(i+4),t.getUint8(i+5),t.getUint8(i+6),t.getUint8(i+7));if(e===0&&(e=r-i),e<8||i+e>r)break;if(a===`tkhd`){let n=t.getUint8(i+8),r=i+Xt(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else Yt.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var Qt=1920,$t=1080,en=640,tn=32,nn=79e5,rn=2073600,an=.95,on={avc:1,hevc:1/.6,vp9:1/.6,av1:1/.4,vp8:1/1.2};function sn(e,t){let n=nn*(t/rn)**an;if(!e.bitrate||!e.pixels)return Math.round(n);let r=(e.codec&&on[e.codec])??1,i=e.bitrate*r*(t/e.pixels)**an;return Math.round(Math.min(n,i))}function cn(){return typeof VideoEncoder<`u`}function ln(e,t){console.warn(`[jant] video probe: ${e} failed`,t)}async function Y(e,t){try{return await t()}catch(t){ln(e,t);return}}function un(e,t,n){let r=document.createElement(`canvas`);r.width=t,r.height=n;let i=r.getContext(`2d`);return i?(i.drawImage(e,0,0,t,n),{canvas:r,ctx:i}):null}async function dn(e){let{Input:t,BlobSource:r,ALL_FORMATS:i,CanvasSink:a}=await Gt(),o=new t({source:new r(e),formats:i});try{let e=await Y(`open video track`,()=>o.getPrimaryVideoTrack());if(!e)return{};let t=await Y(`read codec`,()=>e.getCodec()),r=await Y(`compute bitrate`,async()=>(await e.computePacketStats()).averageBitrate),i=await Y(`compute duration`,()=>o.computeDuration()),s={sourceWidth:e.displayWidth,sourceHeight:e.displayHeight,rotation:e.rotation,durationSeconds:i===void 0?void 0:n(i),videoCodec:t,videoBitrate:r},c=i===void 0?0:Math.min(i*.1,1),l=await Y(`capture frame`,()=>new a(e).getCanvas(c));if(!l)return s;let u=l.canvas,d=u.width,f=u.height,p=Math.min(en/d,1),m=un(u,Math.round(d*p),Math.round(f*p)),h=m?await Y(`encode poster`,()=>new Promise(e=>{m.canvas.toBlob(t=>e(t??void 0),`image/webp`,.8)})):void 0,g=Math.min(tn/d,tn/f,1),_=Math.max(Math.round(d*g),1),v=Math.max(Math.round(f*g),1),y=un(u,_,v),b=y?await Y(`encode blurhash`,async()=>N(y.ctx.getImageData(0,0,_,v).data,_,v,4,3)):void 0;return{...s,poster:h,blurhash:b}}finally{o.dispose()}}function fn(e,t){let{width:n,height:r}=e,i=n||t.maxLongEdge,a=r||t.maxShortEdge,o=!1;if(n&&r){let e=Math.max(n,r),s=Math.min(n,r),c=Math.min(t.maxLongEdge/e,t.maxShortEdge/s,1);o=c<1,o&&(i=Math.round(n*c),a=Math.round(r*c),i+=i%2,a+=a%2)}let s=o||e.videoCodec!==`avc`;return{needsResize:o,width:i,height:a,videoNeedsReencode:s,videoBitrate:s?sn({pixels:(n??0)*(r??0),bitrate:e.videoBitrate,codec:e.videoCodec},i*a):void 0}}async function pn(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s,videoCodec:c,videoBitrate:l}=await dn(e),{needsResize:u,width:d,height:f,videoBitrate:p}=fn({width:i,height:a,videoCodec:c,videoBitrate:l},{maxLongEdge:Qt,maxShortEdge:$t}),{Input:m,Output:h,Mp4OutputFormat:g,BufferTarget:_,BlobSource:v,Conversion:y,Quality:b,ALL_FORMATS:x}=await Gt(),S=new m({source:new v(e),formats:x}),C=new _,w=new h({format:new g({fastStart:`in-memory`}),target:C});try{let i=await y.init({input:S,output:w,video:{codec:`avc`,...u?{width:d,height:f,fit:`contain`}:{},...p===void 0?{}:{quality:new b({bitrate:p})}},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=C.buffer;if(!a)throw Error(`Video processing produced no output`);Zt(a);let c=e.name.replace(/\.[^.]+$/,``),l=new File([a],`${c}.mp4`,{type:`video/mp4`}),m=await _n(l),h=Math.abs(m.width-d)<=2&&Math.abs(m.height-f)<=2;return o&&!h&&(gn(a),l=new File([a],`${c}.mp4`,{type:`video/mp4`}),m=await _n(l)),{file:l,width:m.width,height:m.height,durationSeconds:s,poster:n,blurhash:r}}finally{S.dispose()}}var mn=[65536,0,0,0,65536,0,0,0,1073741824];function hn(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`)&&hn(e,i+8,i+t,r),i+=t}}function gn(e){let t=new DataView(e);hn(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)!==mn[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,mn[e])})}function _n(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 vn={isSupported:cn,processToFile:pn};async function yn(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function bn(e,t,n=`POST`){try{return await fetch(e,{method:n,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:t})}catch{return null}}async function xn(e,t){if(!e)return t?.publishFailedOffline??`Couldn't reach the server. Try again.`;let n=await b(e);return x(n,`error`)??t?.publishFailed??`Couldn't publish. Try again.`}function Sn(e){try{return A(JSON.parse(e))}catch{return!1}}function Cn(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function wn(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function Tn(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?p(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?v(e.replyRefreshId):g(e.replyRefreshId)}var En=new Map,Dn=new Set,X=new Map,Z=null;function Q(){if(!Z)return;let{clientIds:e,baseMsg:t}=Z;if(e.length===0)return;let n=0,r=0;for(let t of e){let e=X.get(t)??0;n+=Math.min(1,Math.max(0,e)),e>=1&&(r+=1)}let a=e.length,o=Math.floor(n/a*100),s=Math.min(r+1,a),c=a===1?`${t} ${o}%`:`${t} ${o}% ${s}/${a}`;i(`compose-deferred`,c)}var $=new Map;function On(e,t){if(!e||e.isConnected)return e;let n=document.querySelectorAll(`jant-compose-editor`);for(let e of n)if(e.hasAttachment(t))return e;return e}function kn(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})}var An=12;async function jn(e){let t=await e.slice(0,An).arrayBuffer();return Je(new Uint8Array(t))===`image/heic`}async function Mn(e,t,n){let r=()=>On(n,t),i=e.type,a=e.name;try{let n,o,s,c,l,d,p;if(i.startsWith(`video/`)){if(!vn.isSupported())return r()?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;let i=kn(e).then(e=>(e&&r()?.updateAttachmentPoster(t,e),e)).catch(()=>null);r()?.updateAttachmentStatus(t,`processing`,null,null);let a=await vn.processToFile(e,e=>{r()?.updateAttachmentProgress(t,e)});n=a.file,e=null,o=a.width,s=a.height,c=a.durationSeconds,l=a.blurhash,p=a.poster??await i??void 0,p&&r()?.updateAttachmentPoster(t,p)}else if(i.startsWith(`audio/`)){if(!Jt.isSupported())return r()?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{d=await yn(e)}catch{}r()?.updateAttachmentStatus(t,`processing`,null,null),n=(await Jt.processToFile(e,e=>{r()?.updateAttachmentProgress(t,e)})).file,e=null}else if(i.startsWith(`image/`)||/\.heic$/i.test(a)||/\.heif$/i.test(a)){let i=e;try{if(await jn(i)){let{heicTo:e}=await f(async()=>{let{heicTo:e}=await import(`./chunks/heic-to-CuP2Qlsw.js`);return{heicTo:e}},[]);r()?.updateAttachmentStatus(t,`processing`,null,null);let n=await e({blob:i,type:`image/jpeg`,quality:.92});i=new File([n],a.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),r()?.updateAttachmentPreview(t,i)}let c=await ae.processToFile(i);n=c.file,o=c.width,s=c.height,l=c.blurhash,e=null,i=null}catch{return r()?.removeAttachment(t),u(`Image format not supported.`,`error`),null}}else n=e;r()?.updateAttachmentStatus(t,`uploading`,null,null);let m,h;if(F(i)===`text`)try{let e=await n.text(),t=e.replace(/\s+/g,` `).trim();h=e.length,m=t.length<=100?t:t.slice(0,100)+`…`}catch{}X.set(t,0),Q();let g=await ce(n,{width:o,height:s,durationSeconds:c,blurhash:l,waveform:d,poster:p,summary:m,chars:h},e=>{r()?.updateAttachmentProgress(t,e),X.set(t,e),Q()});return X.set(t,1),Q(),r()?.updateAttachmentStatus(t,`done`,g.id,null,g.url),$.set(t,g),g.id}catch(e){X.delete(t),Q();let i=e instanceof Error?e.message:`Upload failed`;return r()?.updateAttachmentStatus(t,`error`,null,i),n||u(i,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:n,mediaId:r,persisted:i}=e.detail;$.delete(n),!i&&(r?fetch(t(`/api/media/${r}`),{method:`DELETE`}).catch(()=>{}):Dn.add(n))}),document.addEventListener(`jant:files-selected`,e=>{let n=e,r=Cn(n.target);for(let{file:e,clientId:i}of n.detail.files){let n=Mn(e,i,r).then(e=>Dn.has(i)?(Dn.delete(i),e&&fetch(t(`/api/media/${e}`),{method:`DELETE`}).catch(()=>{}),null):e);En.set(i,n),n.finally(()=>En.delete(i))}});function Nn(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.replyToId?void 0:e.collectionIds,attachments:i||t.length>0?t:void 0,replyToId:e.replyToId||void 0,quietReply:e.quietReply||void 0,language:e.language||void 0,translationOfId:i?void 0:e.translationOfId||void 0}}function Pn(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function Fn(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??$.get(r.clientId)?.id;if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!Pn(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:oe(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let n=e,i=n.detail,a=wn(n.target)??document.querySelector(`jant-compose-dialog`),s=!!a?.pageMode,l=!!document.querySelector(`[data-preview-status]`),d=a?.labels,f=d?.uploading??`Uploading...`,m=d?.publishing??`Publishing...`,h=d?.saving??`Saving...`,_=i.threadPosts?i.threadPosts.some(e=>Sn(e.body)):Sn(i.body),y=i.pendingAttachments.length>0||_,S=d?.published??`Published!`,C=d?.view??`View`,w=!!i.editPostId,ee=!!(i.threadPosts&&i.threadPosts.length>=2),te=i.status===`published`&&(!w||!!i.draftSourceId),T=!0;o(`compose-deferred`,y?f:te?m:h),i.pendingAttachments.length>0&&(Z={clientIds:i.pendingAttachments.map(e=>e.clientId),baseMsg:f},Q());let E=(e,t=`success`)=>{if(Z){for(let e of Z.clientIds)X.delete(e);Z=null}T?(T=!1,r(`compose-deferred`,e,t)):u(e,t)},D=()=>{s&&a&&(a.reset(),a.updateComplete.then(()=>{a.querySelector(`jant-compose-editor`)?.focusInput()}))},ne=()=>{s&&a&&(a.loading=!1)},O=()=>{if(w){i.editPostId&&a?.clearEditDraftFromStorage?.(i.editPostId);return}a?.clearLocalDraftFromStorage?.()},re=()=>{let e=i.threadPosts?.length?i.threadPosts:[i],t=[],n=new Set;for(let r of e)for(let e of r.attachments){if(e.type!==`media`||n.has(e.clientId))continue;n.add(e.clientId);let r=$.get(e.clientId);r&&t.push({clientId:e.clientId,mediaId:r.id,url:r.url,mimeType:r.mimeType,name:r.originalName||void 0,alt:e.alt||void 0})}return t},ie=async()=>{if(a&&!s){if(i.draftSourceId){if(typeof a.openDraft!=`function`)return;await a.openDraft(i.draftSourceId);return}if(w&&i.editPostId){if(typeof a.openEdit!=`function`)return;await a.openEdit(i.editPostId,{restoreToast:!1});return}if(i.replyToId){if(typeof a.openReply!=`function`)return;await a.openReply(i.replyToId,void 0,i.replyThreadRootId,i.replyRefreshKind&&i.replyRefreshId?{kind:i.replyRefreshKind,id:i.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:i.format,restoreToast:!1,restoreMedia:re()});return}typeof a.openNew==`function`&&await a.openNew({restoreDraft:!0,restoreToast:!1,restoreMedia:re()})}},k=async e=>{ne(),await ie(),E(e,`error`)},A=async()=>{await a?.refreshCollections()},j=(e,t)=>{c(e,`success`,t)},M=()=>!s||!a||!a.consumePageLeaveRequest()?!1:(a.preparePageLeave(),globalThis.location.assign(a.closeHref||t(`/`)),!0),N=null;try{let e=i.pendingAttachments.map(e=>e.clientId),n=e.map(e=>En.get(e)??Promise.resolve(null)),r=await Promise.all(n);if(r.filter((t,n)=>t===null&&!$.has(e[n]??``)).length>0){if(i.status===`published`&&!w)N=`upload`;else{await k(`Upload failed. Post not created.`);return}}let o=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=r[t];n&&i&&o.set(n,i)}if(ee&&i.threadPosts){let e=i.threadPosts,t=N?`draft`:i.status,n=(await Promise.all(e.map(async e=>{let n=e.body;if(Sn(n))try{let e=JSON.parse(n),t=await pe(e);n=t?JSON.stringify(t):``}catch{}return{...e,body:n,status:t}}))).map(e=>Nn(e,Fn(e,o))),r={posts:n};w&&i.editPostId&&(r.replaceThreadId=i.editPostId);let c=await bn(`/compose/thread`,JSON.stringify(r));if(!c?.ok){if(i.status===`published`&&!N){let e={posts:n.map(e=>({...e,status:`draft`}))};if((await bn(`/compose/thread`,JSON.stringify(e)))?.ok){N=`server`,O();let e=d?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await A(),M()||D(),E(e);return}}await k(await xn(c,d));return}if(N===`upload`){O();let e=d?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await A(),D(),E(e);return}let u=await b(c),f=x(u,`status`),p=x(u,`permalink`),m=x(u,`toast`);if(f===`published`)O(),l&&i.draftSourceId?(j(S),globalThis.location.assign(p??globalThis.location.pathname)):s?(await A(),D(),E(S)):(j(S,p?{label:C,href:p}:void 0),globalThis.location.reload());else{if(O(),l&&i.draftSourceId){j(m??`Draft saved.`),globalThis.location.assign(globalThis.location.pathname);return}await A(),M()||D(),E(m??`Draft saved.`),In(a,`draft`)}return}let c=Fn(i,o);if(_)try{let e=JSON.parse(i.body),t=await pe(e);i.body=t?JSON.stringify(t):``}catch{}let u=w?`/api/posts/${i.editPostId}`:`/compose`,f=w?`PUT`:`POST`,m=Nn({...i,status:N?`draft`:i.status},c),h=await bn(u,JSON.stringify(m),f);if(!h?.ok){if(i.status===`published`&&!w&&!N){let e={...m,status:`draft`},t=await bn(u,JSON.stringify(e),f);if(t?.ok){N=`server`,O();let e=await b(t),n=d?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await A(),M()||D(),E(n);let r=x(e,`toast`);r&&E(r);return}}await k(await xn(h,d));return}if(w){O();let e=await b(h),n=i.editPostId??``,r=x(e,`slug`),o=x(e,`status`)??i.status,c=r?t(o===`draft`?`/preview/${r}`:`/${r}`):null,u=o===`draft`?`Draft saved.`:i.draftSourceId?S:`Post updated.`;if(o===`draft`){if(l){j(u),globalThis.location.assign(c??globalThis.location.pathname);return}await A(),E(u),In(a,`draft`);return}if(s)c&&c!==globalThis.location.pathname?(j(u),globalThis.location.assign(c)):n&&await v(n)?E(u):(j(u),globalThis.location.assign(globalThis.location.pathname));else if(n){if(document.querySelector(`[data-post-view][data-post-view-id="${n}"]`)){if(c&&c!==globalThis.location.pathname){j(u),globalThis.location.assign(c);return}await v(n)?E(u):(j(u),globalThis.location.reload())}else{let e=document.querySelector(`article[data-post-id="${n}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await p(e):await g(n))?E(u):(j(u),globalThis.location.reload())}}else j(u),globalThis.location.reload();return}if(N===`upload`){O();let e=d?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await A(),D(),E(e);return}let y=await b(h),te=x(y,`status`),T=x(y,`permalink`),ne=x(y,`toast`);if(te===`published`){if(O(),s)await A(),D(),E(S);else if(i.replyToId){if(await A(),!await Tn(i)){j(S,T?{label:C,href:T}:void 0),globalThis.location.reload();return}E(S)}else j(S,T?{label:C,href:T}:void 0),globalThis.location.reload();return}O(),await A(),M()||D(),E(ne??`Draft saved.`),In(a,`draft`)}catch{await k(await xn(null,d))}});function In(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{}),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`));