@novaprose/core 0.7.0 → 0.9.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 (347) hide show
  1. package/README.md +15 -2
  2. package/dist/a11y.cjs +314 -0
  3. package/dist/a11y.cjs.map +1 -0
  4. package/dist/a11y.d.cts +51 -0
  5. package/dist/a11y.d.ts +51 -0
  6. package/dist/a11y.js +11 -0
  7. package/dist/a11y.js.map +1 -0
  8. package/dist/a11ychecker-6ES3UMU3.js +449 -0
  9. package/dist/a11ychecker-6ES3UMU3.js.map +1 -0
  10. package/dist/accordion-ui-B4I2FJXE.js +201 -0
  11. package/dist/accordion-ui-B4I2FJXE.js.map +1 -0
  12. package/dist/advcode-7S6N64C7.js +51 -0
  13. package/dist/advcode-7S6N64C7.js.map +1 -0
  14. package/dist/advcode-editor-ENCPFVLO.js +257 -0
  15. package/dist/advcode-editor-ENCPFVLO.js.map +1 -0
  16. package/dist/{advlist-5FNKPLUX.js → advlist-FEDGNLMQ.js} +10 -7
  17. package/dist/advlist-FEDGNLMQ.js.map +1 -0
  18. package/dist/advtable-ui-JAVJY4L4.js +364 -0
  19. package/dist/advtable-ui-JAVJY4L4.js.map +1 -0
  20. package/dist/ai-5KM776QW.js +1485 -0
  21. package/dist/ai-5KM776QW.js.map +1 -0
  22. package/dist/anchor-ui-VPKNKZ7J.js +81 -0
  23. package/dist/anchor-ui-VPKNKZ7J.js.map +1 -0
  24. package/dist/autocorrect-5QLICCRN.js +851 -0
  25. package/dist/autocorrect-5QLICCRN.js.map +1 -0
  26. package/dist/{autolink-45LTODWB.js → autolink-ZYIPRXBA.js} +11 -8
  27. package/dist/autolink-ZYIPRXBA.js.map +1 -0
  28. package/dist/{autoresize-UB3GOA6D.js → autoresize-YRZAVCNO.js} +2 -2
  29. package/dist/autoresize-YRZAVCNO.js.map +1 -0
  30. package/dist/{autosave-GMWJ5BPE.js → autosave-IC7YYG44.js} +7 -7
  31. package/dist/autosave-IC7YYG44.js.map +1 -0
  32. package/dist/casechange-R7IO2APS.js +201 -0
  33. package/dist/casechange-R7IO2APS.js.map +1 -0
  34. package/dist/{charmap-2GC7LF7G.js → charmap-CARYZFKD.js} +7 -7
  35. package/dist/charmap-CARYZFKD.js.map +1 -0
  36. package/dist/checklist-7E47QW6L.js +189 -0
  37. package/dist/checklist-7E47QW6L.js.map +1 -0
  38. package/dist/chunk-23ZLVT5D.js +163 -0
  39. package/dist/chunk-23ZLVT5D.js.map +1 -0
  40. package/dist/{chunk-ND2CWNVG.js → chunk-3BOK3S3T.js} +2 -27
  41. package/dist/chunk-3BOK3S3T.js.map +1 -0
  42. package/dist/chunk-3KBQEAX2.js +926 -0
  43. package/dist/chunk-3KBQEAX2.js.map +1 -0
  44. package/dist/chunk-3NNILZVB.js +259 -0
  45. package/dist/chunk-3NNILZVB.js.map +1 -0
  46. package/dist/{chunk-PVFKXRID.js → chunk-4VPDY3LF.js} +1 -1
  47. package/dist/chunk-4VPDY3LF.js.map +1 -0
  48. package/dist/chunk-53AY5NAF.js +214 -0
  49. package/dist/chunk-53AY5NAF.js.map +1 -0
  50. package/dist/{chunk-5AW2HHG6.js → chunk-5KERLFDD.js} +50 -3
  51. package/dist/chunk-5KERLFDD.js.map +1 -0
  52. package/dist/{chunk-FCMZ7TUQ.js → chunk-6BJEOL5V.js} +296 -43
  53. package/dist/chunk-6BJEOL5V.js.map +1 -0
  54. package/dist/chunk-6LQM7G4V.js +159 -0
  55. package/dist/chunk-6LQM7G4V.js.map +1 -0
  56. package/dist/chunk-AB67XUSR.js +178 -0
  57. package/dist/chunk-AB67XUSR.js.map +1 -0
  58. package/dist/chunk-ANE5ASXG.js +26 -0
  59. package/dist/chunk-ANE5ASXG.js.map +1 -0
  60. package/dist/{chunk-Z3ELZ77W.js → chunk-AP2PJFLB.js} +5 -2
  61. package/dist/chunk-AP2PJFLB.js.map +1 -0
  62. package/dist/chunk-ARBKIZZU.js +137 -0
  63. package/dist/chunk-ARBKIZZU.js.map +1 -0
  64. package/dist/chunk-AUQSATWL.js +322 -0
  65. package/dist/chunk-AUQSATWL.js.map +1 -0
  66. package/dist/chunk-BMCH63QN.js +165 -0
  67. package/dist/chunk-BMCH63QN.js.map +1 -0
  68. package/dist/chunk-BUABAYZL.js +160 -0
  69. package/dist/chunk-BUABAYZL.js.map +1 -0
  70. package/dist/chunk-DCMPJ25E.js +140 -0
  71. package/dist/chunk-DCMPJ25E.js.map +1 -0
  72. package/dist/chunk-DV7TGRU6.js +47 -0
  73. package/dist/chunk-DV7TGRU6.js.map +1 -0
  74. package/dist/chunk-F2WT77ZG.js +163 -0
  75. package/dist/chunk-F2WT77ZG.js.map +1 -0
  76. package/dist/chunk-FNJ7AEJK.js +955 -0
  77. package/dist/chunk-FNJ7AEJK.js.map +1 -0
  78. package/dist/chunk-G74HNSB6.js +9 -0
  79. package/dist/chunk-G74HNSB6.js.map +1 -0
  80. package/dist/chunk-GTLE2HEW.js +108 -0
  81. package/dist/chunk-GTLE2HEW.js.map +1 -0
  82. package/dist/chunk-GUZCRDK6.js +143 -0
  83. package/dist/chunk-GUZCRDK6.js.map +1 -0
  84. package/dist/chunk-HNEAVVBC.js +98 -0
  85. package/dist/chunk-HNEAVVBC.js.map +1 -0
  86. package/dist/chunk-HSVNJGK3.js +1149 -0
  87. package/dist/chunk-HSVNJGK3.js.map +1 -0
  88. package/dist/chunk-IFSD6O5M.js +29 -0
  89. package/dist/chunk-IFSD6O5M.js.map +1 -0
  90. package/dist/{table-SSNABG5W.js → chunk-IO5PU52K.js} +119 -61
  91. package/dist/chunk-IO5PU52K.js.map +1 -0
  92. package/dist/chunk-K4LFGNS7.js +137 -0
  93. package/dist/chunk-K4LFGNS7.js.map +1 -0
  94. package/dist/chunk-KGEHUWGL.js +79 -0
  95. package/dist/chunk-KGEHUWGL.js.map +1 -0
  96. package/dist/chunk-KW6ATQPN.js +151 -0
  97. package/dist/chunk-KW6ATQPN.js.map +1 -0
  98. package/dist/chunk-NX3KWIP5.js +207 -0
  99. package/dist/chunk-NX3KWIP5.js.map +1 -0
  100. package/dist/chunk-OOVNE6MB.js +28 -0
  101. package/dist/chunk-OOVNE6MB.js.map +1 -0
  102. package/dist/chunk-OQMMHWMZ.js +7 -0
  103. package/dist/chunk-OQMMHWMZ.js.map +1 -0
  104. package/dist/{chunk-JPJVTB45.js → chunk-QU3KXMYT.js} +8 -2
  105. package/dist/chunk-QU3KXMYT.js.map +1 -0
  106. package/dist/chunk-QWT56RVG.js +158 -0
  107. package/dist/chunk-QWT56RVG.js.map +1 -0
  108. package/dist/chunk-RJ7T56OH.js +3787 -0
  109. package/dist/chunk-RJ7T56OH.js.map +1 -0
  110. package/dist/{chunk-KWXFL4WS.js → chunk-RPHA4HRX.js} +8 -5
  111. package/dist/chunk-RPHA4HRX.js.map +1 -0
  112. package/dist/chunk-S4DCQA74.js +66 -0
  113. package/dist/chunk-S4DCQA74.js.map +1 -0
  114. package/dist/chunk-SCIRO4XK.js +144 -0
  115. package/dist/chunk-SCIRO4XK.js.map +1 -0
  116. package/dist/chunk-SNVYHGGO.js +127 -0
  117. package/dist/chunk-SNVYHGGO.js.map +1 -0
  118. package/dist/chunk-T4543CB2.js +67 -0
  119. package/dist/chunk-T4543CB2.js.map +1 -0
  120. package/dist/{chunk-T3GY6IVK.js → chunk-UHUOAQA6.js} +71 -9
  121. package/dist/chunk-UHUOAQA6.js.map +1 -0
  122. package/dist/chunk-UTMS2P2K.js +288 -0
  123. package/dist/chunk-UTMS2P2K.js.map +1 -0
  124. package/dist/{chunk-HPLT3XRZ.js → chunk-V7WUHUHM.js} +13 -1
  125. package/dist/chunk-V7WUHUHM.js.map +1 -0
  126. package/dist/chunk-WAOU5NGN.js +430 -0
  127. package/dist/chunk-WAOU5NGN.js.map +1 -0
  128. package/dist/{chunk-R2UMUCVI.js → chunk-XCXJD5DO.js} +53 -8
  129. package/dist/chunk-XCXJD5DO.js.map +1 -0
  130. package/dist/chunk-XIH4SCO6.js +112 -0
  131. package/dist/chunk-XIH4SCO6.js.map +1 -0
  132. package/dist/chunk-XR7CY4NI.js +11 -0
  133. package/dist/chunk-XR7CY4NI.js.map +1 -0
  134. package/dist/chunk-Y2OXWCM7.js +263 -0
  135. package/dist/chunk-Y2OXWCM7.js.map +1 -0
  136. package/dist/chunk-YDF55N6Z.js +164 -0
  137. package/dist/chunk-YDF55N6Z.js.map +1 -0
  138. package/dist/chunk-YOTA26H7.js +373 -0
  139. package/dist/chunk-YOTA26H7.js.map +1 -0
  140. package/dist/chunk-YP7N47QR.js +101 -0
  141. package/dist/chunk-YP7N47QR.js.map +1 -0
  142. package/dist/{chunk-KPE3QRPB.js → chunk-YYCDRUE2.js} +16 -315
  143. package/dist/chunk-YYCDRUE2.js.map +1 -0
  144. package/dist/codesample-FOWXMCTC.js +546 -0
  145. package/dist/codesample-FOWXMCTC.js.map +1 -0
  146. package/dist/{comments-panel-HXMWSRAW.js → comments-panel-SOLBZ46Q.js} +9 -5
  147. package/dist/comments-panel-SOLBZ46Q.js.map +1 -0
  148. package/dist/{directionality-5JLWQGP2.js → directionality-BXWXNPRZ.js} +13 -10
  149. package/dist/directionality-BXWXNPRZ.js.map +1 -0
  150. package/dist/document-B0hLRhuH.d.cts +39 -0
  151. package/dist/document-Dh-jz1SK.d.ts +39 -0
  152. package/dist/docx.cjs +23575 -0
  153. package/dist/docx.cjs.map +1 -0
  154. package/dist/docx.d.cts +83 -0
  155. package/dist/docx.d.ts +83 -0
  156. package/dist/docx.js +1826 -0
  157. package/dist/docx.js.map +1 -0
  158. package/dist/draghandle-3IBHVHDE.js +389 -0
  159. package/dist/draghandle-3IBHVHDE.js.map +1 -0
  160. package/dist/editimage-GTLFGHYU.js +683 -0
  161. package/dist/editimage-GTLFGHYU.js.map +1 -0
  162. package/dist/editor-DnAN9aPd.d.ts +2948 -0
  163. package/dist/editor-S8w_w5W0.d.cts +2948 -0
  164. package/dist/email-FDSENENR.js +177 -0
  165. package/dist/email-FDSENENR.js.map +1 -0
  166. package/dist/email.cjs +588 -0
  167. package/dist/email.cjs.map +1 -0
  168. package/dist/email.d.cts +7 -0
  169. package/dist/email.d.ts +7 -0
  170. package/dist/email.js +21 -0
  171. package/dist/email.js.map +1 -0
  172. package/dist/{emoticons-ZD6ZRIWG.js → emoticons-SHYSAEID.js} +7 -7
  173. package/dist/emoticons-SHYSAEID.js.map +1 -0
  174. package/dist/exportpdf-TEBDQZSN.js +91 -0
  175. package/dist/exportpdf-TEBDQZSN.js.map +1 -0
  176. package/dist/exportword-BGH2CZXO.js +16 -0
  177. package/dist/exportword-BGH2CZXO.js.map +1 -0
  178. package/dist/footnotes-ui-KPKFDSN7.js +449 -0
  179. package/dist/footnotes-ui-KPKFDSN7.js.map +1 -0
  180. package/dist/form-dialog-SNWFPM2K.js +379 -0
  181. package/dist/form-dialog-SNWFPM2K.js.map +1 -0
  182. package/dist/formatpainter-CB4ZTKR5.js +209 -0
  183. package/dist/formatpainter-CB4ZTKR5.js.map +1 -0
  184. package/dist/fullpagehtml-ui-JPGRMXHD.js +220 -0
  185. package/dist/fullpagehtml-ui-JPGRMXHD.js.map +1 -0
  186. package/dist/html-rules-api-BLDDW9MO.d.cts +42 -0
  187. package/dist/html-rules-api-BLDDW9MO.d.ts +42 -0
  188. package/dist/html-rules.cjs +21 -19
  189. package/dist/html-rules.cjs.map +1 -1
  190. package/dist/html-rules.d.cts +37 -35
  191. package/dist/html-rules.d.ts +37 -35
  192. package/dist/html-rules.js +26 -22
  193. package/dist/html-rules.js.map +1 -1
  194. package/dist/i18n/de.cjs +349 -0
  195. package/dist/i18n/de.cjs.map +1 -1
  196. package/dist/i18n/de.d.cts +1 -1
  197. package/dist/i18n/de.d.ts +1 -1
  198. package/dist/i18n/de.js +349 -0
  199. package/dist/i18n/de.js.map +1 -1
  200. package/dist/i18n/es.cjs +349 -0
  201. package/dist/i18n/es.cjs.map +1 -1
  202. package/dist/i18n/es.d.cts +1 -1
  203. package/dist/i18n/es.d.ts +1 -1
  204. package/dist/i18n/es.js +349 -0
  205. package/dist/i18n/es.js.map +1 -1
  206. package/dist/i18n/fr.cjs +349 -0
  207. package/dist/i18n/fr.cjs.map +1 -1
  208. package/dist/i18n/fr.d.cts +1 -1
  209. package/dist/i18n/fr.d.ts +1 -1
  210. package/dist/i18n/fr.js +349 -0
  211. package/dist/i18n/fr.js.map +1 -1
  212. package/dist/i18n/it.cjs +349 -0
  213. package/dist/i18n/it.cjs.map +1 -1
  214. package/dist/i18n/it.d.cts +1 -1
  215. package/dist/i18n/it.d.ts +1 -1
  216. package/dist/i18n/it.js +349 -0
  217. package/dist/i18n/it.js.map +1 -1
  218. package/dist/i18n/pt-BR.cjs +349 -0
  219. package/dist/i18n/pt-BR.cjs.map +1 -1
  220. package/dist/i18n/pt-BR.d.cts +1 -1
  221. package/dist/i18n/pt-BR.d.ts +1 -1
  222. package/dist/i18n/pt-BR.js +349 -0
  223. package/dist/i18n/pt-BR.js.map +1 -1
  224. package/dist/i18n/ru.cjs +349 -0
  225. package/dist/i18n/ru.cjs.map +1 -1
  226. package/dist/i18n/ru.d.cts +3 -3
  227. package/dist/i18n/ru.d.ts +3 -3
  228. package/dist/i18n/ru.js +349 -0
  229. package/dist/i18n/ru.js.map +1 -1
  230. package/dist/importcss-JLNIRKGH.js +127 -0
  231. package/dist/importcss-JLNIRKGH.js.map +1 -0
  232. package/dist/importword-ZOWLUWSN.js +73 -0
  233. package/dist/importword-ZOWLUWSN.js.map +1 -0
  234. package/dist/{index-C603bU6r.d.ts → index-Pb2r0V-S.d.cts} +39 -17
  235. package/dist/{index-C603bU6r.d.cts → index-Pb2r0V-S.d.ts} +39 -17
  236. package/dist/index.cjs +29422 -10640
  237. package/dist/index.cjs.map +1 -1
  238. package/dist/index.d.cts +139 -64
  239. package/dist/index.d.ts +139 -64
  240. package/dist/index.js +204 -1412
  241. package/dist/index.js.map +1 -1
  242. package/dist/{insertdatetime-CRO7TJAQ.js → insertdatetime-BXQ3XXPH.js} +7 -7
  243. package/dist/insertdatetime-BXQ3XXPH.js.map +1 -0
  244. package/dist/linkchecker-JASSETVI.js +287 -0
  245. package/dist/linkchecker-JASSETVI.js.map +1 -0
  246. package/dist/markdown-OTLTCK26.js +136 -0
  247. package/dist/markdown-OTLTCK26.js.map +1 -0
  248. package/dist/markdown.cjs +94 -11
  249. package/dist/markdown.cjs.map +1 -1
  250. package/dist/markdown.d.cts +12 -10
  251. package/dist/markdown.d.ts +12 -10
  252. package/dist/markdown.js +4 -235
  253. package/dist/markdown.js.map +1 -1
  254. package/dist/math-ui-TY4VZF7Q.js +157 -0
  255. package/dist/math-ui-TY4VZF7Q.js.map +1 -0
  256. package/dist/media-ui-IXN4ENVF.js +123 -0
  257. package/dist/media-ui-IXN4ENVF.js.map +1 -0
  258. package/dist/mediaembed-ui-ODX5ECXC.js +207 -0
  259. package/dist/mediaembed-ui-ODX5ECXC.js.map +1 -0
  260. package/dist/mentions-ui-55GCKC6F.js +58 -0
  261. package/dist/mentions-ui-55GCKC6F.js.map +1 -0
  262. package/dist/mergetags-ui-6T7Z7MAZ.js +73 -0
  263. package/dist/mergetags-ui-6T7Z7MAZ.js.map +1 -0
  264. package/dist/{nonbreaking-66LFZV2W.js → nonbreaking-PONHSOMJ.js} +7 -7
  265. package/dist/nonbreaking-PONHSOMJ.js.map +1 -0
  266. package/dist/pagebreak-ui-AKAW7M5I.js +50 -0
  267. package/dist/pagebreak-ui-AKAW7M5I.js.map +1 -0
  268. package/dist/pageembed-ui-GUNPKMBR.js +172 -0
  269. package/dist/pageembed-ui-GUNPKMBR.js.map +1 -0
  270. package/dist/pagelayout-ui-JSFVEMHS.js +236 -0
  271. package/dist/pagelayout-ui-JSFVEMHS.js.map +1 -0
  272. package/dist/{paste-office-F3QW4WWO.js → paste-office-TORLAZ5L.js} +94 -4
  273. package/dist/paste-office-TORLAZ5L.js.map +1 -0
  274. package/dist/permanentpen-EACURV5U.js +206 -0
  275. package/dist/permanentpen-EACURV5U.js.map +1 -0
  276. package/dist/print-4XJCOANX.js +178 -0
  277. package/dist/print-4XJCOANX.js.map +1 -0
  278. package/dist/{quickbars-7E2QRS7J.js → quickbars-BT5PETRX.js} +20 -12
  279. package/dist/quickbars-BT5PETRX.js.map +1 -0
  280. package/dist/{revisionhistory-DXE7KU4R.js → revisionhistory-3FKLMJHJ.js} +42 -153
  281. package/dist/revisionhistory-3FKLMJHJ.js.map +1 -0
  282. package/dist/save-ZHFXH222.js +120 -0
  283. package/dist/save-ZHFXH222.js.map +1 -0
  284. package/dist/search-bar-6MVRMTK6.js +212 -0
  285. package/dist/search-bar-6MVRMTK6.js.map +1 -0
  286. package/dist/spellchecker-JJKA6B4R.js +474 -0
  287. package/dist/spellchecker-JJKA6B4R.js.map +1 -0
  288. package/dist/suggestions-panel-X37NFLXE.js +596 -0
  289. package/dist/suggestions-panel-X37NFLXE.js.map +1 -0
  290. package/dist/suggestions-ui-WN7QNYHB.js +395 -0
  291. package/dist/suggestions-ui-WN7QNYHB.js.map +1 -0
  292. package/dist/table-PEF56QG5.js +54 -0
  293. package/dist/table-PEF56QG5.js.map +1 -0
  294. package/dist/table-dialogs-QS3VFZD2.js +119 -0
  295. package/dist/table-dialogs-QS3VFZD2.js.map +1 -0
  296. package/dist/tableofcontents-ui-U7EV3UU7.js +167 -0
  297. package/dist/tableofcontents-ui-U7EV3UU7.js.map +1 -0
  298. package/dist/template-ZRTKIP2J.js +278 -0
  299. package/dist/template-ZRTKIP2J.js.map +1 -0
  300. package/dist/typography-S7RO54DB.js +399 -0
  301. package/dist/typography-S7RO54DB.js.map +1 -0
  302. package/dist/upload.cjs +160 -0
  303. package/dist/upload.cjs.map +1 -0
  304. package/dist/upload.d.cts +72 -0
  305. package/dist/upload.d.ts +72 -0
  306. package/dist/upload.js +132 -0
  307. package/dist/upload.js.map +1 -0
  308. package/dist/{visualblocks-6DLBXYOA.js → visualblocks-KJYRHF2L.js} +7 -7
  309. package/dist/visualblocks-KJYRHF2L.js.map +1 -0
  310. package/dist/visualchars-TDLZKFXD.js +134 -0
  311. package/dist/visualchars-TDLZKFXD.js.map +1 -0
  312. package/package.json +53 -3
  313. package/src/style.css +376 -550
  314. package/dist/advlist-5FNKPLUX.js.map +0 -1
  315. package/dist/autolink-45LTODWB.js.map +0 -1
  316. package/dist/autoresize-UB3GOA6D.js.map +0 -1
  317. package/dist/autosave-GMWJ5BPE.js.map +0 -1
  318. package/dist/charmap-2GC7LF7G.js.map +0 -1
  319. package/dist/chunk-5AW2HHG6.js.map +0 -1
  320. package/dist/chunk-DWZLSZDG.js +0 -5664
  321. package/dist/chunk-DWZLSZDG.js.map +0 -1
  322. package/dist/chunk-FCMZ7TUQ.js.map +0 -1
  323. package/dist/chunk-HPLT3XRZ.js.map +0 -1
  324. package/dist/chunk-JPJVTB45.js.map +0 -1
  325. package/dist/chunk-KPE3QRPB.js.map +0 -1
  326. package/dist/chunk-KWXFL4WS.js.map +0 -1
  327. package/dist/chunk-ND2CWNVG.js.map +0 -1
  328. package/dist/chunk-PVFKXRID.js.map +0 -1
  329. package/dist/chunk-R2UMUCVI.js.map +0 -1
  330. package/dist/chunk-T3GY6IVK.js.map +0 -1
  331. package/dist/chunk-Z3ELZ77W.js.map +0 -1
  332. package/dist/comments-panel-HXMWSRAW.js.map +0 -1
  333. package/dist/directionality-5JLWQGP2.js.map +0 -1
  334. package/dist/editor-CXkltf1R.d.ts +0 -1886
  335. package/dist/editor-CgSBFTke.d.cts +0 -1886
  336. package/dist/emoticons-ZD6ZRIWG.js.map +0 -1
  337. package/dist/form-dialog-QH6KAERD.js +0 -180
  338. package/dist/form-dialog-QH6KAERD.js.map +0 -1
  339. package/dist/html-rules-api-D3fKQi-R.d.cts +0 -40
  340. package/dist/html-rules-api-D3fKQi-R.d.ts +0 -40
  341. package/dist/insertdatetime-CRO7TJAQ.js.map +0 -1
  342. package/dist/nonbreaking-66LFZV2W.js.map +0 -1
  343. package/dist/paste-office-F3QW4WWO.js.map +0 -1
  344. package/dist/quickbars-7E2QRS7J.js.map +0 -1
  345. package/dist/revisionhistory-DXE7KU4R.js.map +0 -1
  346. package/dist/table-SSNABG5W.js.map +0 -1
  347. package/dist/visualblocks-6DLBXYOA.js.map +0 -1
