@jant/core 0.10.0 → 0.12.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 (625) hide show
  1. package/bin/commands/db/execute-file.js +1 -1
  2. package/bin/commands/db/export.js +1 -1
  3. package/bin/commands/deploy.js +179 -0
  4. package/bin/commands/migrate.js +4 -4
  5. package/bin/commands/posts/rebuild-html.js +1 -1
  6. package/bin/commands/reset-password.js +1 -1
  7. package/bin/commands/search/reindex.js +1 -1
  8. package/bin/commands/setup.js +4 -2
  9. package/bin/commands/site/export.js +3 -0
  10. package/bin/commands/site/import.js +178 -91
  11. package/bin/commands/site/pull-media.js +3 -2
  12. package/bin/commands/site/snapshot/export.js +3 -1
  13. package/bin/commands/site/snapshot/import.js +3 -2
  14. package/bin/commands/start.js +44 -0
  15. package/bin/commands/telegram/register-webhooks.js +1 -1
  16. package/bin/commands/uploads/cleanup.js +48 -9
  17. package/bin/jant.js +39 -4
  18. package/bin/lib/cloudflare-setup.js +499 -0
  19. package/bin/lib/d1-query.js +26 -1
  20. package/bin/lib/import-sources.js +151 -0
  21. package/bin/lib/node-env.js +14 -9
  22. package/bin/lib/r2-query.js +2 -2
  23. package/bin/lib/runtime-target.js +1 -1
  24. package/bin/lib/site-pull-media.js +56 -4
  25. package/bin/lib/site-snapshot.js +39 -2
  26. package/bin/lib/sql-export.js +66 -10
  27. package/dist/{app-DIVtyB4m.js → app-DSwsDBD0.js} +38257 -9662
  28. package/dist/client/.vite/manifest.json +38 -38
  29. package/dist/client/_assets/chunks/{create-editor-B-m7X7S5.js → create-editor-5Y49x7h5.js} +2 -2
  30. package/dist/client/_assets/chunks/{footnote-rail-CmeoVtnU.js → footnote-rail-BJwswtVQ.js} +1 -1
  31. package/dist/client/_assets/chunks/{settings-paths-C-ZZBTau.js → settings-paths-h6RjIe3C.js} +2 -2
  32. package/dist/client/_assets/chunks/{slug-format-BcIsNKz-.js → slug-format-Dsi0e9Xn.js} +1 -1
  33. package/dist/client/_assets/chunks/{slugify-373citbs.js → slugify-DlHLyUHS.js} +1 -1
  34. package/dist/client/_assets/chunks/sortable-list-DYMcJrlS.js +2 -0
  35. package/dist/client/_assets/chunks/unsafe-svg-DxrzM_Gb.js +2 -0
  36. package/dist/client/_assets/client-BaqmpPQ-.css +2 -0
  37. package/dist/client/_assets/client-DPByjWoU.js +296 -0
  38. package/dist/client/_assets/{client-auth-BpkkKTsV.js → client-auth-CPqPTX1B.js} +2 -2
  39. package/dist/client/_assets/client-author-CGVvrNZ8.css +2 -0
  40. package/dist/client/_assets/{client-compose-C-DXzcFR.js → client-compose-CzEwT5qX.js} +4 -4
  41. package/dist/client/_assets/{client-manage-BfT7ht4M.js → client-manage-CF7x21L4.js} +37 -37
  42. package/dist/client/_assets/{client-settings-CGR_nZ78.js → client-settings-DIM44Zqh.js} +2 -2
  43. package/dist/{url-CKlGzvdN.js → constants-DEgyqWDl.js} +340 -1
  44. package/dist/index.d.ts +44 -0
  45. package/dist/index.js +33 -1
  46. package/dist/node.js +57 -13
  47. package/package.json +43 -48
  48. package/src/__tests__/api-docs.test.ts +168 -1
  49. package/src/__tests__/bin/deploy.test.ts +163 -0
  50. package/src/__tests__/bin/import-sources.test.ts +85 -0
  51. package/src/__tests__/bin/uploads-cleanup.test.ts +66 -26
  52. package/src/__tests__/cli-commands.test.ts +40 -0
  53. package/src/__tests__/config-docs.test.ts +119 -16
  54. package/src/__tests__/custom-url-redirects.test.ts +108 -0
  55. package/src/__tests__/export-collection-custom-urls.test.ts +69 -0
  56. package/src/__tests__/export-docs.test.ts +113 -41
  57. package/src/__tests__/export-feed-ids.test.ts +1 -0
  58. package/src/__tests__/export-format-version.test.ts +88 -0
  59. package/src/__tests__/export-hugo-build.test.ts +143 -8
  60. package/src/__tests__/export-import-roundtrip.test.ts +3 -2
  61. package/src/__tests__/export-service.test.ts +44 -15
  62. package/src/__tests__/export-smart-collection.test.ts +1 -1
  63. package/src/__tests__/feed-docs.test.ts +287 -21
  64. package/src/__tests__/feed-reply-addresses.test.ts +100 -0
  65. package/src/__tests__/feeds-disabled.test.ts +98 -0
  66. package/src/__tests__/fixtures/export-format/1.json +76 -0
  67. package/src/__tests__/fixtures/export-format/2.json +80 -0
  68. package/src/__tests__/fixtures/releases/0.10.0/site-export/README.md +130 -0
  69. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/2thjq/_index.md +25 -0
  70. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/2u5e5/_index.md +35 -0
  71. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/41q27/0x4nv/index.md +18 -0
  72. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/41q27/_index.md +44 -0
  73. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/41q27/faqyt/index.md +30 -0
  74. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/41q27/the-potting-mix-guide-i-keep-rereading/index.md +20 -0
  75. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/5kayp/_index.md +23 -0
  76. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/5ynfs/_index.md +31 -0
  77. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/5ynfs/hu597/index.md +21 -0
  78. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/_index.md +5 -0
  79. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/a-night-heron-field-guide-for-my-walk-folder/_index.md +31 -0
  80. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/a-quiet-saturday-after-a-busy-week/_index.md +36 -0
  81. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/archive/_index.md +8 -0
  82. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/are-na-is-the-only-bookmark-pile-i-still-revisit/_index.md +30 -0
  83. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/bought-too-many-lemons-again/_index.md +37 -0
  84. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/city-walks/_index.md +12 -0
  85. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/cleanshot-for-screenshots-ocr-and-screen-recording-on-the-mac/_index.md +33 -0
  86. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/cleanshotmac-shang-de-jie-tu-ocr-lu-ping-gong-ju/_index.md +32 -0
  87. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/co344/_index.md +25 -0
  88. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/collections/_index.md +5 -0
  89. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/current-tea-rotation/_index.md +34 -0
  90. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/derek-sivers-still-writes-the-kind-of-internet-i-want-more-of/_index.md +30 -0
  91. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/desk-but-better/_index.md +25 -0
  92. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/e0kcg/_index.md +22 -0
  93. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/egi3c/_index.md +24 -0
  94. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/evf9j/_index.md +152 -0
  95. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/featured/_index.md +8 -0
  96. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/from-basho/_index.md +25 -0
  97. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/from-epictetus/_index.md +25 -0
  98. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/from-marcus-aurelius/_index.md +25 -0
  99. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/from-seneca/_index.md +26 -0
  100. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/from-thoreau/_index.md +25 -0
  101. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/gkbvv/2cl6d/index.md +18 -0
  102. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/gkbvv/3zqv7/index.md +30 -0
  103. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/gkbvv/5oxsv/index.md +18 -0
  104. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/gkbvv/_index.md +39 -0
  105. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/gwob9/_index.md +25 -0
  106. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/home-cooking/_index.md +12 -0
  107. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/hz729/_index.md +24 -0
  108. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/inaturalist-ai-zi-ran-she-qu/_index.md +44 -0
  109. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/j4v0q/_index.md +35 -0
  110. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/k278t/_index.md +25 -0
  111. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/k4eee/_index.md +22 -0
  112. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/k5vh8/_index.md +32 -0
  113. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/k5vh8/a-reading-log-idea-i-might-steal/index.md +20 -0
  114. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/k5vh8/a83qu/index.md +18 -0
  115. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/k5vh8/from-seneca-5hibo/index.md +21 -0
  116. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/kan-qi-lai-bi-jiao-ku-de-gong-si-men/_index.md +41 -0
  117. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/l2m7y/_index.md +29 -0
  118. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/lan-ya-yao-kong-qi-chuang-shang-yue-du-de-fan-ye-shen-qi/_index.md +57 -0
  119. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/mynoise-for-rainy-afternoons/_index.md +30 -0
  120. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/n09le/_index.md +23 -0
  121. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/ni-fu-jin-de-wei-ji-bai-ke-tiao-mu/_index.md +42 -0
  122. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/nts-archives-are-good-cleaning-music/_index.md +30 -0
  123. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/qgfcu/_index.md +32 -0
  124. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/qgfcu/c91j0/index.md +18 -0
  125. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/qgfcu/qyucy/index.md +18 -0
  126. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/qgfcu/wsgck/index.md +18 -0
  127. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/rain-makes-my-neighborhood-look-better/_index.md +46 -0
  128. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/reading-notes/_index.md +12 -0
  129. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/s4r3e/_index.md +25 -0
  130. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/serious-eats-on-tomato-and-egg-soup/_index.md +30 -0
  131. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/te812/_index.md +44 -0
  132. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/te812/cxiu6/index.md +18 -0
  133. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/te812/t77ms/index.md +18 -0
  134. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/te812/the-soup-trick-i-always-forget/index.md +20 -0
  135. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/telk3/_index.md +30 -0
  136. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/telk3/from-thoreau-pawt2/index.md +21 -0
  137. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/the-five-minute-reset-is-still-the-best-habit-i-have/_index.md +36 -0
  138. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/the-hallway-light-took-12-minutes-and-3-months/_index.md +32 -0
  139. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/the-recurse-center-manual-is-weirdly-calming/_index.md +30 -0
  140. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/tiny-projects/_index.md +12 -0
  141. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/tong-wang-xing-fu-zhi-lu/_index.md +68 -0
  142. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/tou-ma-yan-jiang-ju-le-bu-chu-ti-yan/_index.md +62 -0
  143. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/useful-links/_index.md +12 -0
  144. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/weekend-notes/_index.md +12 -0
  145. package/src/__tests__/fixtures/releases/0.10.0/site-export/content/what-i-actually-use-my-notebook-for/_index.md +52 -0
  146. package/src/__tests__/fixtures/releases/0.10.0/site-export/data/jant.toml +124 -0
  147. package/src/__tests__/fixtures/releases/0.10.0/site-export/hugo.toml +45 -0
  148. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/_redirects +25 -0
  149. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/40bc6cd1f12e-med_01kn8jtq3penf98tfq4gzmh9g9.png +0 -0
  150. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jtx8qenf98tm9ahxr48sw.webp +0 -0
  151. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jv0jdenf98tp6qr9zgjjc.webp +0 -0
  152. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jv452enf98trbkwrvhvgd.webp +0 -0
  153. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jvb16enf98txp7p0pf5ge.webp +0 -0
  154. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jve5nenf98tzap11gpxzr.webp +0 -0
  155. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jvq58enf98v538w5vsqp4.webp +0 -0
  156. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jvsaeenf98v6ct4gjzppc.webp +0 -0
  157. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01kn8jw26cenf98vc7k0ppz5k8.webp +0 -0
  158. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m313q1hme4e8cmby77dn66yy.webp +0 -0
  159. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m313q2w7e4e8cmc20036yh66.webp +0 -0
  160. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m313q7d2e4e8cmdeqjmyafby.webp +0 -0
  161. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m313q887e4e8cmdjssych7yh.webp +0 -0
  162. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp-poster.webp +0 -0
  163. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp.mp4 +0 -0
  164. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf-poster.webp +0 -0
  165. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf.mp4 +0 -0
  166. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb-poster.webp +0 -0
  167. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb.mp4 +0 -0
  168. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83-poster.webp +0 -0
  169. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83.mp4 +0 -0
  170. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167sm0f6ct88qw5brtsgcw.webp +0 -0
  171. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167tf8f6ct88r169s51j49.webp +0 -0
  172. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167vaaf6ct88rbx5ztenwb.webp +0 -0
  173. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167w51f6ct88rp19pybkw1.webp +0 -0
  174. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167x0nf6ct88rzajb84tw3.webp +0 -0
  175. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167xxbf6ct88s5t2300bjk.webp +0 -0
  176. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167yq5f6ct88s9pjwt5fxg.webp +0 -0
  177. package/src/__tests__/fixtures/releases/0.10.0/site-export/static/media/med_01m3167zg4f6ct88sge8jp28ja.webp +0 -0
  178. package/src/__tests__/fixtures/releases/0.10.0/site-export/themes/jant/static/apple-touch-icon.png +0 -0
  179. package/src/__tests__/fixtures/releases/0.10.0/site-export/themes/jant/static/custom.css +0 -0
  180. package/src/__tests__/fixtures/releases/0.10.0/site-export/themes/jant/static/favicon.ico +0 -0
  181. package/src/__tests__/fixtures/releases/0.10.0/site-export/wrangler.jsonc +24 -0
  182. package/src/__tests__/fixtures/releases/0.10.0/snapshot/db.sql +322 -0
  183. package/src/__tests__/fixtures/releases/0.10.0/snapshot/meta.json +11 -0
  184. package/src/__tests__/fixtures/releases/0.11.0/site-export/README.md +130 -0
  185. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/297kg/_index.md +14 -0
  186. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/2thjq/_index.md +25 -0
  187. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/2u5e5/_index.md +33 -0
  188. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/0x4nv/index.md +18 -0
  189. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/_index.md +42 -0
  190. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/faqyt/index.md +28 -0
  191. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/the-potting-mix-guide-i-keep-rereading/index.md +20 -0
  192. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/5kayp/_index.md +23 -0
  193. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/5ynfs/_index.md +31 -0
  194. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/5ynfs/hu597/index.md +21 -0
  195. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/_index.md +5 -0
  196. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/a-night-heron-field-guide-for-my-walk-folder/_index.md +31 -0
  197. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/a-quiet-saturday-after-a-busy-week/_index.md +36 -0
  198. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/archive/_index.md +8 -0
  199. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/are-na-is-the-only-bookmark-pile-i-still-revisit/_index.md +30 -0
  200. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/bought-too-many-lemons-again/_index.md +35 -0
  201. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/city-walks/_index.md +14 -0
  202. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/cleanshot-for-screenshots-ocr-and-screen-recording-on-the-mac/_index.md +33 -0
  203. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/cleanshotmac-shang-de-jie-tu-ocr-lu-ping-gong-ju/_index.md +32 -0
  204. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/co344/_index.md +25 -0
  205. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/collections/_index.md +5 -0
  206. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/current-tea-rotation/_index.md +34 -0
  207. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/derek-sivers-still-writes-the-kind-of-internet-i-want-more-of/_index.md +30 -0
  208. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/desk-but-better/_index.md +25 -0
  209. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/e0kcg/_index.md +22 -0
  210. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/egi3c/_index.md +24 -0
  211. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/evf9j/_index.md +129 -0
  212. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/featured/_index.md +8 -0
  213. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/fixture-draft/_index.md +17 -0
  214. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/fixture-quotes/_index.md +13 -0
  215. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/fixture-text-attachment/_index.md +29 -0
  216. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-basho/_index.md +25 -0
  217. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-epictetus/_index.md +25 -0
  218. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-marcus-aurelius/_index.md +25 -0
  219. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-seneca/_index.md +26 -0
  220. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-thoreau/_index.md +25 -0
  221. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/2cl6d/index.md +18 -0
  222. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/3zqv7/index.md +28 -0
  223. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/5oxsv/index.md +18 -0
  224. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/_index.md +37 -0
  225. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gwob9/_index.md +25 -0
  226. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/home-cooking/_index.md +12 -0
  227. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/hz729/_index.md +24 -0
  228. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/inaturalist-ai-zi-ran-she-qu/_index.md +42 -0
  229. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/j4v0q/_index.md +33 -0
  230. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k278t/_index.md +25 -0
  231. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k4eee/_index.md +22 -0
  232. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/_index.md +32 -0
  233. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/a-reading-log-idea-i-might-steal/index.md +20 -0
  234. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/a83qu/index.md +18 -0
  235. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/from-seneca-5hibo/index.md +21 -0
  236. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/kan-qi-lai-bi-jiao-ku-de-gong-si-men/_index.md +41 -0
  237. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/l2m7y/_index.md +29 -0
  238. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/lan-ya-yao-kong-qi-chuang-shang-yue-du-de-fan-ye-shen-qi/_index.md +52 -0
  239. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/mynoise-for-rainy-afternoons/_index.md +30 -0
  240. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/n09le/_index.md +23 -0
  241. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/ni-fu-jin-de-wei-ji-bai-ke-tiao-mu/_index.md +40 -0
  242. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/nts-archives-are-good-cleaning-music/_index.md +30 -0
  243. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/_index.md +32 -0
  244. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/c91j0/index.md +18 -0
  245. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/qyucy/index.md +18 -0
  246. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/wsgck/index.md +18 -0
  247. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/rain-makes-my-neighborhood-look-better/_index.md +44 -0
  248. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/reading-notes/_index.md +12 -0
  249. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/s4r3e/_index.md +25 -0
  250. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/serious-eats-on-tomato-and-egg-soup/_index.md +30 -0
  251. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/_index.md +42 -0
  252. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/cxiu6/index.md +18 -0
  253. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/t77ms/index.md +18 -0
  254. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/the-soup-trick-i-always-forget/index.md +20 -0
  255. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/telk3/_index.md +30 -0
  256. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/telk3/from-thoreau-pawt2/index.md +21 -0
  257. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/the-five-minute-reset-is-still-the-best-habit-i-have/_index.md +36 -0
  258. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/the-hallway-light-took-12-minutes-and-3-months/_index.md +32 -0
  259. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/the-recurse-center-manual-is-weirdly-calming/_index.md +30 -0
  260. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/tiny-projects/_index.md +12 -0
  261. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/tong-wang-xing-fu-zhi-lu/_index.md +68 -0
  262. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/tou-ma-yan-jiang-ju-le-bu-chu-ti-yan/_index.md +62 -0
  263. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/useful-links/_index.md +12 -0
  264. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/weekend-notes/_index.md +12 -0
  265. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/what-i-actually-use-my-notebook-for/_index.md +50 -0
  266. package/src/__tests__/fixtures/releases/0.11.0/site-export/data/jant.toml +155 -0
  267. package/src/__tests__/fixtures/releases/0.11.0/site-export/hugo.toml +45 -0
  268. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/_redirects +30 -0
  269. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/3c46a9ea6fe0-med_01kn8jtq3penf98tfq4gzmh9g9.png +0 -0
  270. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jtx8qenf98tm9ahxr48sw.webp +0 -0
  271. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jv0jdenf98tp6qr9zgjjc.webp +0 -0
  272. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jv452enf98trbkwrvhvgd.webp +0 -0
  273. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jvb16enf98txp7p0pf5ge.webp +0 -0
  274. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jve5nenf98tzap11gpxzr.webp +0 -0
  275. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jvq58enf98v538w5vsqp4.webp +0 -0
  276. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jvsaeenf98v6ct4gjzppc.webp +0 -0
  277. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jw26cenf98vc7k0ppz5k8.webp +0 -0
  278. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q1hme4e8cmby77dn66yy.webp +0 -0
  279. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q2w7e4e8cmc20036yh66.webp +0 -0
  280. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q7d2e4e8cmdeqjmyafby.webp +0 -0
  281. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q887e4e8cmdjssych7yh.webp +0 -0
  282. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp-poster.webp +0 -0
  283. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp.mp4 +0 -0
  284. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf-poster.webp +0 -0
  285. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf.mp4 +0 -0
  286. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb-poster.webp +0 -0
  287. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb.mp4 +0 -0
  288. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83-poster.webp +0 -0
  289. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83.mp4 +0 -0
  290. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167sm0f6ct88qw5brtsgcw.webp +0 -0
  291. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167tf8f6ct88r169s51j49.webp +0 -0
  292. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167vaaf6ct88rbx5ztenwb.webp +0 -0
  293. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167w51f6ct88rp19pybkw1.webp +0 -0
  294. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167x0nf6ct88rzajb84tw3.webp +0 -0
  295. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167xxbf6ct88s5t2300bjk.webp +0 -0
  296. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167yq5f6ct88s9pjwt5fxg.webp +0 -0
  297. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167zg4f6ct88sge8jp28ja.webp +0 -0
  298. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m50607a6e8h8gfpa8byqtt7h.md +3 -0
  299. package/src/__tests__/fixtures/releases/0.11.0/site-export/themes/jant/static/apple-touch-icon.png +0 -0
  300. package/src/__tests__/fixtures/releases/0.11.0/site-export/themes/jant/static/custom.css +0 -0
  301. package/src/__tests__/fixtures/releases/0.11.0/site-export/themes/jant/static/favicon.ico +0 -0
  302. package/src/__tests__/fixtures/releases/0.11.0/site-export/wrangler.jsonc +24 -0
  303. package/src/__tests__/fixtures/releases/0.11.0/snapshot/db.sql +339 -0
  304. package/src/__tests__/fixtures/releases/0.11.0/snapshot/meta.json +11 -0
  305. package/src/__tests__/helpers/app.ts +6 -1
  306. package/src/__tests__/helpers/d1-round-trips.ts +213 -0
  307. package/src/__tests__/helpers/export-fixtures.ts +1 -0
  308. package/src/__tests__/import-refused-aliases.test.ts +98 -0
  309. package/src/__tests__/import-site-command.test.ts +73 -8
  310. package/src/__tests__/package-dependencies.test.ts +123 -0
  311. package/src/__tests__/public-page-round-trips.test.ts +203 -0
  312. package/src/__tests__/public-types.test.ts +64 -0
  313. package/src/__tests__/release-fixtures.test.ts +79 -24
  314. package/src/__tests__/release-version.test.ts +84 -0
  315. package/src/__tests__/site-pull-media.test.ts +48 -0
  316. package/src/__tests__/snapshot-tables.test.ts +37 -0
  317. package/src/__tests__/sql-export.test.ts +21 -1
  318. package/src/__tests__/stored-file-headers.test.ts +94 -0
  319. package/src/__tests__/template-deploy-workflow.test.ts +57 -0
  320. package/src/__tests__/theme-docs.test.ts +113 -24
  321. package/src/__tests__/toolchain-versions.test.ts +54 -0
  322. package/src/__tests__/trailing-slash-redirect.test.ts +61 -0
  323. package/src/__tests__/vite-config-graph.test.ts +98 -0
  324. package/src/__tests__/vite-config.test.ts +32 -0
  325. package/src/app.tsx +96 -67
  326. package/src/client/__tests__/compose-bridge-image-upload.test.ts +1 -0
  327. package/src/client/__tests__/compose-bridge.test.ts +87 -0
  328. package/src/client/__tests__/compose-shortcuts.test.ts +4 -4
  329. package/src/client/__tests__/footnote-rail.test.ts +1 -1
  330. package/src/client/__tests__/lazy-entries.test.ts +1 -1
  331. package/src/client/__tests__/media-scroll-hint.test.ts +2 -2
  332. package/src/client/avatar-upload.ts +10 -10
  333. package/src/client/components/__tests__/jant-compose-dialog.test.ts +295 -4
  334. package/src/client/components/__tests__/jant-compose-editor.test.ts +34 -0
  335. package/src/client/components/__tests__/jant-settings-general.test.ts +0 -32
  336. package/src/client/components/compose-types.ts +14 -0
  337. package/src/client/components/jant-compose-dialog.ts +96 -41
  338. package/src/client/components/jant-compose-editor.ts +21 -4
  339. package/src/client/components/jant-config-editor.ts +4 -6
  340. package/src/client/components/jant-media-lightbox.ts +4 -4
  341. package/src/client/components/jant-settings-general.ts +0 -4
  342. package/src/client/components/nav-manager-types.ts +6 -5
  343. package/src/client/compose-bridge.ts +15 -4
  344. package/src/client/compose-launch.ts +4 -6
  345. package/src/client/compose-shortcuts.ts +1 -1
  346. package/src/client/footnote-rail.ts +1 -1
  347. package/src/client/icons.ts +5 -6
  348. package/src/client/lazy-entries.ts +1 -1
  349. package/src/client/media-scroll-hint.ts +2 -2
  350. package/src/client/tiptap/__tests__/markdown-clipboard.test.ts +55 -0
  351. package/src/client/tiptap/markdown-clipboard.ts +50 -2
  352. package/src/client/upload-session.ts +7 -6
  353. package/src/db/__tests__/backfill-external-redirects.test.ts +59 -0
  354. package/src/db/__tests__/backfill-featured-discover.test.ts +56 -0
  355. package/src/db/__tests__/d1-query.test.ts +29 -0
  356. package/src/db/__tests__/migration-rehearsal.test.ts +2 -2
  357. package/src/db/backfills/0007_restore_external_redirect_scheme.sql +20 -0
  358. package/src/db/backfills/0008_turn_off_featured_only_discover.sql +11 -0
  359. package/src/i18n/locales/public/en.po +46 -48
  360. package/src/i18n/locales/public/en.ts +1 -1
  361. package/src/i18n/locales/public/zh-Hans.po +45 -46
  362. package/src/i18n/locales/public/zh-Hans.ts +1 -1
  363. package/src/i18n/locales/public/zh-Hant.po +45 -46
  364. package/src/i18n/locales/public/zh-Hant.ts +1 -1
  365. package/src/i18n/locales/settings/en.po +15 -29
  366. package/src/i18n/locales/settings/en.ts +1 -1
  367. package/src/i18n/locales/settings/zh-Hans.po +15 -29
  368. package/src/i18n/locales/settings/zh-Hans.ts +1 -1
  369. package/src/i18n/locales/settings/zh-Hant.po +15 -29
  370. package/src/i18n/locales/settings/zh-Hant.ts +1 -1
  371. package/src/index.ts +43 -2
  372. package/src/lib/__tests__/api-settings.test.ts +3 -3
  373. package/src/lib/__tests__/constants.test.ts +10 -0
  374. package/src/lib/__tests__/discover.test.ts +8 -9
  375. package/src/lib/__tests__/env-values.test.ts +125 -0
  376. package/src/lib/__tests__/feed-path.test.ts +29 -0
  377. package/src/lib/__tests__/feed.test.ts +50 -22
  378. package/src/lib/__tests__/filter-dimensions.test.ts +22 -8
  379. package/src/lib/__tests__/icons.test.ts +21 -10
  380. package/src/lib/__tests__/post-list-cursor.test.ts +0 -10
  381. package/src/lib/__tests__/rate-limit.test.ts +22 -7
  382. package/src/lib/__tests__/resolve-config.test.ts +5 -3
  383. package/src/lib/__tests__/schemas.test.ts +72 -23
  384. package/src/lib/__tests__/slugify.test.ts +9 -0
  385. package/src/lib/__tests__/startup-config.test.ts +12 -0
  386. package/src/lib/__tests__/storage-s3.test.ts +214 -0
  387. package/src/lib/__tests__/theme.test.ts +20 -1
  388. package/src/lib/__tests__/time.test.ts +56 -0
  389. package/src/lib/__tests__/timeline.test.ts +46 -0
  390. package/src/lib/__tests__/url-fetch.test.ts +65 -1
  391. package/src/lib/__tests__/url.test.ts +60 -1
  392. package/src/lib/api-nav-items.ts +16 -20
  393. package/src/lib/api-post-input.ts +34 -1
  394. package/src/lib/api-posts.ts +128 -24
  395. package/src/lib/api-public-posts.ts +31 -38
  396. package/src/lib/api-search.ts +49 -2
  397. package/src/lib/api-settings.ts +159 -54
  398. package/src/lib/api-threads.ts +34 -11
  399. package/src/lib/constants.ts +26 -0
  400. package/src/lib/discover.ts +7 -23
  401. package/src/lib/env-values.ts +140 -0
  402. package/src/lib/env.ts +203 -12
  403. package/src/lib/feed-path.ts +8 -2
  404. package/src/lib/feed-policy.ts +110 -7
  405. package/src/lib/feed.ts +69 -25
  406. package/src/lib/filter-dimensions.ts +17 -10
  407. package/src/lib/github-sync-site-config.ts +1 -0
  408. package/src/lib/hugo-markdown.ts +5 -6
  409. package/src/lib/icons.ts +96 -34
  410. package/src/lib/navigation.ts +4 -1
  411. package/src/lib/post-display.ts +13 -9
  412. package/src/lib/post-list-cursor.ts +33 -29
  413. package/src/lib/public-storage.ts +43 -0
  414. package/src/lib/rate-limit.ts +31 -16
  415. package/src/lib/render.tsx +5 -0
  416. package/src/lib/resolve-config.ts +16 -19
  417. package/src/lib/schemas.ts +248 -180
  418. package/src/lib/slugify.ts +6 -1
  419. package/src/lib/sse.ts +1 -1
  420. package/src/lib/startup-config.ts +20 -1
  421. package/src/lib/theme.ts +8 -5
  422. package/src/lib/thread-fold.ts +6 -0
  423. package/src/lib/thread-query.ts +19 -24
  424. package/src/lib/time.ts +137 -17
  425. package/src/lib/timeline.ts +76 -31
  426. package/src/lib/url-fetch.ts +141 -40
  427. package/src/lib/url.ts +86 -1
  428. package/src/lib/view.ts +3 -2
  429. package/src/middleware/__tests__/auth.test.ts +27 -0
  430. package/src/middleware/__tests__/cors.test.ts +54 -0
  431. package/src/middleware/__tests__/cross-origin.test.ts +149 -0
  432. package/src/middleware/__tests__/onboarding.test.ts +5 -3
  433. package/src/middleware/__tests__/public-content-access.test.ts +2 -42
  434. package/src/middleware/__tests__/secure-headers.test.ts +40 -42
  435. package/src/middleware/auth.ts +34 -3
  436. package/src/middleware/config.ts +44 -2
  437. package/src/middleware/cors.ts +4 -4
  438. package/src/middleware/cross-origin.ts +124 -0
  439. package/src/middleware/error-handler.ts +7 -0
  440. package/src/middleware/onboarding.ts +12 -3
  441. package/src/middleware/public-content-access.ts +3 -26
  442. package/src/middleware/secure-headers.ts +32 -37
  443. package/src/node/__tests__/cli-deploy-setup.test.ts +373 -0
  444. package/src/node/__tests__/cli-deploy.test.ts +55 -0
  445. package/src/node/__tests__/cli-migrate.test.ts +2 -2
  446. package/src/node/__tests__/cli-runtime-target.test.ts +13 -2
  447. package/src/node/__tests__/cli-site-snapshot.test.ts +57 -0
  448. package/src/node/__tests__/cli-snapshot-meta.test.ts +11 -1
  449. package/src/node/__tests__/cli-sql-export.test.ts +25 -1
  450. package/src/node/__tests__/cli-start.test.ts +66 -0
  451. package/src/node/__tests__/request-handler.test.ts +37 -0
  452. package/src/node/__tests__/runtime.test.ts +56 -1
  453. package/src/node/request-handler.ts +58 -5
  454. package/src/node/runtime.ts +37 -11
  455. package/src/preset.css +3 -3
  456. package/src/routes/__tests__/compose.test.ts +84 -0
  457. package/src/routes/api/__tests__/collections.test.ts +68 -0
  458. package/src/routes/api/__tests__/mcp.test.ts +164 -9
  459. package/src/routes/api/__tests__/media.test.ts +9 -1
  460. package/src/routes/api/__tests__/nav-items.test.ts +27 -1
  461. package/src/routes/api/__tests__/posts.test.ts +269 -78
  462. package/src/routes/api/__tests__/search.test.ts +17 -4
  463. package/src/routes/api/__tests__/settings.test.ts +119 -85
  464. package/src/routes/api/__tests__/telegram.test.ts +11 -6
  465. package/src/routes/api/__tests__/threads.test.ts +11 -0
  466. package/src/routes/api/__tests__/upload-response.test.ts +48 -0
  467. package/src/routes/api/__tests__/uploads.test.ts +35 -2
  468. package/src/routes/api/collections.ts +3 -3
  469. package/src/routes/api/custom-urls.ts +2 -1
  470. package/src/routes/api/export.ts +1 -0
  471. package/src/routes/api/internal/__tests__/post-body-html.test.ts +19 -0
  472. package/src/routes/api/internal/__tests__/uploads.test.ts +2 -0
  473. package/src/routes/api/internal/sites.ts +16 -4
  474. package/src/routes/api/mcp.ts +1 -0
  475. package/src/routes/api/media.ts +7 -8
  476. package/src/routes/api/nav-items.ts +2 -1
  477. package/src/routes/api/posts.ts +18 -24
  478. package/src/routes/api/public/__tests__/posts.test.ts +15 -0
  479. package/src/routes/api/public/__tests__/threads-collections.test.ts +12 -45
  480. package/src/routes/api/public/__tests__/threads.test.ts +41 -9
  481. package/src/routes/api/public/posts.ts +2 -2
  482. package/src/routes/api/public/threads.ts +16 -26
  483. package/src/routes/api/search.ts +7 -41
  484. package/src/routes/api/settings.ts +32 -28
  485. package/src/routes/api/smart-collections.ts +6 -1
  486. package/src/routes/api/threads.ts +25 -26
  487. package/src/routes/api/upload.ts +6 -21
  488. package/src/routes/api/uploads.ts +14 -20
  489. package/src/routes/auth/__tests__/dev.test.ts +16 -13
  490. package/src/routes/auth/__tests__/hosted-sso.test.ts +51 -0
  491. package/src/routes/auth/__tests__/setup-auth.test.ts +2 -0
  492. package/src/routes/auth/__tests__/setup-discover.test.ts +2 -0
  493. package/src/routes/auth/__tests__/setup-flow.test.ts +32 -0
  494. package/src/routes/auth/__tests__/setup-rate-limit.test.ts +72 -0
  495. package/src/routes/auth/__tests__/setup-steps.test.ts +2 -0
  496. package/src/routes/auth/__tests__/signin.test.ts +167 -2
  497. package/src/routes/auth/dev.ts +4 -6
  498. package/src/routes/auth/hosted-sso.ts +9 -6
  499. package/src/routes/auth/setup.tsx +35 -5
  500. package/src/routes/auth/signin.tsx +96 -1
  501. package/src/routes/compose.tsx +47 -47
  502. package/src/routes/dash/__tests__/settings-avatar.test.ts +59 -4
  503. package/src/routes/dash/__tests__/settings-demo-locks.test.ts +147 -0
  504. package/src/routes/dash/custom-urls.tsx +2 -0
  505. package/src/routes/dash/settings.tsx +79 -32
  506. package/src/routes/feed/__tests__/feed.test.ts +93 -3
  507. package/src/routes/feed/__tests__/sitemap.test.ts +42 -0
  508. package/src/routes/feed/feed.ts +130 -175
  509. package/src/routes/feed/sitemap.ts +9 -7
  510. package/src/routes/pages/__tests__/archive-years.test.ts +45 -0
  511. package/src/routes/pages/__tests__/collection-routing.test.ts +40 -0
  512. package/src/routes/pages/__tests__/collections.test.ts +3 -0
  513. package/src/routes/pages/__tests__/language-routing.test.ts +31 -0
  514. package/src/routes/pages/__tests__/post-page-round-trips.test.ts +44 -12
  515. package/src/routes/pages/__tests__/search.test.ts +5 -2
  516. package/src/routes/pages/__tests__/thread-gap.test.ts +207 -0
  517. package/src/routes/pages/archive.tsx +69 -111
  518. package/src/routes/pages/brand.tsx +1 -0
  519. package/src/routes/pages/collection.tsx +86 -120
  520. package/src/routes/pages/collections.tsx +2 -0
  521. package/src/routes/pages/featured.tsx +7 -2
  522. package/src/routes/pages/home.tsx +1 -0
  523. package/src/routes/pages/latest.tsx +6 -2
  524. package/src/routes/pages/new.tsx +1 -0
  525. package/src/routes/pages/page.tsx +113 -66
  526. package/src/routes/pages/search.tsx +8 -4
  527. package/src/routes/pages/smart-collection.tsx +11 -70
  528. package/src/routes/pages/subscribe.tsx +1 -0
  529. package/src/routes/pages/theme-sample.tsx +1 -0
  530. package/src/runtime/__tests__/readiness.test.ts +16 -0
  531. package/src/runtime/cloudflare.ts +2 -3
  532. package/src/runtime/index.ts +3 -1
  533. package/src/runtime/node.ts +3 -5
  534. package/src/runtime/readiness.ts +5 -0
  535. package/src/services/__tests__/auth.test.ts +115 -0
  536. package/src/services/__tests__/collection.test.ts +11 -4
  537. package/src/services/__tests__/github-sync-webhook.test.ts +78 -0
  538. package/src/services/__tests__/hosted-handoff.test.ts +208 -1
  539. package/src/services/__tests__/media.test.ts +47 -27
  540. package/src/services/__tests__/navigation.test.ts +67 -15
  541. package/src/services/__tests__/post.test.ts +103 -56
  542. package/src/services/__tests__/search.test.ts +38 -0
  543. package/src/services/__tests__/settings.test.ts +2 -14
  544. package/src/services/__tests__/smart-collection.test.ts +2 -2
  545. package/src/services/__tests__/telegram-ingest.test.ts +113 -0
  546. package/src/services/__tests__/thread.test.ts +26 -11
  547. package/src/services/auth.ts +36 -4
  548. package/src/services/collection.ts +141 -76
  549. package/src/services/custom-url.ts +11 -4
  550. package/src/services/export-theme/assets/client-site.css +1 -1
  551. package/src/services/export-theme/assets/client-site.js +2 -2
  552. package/src/services/export-theme/layouts/_default/baseof.html +1 -1
  553. package/src/services/export-theme/layouts/collection/single.html +1 -1
  554. package/src/services/export-theme/layouts/partials/featured-thread.html +8 -1
  555. package/src/services/export-theme/layouts/partials/head.html +1 -1
  556. package/src/services/export-theme/layouts/partials/media-gallery.html +6 -3
  557. package/src/services/export-theme/layouts/smart_collection/list.html +1 -1
  558. package/src/services/export-theme/styles/main.css +3 -3
  559. package/src/services/export.ts +70 -20
  560. package/src/services/github-sync.ts +10 -10
  561. package/src/services/hosted-handoff.ts +106 -6
  562. package/src/services/index.ts +3 -1
  563. package/src/services/language.ts +33 -0
  564. package/src/services/mcp.ts +176 -438
  565. package/src/services/media.ts +69 -21
  566. package/src/services/navigation.ts +19 -4
  567. package/src/services/path.ts +45 -3
  568. package/src/services/post.ts +460 -400
  569. package/src/services/search.ts +22 -3
  570. package/src/services/settings.ts +40 -11
  571. package/src/services/site-admin.ts +1 -0
  572. package/src/services/smart-collection.ts +10 -3
  573. package/src/services/telegram.ts +23 -6
  574. package/src/services/thread.ts +11 -3
  575. package/src/services/upload-session.ts +14 -15
  576. package/src/styles/components.css +2 -2
  577. package/src/styles/site-media.css +2 -2
  578. package/src/styles/tokens.css +19 -22
  579. package/src/styles/ui-author.css +73 -94
  580. package/src/styles/ui.css +62 -62
  581. package/src/types/app-context.ts +10 -1
  582. package/src/types/bindings.ts +11 -0
  583. package/src/types/config.ts +4 -4
  584. package/src/types/constants.ts +20 -0
  585. package/src/types/props.ts +34 -8
  586. package/src/types/views.ts +28 -13
  587. package/src/ui/color-themes.ts +6 -5
  588. package/src/ui/dash/settings/GeneralContent.tsx +0 -22
  589. package/src/ui/dash/settings/__tests__/GeneralContent.test.tsx +0 -21
  590. package/src/ui/feed/CuratedThreadPreview.tsx +7 -2
  591. package/src/ui/feed/LinkCard.tsx +1 -2
  592. package/src/ui/feed/NoteCard.tsx +1 -2
  593. package/src/ui/feed/QuoteCard.tsx +2 -2
  594. package/src/ui/feed/ThreadPreview.tsx +6 -6
  595. package/src/ui/feed/TimelineFeed.tsx +1 -7
  596. package/src/ui/feed/__tests__/thread-preview.test.ts +123 -10
  597. package/src/ui/feed/__tests__/timeline-cards.test.ts +18 -1
  598. package/src/ui/layouts/BaseLayout.tsx +5 -0
  599. package/src/ui/pages/ArchivePage.tsx +35 -35
  600. package/src/ui/pages/BrandPage.tsx +1 -1
  601. package/src/ui/pages/CollectionPage.tsx +1 -2
  602. package/src/ui/pages/CollectionsPage.tsx +2 -2
  603. package/src/ui/pages/ComposePage.tsx +1 -1
  604. package/src/ui/pages/FeaturedPage.tsx +1 -1
  605. package/src/ui/pages/HomePage.tsx +1 -1
  606. package/src/ui/pages/PostPage.tsx +1 -1
  607. package/src/ui/pages/SearchPage.tsx +1 -1
  608. package/src/ui/pages/SmartCollectionPage.tsx +4 -5
  609. package/src/ui/pages/SubscribePage.tsx +3 -5
  610. package/src/ui/pages/ThemeSamplePage.tsx +1 -1
  611. package/src/ui/shared/CollectionDirectory.tsx +2 -2
  612. package/src/ui/shared/CollectionsManager.tsx +1 -1
  613. package/src/ui/shared/CopyField.tsx +1 -1
  614. package/src/ui/shared/Icon.tsx +5 -5
  615. package/src/ui/shared/IconSprite.tsx +10 -11
  616. package/src/ui/shared/MediaGallery.tsx +1 -1
  617. package/src/ui/shared/custom-icons.ts +38 -7
  618. package/src/ui/shared/icon-collector.ts +7 -5
  619. package/src/vendor/datastar.js +9 -1956
  620. package/src/vendor/datastar.js.map +4 -4
  621. package/dist/client/_assets/chunks/sortable-list-BJyd-LXE.js +0 -2
  622. package/dist/client/_assets/chunks/unsafe-svg-DU_DNMy5.js +0 -2
  623. package/dist/client/_assets/client-D4AT9Iqr.js +0 -295
  624. package/dist/client/_assets/client-DRuw7XCt.css +0 -2
  625. package/dist/client/_assets/client-author-DQ8R-8KR.css +0 -2