@@ -0,0 +1,3787 @@
1
+ import {
2
+ createMenu,
3
+ focusMenu
4
+ } from "./chunk-YP7N47QR.js";
5
+ import {
6
+ linkBubblePlugin
7
+ } from "./chunk-KW6ATQPN.js";
8
+ import {
9
+ parserFor
10
+ } from "./chunk-KGEHUWGL.js";
11
+ import {
12
+ Popover,
13
+ positionFloating,
14
+ visibleArea
15
+ } from "./chunk-GTLE2HEW.js";
16
+ import {
17
+ searchPlugin
18
+ } from "./chunk-6LQM7G4V.js";
19
+ import {
20
+ registerBuiltins
21
+ } from "./chunk-FNJ7AEJK.js";
22
+ import {
23
+ openLinkDialog
24
+ } from "./chunk-SNVYHGGO.js";
25
+ import {
26
+ embeddedImageUploadPlugin,
27
+ exitImageCaption,
28
+ imageDropPastePlugin,
29
+ openImageDialog
30
+ } from "./chunk-YYCDRUE2.js";
31
+ import {
32
+ insertTable,
33
+ loadTables
34
+ } from "./chunk-RPHA4HRX.js";
35
+ import {
36
+ flatMarkViews
37
+ } from "./chunk-ANE5ASXG.js";
38
+ import {
39
+ openHelp,
40
+ pages,
41
+ toggleFullscreen
42
+ } from "./chunk-23ZLVT5D.js";
43
+ import {
44
+ openDialog,
45
+ textField
46
+ } from "./chunk-AB67XUSR.js";
47
+ import {
48
+ ContentRules,
49
+ Formatter,
50
+ contentRulesPlugin,
51
+ htmlSerializer,
52
+ isRtlLanguage,
53
+ sanitizeJSON,
54
+ schemaFromOptions
55
+ } from "./chunk-3KBQEAX2.js";
56
+ import {
57
+ SET_CONTENT_META
58
+ } from "./chunk-OQMMHWMZ.js";
59
+ import {
60
+ commands,
61
+ isCommandActive,
62
+ listIndent,
63
+ listOutdent,
64
+ nodesOf
65
+ } from "./chunk-UHUOAQA6.js";
66
+ import {
67
+ classAttr,
68
+ imageSize,
69
+ languageTag,
70
+ primaryLanguage,
71
+ schema
72
+ } from "./chunk-6BJEOL5V.js";
73
+ import {
74
+ icons
75
+ } from "./chunk-5KERLFDD.js";
76
+ import {
77
+ createTranslator
78
+ } from "./chunk-XCXJD5DO.js";
79
+ import {
80
+ loadPlugin,
81
+ orderPlugins,
82
+ pageHandlerOf,
83
+ resolveEntries
84
+ } from "./chunk-V7WUHUHM.js";
85
+ import {
86
+ FOCUSABLE,
87
+ activeElement,
88
+ formatShortcut,
89
+ h,
90
+ icon,
91
+ isRtl,
92
+ listenDocument,
93
+ logicalKey,
94
+ uniqueId
95
+ } from "./chunk-QU3KXMYT.js";
96
+ import {
97
+ codeLanguage
98
+ } from "./chunk-G74HNSB6.js";
99
+ import {
100
+ attachCss,
101
+ loadCss,
102
+ scopeCss
103
+ } from "./chunk-YDF55N6Z.js";
104
+ import {
105
+ isSafeImageUrl
106
+ } from "./chunk-4VPDY3LF.js";
107
+
108
+ // src/paste.ts
109
+ import { Fragment, Slice } from "prosemirror-model";
110
+ import { Plugin, PluginKey } from "prosemirror-state";
111
+ function hasLocalFileImages(html) {
112
+ return /<img[^>]+src=["']?file:/i.test(html);
113
+ }
114
+ var cleaner = null;
115
+ var loading = null;
116
+ function loadPasteCleaner() {
117
+ loading ??= import("./paste-office-TORLAZ5L.js").then(
118
+ (module) => cleaner = module,
119
+ () => {
120
+ loading = null;
121
+ return null;
122
+ }
123
+ );
124
+ return loading;
125
+ }
126
+ var key = new PluginKey("nova-paste");
127
+ function htmlToPlainText(html) {
128
+ const template = document.createElement("template");
129
+ template.innerHTML = html;
130
+ const blocks = /^(P|DIV|H[1-6]|LI|BLOCKQUOTE|PRE|TR|SECTION|ARTICLE|HEADER|FOOTER)$/;
131
+ let out = "";
132
+ const walk = (node) => {
133
+ if (node.nodeType === Node.TEXT_NODE) {
134
+ out += (node.textContent ?? "").replace(/\s+/g, " ");
135
+ return;
136
+ }
137
+ if (!(node instanceof Element)) {
138
+ node.childNodes.forEach(walk);
139
+ return;
140
+ }
141
+ if (/^(SCRIPT|STYLE|META|TITLE|HEAD)$/.test(node.tagName)) return;
142
+ if (node.tagName === "BR") {
143
+ out += "\n";
144
+ return;
145
+ }
146
+ const block = blocks.test(node.tagName);
147
+ if (block && out && !out.endsWith("\n")) out += "\n";
148
+ node.childNodes.forEach(walk);
149
+ if (block) out += "\n";
150
+ };
151
+ template.content.childNodes.forEach(walk);
152
+ return out.split("\n").map((line) => line.trim()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
153
+ }
154
+ function textLanguage(editor) {
155
+ return languageTag(editor.options.contentLanguage) ?? languageTag(editor.root.parentElement?.closest("[lang]")?.getAttribute("lang"));
156
+ }
157
+ function withoutTextLanguage(html, lang) {
158
+ if (!lang || !/\slang\s*=/i.test(html)) return html;
159
+ const template = document.createElement("template");
160
+ template.innerHTML = html;
161
+ let changed = false;
162
+ for (const el of template.content.querySelectorAll("[lang]")) {
163
+ const tag = languageTag(el.getAttribute("lang"));
164
+ if (tag && primaryLanguage(tag) === primaryLanguage(lang)) {
165
+ el.removeAttribute("lang");
166
+ changed = true;
167
+ }
168
+ }
169
+ if (!changed) return html;
170
+ const container = document.createElement("div");
171
+ container.append(template.content);
172
+ return container.innerHTML;
173
+ }
174
+ function pastePlugin(editor) {
175
+ let reentrant = false;
176
+ return new Plugin({
177
+ key,
178
+ props: {
179
+ /**
180
+ * Pasting into an empty paragraph replaces it entirely: otherwise the first pasted paragraph "merges" with
181
+ * the empty one and loses its formatting (alignment, spacing, block type). Into a non-empty paragraph
182
+ * it works as usual: the first paragraph continues the current one, as in Word.
183
+ */
184
+ transformPasted(slice, view) {
185
+ const { selection } = view.state;
186
+ const parent = selection.$from.parent;
187
+ if (slice.openStart > 0 && selection.empty && parent.isTextblock && parent.content.size === 0 && slice.content.firstChild?.isBlock) {
188
+ return new Slice(slice.content, 0, slice.openEnd);
189
+ }
190
+ return slice;
191
+ },
192
+ transformPastedHTML(html) {
193
+ const { pastePreprocess, pastePostprocess, pasteStyles } = editor.options;
194
+ let result = pastePreprocess ? pastePreprocess(html, editor) : html;
195
+ if (cleaner) result = cleaner.cleanPastedHTML(result, pasteStyles ?? "clean");
196
+ result = withoutTextLanguage(result, textLanguage(editor));
197
+ if (pastePostprocess) {
198
+ const template = document.createElement("template");
199
+ template.innerHTML = result;
200
+ const container = document.createElement("div");
201
+ container.append(template.content);
202
+ pastePostprocess(container, editor);
203
+ result = container.innerHTML;
204
+ }
205
+ return result;
206
+ },
207
+ handleDOMEvents: {
208
+ /**
209
+ * HTML pasted before the cleanup has loaded (the first milliseconds after creation or
210
+ * a slow network): take the clipboard data now (after the event it is gone), wait for the chunk
211
+ * and paste as usual, through transformPastedHTML, this time with the cleanup.
212
+ */
213
+ paste(view, event) {
214
+ if (cleaner || reentrant || editor.isPasteAsText()) return false;
215
+ const data = event.clipboardData;
216
+ if (data?.getData(VSCODE_DATA)) return false;
217
+ const html = data?.getData("text/html");
218
+ if (!html) return false;
219
+ const rtf = hasLocalFileImages(html) ? data?.getData("text/rtf") ?? "" : "";
220
+ event.preventDefault();
221
+ void loadPasteCleaner().then(() => {
222
+ if (view.isDestroyed) return;
223
+ const withImages = rtf && cleaner && editor.isAllowed("image") ? cleaner.replaceLocalImages(html, cleaner.extractRtfImages(rtf)) : html;
224
+ reentrant = true;
225
+ try {
226
+ view.pasteHTML(withImages);
227
+ } finally {
228
+ reentrant = false;
229
+ }
230
+ });
231
+ return true;
232
+ }
233
+ },
234
+ handlePaste(view, event, slice) {
235
+ if (reentrant) return false;
236
+ const pasteText = (text2) => {
237
+ reentrant = true;
238
+ try {
239
+ view.pasteText(text2);
240
+ } finally {
241
+ reentrant = false;
242
+ }
243
+ };
244
+ if (pasteFromCodeEditor(view, event, editor, pasteText)) return true;
245
+ const html = event.clipboardData?.getData("text/html");
246
+ if (!editor.isPasteAsText()) {
247
+ const rtf = html && hasLocalFileImages(html) ? event.clipboardData?.getData("text/rtf") : "";
248
+ if (!html || !rtf || !cleaner || !editor.isAllowed("image")) return false;
249
+ const withImages = cleaner.replaceLocalImages(html, cleaner.extractRtfImages(rtf));
250
+ if (withImages === html) return false;
251
+ reentrant = true;
252
+ try {
253
+ view.pasteHTML(withImages, event);
254
+ } finally {
255
+ reentrant = false;
256
+ }
257
+ return true;
258
+ }
259
+ const text = html ? htmlToPlainText(html) : event.clipboardData?.getData("text/plain") || slice.content.textBetween(0, slice.content.size, "\n\n");
260
+ if (!text) return false;
261
+ pasteText(text);
262
+ return true;
263
+ }
264
+ }
265
+ });
266
+ }
267
+ var VSCODE_DATA = "vscode-editor-data";
268
+ var VSCODE_LANGUAGES = {
269
+ shellscript: "bash",
270
+ typescriptreact: "tsx",
271
+ javascriptreact: "jsx",
272
+ jsonc: "json"
273
+ };
274
+ function pasteFromCodeEditor(view, event, editor, pasteText) {
275
+ const data = event.clipboardData;
276
+ const meta = data?.getData(VSCODE_DATA);
277
+ const raw = data?.getData("text/plain");
278
+ if (!meta || !raw) return false;
279
+ if (view.state.selection.$from.parent.type.spec.code) return false;
280
+ let mode;
281
+ try {
282
+ mode = JSON.parse(meta).mode;
283
+ } catch {
284
+ }
285
+ if (mode === "markdown" && editor.hasPlugin("markdown") && !editor.isPasteAsText()) return false;
286
+ const text = raw.replace(/\r\n?/g, "\n").replace(/\n$/, "");
287
+ const codeBlock = view.state.schema.nodes.code_block;
288
+ if (!text.includes("\n") || mode === "markdown" || mode === "plaintext" || editor.isPasteAsText() || !codeBlock || !editor.isAllowed("codeblock")) {
289
+ pasteText(text);
290
+ return true;
291
+ }
292
+ const language = typeof mode === "string" ? Object.hasOwn(VSCODE_LANGUAGES, mode) ? VSCODE_LANGUAGES[mode] : codeLanguage(mode) : null;
293
+ const block = codeBlock.create({ language }, view.state.schema.text(text));
294
+ view.dispatch(
295
+ view.state.tr.replaceSelection(new Slice(Fragment.from(block), 0, 0)).setMeta("uiEvent", "paste").scrollIntoView()
296
+ );
297
+ return true;
298
+ }
299
+
300
+ // src/ui/menubar.ts
301
+ var DEFAULT_MENUS = {
302
+ file: {
303
+ title: "menu.file",
304
+ items: "save cancel | fullpagehtml | importword exportword exportpdf | preview | print"
305
+ },
306
+ edit: { title: "menu.edit", items: "undo redo | selectall | searchreplace pastetext" },
307
+ view: { title: "menu.view", items: "code preview | fullscreen | visualblocks visualchars" },
308
+ insert: {
309
+ title: "menu.insert",
310
+ items: "image link media pageembed inserttable hr | insertdatetime template footnotes"
311
+ },
312
+ format: {
313
+ title: "menu.format",
314
+ items: "bold italic underline strikethrough superscript subscript inlinecode | paragraph h1 h2 h3 blockquote codeblock | alignleft aligncenter alignright alignjustify | lowercase uppercase titlecase | formatpainter permanentpen configurepermanentpen | language | removeformat"
315
+ },
316
+ table: {
317
+ title: "menu.table",
318
+ items: "inserttable | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells | advtablesort advtablerownumbering | tabledelete"
319
+ },
320
+ // Not in the default menu bar: its items come from plugins (spellchecker, autocorrect, a11ychecker).
321
+ tools: {
322
+ title: "menu.tools",
323
+ items: "spellchecker spellcheckdialog | autocorrect capitalization typography | linkchecker a11ycheck"
324
+ },
325
+ help: { title: "menu.help", items: "help" }
326
+ };
327
+ var DEFAULT_MENUBAR = "file edit view insert format table help";
328
+ function createMenubar(editor, host, config, menus) {
329
+ const { t } = editor.ui;
330
+ host.className = "nova-menubar";
331
+ host.setAttribute("role", "menubar");
332
+ host.setAttribute("aria-label", t("menu.label"));
333
+ const listeners = new AbortController();
334
+ const { signal } = listeners;
335
+ const title = (def) => def.title.startsWith("menu.") ? t(def.title) : def.title;
336
+ const entries = (def) => {
337
+ const out = [];
338
+ for (const token of def.items.split(/\s+/)) {
339
+ if (!token) continue;
340
+ if (token === "|") {
341
+ if (out.length && out[out.length - 1].type !== "separator")
342
+ out.push({ type: "separator" });
343
+ continue;
344
+ }
345
+ if (!editor.isAllowed(token)) continue;
346
+ const item = editor.ui.registry.getMenuItem(token);
347
+ if (!item) continue;
348
+ out.push({
349
+ id: token,
350
+ label: item.text,
351
+ ...item.icon ? { icon: item.icon } : {},
352
+ ...item.shortcut ? { shortcut: item.shortcut } : {},
353
+ ...item.isActive ? { active: item.isActive(editor), checkbox: true } : {},
354
+ disabled: !editor.isEditable() || (item.isEnabled ? !item.isEnabled(editor) : false),
355
+ onSelect: () => item.onAction(editor)
356
+ });
357
+ }
358
+ while (out.length && out[out.length - 1].type === "separator") out.pop();
359
+ return out;
360
+ };
361
+ const buttons = [];
362
+ let open = null;
363
+ const close = () => {
364
+ open?.popover.close();
365
+ open = null;
366
+ };
367
+ const openMenu = (index, focusFirst) => {
368
+ close();
369
+ const button = buttons[index];
370
+ const def = menus[button.dataset.menu];
371
+ const items = entries(def);
372
+ if (!items.length) return;
373
+ const menu = createMenu(items, () => editor.ui.closePopover(), title(def));
374
+ menu.addEventListener("keydown", (event) => {
375
+ const key2 = logicalKey(event, menu);
376
+ if (key2 !== "ArrowLeft" && key2 !== "ArrowRight") return;
377
+ event.preventDefault();
378
+ const next = (index + (key2 === "ArrowRight" ? 1 : -1) + buttons.length) % buttons.length;
379
+ openMenu(next, true);
380
+ });
381
+ button.setAttribute("aria-expanded", "true");
382
+ const popover = editor.ui.openPopover({
383
+ anchor: button,
384
+ content: menu,
385
+ ignore: [host],
386
+ className: "nova-popover-menu",
387
+ onClose: (reason) => {
388
+ button.setAttribute("aria-expanded", "false");
389
+ if (open?.popover === popover) open = null;
390
+ if (reason === "escape") button.focus();
391
+ }
392
+ });
393
+ open = { index, popover };
394
+ if (focusFirst) focusMenu(menu);
395
+ };
396
+ for (const name of config.split(/\s+/).filter(Boolean)) {
397
+ const def = menus[name];
398
+ if (!def) continue;
399
+ const button = h(
400
+ "button",
401
+ {
402
+ type: "button",
403
+ className: "nova-menubar-item",
404
+ role: "menuitem",
405
+ "aria-haspopup": "menu",
406
+ "aria-expanded": "false",
407
+ "data-menu": name,
408
+ tabindex: buttons.length === 0 ? "0" : "-1"
409
+ },
410
+ title(def)
411
+ );
412
+ const index = buttons.length;
413
+ button.addEventListener("click", (event) => {
414
+ if (open?.index === index) return close();
415
+ openMenu(index, event.detail === 0);
416
+ });
417
+ button.addEventListener("mouseenter", () => {
418
+ if (open && open.index !== index) openMenu(index, false);
419
+ });
420
+ buttons.push(button);
421
+ host.append(button);
422
+ }
423
+ host.addEventListener(
424
+ "keydown",
425
+ (event) => {
426
+ const index = buttons.indexOf(activeElement(host));
427
+ if (index < 0) return;
428
+ const move = (to) => {
429
+ event.preventDefault();
430
+ const next = (to + buttons.length) % buttons.length;
431
+ buttons.forEach((b, i) => b.tabIndex = i === next ? 0 : -1);
432
+ buttons[next].focus();
433
+ };
434
+ const key2 = logicalKey(event, host);
435
+ if (key2 === "ArrowRight") move(index + 1);
436
+ else if (key2 === "ArrowLeft") move(index - 1);
437
+ else if (event.key === "Home") move(0);
438
+ else if (event.key === "End") move(buttons.length - 1);
439
+ else if (event.key === "ArrowDown") {
440
+ event.preventDefault();
441
+ openMenu(index, true);
442
+ } else if (event.key === "Escape") {
443
+ event.preventDefault();
444
+ editor.focus();
445
+ }
446
+ },
447
+ { signal }
448
+ );
449
+ host.addEventListener(
450
+ "mousedown",
451
+ (event) => {
452
+ if (event.target.closest("button")) event.preventDefault();
453
+ },
454
+ { signal }
455
+ );
456
+ return {
457
+ focus: () => (buttons.find((b) => b.tabIndex === 0) ?? buttons[0])?.focus(),
458
+ destroy: () => {
459
+ close();
460
+ listeners.abort();
461
+ host.replaceChildren();
462
+ }
463
+ };
464
+ }
465
+
466
+ // src/ui/menu-items.ts
467
+ import { AllSelection } from "prosemirror-state";
468
+ function printContent(editor) {
469
+ void import("./print-4XJCOANX.js").then(
470
+ (module) => module.print(editor),
471
+ (error) => console.error("[nova] print: could not load the print module", error)
472
+ );
473
+ }
474
+ function openInsertTableDialog(editor) {
475
+ const { t } = editor.ui;
476
+ const rows = textField({ label: t("table.rows"), value: "3" });
477
+ const cols = textField({ label: t("table.cols"), value: "3" });
478
+ for (const field of [rows, cols]) {
479
+ field.input.type = "number";
480
+ field.input.min = "1";
481
+ field.input.max = "50";
482
+ field.input.inputMode = "numeric";
483
+ }
484
+ editor.ui.openDialog({
485
+ title: t("table.insert"),
486
+ body: h("div", { className: "nova-form nova-form-row" }, rows.el, cols.el),
487
+ submitLabel: t("dialog.insert"),
488
+ initialFocus: rows.input,
489
+ onSubmit: () => {
490
+ const r = Number(rows.input.value);
491
+ const c = Number(cols.input.value);
492
+ if (!Number.isInteger(r) || !Number.isInteger(c) || r < 1 || c < 1 || r > 50 || c > 50) {
493
+ return t("table.invalidSize");
494
+ }
495
+ editor.exec(insertTable(r, c));
496
+ return true;
497
+ }
498
+ });
499
+ }
500
+ function registerMenuItems(editor) {
501
+ const { registry, t } = editor.ui;
502
+ registry.addToggleMenuItem("paragraph", {
503
+ text: t("paragraph"),
504
+ icon: icons.paragraph,
505
+ shortcut: "Mod-Alt-0",
506
+ isActive: (e) => e.view.state.selection.$from.parent.type.name === "paragraph",
507
+ onAction: (e) => e.exec("paragraph")
508
+ });
509
+ registry.addMenuItem("selectall", {
510
+ text: t("selectAll"),
511
+ shortcut: "Mod-a",
512
+ onAction: (e) => {
513
+ e.view.dispatch(e.view.state.tr.setSelection(new AllSelection(e.view.state.doc)));
514
+ e.focus();
515
+ }
516
+ });
517
+ registry.addMenuItem("print", {
518
+ text: t("print"),
519
+ icon: icons.print,
520
+ shortcut: "Mod-p",
521
+ onAction: (e) => printContent(e)
522
+ });
523
+ registry.addMenuItem("inserttable", {
524
+ text: t("table.insert"),
525
+ icon: icons.table,
526
+ isEnabled: (e) => e.can(insertTable(1, 1)),
527
+ onAction: (e) => openInsertTableDialog(e)
528
+ });
529
+ }
530
+
531
+ // src/ui/toolbar.ts
532
+ var defaultToolbar = "undo redo | blocks | bold italic underline strikethrough moreformats | forecolor backcolor | link image table | bullist numlist | align lineheight outdent indent | fontfamily fontsize | blockquote codeblock hr | removeformat | searchreplace preview code fullscreen help";
533
+ function parseToolbar(config) {
534
+ const tokens = Array.isArray(config) ? config : config.split(/\s+/);
535
+ const groups = [[]];
536
+ for (const raw of tokens) {
537
+ const token = raw.trim();
538
+ if (!token) continue;
539
+ if (token === "|") groups.push([]);
540
+ else groups[groups.length - 1].push(token);
541
+ }
542
+ return groups.filter((g) => g.length > 0);
543
+ }
544
+ function createToolbar(editor, host, config, mode, { warnUnknown = true } = {}) {
545
+ const { ui } = editor;
546
+ const t = ui.t;
547
+ const listeners = new AbortController();
548
+ const { signal } = listeners;
549
+ host.className = `nova-toolbar nova-toolbar-${mode}`;
550
+ host.setAttribute("role", "toolbar");
551
+ host.setAttribute("aria-label", t("toolbar.label"));
552
+ const controls = [];
553
+ const groups = [];
554
+ for (const names of parseToolbar(config)) {
555
+ const group = h("div", { className: "nova-tb-group", role: "group" });
556
+ for (const name of names) {
557
+ if (!editor.isAllowed(name)) continue;
558
+ const spec = ui.registry.get(name);
559
+ if (!spec) {
560
+ if (warnUnknown) console.warn(`[nova] Unknown toolbar item "${name}"`);
561
+ continue;
562
+ }
563
+ const control = renderControl(editor, name, spec);
564
+ controls.push(control);
565
+ group.append(control.el);
566
+ }
567
+ if (group.childElementCount) {
568
+ groups.push(group);
569
+ host.append(group);
570
+ }
571
+ }
572
+ const overflows = mode === "floating" || mode === "sliding";
573
+ const strip = mode === "sliding";
574
+ const overflowBox = h("div", {
575
+ className: strip ? "nova-toolbar nova-tb-strip" : "nova-toolbar nova-tb-overflow",
576
+ role: "group",
577
+ id: uniqueId("nova-tb-more"),
578
+ "aria-label": t("more"),
579
+ hidden: strip
580
+ });
581
+ const moreButton = h(
582
+ "button",
583
+ {
584
+ type: "button",
585
+ className: "nova-btn nova-tb-more",
586
+ "aria-label": t("more"),
587
+ "aria-expanded": "false",
588
+ "data-tooltip": t("more"),
589
+ hidden: true,
590
+ // The strip is right under the toolbar; the panel floats.
591
+ ...strip ? { "aria-controls": overflowBox.id } : { "aria-haspopup": "true" }
592
+ },
593
+ icon(icons.more)
594
+ );
595
+ ui.tooltip.attach(moreButton);
596
+ let overflowPopover = null;
597
+ const closeOverflow = () => {
598
+ overflowPopover?.close();
599
+ overflowPopover = null;
600
+ if (strip && !overflowBox.hidden) {
601
+ overflowBox.hidden = true;
602
+ moreButton.setAttribute("aria-expanded", "false");
603
+ }
604
+ };
605
+ const offDialog = ui.onDialogOpen(() => {
606
+ if (!strip) closeOverflow();
607
+ });
608
+ moreButton.addEventListener("click", (event) => {
609
+ if (strip) {
610
+ const open = overflowBox.hidden;
611
+ overflowBox.hidden = !open;
612
+ moreButton.setAttribute("aria-expanded", String(open));
613
+ if (open && event.detail === 0)
614
+ overflowBox.querySelector("button:not(:disabled)")?.focus();
615
+ return;
616
+ }
617
+ if (overflowPopover) return closeOverflow();
618
+ moreButton.setAttribute("aria-expanded", "true");
619
+ const popover = new Popover({
620
+ host: ui.overlayHost,
621
+ anchor: moreButton,
622
+ placement: "bottom-end",
623
+ content: overflowBox,
624
+ className: "nova-tb-overflow-popover",
625
+ // Clicks on nested menus (they are in overlayHost too) don't close the panel.
626
+ ignore: [ui.overlayHost, moreButton],
627
+ onClose: (reason) => {
628
+ overflowPopover = null;
629
+ moreButton.setAttribute("aria-expanded", "false");
630
+ if (reason === "escape" && popover.focusWasInside) moreButton.focus();
631
+ }
632
+ });
633
+ overflowPopover = popover;
634
+ if (event.detail === 0)
635
+ overflowBox.querySelector("button:not(:disabled)")?.focus();
636
+ });
637
+ if (overflows) host.append(moreButton);
638
+ if (strip) host.after(overflowBox);
639
+ if (mode === "scrolling") {
640
+ host.addEventListener(
641
+ "focusin",
642
+ (event) => event.target.scrollIntoView?.({ block: "nearest", inline: "nearest" }),
643
+ { signal }
644
+ );
645
+ }
646
+ const layout = () => {
647
+ if (!overflows) return;
648
+ for (const group of groups) host.insertBefore(group, moreButton);
649
+ moreButton.hidden = true;
650
+ if (host.scrollWidth <= host.clientWidth + 1) {
651
+ closeOverflow();
652
+ return;
653
+ }
654
+ moreButton.hidden = false;
655
+ let visible = groups.length;
656
+ while (visible > 1 && host.scrollWidth > host.clientWidth + 1) {
657
+ visible -= 1;
658
+ overflowBox.prepend(groups[visible]);
659
+ }
660
+ if (!overflowBox.childElementCount) {
661
+ moreButton.hidden = true;
662
+ closeOverflow();
663
+ }
664
+ overflowPopover?.reposition();
665
+ resetRoving();
666
+ };
667
+ let lastWidth = -1;
668
+ const resizeObserver = typeof ResizeObserver !== "undefined" && overflows ? new ResizeObserver(() => {
669
+ if (host.clientWidth === lastWidth) return;
670
+ lastWidth = host.clientWidth;
671
+ layout();
672
+ }) : null;
673
+ resizeObserver?.observe(host);
674
+ const focusables = () => [...host.querySelectorAll("button")].filter((b) => !b.disabled && !b.hidden);
675
+ let current = null;
676
+ const resetRoving = () => {
677
+ const list = focusables();
678
+ if (!current || !list.includes(current)) current = list[0] ?? null;
679
+ for (const b of host.querySelectorAll("button"))
680
+ b.tabIndex = b === current ? 0 : -1;
681
+ };
682
+ host.addEventListener(
683
+ "focusin",
684
+ (event) => {
685
+ const target = event.target;
686
+ if (target instanceof HTMLButtonElement && host.contains(target)) {
687
+ current = target;
688
+ resetRoving();
689
+ }
690
+ },
691
+ { signal }
692
+ );
693
+ host.addEventListener(
694
+ "keydown",
695
+ (event) => {
696
+ const list = focusables();
697
+ const index = list.indexOf(activeElement(host));
698
+ if (index < 0) return;
699
+ let next = null;
700
+ const key2 = logicalKey(event, host);
701
+ if (key2 === "ArrowRight") next = index + 1;
702
+ else if (key2 === "ArrowLeft") next = index - 1;
703
+ else if (event.key === "Home") next = 0;
704
+ else if (event.key === "End") next = list.length - 1;
705
+ else if (event.key === "Escape") {
706
+ event.preventDefault();
707
+ editor.focus();
708
+ return;
709
+ }
710
+ if (next === null) return;
711
+ event.preventDefault();
712
+ list[(next + list.length) % list.length].focus();
713
+ },
714
+ { signal }
715
+ );
716
+ const keepFocus = (event) => {
717
+ if (event.target.closest("button")) event.preventDefault();
718
+ };
719
+ host.addEventListener("mousedown", keepFocus, { signal });
720
+ overflowBox.addEventListener("mousedown", keepFocus);
721
+ overflowBox.addEventListener("keydown", (event) => {
722
+ if (event.key === "Escape") {
723
+ if (strip) {
724
+ event.preventDefault();
725
+ closeOverflow();
726
+ moreButton.focus();
727
+ }
728
+ return;
729
+ }
730
+ const list = [...overflowBox.querySelectorAll("button")].filter(
731
+ (b) => !b.disabled
732
+ );
733
+ const index = list.indexOf(activeElement(overflowBox));
734
+ if (index < 0) return;
735
+ const key2 = logicalKey(event, overflowBox);
736
+ if (key2 === "ArrowRight" || key2 === "ArrowDown") {
737
+ event.preventDefault();
738
+ list[(index + 1) % list.length].focus();
739
+ } else if (key2 === "ArrowLeft" || key2 === "ArrowUp") {
740
+ event.preventDefault();
741
+ list[(index - 1 + list.length) % list.length].focus();
742
+ }
743
+ });
744
+ const update = () => {
745
+ for (const control of controls) control.update();
746
+ resetRoving();
747
+ };
748
+ update();
749
+ layout();
750
+ return {
751
+ update,
752
+ focus: () => {
753
+ resetRoving();
754
+ current?.focus();
755
+ },
756
+ destroy: () => {
757
+ resizeObserver?.disconnect();
758
+ offDialog();
759
+ closeOverflow();
760
+ listeners.abort();
761
+ host.replaceChildren();
762
+ if (strip) overflowBox.remove();
763
+ }
764
+ };
765
+ }
766
+ function renderControl(editor, name, spec) {
767
+ if (spec.type === "split") return renderSplit(editor, name, spec);
768
+ const { ui } = editor;
769
+ const el = h("button", {
770
+ type: "button",
771
+ className: `nova-btn nova-tb-${spec.type}`,
772
+ "aria-label": spec.tooltip,
773
+ "data-tooltip": spec.tooltip,
774
+ "data-control": name,
775
+ ...spec.shortcut ? { "data-shortcut": spec.shortcut } : {}
776
+ });
777
+ ui.tooltip.attach(el);
778
+ if (spec.icon) el.append(icon(spec.icon));
779
+ const label = spec.type === "menu" && (spec.label || spec.text) ? h("span", { className: "nova-tb-label" }) : null;
780
+ if (label) {
781
+ if (spec.type === "menu" && spec.minChars) label.style.minWidth = `${spec.minChars}ch`;
782
+ el.append(label);
783
+ el.classList.add("nova-tb-has-label");
784
+ } else if (!spec.icon && spec.text) {
785
+ el.append(spec.text);
786
+ }
787
+ let colorBar = null;
788
+ if (spec.type === "panel" && spec.indicator) {
789
+ colorBar = h("span", { className: "nova-color-bar" });
790
+ el.append(colorBar);
791
+ }
792
+ if (spec.type !== "button") {
793
+ el.setAttribute("aria-haspopup", spec.type === "menu" ? "menu" : "dialog");
794
+ el.setAttribute("aria-expanded", "false");
795
+ el.append(icon(icons.chevronDown));
796
+ el.lastElementChild?.classList.add("nova-chevron");
797
+ }
798
+ el.addEventListener("click", (event) => {
799
+ if (spec.type === "button") {
800
+ spec.onAction(editor);
801
+ return;
802
+ }
803
+ if (el.getAttribute("aria-expanded") === "true") {
804
+ ui.closePopover();
805
+ return;
806
+ }
807
+ const fromKeyboard = event.detail === 0;
808
+ const closeAndRefocus = () => ui.closePopover();
809
+ const content = spec.type === "menu" ? createMenu(spec.items(editor), closeAndRefocus, spec.tooltip) : spec.render(editor, closeAndRefocus);
810
+ el.setAttribute("aria-expanded", "true");
811
+ const popover = ui.openPopover({
812
+ anchor: el,
813
+ content,
814
+ ignore: [el],
815
+ className: spec.type === "menu" ? "nova-popover-menu" : "nova-popover-panel",
816
+ onClose: (reason) => {
817
+ el.setAttribute("aria-expanded", "false");
818
+ if (reason === "escape" && popover.focusWasInside) el.focus();
819
+ }
820
+ });
821
+ if (spec.type === "menu") focusMenu(content);
822
+ else if (fromKeyboard) content.querySelector("button, input")?.focus();
823
+ });
824
+ if (spec.type !== "button") {
825
+ el.addEventListener("keydown", (event) => {
826
+ if (event.key === "ArrowDown" && el.getAttribute("aria-expanded") !== "true") {
827
+ event.preventDefault();
828
+ el.click();
829
+ }
830
+ });
831
+ }
832
+ const update = () => {
833
+ const editable = editor.isEditable();
834
+ el.disabled = !editable || (spec.isEnabled ? !spec.isEnabled(editor) : false);
835
+ if (spec.isActive) {
836
+ const active = spec.isActive(editor);
837
+ el.classList.toggle("is-active", active);
838
+ if (spec.type === "button") el.setAttribute("aria-pressed", String(active));
839
+ }
840
+ if (label && spec.type === "menu") {
841
+ const text = spec.label?.(editor) ?? spec.text ?? "";
842
+ label.textContent = text;
843
+ el.setAttribute(
844
+ "aria-label",
845
+ text && text !== spec.tooltip ? `${text}, ${spec.tooltip}` : spec.tooltip ?? text
846
+ );
847
+ }
848
+ if (colorBar && spec.type === "panel" && spec.indicator) {
849
+ const color = spec.indicator(editor);
850
+ colorBar.style.background = color ?? "";
851
+ colorBar.classList.toggle("is-empty", !color);
852
+ }
853
+ };
854
+ return { el, update };
855
+ }
856
+ function renderSplit(editor, name, spec) {
857
+ const main = renderControl(editor, name, {
858
+ type: "button",
859
+ tooltip: spec.tooltip,
860
+ onAction: spec.onAction,
861
+ ...spec.icon ? { icon: spec.icon } : {},
862
+ ...spec.text ? { text: spec.text } : {},
863
+ ...spec.shortcut ? { shortcut: spec.shortcut } : {},
864
+ ...spec.isActive ? { isActive: spec.isActive } : {},
865
+ ...spec.isEnabled ? { isEnabled: spec.isEnabled } : {}
866
+ });
867
+ const more = renderControl(editor, `${name}-options`, {
868
+ type: "menu",
869
+ tooltip: `${spec.tooltip}: ${editor.ui.t("toolbar.options")}`,
870
+ items: spec.items,
871
+ ...spec.isEnabled ? { isEnabled: spec.isEnabled } : {}
872
+ });
873
+ more.el.classList.add("nova-tb-split-more");
874
+ const el = h("span", { className: "nova-tb-split" }, main.el, more.el);
875
+ return {
876
+ el,
877
+ update: () => {
878
+ main.update();
879
+ more.update();
880
+ }
881
+ };
882
+ }
883
+
884
+ // src/ui/slash.ts
885
+ var exec = (command) => (editor) => editor.exec(command);
886
+ var defaultSlashCommands = [
887
+ {
888
+ name: "paragraph",
889
+ label: "paragraph",
890
+ icon: icons.paragraph,
891
+ keywords: ["text", "p", "paragraph"],
892
+ run: exec("paragraph")
893
+ },
894
+ {
895
+ name: "h1",
896
+ label: "h1",
897
+ icon: icons.h1,
898
+ keywords: ["h1", "heading", "title"],
899
+ shortcut: "Mod-Alt-1",
900
+ run: exec("h1")
901
+ },
902
+ {
903
+ name: "h2",
904
+ label: "h2",
905
+ icon: icons.h2,
906
+ keywords: ["h2", "heading", "subtitle"],
907
+ shortcut: "Mod-Alt-2",
908
+ run: exec("h2")
909
+ },
910
+ {
911
+ name: "h3",
912
+ label: "h3",
913
+ icon: icons.h3,
914
+ keywords: ["h3", "heading"],
915
+ shortcut: "Mod-Alt-3",
916
+ run: exec("h3")
917
+ },
918
+ {
919
+ name: "bullist",
920
+ label: "bulletList",
921
+ icon: icons.bulletList,
922
+ keywords: ["ul", "list", "bullet"],
923
+ shortcut: "Mod-Shift-8",
924
+ run: exec("bulletList")
925
+ },
926
+ {
927
+ name: "numlist",
928
+ label: "orderedList",
929
+ icon: icons.orderedList,
930
+ keywords: ["ol", "list", "numbered"],
931
+ shortcut: "Mod-Shift-7",
932
+ run: exec("orderedList")
933
+ },
934
+ {
935
+ name: "blockquote",
936
+ label: "blockquote",
937
+ icon: icons.blockquote,
938
+ keywords: ["quote", "blockquote", "citation"],
939
+ run: exec("blockquote")
940
+ },
941
+ {
942
+ name: "codeblock",
943
+ label: "codeBlock",
944
+ icon: icons.codeBlock,
945
+ keywords: ["code", "pre", "snippet"],
946
+ run: exec("codeBlock")
947
+ },
948
+ {
949
+ name: "hr",
950
+ label: "horizontalRule",
951
+ icon: icons.horizontalRule,
952
+ keywords: ["hr", "divider", "line", "separator"],
953
+ run: exec("horizontalRule")
954
+ },
955
+ {
956
+ name: "table",
957
+ label: "table",
958
+ icon: icons.table,
959
+ keywords: ["table", "grid"],
960
+ run: (e) => e.exec(insertTable(3, 3))
961
+ },
962
+ {
963
+ name: "image",
964
+ label: "image",
965
+ icon: icons.image,
966
+ keywords: ["image", "picture", "photo", "img"],
967
+ run: (e) => openImageDialog(e)
968
+ },
969
+ {
970
+ name: "link",
971
+ label: "link",
972
+ icon: icons.link,
973
+ keywords: ["link", "url", "href"],
974
+ shortcut: "Mod-k",
975
+ run: (e) => openLinkDialog(e)
976
+ }
977
+ ];
978
+ function rankSlashCommands(commands2, query, t) {
979
+ const q = query.toLowerCase();
980
+ if (!q) return commands2;
981
+ const scored = [];
982
+ commands2.forEach((cmd, index) => {
983
+ const label = t(cmd.label).toLowerCase();
984
+ const words = [label, ...label.split(/\s+/), ...cmd.keywords];
985
+ let score = -1;
986
+ if (label.startsWith(q)) score = 3;
987
+ else if (words.some((w) => w.startsWith(q))) score = 2;
988
+ else if (words.some((w) => w.includes(q))) score = 1;
989
+ if (score > 0) scored.push([score, index, cmd]);
990
+ });
991
+ return scored.sort((a, b) => b[0] - a[0] || a[1] - b[1]).map(([, , cmd]) => cmd);
992
+ }
993
+ function registerSlashCommands(editor, extra = []) {
994
+ const { t } = editor.ui;
995
+ const commands2 = [...defaultSlashCommands, ...extra].filter((cmd) => editor.isAllowed(cmd.name));
996
+ editor.ui.registry.addAutocompleter("slashcommands", {
997
+ trigger: "/",
998
+ label: t("slash.label"),
999
+ emptyText: t("slash.empty"),
1000
+ fetch: (query) => rankSlashCommands(commands2, query, t).map((cmd) => ({
1001
+ value: cmd.name,
1002
+ label: t(cmd.label),
1003
+ icon: cmd.icon,
1004
+ ...cmd.shortcut ? { shortcut: cmd.shortcut } : {}
1005
+ })),
1006
+ onSelect: (item, range, e) => {
1007
+ const cmd = commands2.find((c) => c.name === item.value);
1008
+ if (!cmd) return;
1009
+ e.view.dispatch(e.view.state.tr.delete(range.from, range.to));
1010
+ cmd.run(e);
1011
+ }
1012
+ });
1013
+ }
1014
+
1015
+ // src/ui/statusbar.ts
1016
+ var TAGS = {
1017
+ paragraph: () => "p",
1018
+ heading: (n) => `h${n.attrs.level}`,
1019
+ blockquote: () => "blockquote",
1020
+ code_block: () => "pre",
1021
+ bullet_list: () => "ul",
1022
+ ordered_list: () => "ol",
1023
+ list_item: () => "li",
1024
+ table: () => "table",
1025
+ table_row: () => "tr",
1026
+ table_cell: () => "td",
1027
+ table_header: () => "th"
1028
+ };
1029
+ var MARK_TAGS = {
1030
+ bold: "strong",
1031
+ italic: "em",
1032
+ underline: "u",
1033
+ strike: "s",
1034
+ code: "code",
1035
+ link: "a",
1036
+ subscript: "sub",
1037
+ superscript: "sup"
1038
+ };
1039
+ var CJK = String.raw`\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}`;
1040
+ var LETTER = String.raw`(?:(?![${CJK}])[\p{L}\p{N}])`;
1041
+ var WORD = new RegExp(`[${CJK}]|${LETTER}+(?:['\u2019-]${LETTER}+)*`, "gu");
1042
+ function countWords(text) {
1043
+ return text.match(WORD)?.length ?? 0;
1044
+ }
1045
+ function createStatusbar(editor, host) {
1046
+ host.className = "nova-statusbar";
1047
+ const path = h("div", { className: "nova-path", "aria-hidden": "true" });
1048
+ const words = h("div", { className: "nova-wordcount", "aria-live": "off" });
1049
+ host.append(path, words);
1050
+ const resize = editor.options.resize;
1051
+ const removeHandle = resize ? createResizeHandle(editor, host, resize === "both") : null;
1052
+ let timer = null;
1053
+ const updateWords = () => {
1054
+ const doc = editor.view.state.doc;
1055
+ words.textContent = editor.ui.t("status.words", {
1056
+ count: countWords(doc.textBetween(0, doc.content.size, " ", " "))
1057
+ });
1058
+ };
1059
+ const update = (docChanged) => {
1060
+ const { $from } = editor.view.state.selection;
1061
+ const parts = [];
1062
+ for (let depth = 1; depth <= $from.depth; depth++) {
1063
+ const node = $from.node(depth);
1064
+ const tag = TAGS[node.type.name]?.(node);
1065
+ if (tag) parts.push(tag);
1066
+ }
1067
+ const selected = editor.view.state.selection.node;
1068
+ if (selected?.type.name === "image") parts.push("img");
1069
+ for (const mark of $from.marks()) {
1070
+ const tag = MARK_TAGS[mark.type.name];
1071
+ if (tag) parts.push(tag);
1072
+ }
1073
+ path.replaceChildren(
1074
+ ...parts.flatMap((tag, i) => [
1075
+ ...i ? [" \u203A "] : [],
1076
+ h("span", { className: "nova-path-item" }, tag)
1077
+ ])
1078
+ );
1079
+ if (docChanged) {
1080
+ if (timer) clearTimeout(timer);
1081
+ timer = setTimeout(updateWords, 250);
1082
+ }
1083
+ };
1084
+ updateWords();
1085
+ update(false);
1086
+ return {
1087
+ update,
1088
+ destroy: () => {
1089
+ if (timer) clearTimeout(timer);
1090
+ removeHandle?.();
1091
+ host.replaceChildren();
1092
+ }
1093
+ };
1094
+ }
1095
+ var MIN_HEIGHT = 100;
1096
+ var MIN_WIDTH = 200;
1097
+ var KEY_STEP = 20;
1098
+ var MAX_HEIGHT = 4e3;
1099
+ function createResizeHandle(editor, host, both) {
1100
+ const root = editor.root;
1101
+ const handle = h("div", {
1102
+ className: "nova-resize-handle",
1103
+ role: "separator",
1104
+ tabIndex: 0,
1105
+ "aria-orientation": "horizontal",
1106
+ "aria-label": editor.ui.t("status.resize"),
1107
+ "aria-valuemin": String(MIN_HEIGHT)
1108
+ });
1109
+ handle.append(icon(both ? icons.resizeHandleBoth : icons.resizeHandle));
1110
+ root.dataset.resize = both ? "both" : "vertical";
1111
+ host.append(handle);
1112
+ const sayHeight = () => {
1113
+ const height = Math.max(MIN_HEIGHT, root.offsetHeight);
1114
+ handle.setAttribute("aria-valuenow", String(height));
1115
+ handle.setAttribute("aria-valuemax", String(Math.max(MAX_HEIGHT, height)));
1116
+ };
1117
+ sayHeight();
1118
+ handle.addEventListener("focus", sayHeight);
1119
+ const setSize = (height, width) => {
1120
+ root.style.boxSizing = "border-box";
1121
+ root.style.height = `${Math.max(MIN_HEIGHT, Math.round(height))}px`;
1122
+ if (both && width !== void 0) {
1123
+ const max = root.parentElement?.clientWidth || Infinity;
1124
+ root.style.width = `${Math.min(max, Math.max(MIN_WIDTH, Math.round(width)))}px`;
1125
+ }
1126
+ sayHeight();
1127
+ };
1128
+ let start = null;
1129
+ const onDown = (event) => {
1130
+ if (editor.isDisabled()) return;
1131
+ event.preventDefault();
1132
+ handle.setPointerCapture(event.pointerId);
1133
+ start = {
1134
+ x: event.clientX,
1135
+ y: event.clientY,
1136
+ height: root.offsetHeight,
1137
+ width: root.offsetWidth
1138
+ };
1139
+ };
1140
+ const onMove = (event) => {
1141
+ if (!start) return;
1142
+ const dx = (event.clientX - start.x) * (isRtl(root) ? -1 : 1);
1143
+ setSize(start.height + event.clientY - start.y, start.width + dx);
1144
+ };
1145
+ const onUp = (event) => {
1146
+ if (!start) return;
1147
+ start = null;
1148
+ if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId);
1149
+ };
1150
+ const onKey = (event) => {
1151
+ const dy = event.key === "ArrowDown" ? KEY_STEP : event.key === "ArrowUp" ? -KEY_STEP : 0;
1152
+ const key2 = logicalKey(event, root);
1153
+ const dx = both ? key2 === "ArrowRight" ? KEY_STEP : key2 === "ArrowLeft" ? -KEY_STEP : 0 : 0;
1154
+ if (!dx && !dy) return;
1155
+ event.preventDefault();
1156
+ setSize(root.offsetHeight + dy, root.offsetWidth + dx);
1157
+ };
1158
+ handle.addEventListener("pointerdown", onDown);
1159
+ handle.addEventListener("pointermove", onMove);
1160
+ handle.addEventListener("pointerup", onUp);
1161
+ handle.addEventListener("pointercancel", onUp);
1162
+ handle.addEventListener("keydown", onKey);
1163
+ return () => {
1164
+ handle.remove();
1165
+ delete root.dataset.resize;
1166
+ };
1167
+ }
1168
+
1169
+ // src/sticky-header.ts
1170
+ import { Plugin as Plugin2, PluginKey as PluginKey2 } from "prosemirror-state";
1171
+ function stickyHeader(header, content) {
1172
+ let measured = null;
1173
+ const cover = () => {
1174
+ if (measured !== null) return measured;
1175
+ measured = 0;
1176
+ queueMicrotask(() => measured = null);
1177
+ if (content.scrollHeight > content.clientHeight + 1) return measured;
1178
+ const style = getComputedStyle(header);
1179
+ if (style.position === "sticky" && style.display !== "none")
1180
+ measured = header.offsetHeight + (parseFloat(style.top) || 0);
1181
+ return measured;
1182
+ };
1183
+ const uncover = (view) => {
1184
+ if (!cover() || !view.hasFocus()) return;
1185
+ const box = header.getBoundingClientRect();
1186
+ let caret;
1187
+ try {
1188
+ caret = view.coordsAtPos(view.state.selection.head);
1189
+ } catch {
1190
+ return;
1191
+ }
1192
+ if (caret.bottom <= box.top || caret.top >= box.bottom) return;
1193
+ scrollerOf(header).scrollBy(0, caret.top - box.bottom - 5);
1194
+ };
1195
+ const reveal = (view) => {
1196
+ if (!view.dom.getClientRects().length) return;
1197
+ let rect;
1198
+ try {
1199
+ rect = view.coordsAtPos(view.state.selection.head);
1200
+ } catch {
1201
+ return;
1202
+ }
1203
+ if (content.scrollHeight > content.clientHeight + 1) {
1204
+ const box = content.getBoundingClientRect();
1205
+ if (rect.top < box.top + 5) content.scrollTop -= box.top + 5 - rect.top;
1206
+ else if (rect.bottom > box.bottom - 5) content.scrollTop += rect.bottom - box.bottom + 5;
1207
+ rect = view.coordsAtPos(view.state.selection.head);
1208
+ }
1209
+ const scroller = scrollerOf(content);
1210
+ const area = scroller instanceof HTMLElement ? scroller.getBoundingClientRect() : { top: 0, bottom: scroller.innerHeight };
1211
+ const top = area.top + cover() + 5;
1212
+ const bottom = area.bottom - 5;
1213
+ if (rect.top < top) scroller.scrollBy(0, rect.top - top);
1214
+ else if (rect.bottom > bottom) scroller.scrollBy(0, rect.bottom - bottom);
1215
+ };
1216
+ const plugin = new Plugin2({
1217
+ key: scrolls,
1218
+ // Counts the requests to scroll to the selection (tr.scrollIntoView()).
1219
+ state: {
1220
+ init: () => 0,
1221
+ apply: (tr, count) => tr.scrolledIntoView ? count + 1 : count
1222
+ },
1223
+ view: () => {
1224
+ let frame = 0;
1225
+ return {
1226
+ update(view, prev) {
1227
+ if (scrolls.getState(view.state) !== scrolls.getState(prev) && !view.hasFocus())
1228
+ reveal(view);
1229
+ if (view.state.selection.eq(prev.selection)) return;
1230
+ cancelAnimationFrame(frame);
1231
+ frame = requestAnimationFrame(() => uncover(view));
1232
+ },
1233
+ destroy: () => cancelAnimationFrame(frame)
1234
+ };
1235
+ }
1236
+ });
1237
+ return {
1238
+ plugin,
1239
+ props: {
1240
+ scrollThreshold: {
1241
+ left: 0,
1242
+ right: 0,
1243
+ bottom: 0,
1244
+ get top() {
1245
+ return cover();
1246
+ }
1247
+ },
1248
+ scrollMargin: {
1249
+ left: 5,
1250
+ right: 5,
1251
+ bottom: 5,
1252
+ get top() {
1253
+ return cover() + 5;
1254
+ }
1255
+ }
1256
+ }
1257
+ };
1258
+ }
1259
+ var scrolls = new PluginKey2("nova-scroll-requests");
1260
+ function scrollerOf(el) {
1261
+ for (let parent = el.parentElement; parent; parent = parent.parentElement) {
1262
+ const { overflowY } = getComputedStyle(parent);
1263
+ if (/auto|scroll|overlay/.test(overflowY) && parent.scrollHeight > parent.clientHeight + 1)
1264
+ return parent;
1265
+ }
1266
+ return el.ownerDocument.defaultView ?? window;
1267
+ }
1268
+
1269
+ // src/editor.ts
1270
+ import { dropCursor } from "prosemirror-dropcursor";
1271
+ import { gapCursor } from "prosemirror-gapcursor";
1272
+ import { history } from "prosemirror-history";
1273
+ import { keymap as keymap3 } from "prosemirror-keymap";
1274
+ import { Node as PMNode, Slice as Slice2 } from "prosemirror-model";
1275
+ import { EditorState, Plugin as Plugin9 } from "prosemirror-state";
1276
+ import { EditorView } from "prosemirror-view";
1277
+
1278
+ // src/first-click.ts
1279
+ import { Plugin as Plugin3, Selection } from "prosemirror-state";
1280
+ function browserCaret(view) {
1281
+ const selection = view.dom.ownerDocument.getSelection();
1282
+ const node = selection?.focusNode;
1283
+ if (!selection || !node || !view.dom.contains(node)) return null;
1284
+ try {
1285
+ return view.posAtDOM(node, selection.focusOffset);
1286
+ } catch {
1287
+ return null;
1288
+ }
1289
+ }
1290
+ function firstClickPlugin() {
1291
+ let focusedOnMouseDown = true;
1292
+ return new Plugin3({
1293
+ props: {
1294
+ handleDOMEvents: {
1295
+ mousedown(view) {
1296
+ focusedOnMouseDown = view.hasFocus();
1297
+ return false;
1298
+ }
1299
+ },
1300
+ handleClick(view, pos, event) {
1301
+ if (focusedOnMouseDown || event.button !== 0 || event.shiftKey || event.detail > 1)
1302
+ return false;
1303
+ const { doc } = view.state;
1304
+ const hit = view.posAtCoords({ left: event.clientX, top: event.clientY });
1305
+ const node = hit && hit.inside >= 0 ? doc.nodeAt(hit.inside) : null;
1306
+ if (node && !node.isTextblock) return false;
1307
+ const $pos = doc.resolve(pos);
1308
+ const caret = browserCaret(view);
1309
+ if (caret !== null && doc.resolve(caret).parent === $pos.parent) return false;
1310
+ const selection = Selection.near($pos);
1311
+ if (!view.state.selection.eq(selection))
1312
+ view.dispatch(view.state.tr.setSelection(selection).setMeta("pointer", true));
1313
+ view.focus();
1314
+ return true;
1315
+ }
1316
+ }
1317
+ });
1318
+ }
1319
+
1320
+ // src/announce.ts
1321
+ import { Plugin as Plugin4, PluginKey as PluginKey3 } from "prosemirror-state";
1322
+ var announceKey = new PluginKey3("nova-announce");
1323
+ function spokenCommand(name) {
1324
+ return (state, dispatch, view) => commands[name](state, dispatch && ((tr) => dispatch(tr.setMeta(announceKey, name))), view);
1325
+ }
1326
+ var TOGGLES = /* @__PURE__ */ new Set([
1327
+ "bold",
1328
+ "italic",
1329
+ "underline",
1330
+ "strike",
1331
+ "code",
1332
+ "subscript",
1333
+ "superscript",
1334
+ "bulletList",
1335
+ "orderedList"
1336
+ ]);
1337
+ var BLOCK_TYPES = /* @__PURE__ */ new Set([
1338
+ "paragraph",
1339
+ "h1",
1340
+ "h2",
1341
+ "h3",
1342
+ "h4",
1343
+ "h5",
1344
+ "h6"
1345
+ ]);
1346
+ var ALIGNMENTS = [
1347
+ "alignLeft",
1348
+ "alignCenter",
1349
+ "alignRight",
1350
+ "alignJustify"
1351
+ ];
1352
+ function blockKeys(state) {
1353
+ const { $from } = state.selection;
1354
+ const keys = [];
1355
+ for (let depth = 1; depth <= $from.depth; depth++) {
1356
+ const node = $from.node(depth);
1357
+ const name = node.type.name;
1358
+ if (name === "bullet_list") keys.push("bulletList");
1359
+ else if (name === "ordered_list") keys.push("orderedList");
1360
+ else if (name === "blockquote") keys.push("blockquote");
1361
+ else if (name === "code_block") keys.push("codeBlock");
1362
+ else if (name === "heading")
1363
+ keys.push(`h${Math.min(6, Math.max(1, Number(node.attrs.level) || 1))}`);
1364
+ }
1365
+ return keys;
1366
+ }
1367
+ function describeCommand(state, command, t) {
1368
+ if (TOGGLES.has(command)) {
1369
+ return t(isCommandActive(state, command) ? "announce.on" : "announce.off", {
1370
+ name: t(command)
1371
+ });
1372
+ }
1373
+ if (BLOCK_TYPES.has(command)) {
1374
+ const heading = blockKeys(state).filter((key2) => /^h[1-6]$/.test(key2)).pop();
1375
+ return t(heading ?? "paragraph");
1376
+ }
1377
+ if (ALIGNMENTS.includes(command)) {
1378
+ return t(ALIGNMENTS.find((align) => isCommandActive(state, align)) ?? "alignLeft");
1379
+ }
1380
+ return t(command);
1381
+ }
1382
+ function describeTyped(before, after, t) {
1383
+ const old = blockKeys(before);
1384
+ const now = blockKeys(after);
1385
+ const changed = now.findIndex((key2, i) => key2 !== old[i]);
1386
+ return changed < 0 ? null : t(now[changed]);
1387
+ }
1388
+ function announcePlugin(t, say) {
1389
+ return new Plugin4({
1390
+ key: announceKey,
1391
+ state: {
1392
+ init: () => null,
1393
+ apply(tr, _value, _old, state) {
1394
+ const command = tr.getMeta(announceKey);
1395
+ if (command) return { command };
1396
+ if (state.plugins.some((plugin) => plugin.spec.isInputRules && tr.getMeta(plugin)))
1397
+ return { typed: true };
1398
+ return null;
1399
+ }
1400
+ },
1401
+ view: () => ({
1402
+ update(view, prevState) {
1403
+ const spoken = announceKey.getState(view.state);
1404
+ if (!spoken || spoken === announceKey.getState(prevState)) return;
1405
+ const text = "command" in spoken ? describeCommand(view.state, spoken.command, t) : describeTyped(prevState, view.state, t);
1406
+ if (text) say(text);
1407
+ }
1408
+ })
1409
+ });
1410
+ }
1411
+
1412
+ // src/deprecations.ts
1413
+ var RENAMED = { options: {}, commands: {}, events: {} };
1414
+ var KIND = {
1415
+ options: "the option",
1416
+ commands: "the command",
1417
+ events: "the event"
1418
+ };
1419
+ var warned = /* @__PURE__ */ new Set();
1420
+ function deprecate(what, instead) {
1421
+ if (warned.has(what)) return;
1422
+ warned.add(what);
1423
+ console.warn(
1424
+ `[nova] ${what} is deprecated: use ${instead}. Old names keep working for at least one minor version (https://novaprose.com/project/versioning/).`
1425
+ );
1426
+ }
1427
+ var own = (table, key2) => Object.prototype.hasOwnProperty.call(table, key2) ? table[key2] : void 0;
1428
+ function currentName(kind, name, renamed = RENAMED) {
1429
+ const next = own(renamed[kind], name);
1430
+ if (next === void 0) return name;
1431
+ deprecate(`${KIND[kind]} "${name}"`, `"${next}"`);
1432
+ return next;
1433
+ }
1434
+ function renameOptions(options, renamed = RENAMED) {
1435
+ let result = options;
1436
+ for (const [old, next] of Object.entries(renamed.options)) {
1437
+ if (!Object.prototype.hasOwnProperty.call(options, old)) continue;
1438
+ deprecate(`${KIND.options} "${old}"`, `"${next}"`);
1439
+ if (result === options) result = { ...result };
1440
+ if (!Object.prototype.hasOwnProperty.call(result, next)) result[next] = result[old];
1441
+ delete result[old];
1442
+ }
1443
+ return result;
1444
+ }
1445
+
1446
+ // src/inputrules.ts
1447
+ import {
1448
+ inputRules,
1449
+ textblockTypeInputRule,
1450
+ wrappingInputRule,
1451
+ ellipsis,
1452
+ emDash
1453
+ } from "prosemirror-inputrules";
1454
+ import { keymap } from "prosemirror-keymap";
1455
+ var LANGUAGE = "([A-Za-z0-9_+#.-]{0,32})";
1456
+ function buildInputRules(isAllowed = () => true, schema2 = schema) {
1457
+ const { nodes } = schema2;
1458
+ const rules = [ellipsis, emDash];
1459
+ if (isAllowed("blockquote")) rules.push(wrappingInputRule(/^\s*>\s$/, nodes.blockquote));
1460
+ if (isAllowed("numlist")) {
1461
+ rules.push(
1462
+ wrappingInputRule(
1463
+ /^(\d+)\.\s$/,
1464
+ nodes.ordered_list,
1465
+ (match) => ({ start: Number(match[1]) }),
1466
+ (match, node) => node.childCount + node.attrs.start === Number(match[1])
1467
+ )
1468
+ );
1469
+ }
1470
+ if (isAllowed("bullist")) rules.push(wrappingInputRule(/^\s*([-+*])\s$/, nodes.bullet_list));
1471
+ if (isAllowed("codeblock")) {
1472
+ rules.push(
1473
+ textblockTypeInputRule(new RegExp(`^\`\`\`${LANGUAGE}\\s$`), nodes.code_block, (match) => ({
1474
+ language: match[1] || null
1475
+ }))
1476
+ );
1477
+ }
1478
+ for (let level = 1; level <= 6; level++) {
1479
+ if (!isAllowed(`h${level}`)) continue;
1480
+ rules.push(textblockTypeInputRule(new RegExp(`^(#{${level}})\\s$`), nodes.heading, { level }));
1481
+ }
1482
+ return inputRules({ rules });
1483
+ }
1484
+ function codeFenceKeymap(isAllowed = () => true, schema2 = schema) {
1485
+ const fence = new RegExp(`^\`\`\`${LANGUAGE}$`);
1486
+ const fenceToCodeBlock = (state, dispatch) => {
1487
+ const { $from, empty } = state.selection;
1488
+ const block = $from.parent;
1489
+ if (!empty || block.type !== schema2.nodes.paragraph || !isAllowed("codeblock")) return false;
1490
+ if ($from.parentOffset !== block.content.size || block.childCount !== 1) return false;
1491
+ const match = block.firstChild.isText ? fence.exec(block.textContent) : null;
1492
+ if (!match) return false;
1493
+ const index = $from.index(-1);
1494
+ if (!$from.node(-1).canReplaceWith(index, index + 1, schema2.nodes.code_block)) return false;
1495
+ if (dispatch) {
1496
+ const start = $from.start();
1497
+ const tr = state.tr.delete(start, $from.pos).setBlockType(start, start, schema2.nodes.code_block, { language: match[1] || null });
1498
+ dispatch(tr.scrollIntoView());
1499
+ }
1500
+ return true;
1501
+ };
1502
+ return keymap({ Enter: fenceToCodeBlock });
1503
+ }
1504
+
1505
+ // src/text-patterns.ts
1506
+ import { Plugin as Plugin5, TextSelection } from "prosemirror-state";
1507
+ var FORMATS = {
1508
+ bold: "bold",
1509
+ italic: "italic",
1510
+ underline: "underline",
1511
+ strikethrough: "strike",
1512
+ strike: "strike",
1513
+ code: "code",
1514
+ subscript: "subscript",
1515
+ superscript: "superscript",
1516
+ p: "paragraph",
1517
+ paragraph: "paragraph",
1518
+ h1: "h1",
1519
+ h2: "h2",
1520
+ h3: "h3",
1521
+ h4: "h4",
1522
+ h5: "h5",
1523
+ h6: "h6",
1524
+ blockquote: "blockquote",
1525
+ pre: "codeBlock"
1526
+ };
1527
+ function clean(list) {
1528
+ const out = [];
1529
+ for (const raw of list) {
1530
+ const p = raw;
1531
+ if (!p || typeof p.start !== "string" || !p.start || p.start.length > 40) continue;
1532
+ if (typeof p.replacement === "string") out.push({ start: p.start, replacement: p.replacement });
1533
+ else if (typeof p.format !== "string" && !p.command) continue;
1534
+ else if (typeof p.end === "string" && p.end) out.push(p);
1535
+ else out.push(p);
1536
+ }
1537
+ return out.sort((a, b) => b.start.length - a.start.length);
1538
+ }
1539
+ function textBefore(state) {
1540
+ const { $from, empty } = state.selection;
1541
+ if (!empty || !$from.parent.isTextblock || $from.parent.type.spec.code) return null;
1542
+ if ($from.marks().some((m) => m.type.spec.code)) return null;
1543
+ return $from.parent.textBetween(0, $from.parentOffset, void 0, "\uFFFC");
1544
+ }
1545
+ function run(editor, pattern) {
1546
+ const { format, command, value } = pattern;
1547
+ if (typeof command === "function") command(editor, value);
1548
+ else if (typeof command === "string") editor.exec(command);
1549
+ else if (format && editor.formatter.has(format)) editor.formatter.apply(format);
1550
+ else if (format && FORMATS[format]) editor.exec(FORMATS[format]);
1551
+ }
1552
+ function textPatternsPlugin(editor, patterns, lookup) {
1553
+ const fixed = clean(patterns);
1554
+ const all = (view, text) => {
1555
+ if (!lookup) return fixed;
1556
+ const { $from } = view.state.selection;
1557
+ const dom = view.nodeDOM($from.before());
1558
+ let extra = [];
1559
+ try {
1560
+ extra = lookup({ text, block: dom instanceof HTMLElement ? dom : null });
1561
+ } catch (error) {
1562
+ console.error("[nova] textPatternsLookup failed:", error);
1563
+ }
1564
+ return Array.isArray(extra) ? clean([...fixed, ...extra]) : fixed;
1565
+ };
1566
+ const attempt = (view, trigger) => {
1567
+ const text = textBefore(view.state);
1568
+ if (text === null || !editor.isEditable()) return null;
1569
+ const { $from } = view.state.selection;
1570
+ const start = $from.start();
1571
+ for (const pattern of all(view, text)) {
1572
+ if ("replacement" in pattern) {
1573
+ if (!text.endsWith(pattern.start)) continue;
1574
+ const from = $from.pos - pattern.start.length;
1575
+ if (/<[a-z]/i.test(pattern.replacement)) {
1576
+ view.dispatch(view.state.tr.delete(from, $from.pos));
1577
+ editor.insertContent(pattern.replacement);
1578
+ view.dispatch(view.state.tr.setStoredMarks([]));
1579
+ } else view.dispatch(view.state.tr.insertText(pattern.replacement, from, $from.pos));
1580
+ return "replacement";
1581
+ }
1582
+ if ("end" in pattern) {
1583
+ if (!text.endsWith(pattern.end)) continue;
1584
+ const inner = text.lastIndexOf(pattern.start, text.length - pattern.end.length - 1);
1585
+ const contentStart = inner + pattern.start.length;
1586
+ const contentEnd = text.length - pattern.end.length;
1587
+ if (inner < 0 || contentEnd <= contentStart) continue;
1588
+ if (/^\s|\s$/.test(text.slice(contentStart, contentEnd))) continue;
1589
+ const tr = view.state.tr.delete(start + contentEnd, start + text.length).delete(start + inner, start + contentStart);
1590
+ const from = start + inner;
1591
+ const to = from + (contentEnd - contentStart);
1592
+ view.dispatch(tr.setSelection(TextSelection.create(tr.doc, from, to)));
1593
+ run(editor, pattern);
1594
+ const { state } = view;
1595
+ view.dispatch(state.tr.setSelection(TextSelection.create(state.doc, state.selection.to)));
1596
+ view.dispatch(view.state.tr.setStoredMarks([]));
1597
+ return "inline";
1598
+ }
1599
+ if ((pattern.trigger ?? "space") !== trigger) continue;
1600
+ const matches = trigger === "space" ? text === pattern.start : $from.parent.textContent.startsWith(pattern.start) && $from.parentOffset === $from.parent.content.size;
1601
+ if (!matches) continue;
1602
+ view.dispatch(view.state.tr.delete(start, start + pattern.start.length));
1603
+ run(editor, pattern);
1604
+ return "block";
1605
+ }
1606
+ return null;
1607
+ };
1608
+ return new Plugin5({
1609
+ props: {
1610
+ handleTextInput(view, from, to, text) {
1611
+ if (text !== " " || from !== to) return false;
1612
+ const kind = attempt(view, "space");
1613
+ if (!kind) return false;
1614
+ if (kind !== "block") view.dispatch(view.state.tr.insertText(" "));
1615
+ return true;
1616
+ },
1617
+ handleKeyDown(view, event) {
1618
+ if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey) return false;
1619
+ attempt(view, "enter");
1620
+ return false;
1621
+ }
1622
+ }
1623
+ });
1624
+ }
1625
+
1626
+ // src/keymap.ts
1627
+ import { baseKeymap, chainCommands, exitCode } from "prosemirror-commands";
1628
+ import { keymap as keymap2 } from "prosemirror-keymap";
1629
+ import { splitListItem } from "prosemirror-schema-list";
1630
+ var mac = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
1631
+ var insertHardBreak = chainCommands(exitCode, (state, dispatch) => {
1632
+ dispatch?.(state.tr.replaceSelectionWith(nodesOf(state).hard_break.create()).scrollIntoView());
1633
+ return true;
1634
+ });
1635
+ var byName = (resolve, name) => (state, dispatch, view) => resolve(name)(state, dispatch, view);
1636
+ function buildKeymap(resolve = (name) => commands[name]) {
1637
+ const keys = {
1638
+ "Mod-z": byName(resolve, "undo"),
1639
+ "Shift-Mod-z": byName(resolve, "redo"),
1640
+ // Formatting shortcuts say what they did to screen readers ("Bold on", "Heading 2"): announce.ts.
1641
+ "Mod-b": spokenCommand("bold"),
1642
+ "Mod-i": spokenCommand("italic"),
1643
+ "Mod-u": spokenCommand("underline"),
1644
+ "Mod-Shift-x": spokenCommand("strike"),
1645
+ "Mod-e": spokenCommand("code"),
1646
+ "Mod-,": spokenCommand("subscript"),
1647
+ "Mod-.": spokenCommand("superscript"),
1648
+ "Mod-Alt-0": spokenCommand("paragraph"),
1649
+ "Mod-Alt-1": spokenCommand("h1"),
1650
+ "Mod-Alt-2": spokenCommand("h2"),
1651
+ "Mod-Alt-3": spokenCommand("h3"),
1652
+ "Mod-Alt-4": spokenCommand("h4"),
1653
+ "Mod-Alt-5": spokenCommand("h5"),
1654
+ "Mod-Alt-6": spokenCommand("h6"),
1655
+ "Mod-Shift-7": spokenCommand("orderedList"),
1656
+ "Mod-Shift-8": spokenCommand("bulletList"),
1657
+ "Mod-Shift-l": spokenCommand("alignLeft"),
1658
+ "Mod-Shift-e": spokenCommand("alignCenter"),
1659
+ "Mod-Shift-r": spokenCommand("alignRight"),
1660
+ "Mod-Shift-j": spokenCommand("alignJustify"),
1661
+ "Mod-\\": spokenCommand("clearFormatting"),
1662
+ "Shift-Enter": insertHardBreak,
1663
+ Enter: chainCommands(exitImageCaption, (state, dispatch) => {
1664
+ const item = parentListItem(state);
1665
+ const attrs = typeof item?.attrs.checked === "boolean" ? { checked: false } : void 0;
1666
+ return splitListItem(nodesOf(state).list_item, attrs)(state, dispatch);
1667
+ }),
1668
+ // Tab is for lists only (in a paragraph it still moves focus). A paragraph indent is Mod-] / Mod-[.
1669
+ Tab: listIndent,
1670
+ "Shift-Tab": listOutdent,
1671
+ "Mod-]": commands.indent,
1672
+ "Mod-[": commands.outdent,
1673
+ // Move a block (a list item, a paragraph, a table), as in Word.
1674
+ "Alt-Shift-ArrowUp": commands.moveBlockUp,
1675
+ "Alt-Shift-ArrowDown": commands.moveBlockDown
1676
+ };
1677
+ if (!mac) keys["Mod-y"] = byName(resolve, "redo");
1678
+ return [keymap2(keys), keymap2(baseKeymap)];
1679
+ }
1680
+ function parentListItem(state) {
1681
+ const { $from } = state.selection;
1682
+ for (let depth = $from.depth; depth > 0; depth--) {
1683
+ const node = $from.node(depth);
1684
+ if (node.type === nodesOf(state).list_item) return node;
1685
+ }
1686
+ return null;
1687
+ }
1688
+
1689
+ // src/plugin-views.ts
1690
+ var reconfiguring = /* @__PURE__ */ new WeakSet();
1691
+ var kept = /* @__PURE__ */ new WeakMap();
1692
+ var wrapped = /* @__PURE__ */ new WeakSet();
1693
+ function keepPluginViews(plugins) {
1694
+ for (const plugin of plugins) {
1695
+ const spec = plugin.spec;
1696
+ const create = spec.view;
1697
+ if (!create || wrapped.has(plugin)) continue;
1698
+ wrapped.add(plugin);
1699
+ spec.view = (view) => {
1700
+ let views = kept.get(view);
1701
+ if (!views) kept.set(view, views = /* @__PURE__ */ new Map());
1702
+ let inner = views.get(plugin);
1703
+ if (!inner) views.set(plugin, inner = create(view));
1704
+ const current = inner;
1705
+ return {
1706
+ update: (v, prev) => current.update?.(v, prev),
1707
+ destroy: () => {
1708
+ if (reconfiguring.has(view)) return;
1709
+ views.delete(plugin);
1710
+ current.destroy?.();
1711
+ }
1712
+ };
1713
+ };
1714
+ }
1715
+ }
1716
+ function reconfigurePlugins(view, plugins) {
1717
+ keepPluginViews(plugins);
1718
+ reconfiguring.add(view);
1719
+ try {
1720
+ view.updateState(view.state.reconfigure({ plugins }));
1721
+ } finally {
1722
+ reconfiguring.delete(view);
1723
+ }
1724
+ const views = kept.get(view);
1725
+ if (!views) return;
1726
+ for (const [plugin, inner] of views) {
1727
+ if (!plugins.includes(plugin)) {
1728
+ views.delete(plugin);
1729
+ inner.destroy?.();
1730
+ }
1731
+ }
1732
+ }
1733
+
1734
+ // src/chain.ts
1735
+ function chainableState(state, tr) {
1736
+ let { selection, doc, storedMarks } = tr;
1737
+ return Object.create(state, {
1738
+ doc: { get: () => doc },
1739
+ selection: { get: () => selection },
1740
+ storedMarks: { get: () => storedMarks },
1741
+ tr: {
1742
+ get: () => {
1743
+ ({ selection, doc, storedMarks } = tr);
1744
+ return tr;
1745
+ }
1746
+ }
1747
+ });
1748
+ }
1749
+ function warn(message) {
1750
+ console.warn(`[nova] chain: ${message}`);
1751
+ }
1752
+ function createChain(host) {
1753
+ const steps = [];
1754
+ const attempt = (apply) => {
1755
+ const view = host.view();
1756
+ if (!view) return false;
1757
+ const { state } = view;
1758
+ const tr = state.tr;
1759
+ for (const step of steps) {
1760
+ let foreign = false;
1761
+ const dispatch = (dispatched) => {
1762
+ if (dispatched !== tr) foreign = true;
1763
+ };
1764
+ if (!step(chainableState(state, tr), dispatch, view)) return false;
1765
+ if (foreign) {
1766
+ warn("a command dispatched its own transaction; build it from state.tr");
1767
+ return false;
1768
+ }
1769
+ }
1770
+ if (apply) {
1771
+ view.dispatch(tr);
1772
+ view.focus();
1773
+ }
1774
+ return true;
1775
+ };
1776
+ const chain = {
1777
+ exec(command) {
1778
+ if (command === "undo" || command === "redo") {
1779
+ warn(`"${command}" runs on its own \u2014 use editor.exec()`);
1780
+ steps.push(() => false);
1781
+ } else {
1782
+ steps.push(typeof command === "string" ? host.resolve(command) : command);
1783
+ }
1784
+ return chain;
1785
+ },
1786
+ insertContent(html) {
1787
+ steps.push(host.insertContent(html));
1788
+ return chain;
1789
+ },
1790
+ run: () => attempt(true),
1791
+ can: () => attempt(false)
1792
+ };
1793
+ return chain;
1794
+ }
1795
+
1796
+ // src/selection.ts
1797
+ import { AllSelection as AllSelection2, NodeSelection, Plugin as Plugin6, PluginKey as PluginKey4, TextSelection as TextSelection2 } from "prosemirror-state";
1798
+ var MAX_BOOKMARKS = 200;
1799
+ var bookmarksKey = new PluginKey4("nova-bookmarks");
1800
+ function bookmarksPlugin() {
1801
+ return new Plugin6({
1802
+ key: bookmarksKey,
1803
+ state: {
1804
+ init: () => /* @__PURE__ */ new Map(),
1805
+ apply(tr, kept2) {
1806
+ const added = tr.getMeta(bookmarksKey);
1807
+ if (added) return added;
1808
+ if (!tr.docChanged || !kept2.size) return kept2;
1809
+ const next = /* @__PURE__ */ new Map();
1810
+ for (const [id, mark] of kept2) {
1811
+ const start = tr.mapping.mapResult(mark.from, 1);
1812
+ const end = tr.mapping.mapResult(mark.to, -1);
1813
+ next.set(id, {
1814
+ from: start.pos,
1815
+ to: Math.max(start.pos, end.pos),
1816
+ // A selected text that was deleted as a whole is gone; a cursor always has a place.
1817
+ gone: mark.gone || mark.from !== mark.to && start.pos >= end.pos
1818
+ });
1819
+ }
1820
+ return next;
1821
+ }
1822
+ }
1823
+ });
1824
+ }
1825
+ var nextBookmark = 1;
1826
+ function createSelection(editor) {
1827
+ const view = () => editor.view;
1828
+ const clamp = (pos) => {
1829
+ const size = view().state.doc.content.size;
1830
+ const n = typeof pos === "number" && Number.isFinite(pos) ? Math.round(pos) : 0;
1831
+ return Math.max(0, Math.min(n, size));
1832
+ };
1833
+ const inEditor = (node) => node instanceof Node && node !== view().dom && view().dom.contains(node);
1834
+ const api = {
1835
+ getRange() {
1836
+ const { from, to } = view().state.selection;
1837
+ return { from, to };
1838
+ },
1839
+ setRange(from, to = from) {
1840
+ const { state, dispatch } = view();
1841
+ const selection = TextSelection2.between(
1842
+ state.doc.resolve(clamp(from)),
1843
+ state.doc.resolve(clamp(to))
1844
+ );
1845
+ dispatch(state.tr.setSelection(selection));
1846
+ },
1847
+ isCollapsed: () => view().state.selection.empty,
1848
+ collapse(toStart = false) {
1849
+ const { from, to } = view().state.selection;
1850
+ api.setRange(toStart ? from : to);
1851
+ },
1852
+ selectAll() {
1853
+ const { state, dispatch } = view();
1854
+ dispatch(state.tr.setSelection(new AllSelection2(state.doc)));
1855
+ },
1856
+ getHTML() {
1857
+ const { selection } = view().state;
1858
+ return selection.empty ? "" : htmlSerializer.serializeFragment(selection.content().content);
1859
+ },
1860
+ getText() {
1861
+ const { state } = view();
1862
+ return state.doc.textBetween(state.selection.from, state.selection.to, "\n");
1863
+ },
1864
+ setHTML: (html) => editor.insertContent(html),
1865
+ getNode() {
1866
+ const v = view();
1867
+ const { selection } = v.state;
1868
+ if (selection instanceof NodeSelection) {
1869
+ const dom = v.nodeDOM(selection.from);
1870
+ if (dom instanceof HTMLElement) return dom;
1871
+ }
1872
+ const elementAt = (pos, side) => {
1873
+ const { node } = v.domAtPos(pos, side);
1874
+ return node instanceof HTMLElement ? node : node.parentElement;
1875
+ };
1876
+ let el = elementAt(selection.from, selection.empty ? 0 : 1);
1877
+ if (!selection.empty) {
1878
+ const end = elementAt(selection.to, -1);
1879
+ while (el && end && !el.contains(end)) el = el.parentElement;
1880
+ }
1881
+ return el && v.dom.contains(el) ? el : null;
1882
+ },
1883
+ select(node, content = false) {
1884
+ if (!inEditor(node)) return;
1885
+ const v = view();
1886
+ const { doc } = v.state;
1887
+ const pos = v.posAtDOM(node, 0);
1888
+ for (const at of [pos - 1, pos]) {
1889
+ if (at < 0 || at >= doc.content.size) continue;
1890
+ const found = doc.nodeAt(at);
1891
+ if (!found || found.isText) continue;
1892
+ const dom = v.nodeDOM(at);
1893
+ if (dom !== node && !(found.isLeaf && dom instanceof Node && dom.contains(node))) continue;
1894
+ if (found.isLeaf || !content && NodeSelection.isSelectable(found))
1895
+ v.dispatch(v.state.tr.setSelection(NodeSelection.create(doc, at)));
1896
+ else api.setRange(at + 1, at + found.nodeSize - 1);
1897
+ return;
1898
+ }
1899
+ api.setRange(pos, v.posAtDOM(node, node.childNodes.length));
1900
+ },
1901
+ setCursorLocation(node, offset = 0) {
1902
+ if (!inEditor(node)) return;
1903
+ const max = node.nodeType === 3 ? node.length : node.childNodes.length;
1904
+ api.setRange(view().posAtDOM(node, Math.max(0, Math.min(offset, max))));
1905
+ },
1906
+ getDOMRange() {
1907
+ const v = view();
1908
+ if (!v.dom.isConnected) return null;
1909
+ const { from, to } = v.state.selection;
1910
+ try {
1911
+ const start = v.domAtPos(from);
1912
+ const end = v.domAtPos(to);
1913
+ const range = document.createRange();
1914
+ range.setStart(start.node, start.offset);
1915
+ range.setEnd(end.node, end.offset);
1916
+ return range;
1917
+ } catch {
1918
+ return null;
1919
+ }
1920
+ },
1921
+ getRect() {
1922
+ const v = view();
1923
+ if (!v.dom.isConnected) return null;
1924
+ const { from, to, empty } = v.state.selection;
1925
+ try {
1926
+ if (!empty) {
1927
+ const rect = api.getDOMRange()?.getBoundingClientRect?.();
1928
+ if (rect && (rect.width || rect.height)) return rect;
1929
+ }
1930
+ const a = v.coordsAtPos(from);
1931
+ const b = empty ? a : v.coordsAtPos(to);
1932
+ const left = Math.min(a.left, b.left);
1933
+ const top = Math.min(a.top, b.top);
1934
+ return new DOMRect(
1935
+ left,
1936
+ top,
1937
+ Math.max(a.right, b.right) - left,
1938
+ Math.max(a.bottom, b.bottom) - top
1939
+ );
1940
+ } catch {
1941
+ return null;
1942
+ }
1943
+ },
1944
+ getBookmark() {
1945
+ const v = view();
1946
+ const id = nextBookmark++;
1947
+ if (v.isDestroyed) return { id };
1948
+ const kept2 = new Map(bookmarksKey.getState(v.state));
1949
+ while (kept2.size >= MAX_BOOKMARKS) kept2.delete(kept2.keys().next().value);
1950
+ const { from, to } = v.state.selection;
1951
+ kept2.set(id, { from, to, gone: false });
1952
+ v.dispatch(v.state.tr.setMeta(bookmarksKey, kept2).setMeta("addToHistory", false));
1953
+ return { id };
1954
+ },
1955
+ moveToBookmark(bookmark) {
1956
+ const v = view();
1957
+ const id = bookmark?.id;
1958
+ const mark = typeof id === "number" ? bookmarksKey.getState(v.state)?.get(id) : void 0;
1959
+ if (!mark || mark.gone) return false;
1960
+ api.setRange(mark.from, mark.to);
1961
+ return true;
1962
+ },
1963
+ scrollIntoView() {
1964
+ const { state, dispatch } = view();
1965
+ dispatch(state.tr.scrollIntoView());
1966
+ }
1967
+ };
1968
+ return api;
1969
+ }
1970
+
1971
+ // src/ui/context-toolbar.ts
1972
+ import { NodeSelection as NodeSelection2, Plugin as Plugin7, PluginKey as PluginKey5 } from "prosemirror-state";
1973
+ function contextToolbarPlugin(editor) {
1974
+ return new Plugin7({
1975
+ key: new PluginKey5("nova-context-toolbar"),
1976
+ view(view) {
1977
+ const container = h("div", {
1978
+ className: "nova-bubble nova-context-toolbar",
1979
+ role: "toolbar",
1980
+ hidden: true
1981
+ });
1982
+ editor.ui.overlayHost.append(container);
1983
+ const cache = /* @__PURE__ */ new Map();
1984
+ let current = null;
1985
+ const render = (name, spec) => {
1986
+ let rendered = cache.get(name);
1987
+ if (rendered) return rendered;
1988
+ const el = h("div", { className: "nova-context-items" });
1989
+ const controls = [];
1990
+ parseToolbar(spec.items).forEach((group, index) => {
1991
+ if (index > 0) el.append(h("span", { className: "nova-bubble-sep", role: "separator" }));
1992
+ for (const item of group) {
1993
+ if (!editor.isAllowed(item)) continue;
1994
+ const control = editor.ui.registry.get(item);
1995
+ if (!control) continue;
1996
+ const r = renderControl(editor, item, control);
1997
+ controls.push(r);
1998
+ el.append(r.el);
1999
+ }
2000
+ });
2001
+ rendered = { el, controls };
2002
+ cache.set(name, rendered);
2003
+ return rendered;
2004
+ };
2005
+ const hide = () => {
2006
+ container.hidden = true;
2007
+ current = null;
2008
+ };
2009
+ const anchorRect = (spec) => {
2010
+ const { selection } = view.state;
2011
+ if ((spec.position ?? "node") === "node" && selection instanceof NodeSelection2) {
2012
+ const dom = view.nodeDOM(selection.from);
2013
+ return dom?.getBoundingClientRect() ?? null;
2014
+ }
2015
+ const start = view.coordsAtPos(selection.from);
2016
+ const end = view.coordsAtPos(selection.to);
2017
+ return new DOMRect(
2018
+ start.left,
2019
+ start.top,
2020
+ Math.max(1, end.right - start.left),
2021
+ end.bottom - start.top
2022
+ );
2023
+ };
2024
+ let dragging = false;
2025
+ const onPointerDown = (event) => {
2026
+ if (event.pointerType === "mouse" && event.button === 0) dragging = true;
2027
+ };
2028
+ const onPointerUp = () => {
2029
+ if (!dragging) return;
2030
+ dragging = false;
2031
+ setTimeout(() => update(view), 0);
2032
+ };
2033
+ view.dom.addEventListener("pointerdown", onPointerDown);
2034
+ const stopPointerUp = listenDocument(container, "pointerup", onPointerUp);
2035
+ const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
2036
+ const dock = () => {
2037
+ const area = visibleArea();
2038
+ container.style.left = `${Math.round(area.left)}px`;
2039
+ container.style.width = `${Math.round(area.right - area.left)}px`;
2040
+ container.style.top = `${Math.round(area.bottom - container.offsetHeight)}px`;
2041
+ container.dataset.side = "docked";
2042
+ };
2043
+ const update = (v) => {
2044
+ const focused = v.hasFocus() || container.contains(activeElement(container));
2045
+ if (!focused || !editor.isEditable() || editor.ui.activeDialog || dragging) return hide();
2046
+ const match = editor.ui.registry.getContextToolbars().find(([, spec2]) => spec2.predicate(editor));
2047
+ if (!match) return hide();
2048
+ const [name, spec] = match;
2049
+ const rendered = render(name, spec);
2050
+ if (current !== name) {
2051
+ container.replaceChildren(rendered.el);
2052
+ container.setAttribute("aria-label", spec.label);
2053
+ current = name;
2054
+ }
2055
+ for (const control of rendered.controls) control.update();
2056
+ const rect = spec.anchor ? spec.anchor(editor) : anchorRect(spec);
2057
+ if (!rect) return hide();
2058
+ container.hidden = false;
2059
+ const docked = coarse && spec.position === "selection";
2060
+ container.classList.toggle("nova-context-toolbar-docked", docked);
2061
+ if (docked) return dock();
2062
+ container.style.width = "";
2063
+ const placement = (typeof spec.placement === "function" ? spec.placement(editor) : spec.placement) ?? (spec.position === "selection" ? "bottom-start" : "top-start");
2064
+ positionFloating(container, rect, placement);
2065
+ };
2066
+ container.addEventListener("mousedown", (event) => {
2067
+ if (event.target.closest("button")) event.preventDefault();
2068
+ });
2069
+ container.addEventListener("keydown", (event) => {
2070
+ const buttons = [...container.querySelectorAll("button:not(:disabled)")];
2071
+ const index = buttons.indexOf(activeElement(container));
2072
+ if (event.key === "Escape") {
2073
+ event.preventDefault();
2074
+ editor.focus();
2075
+ } else if (index >= 0 && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
2076
+ event.preventDefault();
2077
+ const step = logicalKey(event, container) === "ArrowRight" ? 1 : -1;
2078
+ buttons[(index + step + buttons.length) % buttons.length].focus();
2079
+ }
2080
+ });
2081
+ const onBlur = (event) => {
2082
+ const next = event.relatedTarget;
2083
+ if (!container.contains(next) && !editor.ui.overlayHost.contains(next)) hide();
2084
+ };
2085
+ view.dom.addEventListener("blur", onBlur);
2086
+ container.addEventListener("focusout", (event) => {
2087
+ const next = event.relatedTarget;
2088
+ if (!container.contains(next) && !view.hasFocus() && !editor.ui.overlayHost.contains(next))
2089
+ hide();
2090
+ });
2091
+ const reposition = () => {
2092
+ if (!container.hidden) update(view);
2093
+ };
2094
+ window.addEventListener("scroll", reposition, true);
2095
+ window.addEventListener("resize", reposition);
2096
+ view.dom.addEventListener("load", reposition, true);
2097
+ window.visualViewport?.addEventListener("resize", reposition);
2098
+ window.visualViewport?.addEventListener("scroll", reposition);
2099
+ return {
2100
+ update,
2101
+ destroy() {
2102
+ view.dom.removeEventListener("blur", onBlur);
2103
+ view.dom.removeEventListener("pointerdown", onPointerDown);
2104
+ stopPointerUp();
2105
+ window.removeEventListener("scroll", reposition, true);
2106
+ window.removeEventListener("resize", reposition);
2107
+ view.dom.removeEventListener("load", reposition, true);
2108
+ window.visualViewport?.removeEventListener("resize", reposition);
2109
+ window.visualViewport?.removeEventListener("scroll", reposition);
2110
+ container.remove();
2111
+ }
2112
+ };
2113
+ }
2114
+ });
2115
+ }
2116
+ function focusContextToolbar(editor) {
2117
+ const button = editor.ui.overlayHost.querySelector(
2118
+ ".nova-context-toolbar:not([hidden]) button:not(:disabled)"
2119
+ );
2120
+ button?.focus();
2121
+ return !!button;
2122
+ }
2123
+
2124
+ // src/ui/image-view.ts
2125
+ import { NodeSelection as NodeSelection3 } from "prosemirror-state";
2126
+ var MIN_WIDTH2 = 24;
2127
+ var ImageView = class {
2128
+ constructor(node, view, getPos, editor) {
2129
+ this.view = view;
2130
+ this.getPos = getPos;
2131
+ this.editor = editor;
2132
+ this.node = node;
2133
+ this.dom = document.createElement("span");
2134
+ this.dom.className = "nova-image";
2135
+ this.img = document.createElement("img");
2136
+ this.img.draggable = false;
2137
+ this.dom.append(this.img);
2138
+ for (const corner of ["nw", "ne", "sw", "se"]) {
2139
+ const handle = document.createElement("span");
2140
+ handle.className = `nova-image-handle nova-image-handle-${corner}`;
2141
+ handle.dataset.corner = corner;
2142
+ handle.addEventListener("pointerdown", (event) => this.startResize(event, corner));
2143
+ this.dom.append(handle);
2144
+ }
2145
+ this.render();
2146
+ }
2147
+ view;
2148
+ getPos;
2149
+ editor;
2150
+ dom;
2151
+ img;
2152
+ node;
2153
+ resizing = false;
2154
+ render() {
2155
+ const { src, alt, title, width, height, align } = this.node.attrs;
2156
+ const safeSrc = isSafeImageUrl(src) ? src : "";
2157
+ if (this.img.getAttribute("src") !== safeSrc) this.img.setAttribute("src", safeSrc);
2158
+ this.setAttr("alt", alt);
2159
+ this.setAttr("title", title);
2160
+ this.setAttr("class", classAttr(this.node.attrs.class).class ?? null);
2161
+ const w = imageSize(width);
2162
+ const h2 = imageSize(height);
2163
+ this.img.style.width = w ? `${w}px` : "";
2164
+ this.img.style.aspectRatio = w && h2 ? `${w} / ${h2}` : "";
2165
+ this.dom.dataset.align = align ?? "";
2166
+ }
2167
+ setAttr(name, value) {
2168
+ if (value) this.img.setAttribute(name, value);
2169
+ else this.img.removeAttribute(name);
2170
+ }
2171
+ update(node) {
2172
+ if (node.type !== this.node.type) return false;
2173
+ this.node = node;
2174
+ if (!this.resizing) this.render();
2175
+ return true;
2176
+ }
2177
+ selectNode() {
2178
+ this.dom.classList.add("is-selected");
2179
+ }
2180
+ deselectNode() {
2181
+ this.dom.classList.remove("is-selected");
2182
+ }
2183
+ /** The handles are ours; ProseMirror must not handle events on them. */
2184
+ stopEvent(event) {
2185
+ return event.target.classList?.contains("nova-image-handle") ?? false;
2186
+ }
2187
+ ignoreMutation() {
2188
+ return true;
2189
+ }
2190
+ startResize(event, corner) {
2191
+ if (!this.editor.isEditable()) return;
2192
+ event.preventDefault();
2193
+ event.stopPropagation();
2194
+ const handle = event.currentTarget;
2195
+ handle.setPointerCapture(event.pointerId);
2196
+ const rect = this.img.getBoundingClientRect();
2197
+ const startX = event.clientX;
2198
+ const startWidth = rect.width;
2199
+ const ratio = rect.width > 0 ? rect.height / rect.width : this.img.naturalHeight / (this.img.naturalWidth || 1);
2200
+ const maxWidth = Math.max(MIN_WIDTH2, this.view.dom.clientWidth - 40);
2201
+ const direction = corner === "ne" || corner === "se" ? 1 : -1;
2202
+ let width = startWidth;
2203
+ this.resizing = true;
2204
+ this.dom.classList.add("is-resizing");
2205
+ const onMove = (e) => {
2206
+ width = Math.round(
2207
+ Math.min(maxWidth, Math.max(MIN_WIDTH2, startWidth + direction * (e.clientX - startX)))
2208
+ );
2209
+ this.img.style.width = `${width}px`;
2210
+ this.dom.dataset.size = `${width} \xD7 ${Math.round(width * ratio)}`;
2211
+ };
2212
+ const onUp = () => {
2213
+ handle.removeEventListener("pointermove", onMove);
2214
+ handle.removeEventListener("pointerup", onUp);
2215
+ handle.removeEventListener("pointercancel", onUp);
2216
+ this.resizing = false;
2217
+ this.dom.classList.remove("is-resizing");
2218
+ delete this.dom.dataset.size;
2219
+ const pos = this.getPos();
2220
+ if (pos === void 0 || Math.abs(width - startWidth) < 1) return this.render();
2221
+ const tr = this.view.state.tr.setNodeMarkup(pos, void 0, {
2222
+ ...this.node.attrs,
2223
+ width,
2224
+ height: Math.round(width * ratio)
2225
+ });
2226
+ tr.setSelection(NodeSelection3.create(tr.doc, pos));
2227
+ this.view.dispatch(tr);
2228
+ };
2229
+ handle.addEventListener("pointermove", onMove);
2230
+ handle.addEventListener("pointerup", onUp);
2231
+ handle.addEventListener("pointercancel", onUp);
2232
+ }
2233
+ };
2234
+
2235
+ // src/ui/autocompleter.ts
2236
+ import { Plugin as Plugin8, PluginKey as PluginKey6 } from "prosemirror-state";
2237
+ var MAX_QUERY = 30;
2238
+ function escapeRegExp(value) {
2239
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2240
+ }
2241
+ function findMatch(view, editor) {
2242
+ const { selection } = view.state;
2243
+ if (!selection.empty) return null;
2244
+ const $pos = selection.$from;
2245
+ if (!$pos.parent.isTextblock || $pos.parent.type.spec.code) return null;
2246
+ const before = $pos.parent.textBetween(
2247
+ Math.max(0, $pos.parentOffset - MAX_QUERY - 1),
2248
+ $pos.parentOffset,
2249
+ "\0",
2250
+ "\0"
2251
+ );
2252
+ for (const [name, spec] of editor.ui.registry.getAutocompleters()) {
2253
+ const re = new RegExp(`(?:^|\\s)${escapeRegExp(spec.trigger)}([\\p{L}\\p{N}_-]*)$`, "u");
2254
+ const m = before.match(re);
2255
+ if (!m) continue;
2256
+ const query = m[1] ?? "";
2257
+ if (query.length < (spec.minChars ?? 0)) continue;
2258
+ const start = $pos.parentOffset - query.length - spec.trigger.length;
2259
+ const prevChar = start > 0 ? $pos.parent.textBetween(start - 1, start, "\0", "\0") : "";
2260
+ if (prevChar && !/\s/.test(prevChar)) continue;
2261
+ return { name, spec, from: $pos.pos - query.length - spec.trigger.length, to: $pos.pos, query };
2262
+ }
2263
+ return null;
2264
+ }
2265
+ function autocompleterPlugin(editor) {
2266
+ let list;
2267
+ let items = [];
2268
+ let active = 0;
2269
+ let match = null;
2270
+ let dismissedAt = null;
2271
+ let requestId = 0;
2272
+ const listId = uniqueId("nova-ac");
2273
+ const isOpen = () => !list.hidden;
2274
+ const close = (view) => {
2275
+ list.hidden = true;
2276
+ match = null;
2277
+ items = [];
2278
+ view.dom.removeAttribute("aria-activedescendant");
2279
+ view.dom.removeAttribute("aria-controls");
2280
+ view.dom.removeAttribute("aria-expanded");
2281
+ };
2282
+ const select = (view, index) => {
2283
+ const item = items[index];
2284
+ if (!item || !match) return;
2285
+ const { spec, from, to } = match;
2286
+ close(view);
2287
+ spec.onSelect(item, { from, to }, editor);
2288
+ };
2289
+ const renderItems = (view) => {
2290
+ if (!match) return;
2291
+ const { spec } = match;
2292
+ list.replaceChildren();
2293
+ list.setAttribute("aria-label", spec.label);
2294
+ if (!items.length) {
2295
+ if (!spec.emptyText) return close(view);
2296
+ list.append(h("div", { className: "nova-ac-empty" }, spec.emptyText));
2297
+ }
2298
+ items.forEach((item, index) => {
2299
+ const option = h(
2300
+ "div",
2301
+ {
2302
+ id: `${listId}-${index}`,
2303
+ className: "nova-menu-item nova-ac-item",
2304
+ role: "option",
2305
+ "aria-selected": String(index === active)
2306
+ },
2307
+ item.icon ? icon(item.icon) : null,
2308
+ h("span", { className: "nova-menu-label" }, item.label),
2309
+ item.shortcut ? h("kbd", { className: "nova-menu-shortcut" }, formatShortcut(item.shortcut)) : item.detail ? h("span", { className: "nova-menu-shortcut" }, item.detail) : null
2310
+ );
2311
+ option.addEventListener("mousedown", (event) => {
2312
+ event.preventDefault();
2313
+ select(view, index);
2314
+ });
2315
+ option.addEventListener("mousemove", () => {
2316
+ if (active !== index) setActive(view, index);
2317
+ });
2318
+ list.append(option);
2319
+ });
2320
+ list.hidden = false;
2321
+ view.dom.setAttribute("aria-controls", listId);
2322
+ setActive(view, Math.min(active, Math.max(0, items.length - 1)));
2323
+ const coords = view.coordsAtPos(match.from);
2324
+ positionFloating(
2325
+ list,
2326
+ new DOMRect(coords.left, coords.top, 1, coords.bottom - coords.top),
2327
+ "bottom-start"
2328
+ );
2329
+ };
2330
+ const setActive = (view, index) => {
2331
+ active = index;
2332
+ list.querySelectorAll('[role="option"]').forEach((el, i) => el.setAttribute("aria-selected", String(i === index)));
2333
+ const current = list.querySelector(`#${listId}-${index}`);
2334
+ if (current) {
2335
+ view.dom.setAttribute("aria-activedescendant", current.id);
2336
+ current.scrollIntoView?.({ block: "nearest" });
2337
+ }
2338
+ };
2339
+ const refresh = (view) => {
2340
+ const next = editor.isEditable() && view.hasFocus() ? findMatch(view, editor) : null;
2341
+ if (!next || next.from === dismissedAt) {
2342
+ if (!next) dismissedAt = null;
2343
+ if (isOpen() || match) close(view);
2344
+ return;
2345
+ }
2346
+ const changed = !match || match.query !== next.query || match.from !== next.from;
2347
+ match = next;
2348
+ if (!changed && isOpen()) return renderItems(view);
2349
+ const id = ++requestId;
2350
+ void Promise.resolve(next.spec.fetch(next.query, editor)).then((result) => {
2351
+ if (id !== requestId || !match) return;
2352
+ items = result.slice(0, next.spec.maxResults ?? 10);
2353
+ active = 0;
2354
+ renderItems(view);
2355
+ });
2356
+ };
2357
+ return new Plugin8({
2358
+ key: new PluginKey6("nova-autocompleter"),
2359
+ view(view) {
2360
+ list = h("div", {
2361
+ className: "nova-popover nova-ac",
2362
+ id: listId,
2363
+ role: "listbox",
2364
+ hidden: true
2365
+ });
2366
+ editor.ui.overlayHost.append(list);
2367
+ view.dom.setAttribute("aria-autocomplete", "list");
2368
+ const onBlur = () => close(view);
2369
+ view.dom.addEventListener("blur", onBlur);
2370
+ return {
2371
+ update: (v) => refresh(v),
2372
+ destroy() {
2373
+ view.dom.removeEventListener("blur", onBlur);
2374
+ list.remove();
2375
+ }
2376
+ };
2377
+ },
2378
+ props: {
2379
+ handleKeyDown(view, event) {
2380
+ if (!isOpen() || !match) return false;
2381
+ const count = items.length;
2382
+ switch (event.key) {
2383
+ case "ArrowDown":
2384
+ if (count) setActive(view, (active + 1) % count);
2385
+ return true;
2386
+ case "ArrowUp":
2387
+ if (count) setActive(view, (active - 1 + count) % count);
2388
+ return true;
2389
+ case "Enter":
2390
+ case "Tab":
2391
+ if (!count) return false;
2392
+ select(view, active);
2393
+ return true;
2394
+ case "Escape":
2395
+ dismissedAt = match.from;
2396
+ close(view);
2397
+ return true;
2398
+ default:
2399
+ return false;
2400
+ }
2401
+ }
2402
+ }
2403
+ });
2404
+ }
2405
+
2406
+ // src/ui/notification.ts
2407
+ var Notifications = class {
2408
+ region;
2409
+ closeLabel;
2410
+ constructor(host, closeLabel) {
2411
+ this.closeLabel = closeLabel;
2412
+ this.region = h("div", { className: "nova-notifications", "aria-live": "polite" });
2413
+ host.append(this.region);
2414
+ }
2415
+ open(options) {
2416
+ const type = options.type ?? "info";
2417
+ const timeout = options.timeout ?? (type === "error" ? 0 : 4e3);
2418
+ const text = h("span", { className: "nova-notification-text" }, options.text);
2419
+ const closeBtn = h(
2420
+ "button",
2421
+ { type: "button", className: "nova-btn", "aria-label": this.closeLabel },
2422
+ icon(icons.close)
2423
+ );
2424
+ const actions = (options.actions ?? []).map(
2425
+ (action) => h("button", { type: "button", className: "nova-btn nova-notification-action" }, action.label)
2426
+ );
2427
+ const el = h(
2428
+ "div",
2429
+ {
2430
+ className: `nova-notification nova-notification-${type}`,
2431
+ role: type === "error" ? "alert" : "status"
2432
+ },
2433
+ text,
2434
+ ...actions,
2435
+ closeBtn
2436
+ );
2437
+ this.region.append(el);
2438
+ let timer = null;
2439
+ let closed = false;
2440
+ const close = () => {
2441
+ if (closed) return;
2442
+ closed = true;
2443
+ if (timer) clearTimeout(timer);
2444
+ el.remove();
2445
+ };
2446
+ const dismiss = () => {
2447
+ if (closed) return;
2448
+ close();
2449
+ options.onClose?.();
2450
+ };
2451
+ actions.forEach(
2452
+ (button, i) => button.addEventListener("click", () => {
2453
+ close();
2454
+ options.actions[i].onAction();
2455
+ })
2456
+ );
2457
+ closeBtn.addEventListener("click", dismiss);
2458
+ if (timeout > 0) timer = setTimeout(dismiss, timeout);
2459
+ actions[0]?.focus({ preventScroll: true });
2460
+ return { close, setText: (value) => text.textContent = value };
2461
+ }
2462
+ destroy() {
2463
+ this.region.remove();
2464
+ }
2465
+ };
2466
+
2467
+ // src/ui/registry.ts
2468
+ var sidebarIcon = icons.sidebar;
2469
+ var Registry = class {
2470
+ controls = /* @__PURE__ */ new Map();
2471
+ addButton(name, spec) {
2472
+ this.controls.set(name.toLowerCase(), { type: "button", ...spec });
2473
+ }
2474
+ /** A synonym of addButton with isActive, for the familiar API. */
2475
+ addToggleButton(name, spec) {
2476
+ this.addButton(name, spec);
2477
+ }
2478
+ addMenuButton(name, spec) {
2479
+ this.controls.set(name.toLowerCase(), { type: "menu", ...spec });
2480
+ }
2481
+ addPanelButton(name, spec) {
2482
+ this.controls.set(name.toLowerCase(), { type: "panel", ...spec });
2483
+ }
2484
+ addSplitButton(name, spec) {
2485
+ this.controls.set(name.toLowerCase(), { type: "split", ...spec });
2486
+ }
2487
+ menuItems = /* @__PURE__ */ new Map();
2488
+ styleFormats = { items: [], replace: false };
2489
+ /**
2490
+ * Items for the Styles menu from a plugin (importcss): after the menu's own items, or instead of
2491
+ * them (`replace`).
2492
+ */
2493
+ addStyleFormats(items, { replace = false } = {}) {
2494
+ this.styleFormats = {
2495
+ items: [...this.styleFormats.items, ...items],
2496
+ replace: this.styleFormats.replace || replace
2497
+ };
2498
+ }
2499
+ /** What plugins added to the Styles menu. */
2500
+ getStyleFormats() {
2501
+ return this.styleFormats;
2502
+ }
2503
+ /** A menu bar item (like addMenuItem). */
2504
+ addMenuItem(name, spec) {
2505
+ this.menuItems.set(name.toLowerCase(), spec);
2506
+ }
2507
+ /** A toggle item (with a check mark). */
2508
+ addToggleMenuItem(name, spec) {
2509
+ this.addMenuItem(name, spec);
2510
+ }
2511
+ /**
2512
+ * A menu item by name. If there is no separate item, it is built from the toolbar button of the
2513
+ * same name (label = tooltip), so each feature isn't defined twice.
2514
+ */
2515
+ getMenuItem(name) {
2516
+ const own2 = this.menuItems.get(name.toLowerCase());
2517
+ if (own2) return own2;
2518
+ const control = this.get(name);
2519
+ if (control?.type !== "button" && control?.type !== "split") return void 0;
2520
+ return {
2521
+ text: control.tooltip,
2522
+ ...control.icon ? { icon: control.icon } : {},
2523
+ ...control.shortcut ? { shortcut: control.shortcut } : {},
2524
+ onAction: control.onAction,
2525
+ ...control.isActive ? { isActive: control.isActive } : {},
2526
+ ...control.isEnabled ? { isEnabled: control.isEnabled } : {}
2527
+ };
2528
+ }
2529
+ contextToolbars = /* @__PURE__ */ new Map();
2530
+ autocompleters = /* @__PURE__ */ new Map();
2531
+ /** An autocompleter on a trigger character: '/' — commands, '@' — mentions, ':' — emoji. */
2532
+ sidebars = /* @__PURE__ */ new Map();
2533
+ /**
2534
+ * A sidebar (shown with editor.ui.sidebar). If the name is free, a toggle button with that name is
2535
+ * added for the toolbar and menus too (`button: false` — without it).
2536
+ */
2537
+ addSidebar(name, spec) {
2538
+ this.sidebars.set(name, spec);
2539
+ if (spec.button === false || this.has(name)) return;
2540
+ this.addToggleButton(name, {
2541
+ tooltip: spec.tooltip ?? spec.title,
2542
+ icon: spec.icon ?? sidebarIcon,
2543
+ isActive: (editor) => editor.ui.sidebar.isOpen(name),
2544
+ onAction: (editor) => void editor.ui.sidebar.toggle(name)
2545
+ });
2546
+ }
2547
+ getSidebar(name) {
2548
+ return this.sidebars.get(name);
2549
+ }
2550
+ views = /* @__PURE__ */ new Map();
2551
+ /** A view: a plugin's screen in place of the editor (shown with editor.ui.view). */
2552
+ addView(name, spec) {
2553
+ this.views.set(name, spec);
2554
+ }
2555
+ getView(name) {
2556
+ return this.views.get(name);
2557
+ }
2558
+ addAutocompleter(name, spec) {
2559
+ this.autocompleters.set(name.toLowerCase(), spec);
2560
+ }
2561
+ getAutocompleters() {
2562
+ return [...this.autocompleters];
2563
+ }
2564
+ addContextToolbar(name, spec) {
2565
+ this.contextToolbars.set(name.toLowerCase(), spec);
2566
+ }
2567
+ /** By descending priority; equal ones in registration order (the sort is stable). */
2568
+ getContextToolbars() {
2569
+ return [...this.contextToolbars].sort((a, b) => (b[1].priority ?? 0) - (a[1].priority ?? 0));
2570
+ }
2571
+ get(name) {
2572
+ return this.controls.get(name.toLowerCase());
2573
+ }
2574
+ has(name) {
2575
+ return this.controls.has(name.toLowerCase());
2576
+ }
2577
+ names() {
2578
+ return [...this.controls.keys()];
2579
+ }
2580
+ };
2581
+
2582
+ // src/ui/sidebar.ts
2583
+ var Sidebars = class {
2584
+ constructor(editor) {
2585
+ this.editor = editor;
2586
+ }
2587
+ editor;
2588
+ current = null;
2589
+ mounted = /* @__PURE__ */ new Map();
2590
+ column = null;
2591
+ opening = Promise.resolve();
2592
+ destroyed = false;
2593
+ /** Name of the open sidebar, or null. */
2594
+ get active() {
2595
+ return this.current;
2596
+ }
2597
+ isOpen(name) {
2598
+ return this.current === name;
2599
+ }
2600
+ /**
2601
+ * Show a sidebar (another open one closes). `focus` — move focus into the sidebar (for example,
2602
+ * when it was opened from the keyboard, to work with it right away).
2603
+ */
2604
+ async show(name, options = {}) {
2605
+ const spec = this.editor.ui.registry.getSidebar(name);
2606
+ if (!spec) {
2607
+ console.warn(`[nova] sidebar "${name}" is not registered`);
2608
+ return;
2609
+ }
2610
+ if (this.current !== name) {
2611
+ this.hide({ restoreFocus: false });
2612
+ this.editor.ui.closeOverlays();
2613
+ this.current = name;
2614
+ const mounted = this.mount(name, spec);
2615
+ this.opening = mounted.ready.then((ok) => {
2616
+ if (!ok || this.current !== name || this.destroyed) {
2617
+ if (this.current === name) this.current = null;
2618
+ return;
2619
+ }
2620
+ mounted.el.hidden = false;
2621
+ this.editor.root.classList.add("nova-sidebar-open");
2622
+ spec.onShow?.(this.editor);
2623
+ this.editor.updateUI();
2624
+ });
2625
+ }
2626
+ await this.opening;
2627
+ if (options.focus && this.current === name) {
2628
+ const el = this.mounted.get(name).el;
2629
+ (el.querySelector(FOCUSABLE) ?? el).focus();
2630
+ }
2631
+ }
2632
+ /** Close the open sidebar. Focus returns from it to the text. */
2633
+ hide(options = {}) {
2634
+ const name = this.current;
2635
+ if (!name) return;
2636
+ this.current = null;
2637
+ const mounted = this.mounted.get(name);
2638
+ if (!mounted) return;
2639
+ const hadFocus = mounted.el.contains(activeElement(mounted.el));
2640
+ mounted.el.hidden = true;
2641
+ this.editor.root.classList.remove("nova-sidebar-open");
2642
+ this.editor.ui.registry.getSidebar(name)?.onHide?.(this.editor);
2643
+ this.editor.updateUI();
2644
+ if (hadFocus && options.restoreFocus !== false) this.editor.focus();
2645
+ }
2646
+ toggle(name, options = {}) {
2647
+ if (this.current === name) {
2648
+ this.hide();
2649
+ return Promise.resolve();
2650
+ }
2651
+ return this.show(name, options);
2652
+ }
2653
+ destroy() {
2654
+ this.destroyed = true;
2655
+ this.mounted.forEach((mounted) => mounted.cleanup?.());
2656
+ this.mounted.clear();
2657
+ }
2658
+ /** The "text + sidebar" column: created with the first sidebar; without sidebars the markup doesn't change. */
2659
+ host() {
2660
+ if (this.column) return this.column;
2661
+ const content = this.editor.view.dom.parentElement;
2662
+ const column = h("div", { className: "nova-body" });
2663
+ content.before(column);
2664
+ column.append(content);
2665
+ this.column = column;
2666
+ return column;
2667
+ }
2668
+ mount(name, spec) {
2669
+ const existing = this.mounted.get(name);
2670
+ if (existing) return existing;
2671
+ const titleId = uniqueId("nova-sidebar-title");
2672
+ const body = h("div", { className: "nova-sidebar-body" });
2673
+ const close = h(
2674
+ "button",
2675
+ {
2676
+ type: "button",
2677
+ className: "nova-btn nova-sidebar-close",
2678
+ "aria-label": this.editor.ui.t("dialog.close"),
2679
+ onClick: () => this.hide()
2680
+ },
2681
+ icon(icons.close)
2682
+ );
2683
+ const header = spec.header === false ? null : h(
2684
+ "div",
2685
+ { className: "nova-sidebar-head" },
2686
+ h("h2", { id: titleId, className: "nova-sidebar-title" }, spec.title),
2687
+ close
2688
+ );
2689
+ const el = h(
2690
+ "div",
2691
+ {
2692
+ className: `nova-sidebar${header ? "" : " nova-sidebar-bare"}`,
2693
+ hidden: true,
2694
+ "data-sidebar": name,
2695
+ ...this.editor.options.language ? { lang: this.editor.options.language } : {},
2696
+ ...header ? { role: "complementary", "aria-labelledby": titleId } : {},
2697
+ onKeydown: ((event) => {
2698
+ if (event.key !== "Escape" || event.defaultPrevented) return;
2699
+ event.preventDefault();
2700
+ this.hide();
2701
+ })
2702
+ },
2703
+ header,
2704
+ body
2705
+ );
2706
+ this.host().append(el);
2707
+ const mounted = { el, ready: Promise.resolve(false) };
2708
+ mounted.ready = (async () => {
2709
+ try {
2710
+ const cleanup = await spec.render(body, this.editor);
2711
+ if (typeof cleanup === "function") mounted.cleanup = cleanup;
2712
+ return true;
2713
+ } catch (error) {
2714
+ console.error(`[nova] sidebar "${name}" failed to render`, error);
2715
+ el.remove();
2716
+ this.mounted.delete(name);
2717
+ return false;
2718
+ }
2719
+ })();
2720
+ this.mounted.set(name, mounted);
2721
+ return mounted;
2722
+ }
2723
+ };
2724
+
2725
+ // nova-raw-css:/home/runner/work/novaprose/novaprose/packages/core/src/ui/editor-views.css?raw
2726
+ var editor_views_default = ".nova-editor.nova-view-open>:not(.nova-view):not(.nova-overlays){display:none}.nova-view{display:flex;flex:1 1 auto;flex-direction:column;min-height:240px;background:var(--nova-surface);color:var(--nova-fg)}.nova-view[hidden]{display:none}.nova-view:focus{outline:none}.nova-view-head{display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid var(--nova-border);background:var(--nova-toolbar-bg)}.nova-view-title{margin:0;font-size:15px;font-weight:600}.nova-view-buttons{display:flex;gap:8px;margin-inline-start:auto}.nova-view-body{flex:1;min-height:0;padding:12px;overflow:auto}";
2727
+
2728
+ // src/ui/editor-views.ts
2729
+ var Views = class {
2730
+ constructor(editor) {
2731
+ this.editor = editor;
2732
+ }
2733
+ editor;
2734
+ current = null;
2735
+ mounted = /* @__PURE__ */ new Map();
2736
+ /** The name of the open view, or null. */
2737
+ get active() {
2738
+ return this.current;
2739
+ }
2740
+ isOpen(name) {
2741
+ return this.current === name;
2742
+ }
2743
+ show(name) {
2744
+ const spec = this.editor.ui.registry.getView(name);
2745
+ if (!spec) {
2746
+ console.warn(`[nova] view "${name}" is not registered`);
2747
+ return;
2748
+ }
2749
+ if (this.current === name) return;
2750
+ this.hide({ restoreFocus: false });
2751
+ this.editor.ui.closeOverlays();
2752
+ this.editor.ui.addStyles("nova-editor-views", editor_views_default);
2753
+ const mounted = this.mount(name, spec);
2754
+ this.current = name;
2755
+ mounted.el.hidden = false;
2756
+ this.editor.root.classList.add("nova-view-open");
2757
+ try {
2758
+ spec.onShow?.(mounted.api);
2759
+ } catch (error) {
2760
+ console.error(`[nova] view "${name}" failed to show`, error);
2761
+ }
2762
+ (mounted.el.querySelector(FOCUSABLE) ?? mounted.el).focus();
2763
+ this.editor.updateUI();
2764
+ }
2765
+ /** Close the open view: the editor comes back, and focus returns to the text. */
2766
+ hide(options = {}) {
2767
+ const name = this.current;
2768
+ if (!name) return;
2769
+ this.current = null;
2770
+ const mounted = this.mounted.get(name);
2771
+ if (!mounted) return;
2772
+ const hadFocus = mounted.el.contains(activeElement(mounted.el));
2773
+ mounted.el.hidden = true;
2774
+ this.editor.root.classList.remove("nova-view-open");
2775
+ try {
2776
+ this.editor.ui.registry.getView(name)?.onHide?.(mounted.api);
2777
+ } catch (error) {
2778
+ console.error(`[nova] view "${name}" failed to hide`, error);
2779
+ }
2780
+ this.editor.updateUI();
2781
+ if (hadFocus && options.restoreFocus !== false) this.editor.focus();
2782
+ }
2783
+ toggle(name) {
2784
+ if (this.current === name) this.hide();
2785
+ else this.show(name);
2786
+ }
2787
+ destroy() {
2788
+ this.mounted.forEach(({ el }) => el.remove());
2789
+ this.mounted.clear();
2790
+ this.current = null;
2791
+ }
2792
+ mount(name, spec) {
2793
+ const existing = this.mounted.get(name);
2794
+ if (existing) return existing;
2795
+ const body = h("div", { className: "nova-view-body" });
2796
+ const buttons = (spec.buttons ?? []).map(
2797
+ (button) => h(
2798
+ "button",
2799
+ {
2800
+ type: "button",
2801
+ className: button.buttonType === "primary" ? "nova-button nova-button-primary" : "nova-button",
2802
+ onClick: () => {
2803
+ try {
2804
+ button.onAction(this.editor);
2805
+ } catch (error) {
2806
+ console.error(`[nova] a button of view "${name}" failed`, error);
2807
+ }
2808
+ }
2809
+ },
2810
+ button.text
2811
+ )
2812
+ );
2813
+ const el = h(
2814
+ "section",
2815
+ {
2816
+ className: "nova-view",
2817
+ hidden: true,
2818
+ tabindex: "-1",
2819
+ "data-view": name,
2820
+ "aria-label": spec.title ?? name,
2821
+ ...this.editor.options.language ? { lang: this.editor.options.language } : {},
2822
+ onKeydown: ((event) => {
2823
+ if (event.key !== "Escape" || event.defaultPrevented) return;
2824
+ event.preventDefault();
2825
+ this.hide();
2826
+ })
2827
+ },
2828
+ h(
2829
+ "div",
2830
+ { className: "nova-view-head" },
2831
+ spec.title ? h("h2", { className: "nova-view-title" }, spec.title) : null,
2832
+ h("div", { className: "nova-view-buttons" }, ...buttons)
2833
+ ),
2834
+ body
2835
+ );
2836
+ this.editor.root.append(el);
2837
+ const mounted = { el, api: { getContainer: () => body } };
2838
+ this.mounted.set(name, mounted);
2839
+ return mounted;
2840
+ }
2841
+ };
2842
+
2843
+ // src/ui/tooltip.ts
2844
+ var SHOW_DELAY = 450;
2845
+ var HIDE_DELAY = 150;
2846
+ var Tooltip = class {
2847
+ el;
2848
+ timer = null;
2849
+ target = null;
2850
+ offEscape = null;
2851
+ constructor(host) {
2852
+ this.el = h("div", { className: "nova-tooltip", role: "tooltip", hidden: true });
2853
+ this.el.addEventListener("pointerenter", () => this.clearTimer());
2854
+ this.el.addEventListener("pointerleave", () => this.hide());
2855
+ this.el.addEventListener("pointerdown", () => this.hide());
2856
+ host.append(this.el);
2857
+ }
2858
+ /** Attach the tooltip to an element. The text comes from data-tooltip and data-shortcut. */
2859
+ attach(target) {
2860
+ target.addEventListener("pointerenter", (e) => {
2861
+ if (e.pointerType === "mouse") this.schedule(target);
2862
+ });
2863
+ target.addEventListener("pointerleave", () => {
2864
+ this.clearTimer();
2865
+ if (!this.el.hidden) this.timer = setTimeout(() => this.hide(), HIDE_DELAY);
2866
+ });
2867
+ target.addEventListener("focus", () => {
2868
+ if (target.matches(":focus-visible")) this.show(target);
2869
+ });
2870
+ target.addEventListener("blur", () => this.hide());
2871
+ target.addEventListener("pointerdown", () => this.hide());
2872
+ }
2873
+ schedule(target) {
2874
+ this.clearTimer();
2875
+ this.timer = setTimeout(() => this.show(target), SHOW_DELAY);
2876
+ }
2877
+ show(target) {
2878
+ this.clearTimer();
2879
+ const text = target.dataset.tooltip;
2880
+ if (!text || target.getAttribute("aria-expanded") === "true") return;
2881
+ this.target = target;
2882
+ const shortcut = target.dataset.shortcut;
2883
+ this.el.replaceChildren(h("span", {}, text));
2884
+ if (shortcut) this.el.append(h("kbd", {}, formatShortcut(shortcut)));
2885
+ this.el.hidden = false;
2886
+ positionFloating(this.el, target.getBoundingClientRect(), "bottom");
2887
+ this.offEscape ??= listenDocument(this.el, "keydown", (event) => {
2888
+ if (event.key !== "Escape" || this.el.hidden) return;
2889
+ event.preventDefault();
2890
+ event.stopPropagation();
2891
+ this.hide();
2892
+ });
2893
+ }
2894
+ hide() {
2895
+ this.clearTimer();
2896
+ this.el.hidden = true;
2897
+ this.target = null;
2898
+ this.offEscape?.();
2899
+ this.offEscape = null;
2900
+ }
2901
+ get current() {
2902
+ return this.target;
2903
+ }
2904
+ destroy() {
2905
+ this.hide();
2906
+ this.el.remove();
2907
+ }
2908
+ clearTimer() {
2909
+ if (this.timer) clearTimeout(this.timer);
2910
+ this.timer = null;
2911
+ }
2912
+ };
2913
+
2914
+ // src/ui/manager.ts
2915
+ var addedStyles = /* @__PURE__ */ new WeakMap();
2916
+ var UiManager = class {
2917
+ constructor(root, t, focusEditor, editor) {
2918
+ this.focusEditor = focusEditor;
2919
+ this.t = t;
2920
+ this.rootEl = root;
2921
+ this.overlayHost = h("div", { className: "nova-overlays" });
2922
+ root.append(this.overlayHost);
2923
+ this.tooltip = new Tooltip(this.overlayHost);
2924
+ this.notifications = new Notifications(root, t("dialog.close"));
2925
+ this.sidebar = new Sidebars(editor);
2926
+ this.view = new Views(editor);
2927
+ this.liveRegion = h("div", {
2928
+ className: "nova-visually-hidden nova-announcer",
2929
+ role: "status",
2930
+ "aria-live": "polite",
2931
+ "aria-atomic": "true"
2932
+ });
2933
+ root.append(this.liveRegion);
2934
+ }
2935
+ focusEditor;
2936
+ registry = new Registry();
2937
+ t;
2938
+ /** The layer for all floating elements. It sits inside .nova-editor, so it inherits the theme. */
2939
+ overlayHost;
2940
+ tooltip;
2941
+ /** Plugin sidebars: show / hide / toggle (register them with registry.addSidebar). */
2942
+ sidebar;
2943
+ /** Plugin views in place of the editor: show / hide / toggle (register them with registry.addView). */
2944
+ view;
2945
+ notifications;
2946
+ popover = null;
2947
+ currentDialog = null;
2948
+ /** The hidden polite live region for announce(); it exists from the start, so screen readers watch it. */
2949
+ liveRegion;
2950
+ announceTimer;
2951
+ rootEl;
2952
+ /**
2953
+ * Say a short message to screen readers without moving focus: what a shortcut or a typed Markdown
2954
+ * shortcut changed ("Bold on", "Bulleted list"). Plugins can use it for their own changes.
2955
+ */
2956
+ announce(message) {
2957
+ const region = this.liveRegion;
2958
+ region.textContent = "";
2959
+ clearTimeout(this.announceTimer);
2960
+ this.announceTimer = setTimeout(() => {
2961
+ region.textContent = message;
2962
+ }, 50);
2963
+ }
2964
+ /**
2965
+ * Add a plugin's styles to the editor's document (or shadow root) — once per page, however many
2966
+ * editors there are. For panels and dialogs that load lazily: their styles don't belong in the
2967
+ * first-load style.css. Constructed style sheets don't need 'unsafe-inline' in your CSP; where they
2968
+ * aren't supported, a plain <style> is used. Override such styles with a selector at least as specific.
2969
+ */
2970
+ addStyles(id, css) {
2971
+ const root = this.rootEl.getRootNode();
2972
+ let ids = addedStyles.get(root);
2973
+ if (!ids) addedStyles.set(root, ids = /* @__PURE__ */ new Set());
2974
+ if (ids.has(id)) return;
2975
+ ids.add(id);
2976
+ if ("adoptedStyleSheets" in root && typeof CSSStyleSheet !== "undefined") {
2977
+ try {
2978
+ const sheet = new CSSStyleSheet();
2979
+ sheet.replaceSync(css);
2980
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
2981
+ return;
2982
+ } catch {
2983
+ }
2984
+ }
2985
+ const style = document.createElement("style");
2986
+ style.dataset.novaStyles = id;
2987
+ style.textContent = css;
2988
+ (root.head ?? root).append(style);
2989
+ }
2990
+ /**
2991
+ * A dialog described by its fields (for plugins): validation, errors at the fields, accessibility.
2992
+ * Returns the data, or null if the dialog was closed. The implementation loads when first opened.
2993
+ */
2994
+ async dialog(spec) {
2995
+ const { openFormDialog, formDialogCss } = await import("./form-dialog-SNWFPM2K.js");
2996
+ this.addStyles("nova-form-dialog", formDialogCss);
2997
+ return openFormDialog(spec, this.t, (options) => this.openDialog(options));
2998
+ }
2999
+ /** Open a popover; only one is open at a time (except the toolbar overflow panel). */
3000
+ openPopover(options) {
3001
+ this.closePopover();
3002
+ this.tooltip.hide();
3003
+ const popover = new Popover({
3004
+ ...options,
3005
+ host: this.overlayHost,
3006
+ onClose: (reason) => {
3007
+ if (this.popover === popover) this.popover = null;
3008
+ options.onClose?.(reason);
3009
+ }
3010
+ });
3011
+ this.popover = popover;
3012
+ return popover;
3013
+ }
3014
+ closePopover() {
3015
+ this.popover?.close("api");
3016
+ this.popover = null;
3017
+ }
3018
+ get activePopover() {
3019
+ return this.popover;
3020
+ }
3021
+ dialogListeners = /* @__PURE__ */ new Set();
3022
+ /**
3023
+ * Subscribe to a dialog opening (returns an unsubscribe function). The toolbar uses it to close
3024
+ * its "⋯" panel, which on a narrow screen otherwise stayed over the text after a dialog opened from it closed.
3025
+ */
3026
+ onDialogOpen(listener) {
3027
+ this.dialogListeners.add(listener);
3028
+ return () => this.dialogListeners.delete(listener);
3029
+ }
3030
+ /**
3031
+ * Close floating panels and the toolbar's "⋯" before a plugin opens its own panel or view (version
3032
+ * history, comments), so they don't stay on top.
3033
+ */
3034
+ closeOverlays() {
3035
+ this.closePopover();
3036
+ this.dialogListeners.forEach((listener) => listener());
3037
+ }
3038
+ openDialog(options) {
3039
+ this.closePopover();
3040
+ this.dialogListeners.forEach((listener) => listener());
3041
+ this.currentDialog?.close();
3042
+ const handle = openDialog({
3043
+ cancelLabel: this.t("dialog.cancel"),
3044
+ closeLabel: this.t("dialog.close"),
3045
+ ...options,
3046
+ host: this.overlayHost,
3047
+ returnFocus: this.focusEditor,
3048
+ onClose: () => {
3049
+ if (this.currentDialog === handle) this.currentDialog = null;
3050
+ options.onClose?.();
3051
+ }
3052
+ });
3053
+ this.currentDialog = handle;
3054
+ return handle;
3055
+ }
3056
+ get activeDialog() {
3057
+ return this.currentDialog;
3058
+ }
3059
+ notify(options) {
3060
+ return this.notifications.open(typeof options === "string" ? { text: options } : options);
3061
+ }
3062
+ destroy() {
3063
+ this.sidebar.destroy();
3064
+ this.view.destroy();
3065
+ this.closePopover();
3066
+ this.currentDialog?.close();
3067
+ this.tooltip.destroy();
3068
+ this.notifications.destroy();
3069
+ this.overlayHost.remove();
3070
+ clearTimeout(this.announceTimer);
3071
+ this.liveRegion.remove();
3072
+ }
3073
+ };
3074
+
3075
+ // src/editor.ts
3076
+ var REMOTE_CHANGE_META = "nova:remote";
3077
+ var API_CHANGE_META = "nova:api";
3078
+ var INSERT_BLOCK_TAGS = new Set(
3079
+ "P H1 H2 H3 H4 H5 H6 UL OL TABLE BLOCKQUOTE PRE HR DIV FIGURE".split(" ")
3080
+ );
3081
+ function insertContentCommand(html) {
3082
+ return (state, dispatch) => {
3083
+ if (!dispatch) return true;
3084
+ const template = document.createElement("template");
3085
+ template.innerHTML = html;
3086
+ const container = document.createElement("div");
3087
+ container.append(template.content);
3088
+ const parser = parserFor(state.schema);
3089
+ const hasBlocks = [...container.children].some((el) => INSERT_BLOCK_TAGS.has(el.tagName));
3090
+ const slice = hasBlocks ? new Slice2(parser.parse(container).content, 0, 0) : parser.parseSlice(container);
3091
+ let hasTable = false;
3092
+ slice.content.descendants((node) => {
3093
+ if (node.type.spec.tableRole === "table") hasTable = true;
3094
+ return !hasTable;
3095
+ });
3096
+ const { $from } = state.selection;
3097
+ let tableDepth = 0;
3098
+ for (let depth = 1; depth <= $from.depth; depth++) {
3099
+ if ($from.node(depth).type.spec.tableRole === "table") {
3100
+ tableDepth = depth;
3101
+ break;
3102
+ }
3103
+ }
3104
+ const tr = hasTable && tableDepth ? state.tr.insert($from.after(tableDepth), slice.content) : state.tr.replaceSelection(slice);
3105
+ dispatch(tr.setMeta(API_CHANGE_META, true).scrollIntoView());
3106
+ return true;
3107
+ };
3108
+ }
3109
+ var contentScopeId = 0;
3110
+ var unknownCommands = /* @__PURE__ */ new Set();
3111
+ var Editor = class {
3112
+ view;
3113
+ root;
3114
+ ui;
3115
+ options;
3116
+ listeners = /* @__PURE__ */ new Map();
3117
+ /** Resolves when all lazy plugins are loaded and set up. */
3118
+ ready;
3119
+ toolbar;
3120
+ toolbarHost;
3121
+ menubar;
3122
+ mode;
3123
+ /** The editor's writing direction (the direction option, the language or the page's dir). */
3124
+ direction;
3125
+ pluginsByName = /* @__PURE__ */ new Map();
3126
+ commandOverrides = /* @__PURE__ */ new Map();
3127
+ transactionTransforms = [];
3128
+ cleanups = [];
3129
+ /** Content restrictions (validElements/invalidElements/validStyles), or null when there are none. */
3130
+ contentRules;
3131
+ /** This editor's document schema: the built-in one plus nodes and marks of plugins. */
3132
+ schema;
3133
+ /** Formats: register / apply / remove / toggle / match. */
3134
+ formatter;
3135
+ /** The selection: its HTML and text, its range and place on screen, moving it, bookmarks. */
3136
+ selection;
3137
+ statusbar;
3138
+ /** The find and replace bar: a lazy part, there once editor.ready resolves (see loadSearchBar). */
3139
+ searchBar = null;
3140
+ searchBarLoad = null;
3141
+ contentHost;
3142
+ destroyed = false;
3143
+ editable;
3144
+ disabled;
3145
+ pasteAsText;
3146
+ constructor(options) {
3147
+ options = renameOptions(options);
3148
+ this.options = options;
3149
+ this.root = document.createElement("div");
3150
+ this.root.className = "nova-editor";
3151
+ const direction = options.direction ?? (isRtlLanguage(options.language) ? "rtl" : void 0);
3152
+ if (direction) this.root.dir = direction;
3153
+ this.direction = direction ?? (options.element.closest("[dir]")?.getAttribute("dir") === "rtl" ? "rtl" : "ltr");
3154
+ options.element.appendChild(this.root);
3155
+ const toolbarHost = document.createElement("div");
3156
+ const contentHost = document.createElement("div");
3157
+ const statusbarHost = document.createElement("div");
3158
+ contentHost.className = "nova-content";
3159
+ const header = document.createElement("div");
3160
+ header.className = "nova-header";
3161
+ const menubarHost = document.createElement("div");
3162
+ header.append(menubarHost, toolbarHost);
3163
+ this.root.append(header, contentHost, statusbarHost);
3164
+ this.toolbarHost = toolbarHost;
3165
+ const stickyOffset = Number(options.toolbarStickyOffset);
3166
+ if (Number.isFinite(stickyOffset) && stickyOffset > 0)
3167
+ this.root.style.setProperty("--nova-sticky-offset", `${Math.min(stickyOffset, 1e3)}px`);
3168
+ this.mode = options.mode ?? "classic";
3169
+ this.root.classList.add(`nova-mode-${this.mode}`);
3170
+ const distractionFree = this.mode === "distraction-free";
3171
+ if (this.mode !== "classic") {
3172
+ this.root.addEventListener("focusin", () => this.root.classList.add("is-focused"));
3173
+ this.root.addEventListener("focusout", () => {
3174
+ setTimeout(() => {
3175
+ if (!this.root.contains(activeElement(this.root)))
3176
+ this.root.classList.remove("is-focused");
3177
+ }, 0);
3178
+ });
3179
+ }
3180
+ this.ui = new UiManager(
3181
+ this.root,
3182
+ createTranslator(options.language, options.translations),
3183
+ () => this.focus(),
3184
+ this
3185
+ );
3186
+ if (options.language) {
3187
+ for (const part of [header, statusbarHost, this.ui.overlayHost]) part.lang = options.language;
3188
+ }
3189
+ this.root.style.setProperty(
3190
+ "--nova-caption-placeholder",
3191
+ JSON.stringify(this.ui.t("image.captionPlaceholder"))
3192
+ );
3193
+ const editorKeys = keymap3({
3194
+ "Mod-k": () => (openLinkDialog(this), true),
3195
+ // The standard accessibility shortcut: move from the text to the toolbar.
3196
+ "Alt-F9": () => {
3197
+ if (!this.menubar) return false;
3198
+ this.menubar.focus();
3199
+ return true;
3200
+ },
3201
+ "Alt-F10": () => {
3202
+ if (!this.toolbar) return false;
3203
+ this.toolbar.focus();
3204
+ return true;
3205
+ },
3206
+ // Move to the context toolbar (image, table).
3207
+ "Ctrl-F9": () => focusContextToolbar(this),
3208
+ "Mod-f": () => (this.openSearch(), true),
3209
+ "Mod-Shift-f": () => (toggleFullscreen(this), true),
3210
+ "Alt-0": () => (openHelp(this), true),
3211
+ // Escape in the text closes the search bar if it is open.
3212
+ Escape: () => {
3213
+ if (!this.searchBar?.isOpen()) return false;
3214
+ this.searchBar.close();
3215
+ return true;
3216
+ }
3217
+ });
3218
+ const pluginEntries = [...options.plugins ?? []];
3219
+ if (distractionFree && !pluginEntries.includes("quickbars")) pluginEntries.push("quickbars");
3220
+ const resolved = resolveEntries(pluginEntries);
3221
+ resolved.errors.forEach((message) => reportPluginError(message));
3222
+ const { ordered: syncPlugins, errors: orderErrors } = orderPlugins(resolved.plugins);
3223
+ orderErrors.forEach((message) => reportPluginError(message));
3224
+ for (const plugin of syncPlugins) if (plugin.load) resolved.loaders.push(plugin.load);
3225
+ const pluginPm = syncPlugins.flatMap((plugin) => this.collectPmPlugins(plugin));
3226
+ const hasRules = options.validElements !== void 0 || options.invalidElements !== void 0 || options.validStyles !== void 0;
3227
+ this.contentRules = hasRules ? new ContentRules(options) : null;
3228
+ const { schema: schema2, allowedClasses } = schemaFromOptions(
3229
+ options,
3230
+ syncPlugins,
3231
+ this.direction,
3232
+ this
3233
+ );
3234
+ this.schema = schema2;
3235
+ this.formatter = new Formatter(this, allowedClasses);
3236
+ this.selection = createSelection(this);
3237
+ for (const [name, spec] of Object.entries(options.formats ?? {}))
3238
+ this.formatter.register(name, spec);
3239
+ syncPlugins.forEach((plugin) => this.registerCommands(plugin));
3240
+ const page = pageHandlerOf(syncPlugins, this);
3241
+ if (page) pages.set(this, page);
3242
+ const initialDoc = parseContent(this.schema, options.content ?? "", page);
3243
+ const tablesAnchor = searchPlugin();
3244
+ const sticky = stickyHeader(header, contentHost);
3245
+ const initialPlugins = [
3246
+ // First: while the list is open, Enter/Tab/arrows belong to the autocompleter, not the keymap.
3247
+ autocompleterPlugin(this),
3248
+ ...options.textPatterns === false ? [] : Array.isArray(options.textPatterns) || options.textPatternsLookup ? [
3249
+ textPatternsPlugin(
3250
+ this,
3251
+ Array.isArray(options.textPatterns) ? options.textPatterns : [],
3252
+ options.textPatternsLookup
3253
+ )
3254
+ ] : [
3255
+ buildInputRules((name) => this.isAllowed(name), this.schema),
3256
+ codeFenceKeymap((name) => this.isAllowed(name), this.schema)
3257
+ ],
3258
+ editorKeys,
3259
+ // The table plugins go here (before the general keymap) once the mechanics load: Tab in a table is
3260
+ // the next cell, not a list indent. See installTables().
3261
+ tablesAnchor,
3262
+ ...buildKeymap((name) => this.resolveCommand(name)),
3263
+ // Screen readers hear what a formatting shortcut or a typed Markdown shortcut changed.
3264
+ announcePlugin(this.ui.t, (text) => this.ui.announce(text)),
3265
+ ...syncPlugins.some((plugin) => plugin.replaceHistory) ? [] : [history()],
3266
+ dropCursor({ color: "var(--nova-accent)", width: 2 }),
3267
+ gapCursor(),
3268
+ imageDropPastePlugin(this),
3269
+ embeddedImageUploadPlugin(this),
3270
+ pastePlugin(this),
3271
+ linkBubblePlugin(this),
3272
+ contextToolbarPlugin(this),
3273
+ ...this.contentRules ? [contentRulesPlugin(this.contentRules)] : [],
3274
+ // After plugins with their own clicks (link, panels): the first click without focus lands where you clicked.
3275
+ firstClickPlugin(),
3276
+ // editor.selection's bookmarks move along with the changes.
3277
+ bookmarksPlugin(),
3278
+ // The line with the caret is never left under the sticky header.
3279
+ sticky.plugin,
3280
+ ...pluginPm,
3281
+ ...options.prosemirrorPlugins ?? []
3282
+ ];
3283
+ keepPluginViews(initialPlugins);
3284
+ const state = EditorState.create({
3285
+ doc: this.contentRules ? this.contentRules.normalizeDoc(initialDoc) : initialDoc,
3286
+ plugins: initialPlugins
3287
+ });
3288
+ this.editable = options.editable ?? true;
3289
+ this.disabled = options.disabled ?? false;
3290
+ this.pasteAsText = options.pasteAsText ?? false;
3291
+ const handleTransaction = this.handleTransaction.bind(this);
3292
+ const contentLanguage = languageTag(options.contentLanguage);
3293
+ this.view = new EditorView(contentHost, {
3294
+ state,
3295
+ editable: () => this.isEditable(),
3296
+ ...sticky.props,
3297
+ attributes: {
3298
+ class: "nova-prosemirror",
3299
+ role: "textbox",
3300
+ "aria-multiline": "true",
3301
+ "aria-label": this.ui.t("editor.label"),
3302
+ ...contentLanguage ? { lang: contentLanguage } : {},
3303
+ // The visible placeholder is CSS generated content with empty alternative text (style.css);
3304
+ // screen readers get it as aria-placeholder, not as text inside the document.
3305
+ ...options.placeholder ? { "data-placeholder": options.placeholder, "aria-placeholder": options.placeholder } : {}
3306
+ },
3307
+ // ProseMirror calls dispatchTransaction with this = the view: plugins (collaboration sync,
3308
+ // for example) may dispatch a transaction while still inside the EditorView constructor,
3309
+ // when the editor's this.view isn't assigned yet.
3310
+ dispatchTransaction: function(tr) {
3311
+ handleTransaction(tr, this);
3312
+ },
3313
+ // The same parser for paste as for setContent: the same preprocessing.
3314
+ clipboardParser: parserFor(this.schema),
3315
+ nodeViews: {
3316
+ image: (node, view, getPos) => new ImageView(node, view, getPos, this)
3317
+ },
3318
+ // Bold, italic and the like stay part of the line's text for screen readers (mark-views.ts).
3319
+ markViews: flatMarkViews(this.schema),
3320
+ handleDOMEvents: {
3321
+ focus: (_view, event) => (this.emit("focus", { event }), false),
3322
+ blur: (_view, event) => (this.emit("blur", { event }), false)
3323
+ },
3324
+ handleKeyDown: (_view, event) => {
3325
+ this.emit("keydown", { event });
3326
+ return event.defaultPrevented;
3327
+ }
3328
+ });
3329
+ this.root.classList.toggle("nova-readonly", !this.editable);
3330
+ this.applyDisabled();
3331
+ registerBuiltins(this);
3332
+ registerMenuItems(this);
3333
+ if (options.slashCommands !== false) registerSlashCommands(this, options.slashCommands ?? []);
3334
+ syncPlugins.forEach((plugin) => this.setupPlugin(plugin));
3335
+ options.setup?.(this);
3336
+ const menubarConfig = options.menubar === true ? DEFAULT_MENUBAR : typeof options.menubar === "string" ? options.menubar : null;
3337
+ this.menubar = menubarConfig ? createMenubar(this, menubarHost, menubarConfig, { ...DEFAULT_MENUS, ...options.menu }) : null;
3338
+ if (!this.menubar) menubarHost.remove();
3339
+ this.toolbar = options.toolbar === false || distractionFree && options.toolbar === void 0 ? null : createToolbar(
3340
+ this,
3341
+ toolbarHost,
3342
+ this.toolbarConfig(),
3343
+ options.toolbarMode ?? "floating",
3344
+ // Until lazy plugins load, their buttons aren't registered yet, so no warning.
3345
+ { warnUnknown: resolved.loaders.length === 0 }
3346
+ );
3347
+ if (!this.toolbar) toolbarHost.remove();
3348
+ if (!this.toolbar && !this.menubar) header.remove();
3349
+ this.contentHost = contentHost;
3350
+ const searchBar = this.loadSearchBar();
3351
+ const statusbar = options.statusbar ?? this.mode === "classic";
3352
+ this.statusbar = statusbar ? createStatusbar(this, statusbarHost) : null;
3353
+ if (!this.statusbar) statusbarHost.remove();
3354
+ if (options.onChange) this.on("change", options.onChange);
3355
+ this.updatePlaceholder();
3356
+ const contentCss = this.applyContentStyles();
3357
+ this.ready = Promise.all([
3358
+ resolved.loaders.length ? this.loadLazyPlugins(resolved.loaders) : void 0,
3359
+ contentCss,
3360
+ // Office paste cleanup is a separate chunk, loaded in the background (see paste.ts).
3361
+ loadPasteCleaner(),
3362
+ // Table mechanics are a separate chunk (~10 KB gzip), loaded in the background (see tables.ts).
3363
+ this.installTables(tablesAnchor),
3364
+ searchBar
3365
+ ]).then(() => {
3366
+ if (!this.destroyed) this.emit("init");
3367
+ });
3368
+ }
3369
+ /**
3370
+ * Install table editing (cell selection, column widths, Tab between cells) once it has loaded, at
3371
+ * its place before `anchor`, as if the plugins had been there from the start.
3372
+ */
3373
+ async installTables(anchor) {
3374
+ const tables = await loadTables();
3375
+ if (!tables || this.destroyed) return;
3376
+ const { state } = this.view;
3377
+ const at = state.plugins.indexOf(anchor);
3378
+ const plugins = [...state.plugins];
3379
+ plugins.splice(at < 0 ? plugins.length : at, 0, ...tables.tablePlugins());
3380
+ reconfigurePlugins(this.view, plugins);
3381
+ this.updateUI();
3382
+ }
3383
+ /** contentStyle right away, contentCss as it loads. Each editor gets its own scope. */
3384
+ applyContentStyles() {
3385
+ const { contentStyle, contentCss } = this.options;
3386
+ const files = contentCss === void 0 ? [] : Array.isArray(contentCss) ? contentCss : [contentCss];
3387
+ if (!contentStyle && !files.length) return void 0;
3388
+ const id = `nova-cs-${++contentScopeId}`;
3389
+ this.root.classList.add(id);
3390
+ const scope = `.nova-editor.${id} .nova-prosemirror`;
3391
+ const sheets = files.map(() => "");
3392
+ let detach = null;
3393
+ const apply = () => {
3394
+ if (this.destroyed) return;
3395
+ detach?.();
3396
+ detach = attachCss(this.root, scopeCss([...sheets, contentStyle ?? ""].join("\n"), scope));
3397
+ };
3398
+ this.cleanups.push(() => detach?.());
3399
+ apply();
3400
+ if (!files.length) return void 0;
3401
+ return Promise.all(
3402
+ files.map(
3403
+ (url, index) => loadCss(url).then(
3404
+ (css) => {
3405
+ sheets[index] = css;
3406
+ },
3407
+ (error) => console.warn(`[nova] contentCss: could not load ${url}`, error)
3408
+ )
3409
+ )
3410
+ ).then(apply);
3411
+ }
3412
+ // ---------- plugins ----------
3413
+ /** Whether content restrictions allow a control, command or tag (always true without restrictions). */
3414
+ isAllowed(name) {
3415
+ return this.contentRules?.isAllowed(name) ?? true;
3416
+ }
3417
+ hasPlugin(name) {
3418
+ return this.pluginsByName.has(name);
3419
+ }
3420
+ collectPmPlugins(plugin) {
3421
+ try {
3422
+ const pm = plugin.prosemirrorPlugins?.(this) ?? [];
3423
+ if (plugin.nodeViews) {
3424
+ const nodeViews = Object.fromEntries(
3425
+ Object.entries(plugin.nodeViews).map(([name, factory]) => [name, factory(this)])
3426
+ );
3427
+ pm.push(new Plugin9({ props: { nodeViews } }));
3428
+ }
3429
+ return pm;
3430
+ } catch (error) {
3431
+ reportPluginError(`Plugin "${plugin.name}" failed to create ProseMirror plugins`, error);
3432
+ return [];
3433
+ }
3434
+ }
3435
+ /** setup with errors isolated: a failing plugin doesn't break the editor. */
3436
+ setupPlugin(plugin) {
3437
+ try {
3438
+ const cleanup = plugin.setup?.(this);
3439
+ if (typeof cleanup === "function") this.cleanups.push(cleanup);
3440
+ this.pluginsByName.set(plugin.name, plugin);
3441
+ } catch (error) {
3442
+ reportPluginError(`Plugin "${plugin.name}" failed during setup`, error);
3443
+ }
3444
+ }
3445
+ async loadLazyPlugins(loaders) {
3446
+ const results = await Promise.all(
3447
+ loaders.map(
3448
+ (loader) => loadPlugin(loader).catch((error) => {
3449
+ reportPluginError("Failed to load plugin", error);
3450
+ return null;
3451
+ })
3452
+ )
3453
+ );
3454
+ if (this.destroyed) return;
3455
+ const loaded = results.filter((p) => {
3456
+ if (!p) return false;
3457
+ if (p.nodes || p.marks) {
3458
+ reportPluginError(
3459
+ `Plugin "${p.name}" defines nodes or marks and cannot be loaded lazily; pass the plugin object instead`
3460
+ );
3461
+ return false;
3462
+ }
3463
+ return true;
3464
+ });
3465
+ const { ordered, errors } = orderPlugins(loaded, new Set(this.pluginsByName.keys()));
3466
+ errors.forEach((message) => reportPluginError(message));
3467
+ const extraPm = ordered.flatMap((plugin) => this.collectPmPlugins(plugin));
3468
+ if (extraPm.length) {
3469
+ reconfigurePlugins(this.view, [...this.view.state.plugins, ...extraPm]);
3470
+ }
3471
+ ordered.forEach((plugin) => {
3472
+ this.registerCommands(plugin);
3473
+ this.setupPlugin(plugin);
3474
+ });
3475
+ this.rebuildToolbar();
3476
+ }
3477
+ /**
3478
+ * Refresh the button state (pressed / enabled) without changing the document — for example, after a
3479
+ * plugin switched a display mode. Document changes refresh the UI by themselves.
3480
+ */
3481
+ updateUI() {
3482
+ if (this.destroyed) return;
3483
+ this.toolbar?.update();
3484
+ }
3485
+ /** Rebuild the toolbar (after plugins registered new buttons). */
3486
+ rebuildToolbar() {
3487
+ if (!this.toolbar || this.destroyed) return;
3488
+ this.toolbar.destroy();
3489
+ this.toolbar = createToolbar(
3490
+ this,
3491
+ this.toolbarHost,
3492
+ this.toolbarConfig(),
3493
+ this.options.toolbarMode ?? "floating"
3494
+ );
3495
+ }
3496
+ /** Toolbar configuration: yours as it is; the default one plus the buttons of active plugins. */
3497
+ toolbarConfig() {
3498
+ if (this.options.toolbar) return this.options.toolbar;
3499
+ const extra = [...this.pluginsByName.values()].map((p) => p.toolbar).filter(Boolean);
3500
+ return extra.length ? `${defaultToolbar} | ${extra.join(" ")}` : defaultToolbar;
3501
+ }
3502
+ handleTransaction(tr, view = this.view) {
3503
+ if (view.isDestroyed) return;
3504
+ for (const transform of this.transactionTransforms) tr = transform(tr, view.state, this);
3505
+ view.updateState(view.state.apply(tr));
3506
+ if (!this.view) return;
3507
+ this.toolbar?.update();
3508
+ this.statusbar?.update(tr.docChanged);
3509
+ this.searchBar?.update();
3510
+ this.updatePlaceholder();
3511
+ if (tr.docChanged) {
3512
+ this.emit("change", { transaction: tr });
3513
+ const programmatic = tr.getMeta(API_CHANGE_META) || tr.getMeta(REMOTE_CHANGE_META);
3514
+ if (!programmatic && tr.getMeta("addToHistory") !== false) {
3515
+ this.emit("input", { transaction: tr });
3516
+ }
3517
+ }
3518
+ if (tr.selectionSet || tr.docChanged) this.emit("selectionChange", { transaction: tr });
3519
+ }
3520
+ updatePlaceholder() {
3521
+ const doc = this.view.state.doc;
3522
+ const empty = doc.childCount === 1 && doc.firstChild?.type === this.schema.nodes.paragraph && doc.firstChild.content.size === 0;
3523
+ this.view.dom.classList.toggle("nova-empty", empty);
3524
+ }
3525
+ // ---------- content ----------
3526
+ /**
3527
+ * The document's HTML. Deterministic: the same in every browser and in Node. With the fullpagehtml
3528
+ * plugin it is the whole page (doctype, head, body); `fullPage: false` gives only the content.
3529
+ */
3530
+ getHTML({ fullPage = true } = {}) {
3531
+ const doc = this.view.state.doc;
3532
+ const content = htmlSerializer.serializeFragment(doc.content);
3533
+ const page = fullPage ? pages.get(this) : void 0;
3534
+ return page ? page.write(content, doc.attrs) : content;
3535
+ }
3536
+ getJSON() {
3537
+ return this.view.state.doc.toJSON();
3538
+ }
3539
+ getText() {
3540
+ return this.view.state.doc.textBetween(0, this.view.state.doc.content.size, "\n\n");
3541
+ }
3542
+ /**
3543
+ * Replace the content. By default it can be undone. With the fullpagehtml plugin, HTML that is a
3544
+ * whole page (or JSON) replaces the page too; HTML that is only content, or `fullPage: false`,
3545
+ * keeps the page as it is.
3546
+ */
3547
+ setContent(content, { addToHistory = true, fullPage = true } = {}) {
3548
+ const detail = { content };
3549
+ this.emit("beforeSetContent", detail);
3550
+ const page = fullPage ? pages.get(this) : void 0;
3551
+ const doc = parseContent(this.schema, detail.content, page);
3552
+ const tr = this.view.state.tr.replaceWith(0, this.view.state.doc.content.size, doc.content);
3553
+ if (page && (typeof detail.content !== "string" || wholePages.has(doc))) {
3554
+ for (const [name, value] of Object.entries(doc.attrs)) {
3555
+ if (value !== this.view.state.doc.attrs[name]) tr.setDocAttribute(name, value);
3556
+ }
3557
+ }
3558
+ tr.setMeta(API_CHANGE_META, true).setMeta(SET_CONTENT_META, true);
3559
+ if (!addToHistory) tr.setMeta("addToHistory", false);
3560
+ this.view.dispatch(tr);
3561
+ this.emit("setContent", { content: detail.content });
3562
+ }
3563
+ /**
3564
+ * Insert HTML at the cursor (like insertContent in TinyMCE). The HTML is parsed by the editor's
3565
+ * schema, as a paste is: no scripts, unsafe links or unknown tags. Blocks (paragraphs, tables) are
3566
+ * inserted as separate blocks. A table inserted with the cursor inside a table goes after it
3567
+ * rather than replacing its cells.
3568
+ */
3569
+ insertContent(html) {
3570
+ if (!this.isEditable()) return false;
3571
+ return insertContentCommand(html)(this.view.state, this.view.dispatch);
3572
+ }
3573
+ isEmpty() {
3574
+ return this.view.dom.classList.contains("nova-empty");
3575
+ }
3576
+ // ---------- commands ----------
3577
+ /** The command for a name: a plugin's override or the built-in one; unknown names return false. */
3578
+ resolveCommand(name) {
3579
+ name = currentName("commands", name);
3580
+ const command = this.commandOverrides.get(name) ?? (Object.prototype.hasOwnProperty.call(commands, name) ? commands[name] : void 0);
3581
+ if (command) return command;
3582
+ if (!unknownCommands.has(name)) {
3583
+ unknownCommands.add(name);
3584
+ console.warn(`[nova] unknown command "${String(name)}": editor.exec() returns false`);
3585
+ }
3586
+ return () => false;
3587
+ }
3588
+ registerCommands(plugin) {
3589
+ for (const [name, command] of Object.entries(plugin.commands ?? {})) {
3590
+ if (command) this.commandOverrides.set(name, command);
3591
+ }
3592
+ if (plugin.transformTransaction) this.transactionTransforms.push(plugin.transformTransaction);
3593
+ }
3594
+ /** Run a named command or any ProseMirror command; returns whether it ran. */
3595
+ exec(command) {
3596
+ const cmd = typeof command === "string" ? this.resolveCommand(command) : command;
3597
+ const result = cmd(this.view.state, this.view.dispatch, this.view);
3598
+ if (result) this.view.focus();
3599
+ return result;
3600
+ }
3601
+ /**
3602
+ * Several commands as one edit — one undo step, one change event:
3603
+ * `editor.chain().exec('h2').exec('alignCenter').run()`. If a step fails, the document doesn't
3604
+ * change and run() returns false; `chain().….can()` checks without changing anything (for buttons).
3605
+ */
3606
+ chain() {
3607
+ return createChain({
3608
+ view: () => this.destroyed ? null : this.view,
3609
+ resolve: (name) => this.resolveCommand(name),
3610
+ insertContent: (html) => (state, dispatch, view) => this.isEditable() && insertContentCommand(html)(state, dispatch, view)
3611
+ });
3612
+ }
3613
+ /**
3614
+ * Whether the command can run in the current state (for disabled buttons). A command that throws
3615
+ * (a document with content its schema doesn't allow, from JSON) can't run: the buttons go on
3616
+ * updating instead of breaking.
3617
+ */
3618
+ can(command) {
3619
+ const cmd = typeof command === "string" ? this.resolveCommand(command) : command;
3620
+ try {
3621
+ return cmd(this.view.state, void 0, this.view);
3622
+ } catch {
3623
+ return false;
3624
+ }
3625
+ }
3626
+ /** Whether a named command is active for the current selection (for your own toolbar buttons). */
3627
+ isActive(command) {
3628
+ return isCommandActive(this.view.state, currentName("commands", command));
3629
+ }
3630
+ /**
3631
+ * The state of a named command for your own toolbar: whether it is active (a pressed button) and
3632
+ * whether it can run now. The equivalent of queryCommandState / queryCommandEnabled.
3633
+ */
3634
+ getCommandState(command) {
3635
+ return { active: this.isActive(command), enabled: this.isEditable() && this.can(command) };
3636
+ }
3637
+ focus() {
3638
+ if (!this.destroyed) this.view.focus();
3639
+ }
3640
+ /** "Paste as text" mode (the pastetext toggle). */
3641
+ isPasteAsText() {
3642
+ return this.pasteAsText;
3643
+ }
3644
+ setPasteAsText(value) {
3645
+ this.pasteAsText = value;
3646
+ this.toolbar?.update();
3647
+ }
3648
+ /** The find and replace bar, loaded once (a separate chunk: the first load stays smaller). */
3649
+ loadSearchBar() {
3650
+ this.searchBarLoad ??= import("./search-bar-6MVRMTK6.js").then(
3651
+ ({ createSearchBar }) => {
3652
+ if (this.destroyed) return null;
3653
+ const header = this.toolbarHost.parentElement;
3654
+ this.searchBar = createSearchBar(
3655
+ this,
3656
+ (bar) => header ? header.append(bar) : this.contentHost.before(bar)
3657
+ );
3658
+ return this.searchBar;
3659
+ },
3660
+ (error) => {
3661
+ reportPluginError("The find and replace bar failed to load", error);
3662
+ return null;
3663
+ }
3664
+ );
3665
+ return this.searchBarLoad;
3666
+ }
3667
+ /** Open the find and replace bar (Ctrl/Cmd+F). Resolves once it is open. */
3668
+ openSearch() {
3669
+ return this.loadSearchBar().then((bar) => bar?.open());
3670
+ }
3671
+ closeSearch() {
3672
+ this.searchBar?.close();
3673
+ }
3674
+ /** Whether the text can be edited now: neither read-only nor disabled. */
3675
+ isEditable() {
3676
+ return this.editable && !this.disabled;
3677
+ }
3678
+ isDisabled() {
3679
+ return this.disabled;
3680
+ }
3681
+ /** Disable or enable the editor (like disabled on a form field). */
3682
+ setDisabled(value) {
3683
+ if (this.disabled === value) return;
3684
+ this.disabled = value;
3685
+ this.view.setProps({});
3686
+ this.applyDisabled();
3687
+ if (value) {
3688
+ this.ui.closePopover();
3689
+ this.view.dom.blur();
3690
+ }
3691
+ this.toolbar?.update();
3692
+ this.emit("editableChange");
3693
+ }
3694
+ applyDisabled() {
3695
+ this.root.classList.toggle("nova-disabled", this.disabled);
3696
+ if (this.disabled) this.root.setAttribute("aria-disabled", "true");
3697
+ else this.root.removeAttribute("aria-disabled");
3698
+ if (this.disabled) this.view.dom.setAttribute("tabindex", "-1");
3699
+ else this.view.dom.removeAttribute("tabindex");
3700
+ }
3701
+ setEditable(value) {
3702
+ if (this.editable === value) return;
3703
+ this.editable = value;
3704
+ this.view.setProps({});
3705
+ this.root.classList.toggle("nova-readonly", !value);
3706
+ if (!value) this.ui.closePopover();
3707
+ this.toolbar?.update();
3708
+ this.emit("editableChange");
3709
+ }
3710
+ // ---------- events ----------
3711
+ on(event, listener) {
3712
+ event = currentName("events", event);
3713
+ let set = this.listeners.get(event);
3714
+ if (!set) this.listeners.set(event, set = /* @__PURE__ */ new Set());
3715
+ set.add(listener);
3716
+ return () => this.off(event, listener);
3717
+ }
3718
+ off(event, listener) {
3719
+ event = currentName("events", event);
3720
+ this.listeners.get(event)?.delete(listener);
3721
+ }
3722
+ emit(event, ...[detail]) {
3723
+ for (const listener of this.listeners.get(event) ?? []) {
3724
+ try {
3725
+ listener(this, detail);
3726
+ } catch (error) {
3727
+ reportPluginError(`Listener for "${event}" failed`, error);
3728
+ }
3729
+ }
3730
+ }
3731
+ destroy() {
3732
+ if (this.destroyed) return;
3733
+ this.emit("destroy");
3734
+ this.destroyed = true;
3735
+ this.menubar?.destroy();
3736
+ this.ui.destroy();
3737
+ this.toolbar?.destroy();
3738
+ this.statusbar?.destroy();
3739
+ for (const cleanup of this.cleanups.splice(0)) {
3740
+ try {
3741
+ cleanup();
3742
+ } catch (error) {
3743
+ reportPluginError("Plugin cleanup failed", error);
3744
+ }
3745
+ }
3746
+ this.searchBar?.destroy();
3747
+ if (this.root.classList.contains("nova-fullscreen")) toggleFullscreen(this, false);
3748
+ this.view.destroy();
3749
+ this.root.remove();
3750
+ this.listeners.clear();
3751
+ }
3752
+ };
3753
+ function reportPluginError(message, error) {
3754
+ console.error(`[nova] ${message}`, ...error === void 0 ? [] : [error]);
3755
+ }
3756
+ var wholePages = /* @__PURE__ */ new WeakSet();
3757
+ function parseContent(schema2, content, page) {
3758
+ if (typeof content !== "string") return PMNode.fromJSON(schema2, sanitizeJSON(schema2, content));
3759
+ const parts = page ? page.read(content) : null;
3760
+ const container = document.createElement("div");
3761
+ const template = document.createElement("template");
3762
+ template.innerHTML = parts ? parts.content : content;
3763
+ container.appendChild(template.content);
3764
+ const doc = parserFor(schema2).parse(container);
3765
+ if (!parts) return doc;
3766
+ const whole = doc.type.create(parts.attrs, doc.content);
3767
+ wholePages.add(whole);
3768
+ return whole;
3769
+ }
3770
+ function createEditor(options) {
3771
+ return new Editor(options);
3772
+ }
3773
+
3774
+ export {
3775
+ htmlToPlainText,
3776
+ DEFAULT_MENUS,
3777
+ DEFAULT_MENUBAR,
3778
+ printContent,
3779
+ defaultToolbar,
3780
+ defaultSlashCommands,
3781
+ countWords,
3782
+ REMOTE_CHANGE_META,
3783
+ Editor,
3784
+ parseContent,
3785
+ createEditor
3786
+ };
3787
+ //# sourceMappingURL=chunk-RJ7T56OH.js.map