@@ -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-CmeoVtnU.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-DU_DNMy5.js";import{i as y,r as b,t as x}from"./chunks/slug-format-BcIsNKz-.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-BJyd-LXE.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-B-m7X7S5.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{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-DxrzM_Gb.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-DYMcJrlS.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(`
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" />
@@ -117,7 +117,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
117
117
  aria-hidden="true"
118
118
  >
119
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})),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}_buildSnapshot(){let e=this._editor;if(!e)return null;let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=t.rating>0&&e._showRating;return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,language:this._language,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}if(this._editPostId){this._hasUnsavedChanges()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset());return}this._hasWorkToLose()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),l(this.labels.draftDeleted)}this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this._editor?.hasPendingInlineImageUploads()?this._saveDraftAndOpenDrafts():this._finishDraftSaveAndOpenDrafts()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){if(this._confirmForAttachedText)this._confirmPanelOpen=!1,this._discardAttachedPanel();else if(this._confirmForDrafts){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),l(this.labels.draftDeleted)}this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()}else 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||void 0});continue}let n=o.get(e);n?.bodyJson&&s.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson: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._hasWorkToLose()?(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})),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}]:[])}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}))}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}]:[]});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,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`
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`
121
121
  <div class="compose-drafts-panel">
122
122
  <div class="compose-alt-header">
123
123
  <button
@@ -1320,7 +1320,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
1320
1320
  >
1321
1321
  ${v(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,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.textAttachments.map(e=>{let t=null;try{t=JSON.parse(e.bodyJson)}catch{}return{clientId:e.clientId??L(),bodyJson:t,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:t}});this._attachedTexts=t,this._attachmentOrder=[...this._attachmentOrder,...t.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,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}}))),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 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
1324
1324
  width="${t}"
1325
1325
  height="${t}"
1326
1326
  viewBox="0 0 24 24"
@@ -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}=e.detail;$.delete(t),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: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.filename||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??=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`));