@notectl/core 2.4.2 → 2.5.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 (415) hide show
  1. package/dist/chunks/AlignmentPlugin-C26pIVcw.mjs +2 -0
  2. package/dist/chunks/{AlignmentPlugin-Cp7HYGaH.mjs.map → AlignmentPlugin-C26pIVcw.mjs.map} +1 -1
  3. package/dist/chunks/BidiIsolationPlugin-nWd1NEF-.mjs +2 -0
  4. package/dist/chunks/{BidiIsolationPlugin-GWukKdgJ.mjs.map → BidiIsolationPlugin-nWd1NEF-.mjs.map} +1 -1
  5. package/dist/chunks/BlockquotePlugin-Bag42Zc0.mjs +2 -0
  6. package/dist/chunks/{BlockquotePlugin-CSL_7Yit.mjs.map → BlockquotePlugin-Bag42Zc0.mjs.map} +1 -1
  7. package/dist/chunks/CaretNavigationPlugin-DUAoHygg.mjs +2 -0
  8. package/dist/chunks/{CaretNavigationPlugin-BQPqqK4n.mjs.map → CaretNavigationPlugin-DUAoHygg.mjs.map} +1 -1
  9. package/dist/chunks/CodeBlockPlugin-Dk_J8NAl.mjs +2 -0
  10. package/dist/chunks/{CodeBlockPlugin-B4AcDJRK.mjs.map → CodeBlockPlugin-Dk_J8NAl.mjs.map} +1 -1
  11. package/dist/chunks/Commands-vqbwh6Ic.mjs +2 -0
  12. package/dist/chunks/{Commands-Bk7Cl1nH.mjs.map → Commands-vqbwh6Ic.mjs.map} +1 -1
  13. package/dist/chunks/DocumentParser-D4g5npEi.mjs +2 -0
  14. package/dist/chunks/DocumentParser-D4g5npEi.mjs.map +1 -0
  15. package/dist/chunks/EditorUI-DrQI95FW.mjs +2 -0
  16. package/dist/chunks/EditorUI-DrQI95FW.mjs.map +1 -0
  17. package/dist/chunks/FontPlugin-Bzlluh1_.mjs +2 -0
  18. package/dist/chunks/{FontPlugin-BcXNFqqO.mjs.map → FontPlugin-Bzlluh1_.mjs.map} +1 -1
  19. package/dist/chunks/FontSizePlugin-kv3zHG0f.mjs +2 -0
  20. package/dist/chunks/{FontSizePlugin-Dswra3oU.mjs.map → FontSizePlugin-kv3zHG0f.mjs.map} +1 -1
  21. package/dist/chunks/FormulaPlugin-20vW4Gge.mjs +2 -0
  22. package/dist/chunks/{FormulaPlugin-DVpLaKi5.mjs.map → FormulaPlugin-20vW4Gge.mjs.map} +1 -1
  23. package/dist/chunks/GapCursorPlugin-BPyNXY4H.mjs +2 -0
  24. package/dist/chunks/{GapCursorPlugin-QDGwnaRR.mjs.map → GapCursorPlugin-BPyNXY4H.mjs.map} +1 -1
  25. package/dist/chunks/HTMLSanitization-BRipXyhI.mjs +2 -0
  26. package/dist/chunks/HTMLSanitization-BRipXyhI.mjs.map +1 -0
  27. package/dist/chunks/{HardBreakPlugin-gjCq8prD.mjs → HardBreakPlugin-lo8Mcg9G.mjs} +2 -2
  28. package/dist/chunks/{HardBreakPlugin-gjCq8prD.mjs.map → HardBreakPlugin-lo8Mcg9G.mjs.map} +1 -1
  29. package/dist/chunks/HeadingPlugin-CEZF5DBM.mjs +2 -0
  30. package/dist/chunks/{HeadingPlugin-B7EfynaH.mjs.map → HeadingPlugin-CEZF5DBM.mjs.map} +1 -1
  31. package/dist/chunks/HighlightPlugin-yH44UWoe.mjs +2 -0
  32. package/dist/chunks/{HighlightPlugin-LdO0INtJ.mjs.map → HighlightPlugin-yH44UWoe.mjs.map} +1 -1
  33. package/dist/chunks/HorizontalRulePlugin-SNNum-9V.mjs +2 -0
  34. package/dist/chunks/{HorizontalRulePlugin-YywXVZYr.mjs.map → HorizontalRulePlugin-SNNum-9V.mjs.map} +1 -1
  35. package/dist/chunks/ImagePlugin-aeqHr5zx.mjs +2 -0
  36. package/dist/chunks/{ImagePlugin-BAhZuVdE.mjs.map → ImagePlugin-aeqHr5zx.mjs.map} +1 -1
  37. package/dist/chunks/InlineCodePlugin-CIks06ti.mjs +2 -0
  38. package/dist/chunks/{InlineCodePlugin-Bu9-rE4B.mjs.map → InlineCodePlugin-CIks06ti.mjs.map} +1 -1
  39. package/dist/chunks/LinkPlugin-CFw22a9X.mjs +2 -0
  40. package/dist/chunks/LinkPlugin-CFw22a9X.mjs.map +1 -0
  41. package/dist/chunks/ListPlugin-ZNEx8pvk.mjs +2 -0
  42. package/dist/chunks/{ListPlugin-U1r4p_fE.mjs.map → ListPlugin-ZNEx8pvk.mjs.map} +1 -1
  43. package/dist/chunks/LocaleLoader-DEpTFuVc.mjs +2 -0
  44. package/dist/chunks/LocaleLoader-DEpTFuVc.mjs.map +1 -0
  45. package/dist/chunks/{MarkdownHTMLRegistry-BunUDiza.mjs → MarkdownHTMLRegistry-Cj7N2wqs.mjs} +2 -2
  46. package/dist/chunks/{MarkdownHTMLRegistry-BunUDiza.mjs.map → MarkdownHTMLRegistry-Cj7N2wqs.mjs.map} +1 -1
  47. package/dist/chunks/{MarkdownParser-uX1p_GQk.mjs → MarkdownParser-JOfPSvGv.mjs} +2 -2
  48. package/dist/chunks/{MarkdownParser-uX1p_GQk.mjs.map → MarkdownParser-JOfPSvGv.mjs.map} +1 -1
  49. package/dist/chunks/{MarkdownSerializer--MrgJTdJ.mjs → MarkdownSerializer-Y6saYClE.mjs} +2 -2
  50. package/dist/chunks/{MarkdownSerializer--MrgJTdJ.mjs.map → MarkdownSerializer-Y6saYClE.mjs.map} +1 -1
  51. package/dist/chunks/PopupManager-DpxoBl54.mjs +2 -0
  52. package/dist/chunks/PopupManager-DpxoBl54.mjs.map +1 -0
  53. package/dist/chunks/PopupPositioning-CIqgpqlW.mjs.map +1 -1
  54. package/dist/chunks/PrintPlugin-CYkdUy-m.mjs +2 -0
  55. package/dist/chunks/{PrintPlugin-DAEiEyKQ.mjs.map → PrintPlugin-CYkdUy-m.mjs.map} +1 -1
  56. package/dist/chunks/{SchemaRegistry-Cs7rxafF.mjs → SchemaRegistry-CT3T7S1i.mjs} +2 -2
  57. package/dist/chunks/{SchemaRegistry-Cs7rxafF.mjs.map → SchemaRegistry-CT3T7S1i.mjs.map} +1 -1
  58. package/dist/chunks/{SelectionReplacement-vC1xhFS0.mjs → SelectionReplacement-Cj4FLlPz.mjs} +2 -2
  59. package/dist/chunks/{SelectionReplacement-vC1xhFS0.mjs.map → SelectionReplacement-Cj4FLlPz.mjs.map} +1 -1
  60. package/dist/chunks/{SelectionSync-BkjCwGp-.mjs → SelectionSync-8y0nbBHZ.mjs} +2 -2
  61. package/dist/chunks/{SelectionSync-BkjCwGp-.mjs.map → SelectionSync-8y0nbBHZ.mjs.map} +1 -1
  62. package/dist/chunks/SimpleMark-DPTsIl9w.mjs +2 -0
  63. package/dist/chunks/{SimpleMark-D6vz3Nfd.mjs.map → SimpleMark-DPTsIl9w.mjs.map} +1 -1
  64. package/dist/chunks/SmartPastePlugin-BSMHDDQ2.mjs +2 -0
  65. package/dist/chunks/{SmartPastePlugin-BHsYKbgd.mjs.map → SmartPastePlugin-BSMHDDQ2.mjs.map} +1 -1
  66. package/dist/chunks/StrikethroughPlugin-CqqIF3Zk.mjs +2 -0
  67. package/dist/chunks/{StrikethroughPlugin-v-VJZzUZ.mjs.map → StrikethroughPlugin-CqqIF3Zk.mjs.map} +1 -1
  68. package/dist/chunks/SuperSubPlugin-5ZFM6wdU.mjs +2 -0
  69. package/dist/chunks/{SuperSubPlugin-x1iPnZyt.mjs.map → SuperSubPlugin-5ZFM6wdU.mjs.map} +1 -1
  70. package/dist/chunks/{TableDimensions-BSEOEox2.mjs → TableDimensions-B-OWjTuW.mjs} +2 -2
  71. package/dist/chunks/{TableDimensions-BSEOEox2.mjs.map → TableDimensions-B-OWjTuW.mjs.map} +1 -1
  72. package/dist/chunks/TablePlugin-D1Wg-pjl.mjs +2 -0
  73. package/dist/chunks/TablePlugin-D1Wg-pjl.mjs.map +1 -0
  74. package/dist/chunks/TableSelectionTypes-t2cLhe16.mjs +2 -0
  75. package/dist/chunks/TableSelectionTypes-t2cLhe16.mjs.map +1 -0
  76. package/dist/chunks/TextColorPlugin-Dwp7eW7F.mjs +2 -0
  77. package/dist/chunks/{TextColorPlugin-Bnl9of9E.mjs.map → TextColorPlugin-Dwp7eW7F.mjs.map} +1 -1
  78. package/dist/chunks/{TextDirectionAutoPlugin-DOH5cfyy.mjs → TextDirectionAutoPlugin-CkIETM5n.mjs} +2 -2
  79. package/dist/chunks/{TextDirectionAutoPlugin-DOH5cfyy.mjs.map → TextDirectionAutoPlugin-CkIETM5n.mjs.map} +1 -1
  80. package/dist/chunks/TextDirectionPlugin-DAcPR5Qc.mjs +2 -0
  81. package/dist/chunks/{TextDirectionPlugin-JwlR-R-b.mjs.map → TextDirectionPlugin-DAcPR5Qc.mjs.map} +1 -1
  82. package/dist/chunks/TextDirectionService-OFOU6r_s.mjs +2 -0
  83. package/dist/chunks/{TextDirectionService-BcX07mw2.mjs.map → TextDirectionService-OFOU6r_s.mjs.map} +1 -1
  84. package/dist/chunks/TextFormattingPlugin-vml-lduV.mjs +2 -0
  85. package/dist/chunks/{TextFormattingPlugin-Kc_UNoOz.mjs.map → TextFormattingPlugin-vml-lduV.mjs.map} +1 -1
  86. package/dist/chunks/ToolbarPlugin-Cxmb0MFr.mjs +2 -0
  87. package/dist/chunks/ToolbarPlugin-Cxmb0MFr.mjs.map +1 -0
  88. package/dist/chunks/VideoPlugin-lZCBlIon.mjs +2 -0
  89. package/dist/chunks/{VideoPlugin-DJXfuNA9.mjs.map → VideoPlugin-lZCBlIon.mjs.map} +1 -1
  90. package/dist/chunks/ar-Dp1oBWyG.mjs +2 -0
  91. package/dist/chunks/ar-Dp1oBWyG.mjs.map +1 -0
  92. package/dist/chunks/de-D3J8XPCR.mjs +2 -0
  93. package/dist/chunks/de-D3J8XPCR.mjs.map +1 -0
  94. package/dist/chunks/es-Bbz885DZ.mjs +2 -0
  95. package/dist/chunks/es-Bbz885DZ.mjs.map +1 -0
  96. package/dist/chunks/fr-GEgM1j3w.mjs +2 -0
  97. package/dist/chunks/fr-GEgM1j3w.mjs.map +1 -0
  98. package/dist/chunks/full-wDTdOuGt.mjs +2 -0
  99. package/dist/chunks/{full-BsWAZr1w.mjs.map → full-wDTdOuGt.mjs.map} +1 -1
  100. package/dist/chunks/hi-CKg8i4Mm.mjs +2 -0
  101. package/dist/chunks/hi-CKg8i4Mm.mjs.map +1 -0
  102. package/dist/chunks/minimal-FfmHwMGU.mjs +2 -0
  103. package/dist/chunks/{minimal-DO7LiFTa.mjs.map → minimal-FfmHwMGU.mjs.map} +1 -1
  104. package/dist/chunks/nl-2IdjTNeJ.mjs +2 -0
  105. package/dist/chunks/nl-2IdjTNeJ.mjs.map +1 -0
  106. package/dist/chunks/nl-B1i04NvZ.mjs +2 -0
  107. package/dist/chunks/nl-B1i04NvZ.mjs.map +1 -0
  108. package/dist/chunks/nl-BEmzpzKO.mjs +2 -0
  109. package/dist/chunks/nl-BEmzpzKO.mjs.map +1 -0
  110. package/dist/chunks/nl-B_U0D3Qq.mjs +2 -0
  111. package/dist/chunks/nl-B_U0D3Qq.mjs.map +1 -0
  112. package/dist/chunks/nl-C437Xz6z.mjs +2 -0
  113. package/dist/chunks/nl-C437Xz6z.mjs.map +1 -0
  114. package/dist/chunks/nl-C5P8Fogm.mjs +2 -0
  115. package/dist/chunks/nl-C5P8Fogm.mjs.map +1 -0
  116. package/dist/chunks/nl-CST62bzx.mjs +2 -0
  117. package/dist/chunks/nl-CST62bzx.mjs.map +1 -0
  118. package/dist/chunks/nl-CWQT-W-6.mjs +2 -0
  119. package/dist/chunks/nl-CWQT-W-6.mjs.map +1 -0
  120. package/dist/chunks/nl-CdpcDkbM.mjs +2 -0
  121. package/dist/chunks/nl-CdpcDkbM.mjs.map +1 -0
  122. package/dist/chunks/nl-CgYWZnga.mjs +2 -0
  123. package/dist/chunks/nl-CgYWZnga.mjs.map +1 -0
  124. package/dist/chunks/nl-Cr--x8bX.mjs +2 -0
  125. package/dist/chunks/nl-Cr--x8bX.mjs.map +1 -0
  126. package/dist/chunks/nl-Cwl5dxFZ.mjs +2 -0
  127. package/dist/chunks/nl-Cwl5dxFZ.mjs.map +1 -0
  128. package/dist/chunks/nl-Czjd9Bw9.mjs +2 -0
  129. package/dist/chunks/nl-Czjd9Bw9.mjs.map +1 -0
  130. package/dist/chunks/nl-DUOT2ZMQ.mjs +2 -0
  131. package/dist/chunks/nl-DUOT2ZMQ.mjs.map +1 -0
  132. package/dist/chunks/nl-DYnRYvZ5.mjs +2 -0
  133. package/dist/chunks/nl-DYnRYvZ5.mjs.map +1 -0
  134. package/dist/chunks/nl-DaNJ-ffX.mjs +2 -0
  135. package/dist/chunks/nl-DaNJ-ffX.mjs.map +1 -0
  136. package/dist/chunks/nl-DeOJ64xy.mjs +2 -0
  137. package/dist/chunks/nl-DeOJ64xy.mjs.map +1 -0
  138. package/dist/chunks/nl-DwZajfpP.mjs +2 -0
  139. package/dist/chunks/nl-DwZajfpP.mjs.map +1 -0
  140. package/dist/chunks/nl-Dyjc9M7o.mjs +2 -0
  141. package/dist/chunks/nl-Dyjc9M7o.mjs.map +1 -0
  142. package/dist/chunks/nl-GBpv7W4L.mjs +2 -0
  143. package/dist/chunks/nl-GBpv7W4L.mjs.map +1 -0
  144. package/dist/chunks/nl-HFfWJOEo.mjs +2 -0
  145. package/dist/chunks/nl-HFfWJOEo.mjs.map +1 -0
  146. package/dist/chunks/nl-KqmiCeD7.mjs +2 -0
  147. package/dist/chunks/nl-KqmiCeD7.mjs.map +1 -0
  148. package/dist/chunks/nl-_QT7e2Qt.mjs +2 -0
  149. package/dist/chunks/nl-_QT7e2Qt.mjs.map +1 -0
  150. package/dist/chunks/nl-i79IajbC.mjs +2 -0
  151. package/dist/chunks/nl-i79IajbC.mjs.map +1 -0
  152. package/dist/chunks/nl-lcZvrAz6.mjs +2 -0
  153. package/dist/chunks/nl-lcZvrAz6.mjs.map +1 -0
  154. package/dist/chunks/nl-tWJ2imhe.mjs +2 -0
  155. package/dist/chunks/nl-tWJ2imhe.mjs.map +1 -0
  156. package/dist/chunks/nl-xfiNOCgg.mjs +2 -0
  157. package/dist/chunks/nl-xfiNOCgg.mjs.map +1 -0
  158. package/dist/chunks/pt-DP5c76Vo.mjs +2 -0
  159. package/dist/chunks/pt-DP5c76Vo.mjs.map +1 -0
  160. package/dist/chunks/register-DSRtHVkk.mjs +3 -0
  161. package/dist/chunks/register-DSRtHVkk.mjs.map +1 -0
  162. package/dist/chunks/ru--iYEtsT5.mjs +2 -0
  163. package/dist/chunks/ru--iYEtsT5.mjs.map +1 -0
  164. package/dist/chunks/src-DDkRstYh.mjs +2 -0
  165. package/dist/chunks/src-DDkRstYh.mjs.map +1 -0
  166. package/dist/chunks/zh-DUS7JduA.mjs +2 -0
  167. package/dist/chunks/zh-DUS7JduA.mjs.map +1 -0
  168. package/dist/commands/Commands.d.ts +3 -0
  169. package/dist/commands/Commands.d.ts.map +1 -1
  170. package/dist/commands/CompositionCommands.d.ts +14 -8
  171. package/dist/commands/CompositionCommands.d.ts.map +1 -1
  172. package/dist/commands/CompositionFallback.d.ts +13 -0
  173. package/dist/commands/CompositionFallback.d.ts.map +1 -0
  174. package/dist/commands/CompositionRebase.d.ts +17 -10
  175. package/dist/commands/CompositionRebase.d.ts.map +1 -1
  176. package/dist/editor/locales/nl.d.ts +4 -0
  177. package/dist/editor/locales/nl.d.ts.map +1 -0
  178. package/dist/editor/styles/link.d.ts +2 -2
  179. package/dist/editor/styles/link.d.ts.map +1 -1
  180. package/dist/fonts.mjs +1 -1
  181. package/dist/full.mjs +1 -1
  182. package/dist/html.mjs +1 -1
  183. package/dist/i18n/Locale.d.ts +1 -0
  184. package/dist/i18n/Locale.d.ts.map +1 -1
  185. package/dist/input/CompositionController.d.ts.map +1 -1
  186. package/dist/input/HTMLLineBreaks.d.ts +14 -0
  187. package/dist/input/HTMLLineBreaks.d.ts.map +1 -0
  188. package/dist/input/HTMLParser.d.ts +1 -7
  189. package/dist/input/HTMLParser.d.ts.map +1 -1
  190. package/dist/input/PasteHTMLHandler.d.ts +0 -1
  191. package/dist/input/PasteHTMLHandler.d.ts.map +1 -1
  192. package/dist/markdown.mjs +1 -1
  193. package/dist/notectl-core.mjs +1 -1
  194. package/dist/notectl-core.umd.js +1 -1
  195. package/dist/notectl-core.umd.js.map +1 -1
  196. package/dist/plugins/PluginContextFactory.d.ts +1 -0
  197. package/dist/plugins/PluginContextFactory.d.ts.map +1 -1
  198. package/dist/plugins/PluginManager.d.ts +5 -0
  199. package/dist/plugins/PluginManager.d.ts.map +1 -1
  200. package/dist/plugins/alignment/locales/nl.d.ts +4 -0
  201. package/dist/plugins/alignment/locales/nl.d.ts.map +1 -0
  202. package/dist/plugins/alignment.mjs +1 -1
  203. package/dist/plugins/bidi-isolation/locales/nl.d.ts +4 -0
  204. package/dist/plugins/bidi-isolation/locales/nl.d.ts.map +1 -0
  205. package/dist/plugins/bidi-isolation.mjs +1 -1
  206. package/dist/plugins/blockquote/locales/nl.d.ts +4 -0
  207. package/dist/plugins/blockquote/locales/nl.d.ts.map +1 -0
  208. package/dist/plugins/blockquote.mjs +1 -1
  209. package/dist/plugins/caret-navigation/locales/nl.d.ts +4 -0
  210. package/dist/plugins/caret-navigation/locales/nl.d.ts.map +1 -0
  211. package/dist/plugins/caret-navigation.mjs +1 -1
  212. package/dist/plugins/code-block/locales/nl.d.ts +4 -0
  213. package/dist/plugins/code-block/locales/nl.d.ts.map +1 -0
  214. package/dist/plugins/code-block.mjs +1 -1
  215. package/dist/plugins/editor-ui/EditorUI.d.ts +50 -0
  216. package/dist/plugins/editor-ui/EditorUI.d.ts.map +1 -0
  217. package/dist/plugins/editor-ui/EditorUIRuntime.d.ts +44 -0
  218. package/dist/plugins/editor-ui/EditorUIRuntime.d.ts.map +1 -0
  219. package/dist/plugins/editor-ui/index.d.ts +6 -0
  220. package/dist/plugins/editor-ui/index.d.ts.map +1 -0
  221. package/dist/plugins/font/locales/nl.d.ts +4 -0
  222. package/dist/plugins/font/locales/nl.d.ts.map +1 -0
  223. package/dist/plugins/font-size/locales/nl.d.ts +4 -0
  224. package/dist/plugins/font-size/locales/nl.d.ts.map +1 -0
  225. package/dist/plugins/font-size.mjs +1 -1
  226. package/dist/plugins/font.mjs +1 -1
  227. package/dist/plugins/formula/locales/nl.d.ts +4 -0
  228. package/dist/plugins/formula/locales/nl.d.ts.map +1 -0
  229. package/dist/plugins/formula.mjs +1 -1
  230. package/dist/plugins/gap-cursor/locales/nl.d.ts +4 -0
  231. package/dist/plugins/gap-cursor/locales/nl.d.ts.map +1 -0
  232. package/dist/plugins/gap-cursor.mjs +1 -1
  233. package/dist/plugins/hard-break.mjs +1 -1
  234. package/dist/plugins/heading/locales/nl.d.ts +4 -0
  235. package/dist/plugins/heading/locales/nl.d.ts.map +1 -0
  236. package/dist/plugins/heading.mjs +1 -1
  237. package/dist/plugins/highlight/locales/nl.d.ts +4 -0
  238. package/dist/plugins/highlight/locales/nl.d.ts.map +1 -0
  239. package/dist/plugins/highlight.mjs +1 -1
  240. package/dist/plugins/horizontal-rule/locales/nl.d.ts +4 -0
  241. package/dist/plugins/horizontal-rule/locales/nl.d.ts.map +1 -0
  242. package/dist/plugins/horizontal-rule.mjs +1 -1
  243. package/dist/plugins/image/locales/nl.d.ts +4 -0
  244. package/dist/plugins/image/locales/nl.d.ts.map +1 -0
  245. package/dist/plugins/image.mjs +1 -1
  246. package/dist/plugins/inline-code/locales/nl.d.ts +4 -0
  247. package/dist/plugins/inline-code/locales/nl.d.ts.map +1 -0
  248. package/dist/plugins/inline-code.mjs +1 -1
  249. package/dist/plugins/link/{LinkPreview.d.ts → LinkBubble.d.ts} +10 -7
  250. package/dist/plugins/link/LinkBubble.d.ts.map +1 -0
  251. package/dist/plugins/link/LinkBubbleContent.d.ts +4 -0
  252. package/dist/plugins/link/LinkBubbleContent.d.ts.map +1 -0
  253. package/dist/plugins/link/LinkInteractionController.d.ts +17 -3
  254. package/dist/plugins/link/LinkInteractionController.d.ts.map +1 -1
  255. package/dist/plugins/link/LinkLocale.d.ts +3 -0
  256. package/dist/plugins/link/LinkLocale.d.ts.map +1 -1
  257. package/dist/plugins/link/LinkPlugin.d.ts +0 -1
  258. package/dist/plugins/link/LinkPlugin.d.ts.map +1 -1
  259. package/dist/plugins/link/LinkRange.d.ts +12 -0
  260. package/dist/plugins/link/LinkRange.d.ts.map +1 -0
  261. package/dist/plugins/link/locales/ar.d.ts.map +1 -1
  262. package/dist/plugins/link/locales/de.d.ts.map +1 -1
  263. package/dist/plugins/link/locales/es.d.ts.map +1 -1
  264. package/dist/plugins/link/locales/fr.d.ts.map +1 -1
  265. package/dist/plugins/link/locales/hi.d.ts.map +1 -1
  266. package/dist/plugins/link/locales/nl.d.ts +4 -0
  267. package/dist/plugins/link/locales/nl.d.ts.map +1 -0
  268. package/dist/plugins/link/locales/pt.d.ts.map +1 -1
  269. package/dist/plugins/link/locales/ru.d.ts.map +1 -1
  270. package/dist/plugins/link/locales/zh.d.ts.map +1 -1
  271. package/dist/plugins/link.mjs +1 -1
  272. package/dist/plugins/list/locales/nl.d.ts +4 -0
  273. package/dist/plugins/list/locales/nl.d.ts.map +1 -0
  274. package/dist/plugins/list.mjs +1 -1
  275. package/dist/plugins/print/locales/nl.d.ts +4 -0
  276. package/dist/plugins/print/locales/nl.d.ts.map +1 -0
  277. package/dist/plugins/print.mjs +1 -1
  278. package/dist/plugins/shared/PopupManager.d.ts +15 -2
  279. package/dist/plugins/shared/PopupManager.d.ts.map +1 -1
  280. package/dist/plugins/shared/PopupPositioning.d.ts +2 -6
  281. package/dist/plugins/shared/PopupPositioning.d.ts.map +1 -1
  282. package/dist/plugins/shared/index.d.ts +1 -1
  283. package/dist/plugins/shared/index.d.ts.map +1 -1
  284. package/dist/plugins/shared.mjs +1 -1
  285. package/dist/plugins/smart-paste/locales/nl.d.ts +4 -0
  286. package/dist/plugins/smart-paste/locales/nl.d.ts.map +1 -0
  287. package/dist/plugins/smart-paste.mjs +1 -1
  288. package/dist/plugins/strikethrough/locales/nl.d.ts +4 -0
  289. package/dist/plugins/strikethrough/locales/nl.d.ts.map +1 -0
  290. package/dist/plugins/strikethrough.mjs +1 -1
  291. package/dist/plugins/super-sub/locales/nl.d.ts +4 -0
  292. package/dist/plugins/super-sub/locales/nl.d.ts.map +1 -0
  293. package/dist/plugins/super-sub.mjs +1 -1
  294. package/dist/plugins/table/TableContextMenu.d.ts.map +1 -1
  295. package/dist/plugins/table/TableSelection.d.ts +4 -20
  296. package/dist/plugins/table/TableSelection.d.ts.map +1 -1
  297. package/dist/plugins/table/TableSelectionTypes.d.ts +21 -0
  298. package/dist/plugins/table/TableSelectionTypes.d.ts.map +1 -0
  299. package/dist/plugins/table/locales/nl.d.ts +4 -0
  300. package/dist/plugins/table/locales/nl.d.ts.map +1 -0
  301. package/dist/plugins/table.mjs +1 -1
  302. package/dist/plugins/text-color/locales/nl.d.ts +4 -0
  303. package/dist/plugins/text-color/locales/nl.d.ts.map +1 -0
  304. package/dist/plugins/text-color.mjs +1 -1
  305. package/dist/plugins/text-direction/locales/nl.d.ts +4 -0
  306. package/dist/plugins/text-direction/locales/nl.d.ts.map +1 -0
  307. package/dist/plugins/text-direction-auto.mjs +1 -1
  308. package/dist/plugins/text-direction.mjs +1 -1
  309. package/dist/plugins/text-formatting/locales/nl.d.ts +4 -0
  310. package/dist/plugins/text-formatting/locales/nl.d.ts.map +1 -0
  311. package/dist/plugins/text-formatting.mjs +1 -1
  312. package/dist/plugins/toolbar/ToolbarOverflowController.d.ts +2 -2
  313. package/dist/plugins/toolbar/ToolbarOverflowController.d.ts.map +1 -1
  314. package/dist/plugins/toolbar/ToolbarPlugin.d.ts +2 -1
  315. package/dist/plugins/toolbar/ToolbarPlugin.d.ts.map +1 -1
  316. package/dist/plugins/toolbar/ToolbarPopupController.d.ts +8 -3
  317. package/dist/plugins/toolbar/ToolbarPopupController.d.ts.map +1 -1
  318. package/dist/plugins/toolbar/ToolbarRegistry.d.ts +4 -0
  319. package/dist/plugins/toolbar/ToolbarRegistry.d.ts.map +1 -1
  320. package/dist/plugins/toolbar/locales/nl.d.ts +4 -0
  321. package/dist/plugins/toolbar/locales/nl.d.ts.map +1 -0
  322. package/dist/plugins/toolbar.mjs +1 -1
  323. package/dist/plugins/video/locales/nl.d.ts +4 -0
  324. package/dist/plugins/video/locales/nl.d.ts.map +1 -0
  325. package/dist/plugins/video.mjs +1 -1
  326. package/dist/presets/full.mjs +1 -1
  327. package/dist/presets/minimal.mjs +1 -1
  328. package/dist/presets.mjs +1 -1
  329. package/dist/register.mjs +1 -1
  330. package/dist/serialization/DocumentParser.d.ts +2 -2
  331. package/dist/serialization/DocumentParser.d.ts.map +1 -1
  332. package/dist/serialization/HTMLParseRules.d.ts.map +1 -1
  333. package/dist/serialization/HTMLSanitization.d.ts +6 -0
  334. package/dist/serialization/HTMLSanitization.d.ts.map +1 -1
  335. package/dist/serialization/PreformattedText.d.ts +3 -0
  336. package/dist/serialization/PreformattedText.d.ts.map +1 -0
  337. package/dist/state/RangeMapping.d.ts +10 -0
  338. package/dist/state/RangeMapping.d.ts.map +1 -0
  339. package/dist/ui.d.ts +3 -0
  340. package/dist/ui.d.ts.map +1 -0
  341. package/dist/ui.mjs +1 -0
  342. package/dist/view/EditorInteraction.d.ts +23 -0
  343. package/dist/view/EditorInteraction.d.ts.map +1 -0
  344. package/dist/view/EditorView.d.ts +2 -0
  345. package/dist/view/EditorView.d.ts.map +1 -1
  346. package/dist/view/SelectionGeometry.d.ts +29 -0
  347. package/dist/view/SelectionGeometry.d.ts.map +1 -0
  348. package/dist/view/SelectionObserver.d.ts +19 -0
  349. package/dist/view/SelectionObserver.d.ts.map +1 -0
  350. package/dist/view/SelectionSync.d.ts +7 -0
  351. package/dist/view/SelectionSync.d.ts.map +1 -1
  352. package/package.json +6 -2
  353. package/dist/chunks/AlignmentPlugin-Cp7HYGaH.mjs +0 -2
  354. package/dist/chunks/BidiIsolationPlugin-GWukKdgJ.mjs +0 -2
  355. package/dist/chunks/BlockquotePlugin-CSL_7Yit.mjs +0 -2
  356. package/dist/chunks/CaretNavigationPlugin-BQPqqK4n.mjs +0 -2
  357. package/dist/chunks/CodeBlockPlugin-B4AcDJRK.mjs +0 -2
  358. package/dist/chunks/Commands-Bk7Cl1nH.mjs +0 -2
  359. package/dist/chunks/DocumentParser-C99N0MWF.mjs +0 -2
  360. package/dist/chunks/DocumentParser-C99N0MWF.mjs.map +0 -1
  361. package/dist/chunks/FontPlugin-BcXNFqqO.mjs +0 -2
  362. package/dist/chunks/FontSizePlugin-Dswra3oU.mjs +0 -2
  363. package/dist/chunks/FormulaPlugin-DVpLaKi5.mjs +0 -2
  364. package/dist/chunks/GapCursorPlugin-QDGwnaRR.mjs +0 -2
  365. package/dist/chunks/HTMLSanitization-Ce9dVT1q.mjs +0 -2
  366. package/dist/chunks/HTMLSanitization-Ce9dVT1q.mjs.map +0 -1
  367. package/dist/chunks/HeadingPlugin-B7EfynaH.mjs +0 -2
  368. package/dist/chunks/HighlightPlugin-LdO0INtJ.mjs +0 -2
  369. package/dist/chunks/HorizontalRulePlugin-YywXVZYr.mjs +0 -2
  370. package/dist/chunks/ImagePlugin-BAhZuVdE.mjs +0 -2
  371. package/dist/chunks/InlineCodePlugin-Bu9-rE4B.mjs +0 -2
  372. package/dist/chunks/LinkPlugin-CAUaWW5-.mjs +0 -2
  373. package/dist/chunks/LinkPlugin-CAUaWW5-.mjs.map +0 -1
  374. package/dist/chunks/ListPlugin-U1r4p_fE.mjs +0 -2
  375. package/dist/chunks/PluginHelpers-B3gk3VB3.mjs +0 -2
  376. package/dist/chunks/PluginHelpers-B3gk3VB3.mjs.map +0 -1
  377. package/dist/chunks/PopupManager-Dxv0OVMo.mjs +0 -2
  378. package/dist/chunks/PopupManager-Dxv0OVMo.mjs.map +0 -1
  379. package/dist/chunks/PrintPlugin-DAEiEyKQ.mjs +0 -2
  380. package/dist/chunks/SimpleMark-D6vz3Nfd.mjs +0 -2
  381. package/dist/chunks/SmartPastePlugin-BHsYKbgd.mjs +0 -2
  382. package/dist/chunks/StrikethroughPlugin-v-VJZzUZ.mjs +0 -2
  383. package/dist/chunks/SuperSubPlugin-x1iPnZyt.mjs +0 -2
  384. package/dist/chunks/TablePlugin-CjKThPug.mjs +0 -2
  385. package/dist/chunks/TablePlugin-CjKThPug.mjs.map +0 -1
  386. package/dist/chunks/TextColorPlugin-Bnl9of9E.mjs +0 -2
  387. package/dist/chunks/TextDirectionPlugin-JwlR-R-b.mjs +0 -2
  388. package/dist/chunks/TextDirectionService-BcX07mw2.mjs +0 -2
  389. package/dist/chunks/TextFormattingPlugin-Kc_UNoOz.mjs +0 -2
  390. package/dist/chunks/ToolbarPlugin-CgZA2hz8.mjs +0 -2
  391. package/dist/chunks/ToolbarPlugin-CgZA2hz8.mjs.map +0 -1
  392. package/dist/chunks/VideoPlugin-DJXfuNA9.mjs +0 -2
  393. package/dist/chunks/ar-DhwCFHql.mjs +0 -2
  394. package/dist/chunks/ar-DhwCFHql.mjs.map +0 -1
  395. package/dist/chunks/de-CjLUbQmg.mjs +0 -2
  396. package/dist/chunks/de-CjLUbQmg.mjs.map +0 -1
  397. package/dist/chunks/es-CMSzvjOT.mjs +0 -2
  398. package/dist/chunks/es-CMSzvjOT.mjs.map +0 -1
  399. package/dist/chunks/fr-DB_OvHWH.mjs +0 -2
  400. package/dist/chunks/fr-DB_OvHWH.mjs.map +0 -1
  401. package/dist/chunks/full-BsWAZr1w.mjs +0 -2
  402. package/dist/chunks/hi-ChNQZZ1z.mjs +0 -2
  403. package/dist/chunks/hi-ChNQZZ1z.mjs.map +0 -1
  404. package/dist/chunks/minimal-DO7LiFTa.mjs +0 -2
  405. package/dist/chunks/pt-CI8t6oul.mjs +0 -2
  406. package/dist/chunks/pt-CI8t6oul.mjs.map +0 -1
  407. package/dist/chunks/register-DXLu8Njp.mjs +0 -3
  408. package/dist/chunks/register-DXLu8Njp.mjs.map +0 -1
  409. package/dist/chunks/ru-9WtNGZtl.mjs +0 -2
  410. package/dist/chunks/ru-9WtNGZtl.mjs.map +0 -1
  411. package/dist/chunks/src-5GKFQ2mQ.mjs +0 -2
  412. package/dist/chunks/src-5GKFQ2mQ.mjs.map +0 -1
  413. package/dist/chunks/zh-BrqJ4ywP.mjs +0 -2
  414. package/dist/chunks/zh-BrqJ4ywP.mjs.map +0 -1
  415. package/dist/plugins/link/LinkPreview.d.ts.map +0 -1
@@ -0,0 +1,3 @@
1
+ import{a as e,c as t,l as n,n as i}from"./HTMLUtils-DTpsjZyK.mjs";import{A as s,B as r,C as o,D as a,E as c,G as l,H as d,K as h,L as u,M as p,O as f,P as m,R as g,S as y,T as k,U as b,V as v,W as w,_ as I,a as S,b as x,c as R,d as C,f as M,g as P,h as E,i as T,j as B,k as A,l as O,m as D,o as N,p as L,q as H,r as z,s as _,t as F,u as j,v as $,w as K,x as V,y as q,z as U}from"./Document-ssR6hBzG.mjs";import{c as W,n as G,o as J,r as Q,s as X}from"./NodeResolver-F4RtpoEd.mjs";import{a as Y,c as Z,d as ee,f as te,i as ne,m as ie,n as se,o as re,p as oe,r as ae,s as ce,t as le,u as de}from"./Selection-DC6AOGgF.mjs";import{a as he,i as ue,r as pe,t as fe}from"./TypeBrands-Ch9856Gb.mjs";import{a as me,i as ge,n as ye,r as ke,t as be}from"./Schema-BSM4YLNT.mjs";import{S as ve,b as we,d as Ie,f as Se,h as xe,l as Re,m as Ce,n as Me,p as Pe,r as Ee,s as Te,t as Be,u as Ae,v as Oe,x as De}from"./BlockInsertion-CXfXqUZl.mjs";import{t as Ne}from"./ContentModel-dkGOh3N7.mjs";import{i as Le,t as He}from"./NodeSelectionCommands-CAqIHW_6.mjs";import{a as ze,c as _e,d as Fe,i as je,l as $e,n as Ke,o as Ve,r as qe,s as Ue,u as We}from"./Commands-vqbwh6Ic.mjs";import{t as Ge}from"./MarkCommands-C0ps9h0z.mjs";import{A as Je,F as Qe,I as Xe,L as Ye,M as Ze,N as et,P as tt,R as nt,j as it,t as st,z as rt}from"./CaretNavigationPlugin-DUAoHygg.mjs";import{_ as ot,b as at,c as ct,d as lt,f as dt,g as ht,i as ut,n as pt,p as ft,u as mt,y as gt}from"./ThemeEngine-kIXtSRkI.mjs";import{T as yt,_ as kt,h as bt,m as vt,p as wt,v as It,y as St}from"./TableDimensions-B-OWjTuW.mjs";import{r as xt,t as Rt}from"./HTMLSanitization-BRipXyhI.mjs";import{a as Ct,c as Mt,i as Pt,l as Et,n as Tt,o as Bt,r as At,s as Ot,t as Dt}from"./DocumentParser-D4g5npEi.mjs";import{_ as Nt,c as Lt,d as Ht,f as zt,g as _t,l as Ft,m as jt,n as $t,p as Kt,r as Vt,s as qt,t as Ut,u as Wt}from"./Decoration-BoFcdSXk.mjs";import{i as Gt,n as Jt,r as Qt,t as Xt}from"./PopupManager-DpxoBl54.mjs";import{l as Yt,s as Zt,t as en,u as tn}from"./LocaleLoader-DEpTFuVc.mjs";import{n as nn,t as sn}from"./EditorEventBoundary-zpYRxryo.mjs";import{n as rn}from"./SelectionReplacement-Cj4FLlPz.mjs";import{a as on,c as an,l as cn,r as ln,t as dn,u as hn}from"./StyleRuntime-C0RSqKzG.mjs";import{i as un,t as pn}from"./Platform-ByobkiCc.mjs";import{t as fn}from"./SchemaRegistry-CT3T7S1i.mjs";import{n as mn,t as gn}from"./DomUtils-Bf7JLFlx.mjs";import{a as yn,c as kn,d as bn,f as vn,i as wn,l as In,n as Sn,o as xn,p as Rn,r as Cn,s as Mn,t as Pn,u as En}from"./SelectionSync-8y0nbBHZ.mjs";import{n as Tn}from"./PopupPositioning-CIqgpqlW.mjs";import{t as Bn}from"./TableSelectionTypes-t2cLhe16.mjs";import{a as An,c as On,i as Dn,l as Nn,o as Ln,s as Hn,t as zn}from"./ToolbarPlugin-Cxmb0MFr.mjs";import{n as _n,r as Fn}from"./KeyboardNav-D0my3wuy.mjs";import{t as jn}from"./EditorUI-DrQI95FW.mjs";import{t as $n}from"./BlockTypePickerRegistry-BTET9jM-.mjs";import{n as Kn,t as Vn}from"./GapCursorPlugin-BPyNXY4H.mjs";import{t as qn}from"./TextFormattingPlugin-vml-lduV.mjs";function Un(e,t){const n=e.selection;if(ee(n))return He(e,n);if(de(n))return null;if(!Z(n))return Ke(e);const i=e.getBlock(n.anchor.blockId);if(!i)return null;const s=t.range(i,n.anchor.offset);if(!s)return t.merge(e);const[r,o]=s;return e.transaction("input").deleteTextAt(i.id,r,o).setSelection(se(i.id,r)).build()}function Wn(e){return Un(e,{merge:ze,range:(e,t)=>{if(t<=0)return null;if("inline"===p(e,t-1)?.kind)return[t-1,t];const n=B(e),i=T(e,t);return[t-(rt(n,i)||1),t]}})}function Gn(e){return Un(e,{merge:Ve,range:(e,t)=>{if(t>=A(e))return null;if("inline"===p(e,t)?.kind)return[t,t+1];const n=B(e),i=T(e,t);return[t,t+(nt(n,i)||1)]}})}function Jn(e,t){return{children:e.children.map(e=>Qn(e,t))}}function Qn(e,t){const n=t.getNodeSpec(e.type);let i=e;if(n?.content&&n.content.allow.some(e=>"text"!==e)){const s=n.content.allow.includes("text");if(r(e)){if(!s&&(0!==e.children.length||0!==n.content.min)){const t=e.children.length>0?e.children:void 0,n=L(he("paragraph"),t);i=L(e.type,[n],e.id,e.attrs,e.htmlId)}}else{const n=function(e,t){const n=[];let i=[];const s=()=>{0!==i.length&&(n.push(L(he("paragraph"),i)),i=[])};for(const r of e)v(r)||U(r)?i.push(r):(s(),n.push(Qn(r,t)));return s(),n}(e.children,t);i=L(e.type,n,e.id,e.attrs,e.htmlId)}}const s=n?.normalizeAttrs?.(i);if(n?.normalizeAttrs&&!z(i.attrs,s)){const{attrs:e,...t}=i;i={...t,...s?{attrs:s}:{}}}return n?.normalizeNode?.(i)??i}function Xn(e,t,n){if(ee(n))return G(e,n.nodeId)?n:Yn(e,t)??n;if(de(n))return G(e,n.blockId)?n:Yn(e,t)??n;const i=Zn(e,t,n.anchor),s=Zn(e,t,n.head);return i.blockId===s.blockId&&function(e,t,n){const i=G(e,n);return void 0!==i&&ge(t,i.type)}(e,t,i.blockId)?ni(e,i.blockId):i===n.anchor&&s===n.head?n:re(i,s)}function Yn(e,t){const n=ei(e.children,t);return n?ge(t,n.type)?ni(e,n.id):se(n.id,0):null}function Zn(e,t,n){const i=G(e,n.blockId);if(i&&r(i))return function(e,t){const n=A(e),i=Number.isFinite(t.offset)?Math.trunc(t.offset):0,s=Math.max(0,Math.min(n,i));return s===t.offset?t:Y(t.blockId,s,t.path)}(i,n);const s=ei(i?i.children:e.children,t)??(i?ei(e.children,t):null);return s?Y(s.id,0):n}function ei(e,t){return ti(e,e=>!ge(t,e.type))??ti(e,()=>!0)}function ti(e,t){for(const n of e){if(!g(n))continue;if(r(n)){if(t(n))return n;continue}const e=ti(n.children,t);if(e)return e}return null}function ni(e,t){const n=Q(e,t)??[];return ne(t,n)}function ii(e,t,n){return{children:si(e.children,t,n)}}function si(e,t,n){let i=!1;const s=e.map(e=>{if(!g(e))return e;if(e.id===t)return i=!0,n(e);const s=si(e.children,t,n);return s===e.children?e:(i=!0,{...e,children:s})});return i?s:e}function ri(e,t,n){if(0===t.length)return e;const i=t[0];return i?{children:e.children.map(e=>g(e)&&e.id===i?1===t.length?n(e):oi(e,t,1,n):e)}:e}function oi(e,t,n,i){const s=t[n];if(!s)return e;const r=e.children.map(e=>g(e)&&e.id===s?n===t.length-1?i(e):oi(e,t,n+1,i):e);return{...e,children:r}}function ai(e,t,n){if(t(e))return n(e);let i=!1;const s=e.map(e=>{if(!g(e))return e;const s=ai(e.children,t,n);return s?(i=!0,{...e,children:s}):e});return i?s:null}function ci(e,t,n){const i=[];let s=0,r=!1;for(const o of e){if(U(o)){r||t!==s||(i.push(...n()),r=!0),i.push(o),s+=1;continue}const e=s+o.text.length;if(!r&&t>=s&&t<=e){const e=t-s,a=o.text.slice(0,e),c=o.text.slice(e);a&&i.push(I(a,o.marks)),i.push(...n()),c&&i.push(I(c,o.marks)),r=!0}else i.push(o);s=e}return r||i.push(...n()),i}function li(e,t,n){const i=[];let s=0;for(const r of e){if(U(r)){const e=s+1;e>t&&s<n&&i.push(r),s=e;continue}const e=s+r.text.length;if(e<=t||s>=n);else{const e=Math.max(0,t-s),o=Math.min(r.text.length,n-s),a=r.text.slice(e,o);a.length>0&&i.push(I(a,r.marks))}s=e}return 0===i.length&&i.push(I("")),i}function di(e,t,n,i,s){const r=[];let o=0;for(const a of e){if(U(a)){r.push(a),o+=1;continue}const e=o+a.text.length;if(e<=t||o>=n)r.push(a);else if(o>=t&&e<=n){const e=s?F(a.marks,i):l(a.marks,i.type);r.push(I(a.text,e))}else{const e=Math.max(0,t-o),c=Math.min(a.text.length,n-o),d=a.text.slice(0,e),h=a.text.slice(e,c),u=a.text.slice(c);if(d&&r.push(I(d,a.marks)),h){const e=s?F(a.marks,i):l(a.marks,i.type);r.push(I(h,e))}u&&r.push(I(u,a.marks))}o=e}return r}function hi(e,t){if(e.every(e=>v(e)||U(e)))return t;const n=e.filter(e=>!v(e)&&!U(e));return[...t,...n]}function ui(e){return e.reduce((e,t)=>e+("inline"===t.kind?1:t.text.length),0)}var pi=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function fi(e){return e.replace(pi,"").length>0}function mi(e){return"inline"===e.kind||fi(e.text)}function gi(e){return bi(e.fromParentPath,e.toParentPath)&&e.toIndex>e.fromIndex?e.toIndex-1:e.toIndex}function yi(e){return bi(e.fromParentPath,e.toParentPath)&&gi(e)===e.fromIndex}function ki(e,t){const n=X(e,t.fromParentPath,t.fromIndex);if(!n||n.id!==t.movedNode.id)return null;if(t.toParentPath.includes(n.id))return null;const i=0===t.toParentPath.length?e.children.length:W(e,t.toParentPath)?.children.length??null;if(null===i||!Number.isInteger(t.toIndex)||t.toIndex<0||t.toIndex>i)return null;const s=bi(t.fromParentPath,t.toParentPath),r=gi(t);return r<0||r>i-(s?1:0)?null:{movedNode:n,destinationIndex:r}}function bi(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function vi(e){return e.segments?ui(e.segments):e.text.length}var wi=class extends Error{constructor(e){super(e),this.name="StructuralPositionError"}};function Ii(e,t,n,i){return new wi(`${e} at parent path [${t.join(", ")}], index ${n}: ${i}`)}function Si(e,t,n){if(!Number.isInteger(n)||n<0)throw Ii(e,t,n,"expected a nonnegative integer.")}function xi(e,t,n,i){if(Si(t,n,i),0===n.length)return e.children;const s=W(e,n);if(!s)throw Ii(t,n,i,"parent does not exist.");return s.children}function Ri(e,t,n){if(Si("insertNode",t,n),!e)return;const i=xi(e,"insertNode",t,n);if(n>i.length)throw Ii("insertNode",t,n,`expected an index in 0 … ${i.length}.`)}function Ci(e,t,n,i){const s=xi(e,"removeNode",t,n)[n];if(!s||!g(s))throw Ii("removeNode",t,n,"no block exists at this position.");if(void 0!==i&&s.id!==i)throw Ii("removeNode",t,n,`expected block "${i}", found "${s.id}".`);return s}function Mi(e,t,n,i=!0){return ii(e,t,e=>{const t=n(m(e));return{...e,children:hi(e.children,i?w(t):t)}})}function Pi(e,t){if(Ri(e,t.parentPath,t.index),0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,0,t.node),{children:n}}return ri(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,0,t.node),{...e,children:n}})}function Ei(e,t){if(Ci(e,t.parentPath,t.index,t.removedNode.id),0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,1),{children:n}}return ri(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,1),{...e,children:n}})}function Ti(e){return e.path?{path:e.path}:{}}function Bi(e){for(const t of e.steps)if("setStoredMarks"===t.type)return t.previousMarks;return e.storedMarksAfter}function Ai(e,t,n){return n?e!==t?{}:{path:n}:{}}function Oi(e,t,n){if(0===e.length)return!0;for(const i of e){const e=t.mapResult({blockId:i,offset:0},-1);if(e.deleted)return!1;if(e.pos.blockId!==i)return!1}return void 0!==W(n,e)}function Di(e,t){return t.blockId===e.blockId&&t.from===e.from&&t.to===e.to}function Ni(e,t,n){const i=zt(e,t,t+1,n);return i?i.to-i.from!==1?null:i:null}var Li=/* @__PURE__ */new WeakSet;function Hi(e){return ce(le(e))}function zi(e){if(!e)return null;const t=C(e);return k(t),t}function _i(e){switch(e.type){case"insertText":return Object.freeze({...e,marks:zi(e.marks)??Object.freeze([]),...e.segments?{segments:Ui(e.segments)}:{},...e.path?{path:Wi(e.path)}:{}});case"deleteText":return Object.freeze({...e,deletedMarks:zi(e.deletedMarks)??Object.freeze([]),deletedSegments:Ui(e.deletedSegments),...e.path?{path:Wi(e.path)}:{}});case"splitBlock":return Object.freeze({...e,...e.newBlockAttrs?{newBlockAttrs:$i(e.newBlockAttrs)}:{},...e.path?{path:Wi(e.path)}:{}});case"mergeBlocks":return Object.freeze({...e,...e.sourceAttrs?{sourceAttrs:$i(e.sourceAttrs)}:{},...e.path?{path:Wi(e.path)}:{}});case"addMark":case"removeMark":return Object.freeze({...e,mark:ji(e.mark),...e.path?{path:Wi(e.path)}:{}});case"setStoredMarks":return Object.freeze({...e,marks:zi(e.marks),previousMarks:zi(e.previousMarks)});case"setBlockType":return Object.freeze({...e,...e.attrs?{attrs:$i(e.attrs)}:{},...e.previousAttrs?{previousAttrs:$i(e.previousAttrs)}:{},...e.path?{path:Wi(e.path)}:{}});case"insertNode":return Object.freeze({...e,parentPath:Wi(e.parentPath),node:Vi(e.node)});case"removeNode":return Object.freeze({...e,parentPath:Wi(e.parentPath),removedNode:Vi(e.removedNode)});case"moveNode":return Object.freeze({...e,fromParentPath:Wi(e.fromParentPath),toParentPath:Wi(e.toParentPath),movedNode:Vi(e.movedNode)});case"setNodeAttr":return Object.freeze({...e,path:Wi(e.path),...e.attrs?{attrs:$i(e.attrs)}:{},...e.previousAttrs?{previousAttrs:$i(e.previousAttrs)}:{}});case"insertInlineNode":return Object.freeze({...e,node:qi(e.node),...e.path?{path:Wi(e.path)}:{}});case"removeInlineNode":return Object.freeze({...e,removedNode:qi(e.removedNode),...e.path?{path:Wi(e.path)}:{}});case"setInlineNodeAttr":return Object.freeze({...e,attrs:Ki(e.attrs),previousAttrs:Ki(e.previousAttrs),...e.path?{path:Wi(e.path)}:{}})}}function Fi(e,t){if(e.steps.length!==e.forwardStepMaps.length)throw new Error("A transaction requires exactly one forward StepMap per step.");const n=Object.freeze({steps:Object.freeze([...e.steps]),selectionBefore:e.selectionBefore,selectionAfter:e.selectionAfter,storedMarksAfter:e.storedMarksAfter,mapping:Lt.from(e.forwardStepMaps),forwardStepMaps:Object.freeze([...e.forwardStepMaps]),metadata:Object.freeze({...e.metadata})});return!1!==t?.mapsVerified&&Li.add(n),n}function ji(e){const t=j(e);return K(t),t}function $i(e){const t=S(e);return q(t),t}function Ki(e){return Object.freeze({...e})}function Vi(e){const t=N(e);return x(t),t}function qi(e){const t=O(e);return o(t),t}function Ui(e){const t=_(e);return V(t),t}function Wi(e){return Object.freeze([...e])}var Gi={insertText:{apply:function(e,t){return Mi(e,t.blockId,e=>{return t.segments?(n=e,i=t.offset,s=t.segments,ci(n,i,()=>s.map(M))):function(e,t,n,i){return ci(e,t,()=>[I(n,i)])}(e,t.offset,t.text,t.marks);var n,i,s})},invert:function(e){return{type:"deleteText",blockId:e.blockId,from:e.offset,to:e.offset+vi(e),deletedText:e.text,deletedMarks:e.marks,deletedSegments:e.segments??[H(e.text,[...e.marks])],...Ti(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.offset,to:t.offset,newLen:vi(t)}},map:function(e,t,n){const i=jt(e.blockId,e.offset,t,-1);return i?i.blockId===e.blockId&&i.from===e.offset?e:{type:"insertText",blockId:i.blockId,offset:i.from,text:e.text,marks:e.marks,...e.segments?{segments:e.segments}:{},...Ai(e.blockId,i.blockId,e.path)}:null}},deleteText:{apply:function(e,t){return Mi(e,t.blockId,e=>function(e,t,n){const i=[];let s=0;for(const r of e){if(U(r)){const e=s+1;(e<=t||s>=n)&&i.push(r),s=e;continue}const e=s+r.text.length;if(e<=t||s>=n)i.push(r);else{const e=Math.max(0,t-s),o=Math.min(r.text.length,n-s),a=r.text.slice(0,e)+r.text.slice(o);a.length>0&&i.push(I(a,r.marks))}s=e}return i}(e,t.from,t.to))},invert:function(e){return{type:"insertText",blockId:e.blockId,offset:e.from,text:e.deletedText,marks:e.deletedMarks,segments:e.deletedSegments,...Ti(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.from,to:t.to,newLen:0}},map:function(e,t,n){const i=zt(e.blockId,e.from,e.to,t);if(!i)return null;if(Di({blockId:e.blockId,from:e.from,to:e.to},i))return e;const r=G(n,i.blockId);if(!r)return null;const o=B(r).slice(i.from,i.to),a=s(r,i.from),c=f(r,i.from,i.to);return{type:"deleteText",blockId:i.blockId,from:i.from,to:i.to,deletedText:o,deletedMarks:a,deletedSegments:c,...Ai(e.blockId,i.blockId,e.path)}}},splitBlock:{apply:function(e,t){const n=ai(e.children,e=>e.some(e=>g(e)&&e.id===t.blockId),e=>{const n=e.findIndex(e=>g(e)&&e.id===t.blockId);if(-1===n)return e;const i=e[n],s=m(i),r=A(i),o=li(s,0,t.offset),a=li(s,t.offset,r),c={...i,children:w(o)},l=void 0!==t.newBlockType,d=t.newBlockType??i.type,h=l?t.newBlockAttrs:i.attrs,u=L(d,w(a),t.newBlockId,h,t.newBlockHTMLId),p=[...e];return p.splice(n,1,c,u),p});return n?{children:n}:e},invert:function(e){return{type:"mergeBlocks",targetBlockId:e.blockId,sourceBlockId:e.newBlockId,targetLengthBefore:e.offset,...void 0!==e.newBlockType?{sourceType:e.newBlockType}:{},...e.newBlockAttrs?{sourceAttrs:e.newBlockAttrs}:{},...void 0!==e.newBlockHTMLId?{sourceHTMLId:e.newBlockHTMLId}:{},...Ti(e)}},getMap:function(e,t){return{type:"split",blockId:t.blockId,offset:t.offset,newBlockId:t.newBlockId}},map:function(e,t,n){const i=jt(e.blockId,e.offset,t,-1);return i?i.blockId===e.blockId&&i.from===e.offset?e:{type:"splitBlock",blockId:i.blockId,offset:i.from,newBlockId:e.newBlockId,...void 0!==e.newBlockType?{newBlockType:e.newBlockType}:{},...e.newBlockAttrs?{newBlockAttrs:e.newBlockAttrs}:{},...void 0!==e.newBlockHTMLId?{newBlockHTMLId:e.newBlockHTMLId}:{},...Ai(e.blockId,i.blockId,e.path)}:null}},mergeBlocks:{apply:function(e,t){const n=ai(e.children,e=>e.some(e=>g(e)&&e.id===t.targetBlockId)&&e.some(e=>g(e)&&e.id===t.sourceBlockId),e=>{const n=e.findIndex(e=>g(e)&&e.id===t.targetBlockId),i=e.findIndex(e=>g(e)&&e.id===t.sourceBlockId);if(-1===n||-1===i)return e;const s=e[n],r=e[i],o=m(s),a=m(r),c=w([...o,...a]),l={...s,children:c};return e.filter(e=>!g(e)||e.id!==t.sourceBlockId).map(e=>g(e)&&e.id===t.targetBlockId?l:e)});return n?{children:n}:e},invert:function(e){return{type:"splitBlock",blockId:e.targetBlockId,offset:e.targetLengthBefore,newBlockId:e.sourceBlockId,...void 0!==e.sourceType?{newBlockType:e.sourceType}:{},...e.sourceAttrs?{newBlockAttrs:e.sourceAttrs}:{},...void 0!==e.sourceHTMLId?{newBlockHTMLId:e.sourceHTMLId}:{},...Ti(e)}},getMap:function(e,t){return{type:"merge",targetBlockId:t.targetBlockId,sourceBlockId:t.sourceBlockId,targetLengthBefore:t.targetLengthBefore}},map:function(e,t,n){if(t.isEmpty)return e;const i=t.mapResult({blockId:e.targetBlockId,offset:0},-1),s=t.mapResult({blockId:e.sourceBlockId,offset:0},-1);if(i.deleted||s.deleted)return null;const r=i.pos.blockId,o=s.pos.blockId;if(r===o)return null;const a=G(n,r);if(!a)return null;const c=A(a);return r===e.targetBlockId&&o===e.sourceBlockId&&c===e.targetLengthBefore?e:{type:"mergeBlocks",targetBlockId:r,sourceBlockId:o,targetLengthBefore:c,...void 0!==e.sourceType?{sourceType:e.sourceType}:{},...e.sourceAttrs?{sourceAttrs:e.sourceAttrs}:{},...void 0!==e.sourceHTMLId?{sourceHTMLId:e.sourceHTMLId}:{},...Ai(e.targetBlockId,r,e.path)}}},addMark:{apply:function(e,t){return Mi(e,t.blockId,e=>di(e,t.from,t.to,t.mark,!0))},invert:function(e){return{type:"removeMark",blockId:e.blockId,from:e.from,to:e.to,mark:e.mark,...Ti(e)}},getMap:function(e,t){return qt},map:function(e,t,n){const i=zt(e.blockId,e.from,e.to,t);return i?Di({blockId:e.blockId,from:e.from,to:e.to},i)?e:{type:"addMark",blockId:i.blockId,from:i.from,to:i.to,mark:e.mark,...Ai(e.blockId,i.blockId,e.path)}:null}},removeMark:{apply:function(e,t){return Mi(e,t.blockId,e=>di(e,t.from,t.to,t.mark,!1))},invert:function(e){return{type:"addMark",blockId:e.blockId,from:e.from,to:e.to,mark:e.mark,...Ti(e)}},getMap:function(e,t){return qt},map:function(e,t,n){const i=zt(e.blockId,e.from,e.to,t);return i?Di({blockId:e.blockId,from:e.from,to:e.to},i)?e:{type:"removeMark",blockId:i.blockId,from:i.from,to:i.to,mark:e.mark,...Ai(e.blockId,i.blockId,e.path)}:null}},setStoredMarks:{apply:function(e){return e},invert:function(e){return{type:"setStoredMarks",marks:e.previousMarks,previousMarks:e.marks}},getMap:function(e,t){return qt},map:function(e,t,n){return e}},setBlockType:{apply:function(e,t){return ii(e,t.blockId,e=>{const{attrs:n,...i}=e;return{...i,type:t.nodeType,...t.attrs?{attrs:t.attrs}:{}}})},invert:function(e){return{type:"setBlockType",blockId:e.blockId,nodeType:e.previousNodeType,attrs:e.previousAttrs,previousNodeType:e.nodeType,previousAttrs:e.attrs,...Ti(e)}},getMap:function(e,t){return qt},map:function(e,t,n){if(t.isEmpty)return e;const i=t.mapResult({blockId:e.blockId,offset:0},-1);if(i.deleted)return null;const s=i.pos.blockId,r=G(n,s);return r?s===e.blockId&&r.type===e.previousNodeType&&z(r.attrs,e.previousAttrs)?e:{type:"setBlockType",blockId:s,nodeType:e.nodeType,...e.attrs?{attrs:e.attrs}:{},previousNodeType:r.type,...r.attrs?{previousAttrs:r.attrs}:{},...Ai(e.blockId,s,e.path)}:null}},insertNode:{apply:Pi,invert:function(e){return{type:"removeNode",parentPath:e.parentPath,index:e.index,removedNode:e.node}},getMap:function(e,t){return{type:"childIndexShift",parentPath:t.parentPath,fromIndex:t.index,delta:1,insertedBlockIds:Ft(t.node)}},map:function(e,t,n){if(!Oi(e.parentPath,t,n))return null;const i=Kt(e.parentPath,e.index,t);return i===e.index?e:{type:"insertNode",parentPath:e.parentPath,index:i,node:e.node}}},removeNode:{apply:Ei,invert:function(e){return{type:"insertNode",parentPath:e.parentPath,index:e.index,node:e.removedNode}},getMap:function(e,t){return{type:"blockRemoval",removedBlockIds:Ft(t.removedNode),parentPath:t.parentPath,index:t.index}},map:function(e,t,n){if(!Oi(e.parentPath,t,n))return null;const i=t.mapResult({blockId:e.removedNode.id,offset:0},-1);if(i.deleted)return null;if(i.pos.blockId!==e.removedNode.id)return null;const s=Ht(e.parentPath,e.index,t);if(null===s)return null;const r=X(n,e.parentPath,s);return r?r.id!==e.removedNode.id?null:s===e.index&&r===e.removedNode?e:{type:"removeNode",parentPath:e.parentPath,index:s,removedNode:r}:null}},moveNode:{apply:function(e,t){const n=ki(e,t);return!n||yi(t)?e:Pi(Ei(e,{type:"removeNode",parentPath:t.fromParentPath,index:t.fromIndex,removedNode:n.movedNode}),{type:"insertNode",parentPath:t.toParentPath,index:n.destinationIndex,node:n.movedNode})},invert:function(e){const t=gi(e),n=e.fromParentPath.length===e.toParentPath.length&&e.fromParentPath.every((t,n)=>t===e.toParentPath[n])&&e.fromIndex>t?e.fromIndex+1:e.fromIndex;return{type:"moveNode",fromParentPath:e.toParentPath,fromIndex:t,toParentPath:e.fromParentPath,toIndex:n,movedNode:e.movedNode}},getMap:function(e,t){const n=ki(e,t);return!n||yi(t)?qt:{type:"moveNode",movedNodeId:t.movedNode.id,fromParentPath:t.fromParentPath,fromIndex:t.fromIndex,toParentPath:t.toParentPath,destinationIndex:n.destinationIndex}},map:function(e,t,n){if(!Oi(e.fromParentPath,t,n))return null;if(!Oi(e.toParentPath,t,n))return null;const i=t.mapResult({blockId:e.movedNode.id,offset:0},-1);if(i.deleted||i.pos.blockId!==e.movedNode.id)return null;const s=Ht(e.fromParentPath,e.fromIndex,t);if(null===s)return null;const r=Kt(e.toParentPath,e.toIndex,t),o=X(n,e.fromParentPath,s);if(!o||o.id!==e.movedNode.id)return null;const a={type:"moveNode",fromParentPath:e.fromParentPath,fromIndex:s,toParentPath:e.toParentPath,toIndex:r,movedNode:o};return ki(n,a)?s===e.fromIndex&&r===e.toIndex&&o===e.movedNode?e:a:null}},setNodeAttr:{apply:function(e,t){const n=t.path[t.path.length-1];return n?ii(e,n,e=>({...e,attrs:t.attrs})):e},invert:function(e){return{type:"setNodeAttr",path:e.path,attrs:e.previousAttrs,previousAttrs:e.attrs}},getMap:function(e,t){return qt},map:function(e,t,n){if(t.isEmpty)return e;if(!Oi(e.path,t,n))return null;const i=W(n,e.path);return i?{type:"setNodeAttr",path:e.path,attrs:e.attrs,...i.attrs?{previousAttrs:i.attrs}:{}}:null}},insertInlineNode:{apply:function(e,t){return Mi(e,t.blockId,e=>function(e,t,n){const i=[];let s=0,r=!1;for(const o of e){if(U(o)){r||t!==s||(i.push(n),r=!0),i.push(o),s+=1;continue}const e=s+o.text.length;if(!r&&t>=s&&t<=e){const e=t-s,a=o.text.slice(0,e),c=o.text.slice(e);a&&i.push(I(a,o.marks)),i.push(n),c&&i.push(I(c,o.marks)),r=!0}else i.push(o);s=e}return r||i.push(n),i}(e,t.offset,t.node))},invert:function(e){return{type:"removeInlineNode",blockId:e.blockId,offset:e.offset,removedNode:e.node,...Ti(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.offset,to:t.offset,newLen:1}},map:function(e,t,n){const i=jt(e.blockId,e.offset,t,-1);return i?i.blockId===e.blockId&&i.from===e.offset?e:{type:"insertInlineNode",blockId:i.blockId,offset:i.from,node:e.node,...Ai(e.blockId,i.blockId,e.path)}:null}},removeInlineNode:{apply:function(e,t){return Mi(e,t.blockId,e=>function(e,t){const n=[];let i=0;for(const s of e)U(s)?(i!==t&&n.push(s),i+=1):(n.push(s),i+=s.text.length);return n}(e,t.offset))},invert:function(e){return{type:"insertInlineNode",blockId:e.blockId,offset:e.offset,node:e.removedNode,...Ti(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.offset,to:t.offset+1,newLen:0}},map:function(e,t,n){const i=Ni(e.blockId,e.offset,t);if(!i)return null;const s=G(n,i.blockId);if(!s)return null;const r=p(s,i.from);return r&&"inline"===r.kind&&U(r.node)?(o=e.removedNode)===(a=r.node)||o.inlineType===a.inlineType&&z(o.attrs,a.attrs)?i.blockId===e.blockId&&i.from===e.offset?e:{type:"removeInlineNode",blockId:i.blockId,offset:i.from,removedNode:r.node,...Ai(e.blockId,i.blockId,e.path)}:null:null;var o,a}},setInlineNodeAttr:{apply:function(e,t){return Mi(e,t.blockId,e=>function(e,t,n){const i=[];let s=0;for(const r of e)U(r)?(s===t?i.push({...r,attrs:n}):i.push(r),s+=1):(i.push(r),s+=r.text.length);return i}(e,t.offset,t.attrs),!1)},invert:function(e){return{type:"setInlineNodeAttr",blockId:e.blockId,offset:e.offset,attrs:e.previousAttrs,previousAttrs:e.attrs,...Ti(e)}},getMap:function(e,t){return qt},map:function(e,t,n){const i=Ni(e.blockId,e.offset,t);if(!i)return null;if(i.blockId===e.blockId&&i.from===e.offset)return e;const s=G(n,i.blockId);if(!s)return null;const r=p(s,i.from);return r&&"inline"===r.kind&&U(r.node)?{type:"setInlineNodeAttr",blockId:i.blockId,offset:i.from,attrs:e.attrs,previousAttrs:r.node.attrs,...Ai(e.blockId,i.blockId,e.path)}:null}}};function Ji(e){return Gi[e.type]}function Qi(e,t){return Ji(t).apply(e,t)}function Xi(e){return Ji(e).invert(e)}function Yi(e,t){return Ji(t).getMap(e,t)}function Zi(e,t,n){return t.isEmpty?e:Ji(e).map(e,t,n)}function es(e){const t=e.steps.map(Xi).reverse().map(_i);return Fi({steps:t,selectionBefore:Hi(e.selectionAfter),selectionAfter:Hi(e.selectionBefore),storedMarksAfter:zi(Bi(e)),forwardStepMaps:t.map(()=>qt),metadata:{origin:"history",timestamp:Date.now()}},{mapsVerified:!1})}var ts=class{steps=[];stepMaps=[];selection;storedMarks;selectionBefore;origin;workingDoc;_readonlyAllowed=!1;constructor(e,t,n="api",i){const s=Hi(e);this.selection=s,this.selectionBefore=s,this.storedMarks=zi(t),this.origin=n,this.workingDoc=i??null}insertText(e,t,n,i,s){const r={type:"insertText",blockId:e,offset:t,text:n,marks:i,...s?{segments:s}:{}};return this.appendStep(r),this}deleteText(e,t,n,i,s,r){let o;if(r)o=r;else if(this.workingDoc){const r=G(this.workingDoc,e);o=r?f(r,t,n):[H(i,[...s])]}else o=[H(i,[...s])];const a={type:"deleteText",blockId:e,from:t,to:n,deletedText:i,deletedMarks:s,deletedSegments:o};return this.appendStep(a),this}deleteTextAt(e,t,n){const i=this.requireDoc("deleteTextAt"),r=this.requireBlock(i,e),o=B(r).slice(t,n),a=s(r,t),c=f(r,t,n);return this.deleteText(e,t,n,o,a,c)}splitBlock(e,t,n){const i={type:"splitBlock",blockId:e,offset:t,newBlockId:n};return this.appendStep(i),this}mergeBlocks(e,t,n,i,s,r){if(this.workingDoc&&!J(this.workingDoc,e,t))throw new Error(`Cannot merge blocks "${e}" and "${t}": both must exist under the same parent in the working document.`);const o={type:"mergeBlocks",targetBlockId:e,sourceBlockId:t,targetLengthBefore:n,...void 0!==i?{sourceType:i}:{},...s?{sourceAttrs:s}:{},...void 0!==r?{sourceHTMLId:r}:{}};return this.appendStep(o),this}mergeBlocksAt(e,t){const n=this.requireDoc("mergeBlocksAt"),i=this.requireBlock(n,e),s=this.requireBlock(n,t),r=A(i);return this.mergeBlocks(e,t,r,s.type,s.attrs,s.htmlId)}addMark(e,t,n,i){const s=this.tryGetBlock(e);if(!s){const s={type:"addMark",blockId:e,from:t,to:n,mark:i};return this.appendStep(s),this}const r=function(e,t,n,i){const s=[];if(t>=n)return s;let r=null,o=0;const a=()=>{r&&(s.push(r),r=null)};for(const c of e){const e=o+(U(c)?1:c.text.length);if(e<=t||o>=n){o=e;continue}const s=Math.max(o,t),l=Math.min(e,n);U(c)?r&&(r.to=l):c.marks.some(e=>e.type===i)?a():r?r.to=l:r={from:s,to:l},o=e}return a(),s}(m(s),t,n,i.type);for(const o of r){const t={type:"addMark",blockId:e,from:o.from,to:o.to,mark:i};this.appendStep(t)}return this}removeMark(e,t,n,i){const s=this.tryGetBlock(e);if(!s){const s={type:"removeMark",blockId:e,from:t,to:n,mark:i};return this.appendStep(s),this}const r=function(e,t,n,i){const s=[];if(t>=n)return s;let r=null,o=0;const a=()=>{r&&(s.push(r),r=null)};for(const c of e){const e=o+(U(c)?1:c.text.length);if(e<=t||o>=n){o=e;continue}const s=Math.max(o,t),l=Math.min(e,n);if(U(c))r&&(r.to=l);else{const e=c.marks.find(e=>e.type===i);e?r&&b(r.mark,e)?r.to=l:(a(),r={from:s,to:l,mark:e}):a()}o=e}return a(),s}(m(s),t,n,i.type);for(const o of r){const t={type:"removeMark",blockId:e,from:o.from,to:o.to,mark:o.mark};this.appendStep(t)}return this}setBlockType(e,t,n){const i=this.requireDoc("setBlockType"),s=this.requireBlock(i,e),r={type:"setBlockType",blockId:e,nodeType:t,...n?{attrs:n}:{},previousNodeType:s.type,...s.attrs?{previousAttrs:s.attrs}:{}};return this.appendStep(r),this}insertNode(e,t,n){Ri(this.workingDoc,e,t);const i={type:"insertNode",parentPath:e,index:t,node:n};return this.appendStep(i),this}removeNode(e,t){const n={type:"removeNode",parentPath:e,index:t,removedNode:Ci(this.requireDoc("removeNode"),e,t)};return this.appendStep(n),this}moveNode(e,t,n,i){const s=this.requireDoc("moveNode"),r=X(s,e,t);if(!r)throw new Error(`Node at index ${t} not found under source path [${e.join(", ")}].`);if(n.includes(r.id))throw new Error(`Cannot move node "${r.id}" into its own subtree.`);const o=0===n.length?s.children.length:W(s,n)?.children.length??-1;if(!Number.isInteger(i)||i<0||i>o)throw new Error(`Invalid destination index ${i} under path [${n.join(", ")}].`);const a={type:"moveNode",fromParentPath:e,fromIndex:t,toParentPath:n,toIndex:i,movedNode:r};return yi(a)||this.appendStep(a),this}setNodeAttr(e,t){const n=this.requireDoc("setNodeAttr"),i=W(n,e);if(!i)throw new Error(`Node not found at path [${e.join(", ")}].`);const s={type:"setNodeAttr",path:e,attrs:t,...i.attrs?{previousAttrs:i.attrs}:{}};return this.appendStep(s),this}insertInlineNode(e,t,n){const i={type:"insertInlineNode",blockId:e,offset:t,node:n};return this.appendStep(i),this}removeInlineNode(e,t){const n=this.requireDoc("removeInlineNode"),i=this.requireBlock(n,e),s=p(i,t);if(!s||"inline"!==s.kind)throw new Error(`No InlineNode at offset ${t} in block "${e}".`);const r={type:"removeInlineNode",blockId:e,offset:t,removedNode:s.node};return this.appendStep(r),this}setInlineNodeAttr(e,t,n){const i=this.requireDoc("setInlineNodeAttr"),s=this.requireBlock(i,e),r=m(s);let o=0;for(const a of r){if(U(a)&&o===t){const i={type:"setInlineNodeAttr",blockId:e,offset:t,attrs:n,previousAttrs:a.attrs};return this.appendStep(i),this}o+=U(a)?1:a.text.length}throw new Error(`No InlineNode at offset ${t} in block "${e}".`)}readonlyAllowed(){return this._readonlyAllowed=!0,this}setSelection(e){return this.selection=Hi(e),this}setNodeSelection(e,t){return this.selection=Hi(ne(e,t)),this}setStoredMarks(e,t){return this.appendStep({type:"setStoredMarks",marks:e,previousMarks:t}),this.storedMarks=zi(e),this}build(){return Fi({steps:this.steps,selectionBefore:this.selectionBefore,selectionAfter:this.selection,storedMarksAfter:this.storedMarks,forwardStepMaps:this.stepMaps,metadata:{origin:this.origin,timestamp:Date.now(),...this._readonlyAllowed?{readonlyAllowed:!0}:{}}})}requireDoc(e){if(!this.workingDoc)throw new Error(`${e} requires a document. Use state.transaction() or provide doc to constructor.`);return this.workingDoc}requireBlock(e,t){const n=G(e,t);if(!n)throw new Error(`Block "${t}" not found in working document.`);return n}tryGetBlock(e){return this.workingDoc?G(this.workingDoc,e)??null:null}appendStep(e){const t=_i(e),n=this.workingDoc??ns,i=this.workingDoc?Qi(this.workingDoc,t):null,s=_t(Yi(n,t));this.steps.push(t),this.stepMaps.push(s),this.workingDoc=i}},ns={children:[]},is=class e{doc;selection;storedMarks;schema;_blockMap=null;_blockOrder=null;constructor(e,t,n,i){if(this.doc=y(e),this.selection=ce(t),n){const e=C(n);k(e),this.storedMarks=e}else this.storedMarks=null;this.schema=i}static create(t){const n=t?.schema??be(),i=t?.doc?R(t.doc):D(),s=t?.selection?Xn(i,n,le(t.selection)):Yn(i,n)??se(fe(""),0);return new e(i,s,null,n)}transaction(e="api"){return new ts(this.selection,this.storedMarks,e,this.doc)}apply(t){let n=this.doc;for(const e of t.steps)n=Qi(n,e);const i=Xn(n,this.schema,le(t.selectionAfter));return new e(n,i,t.storedMarksAfter,this.schema)}getBlock(e){return this._blockMap??=function(e){const t=/* @__PURE__ */new Map;return function e(n){for(const i of n)g(i)&&(t.set(i.id,i),e(i.children))}(e.children),t}(this.doc),this._blockMap.get(e)}getBlockOrder(){return this._blockOrder??=function(e){const t=[];return function e(n){for(const i of n)g(i)&&(r(i)?t.push(i.id):e(i.children))}(e.children),Object.freeze(t)}(this.doc),this._blockOrder}getNodePath(e){return Q(this.doc,e)}getParent(e){const t=Q(this.doc,e);if(!t||t.length<=1)return;const n=t[t.length-2];return n?G(this.doc,n):void 0}withSelection(t){const n=Xn(this.doc,this.schema,le(t));return new e(this.doc,n,this.storedMarks,this.schema)}withStoredMarks(t){return new e(this.doc,this.selection,t,this.schema)}toJSON(){return{doc:R(this.doc),selection:le(this.selection)}}static fromJSON(t,n){return e.create({doc:t.doc,selection:t.selection,schema:n})}};function ss(e,t){const n=/* @__PURE__ */new Set;rs(e.children,t.children,n);const i=new as(n);return{...e,children:e.children.map((e,n)=>os(e,t.children[n],i))}}function rs(e,t,n){e.forEach((e,i)=>{const s=t[i];s&&(n.add(s.id),rs(a(e),a(s),n))})}function os(e,t,n){const i=n.claim(t?.id,e.id),s=t?a(t):[];let r=0;const o=e.children.map(e=>{if(!g(e))return e;const t=os(e,s[r],n);return r++,t});return{...e,id:i,children:o}}var as=class{reused;taken=/* @__PURE__ */new Set;constructor(e){this.reused=e}claim(e,t){return void 0===e||this.taken.has(e)?this.reused.has(t)||this.taken.has(t)?this.take(this.freshId()):this.take(t):this.take(e)}freshId(){let e=c();for(;this.reused.has(e)||this.taken.has(e);)e=c();return e}take(e){return this.taken.add(e),e}};function cs(e,t,n){n(ds(ls(e,t),t))}function ls(e,t){const n=function(e){const t=ps(e.children,us);return t===e.children?e:{children:t}}(function(e){const t=ps(e.children,hs);return t===e.children?e:{children:t}}(e)),i=R(n);return t?Jn(i,t):i}function ds(e,t){const n=t?me(t):void 0;return is.create({doc:e,schema:n})}function hs(e){const n=ps(e.children,e=>v(e)||U(e)?e:hs(e)),i=e.htmlId,s=t(i),r=Object.prototype.hasOwnProperty.call(e,"htmlId"),o=i===s&&(void 0!==s||!r);if(n===e.children&&o)return e;const{htmlId:a,...c}=e;return{...c,...s?{htmlId:s}:{},children:n}}function us(e){if(!e.children)return e;const t=ps(e.children,e=>v(e)||U(e)?e.marks?e:{...e,marks:[]}:us(e));return t===e.children?e:{...e,children:t}}function ps(e,t){let n=!1;const i=e.map(e=>{const i=t(e);return i!==e&&(n=!0),i});return n?i:e}function fs(e){return e.doc.children.map(ms).join("\n")}function ms(e){return r(e)?B(e):a(e).map(ms).join("\n")}function gs(e){if(!e)return!0;if(0===e.children.length)return!0;if(e.children.length>1)return!1;const t=e.children[0];return!t||"paragraph"===t.type&&0===A(t)}var ys={shorthand:!0,paste:"auto"},ks={shorthand:!1,paste:"never"};function bs(e){return void 0===e||!0===e?ys:!1===e?ks:{shorthand:e.shorthand??!0,paste:e.paste??"auto"}}var vs=class{config={};getConfig(){return this.config}setConfig(e){this.config=e}mergeConfig(e){this.config={...this.config,...e}}applyAttribute(e,t,n){if("placeholder"===e){const e=t??void 0;this.config={...this.config,placeholder:e},this.applyPlaceholder(e,n.contentElement)}if("readonly"===e){const e=null!==t;this.applyReadonly(e,n.contentElement,n.pluginManager),this.config={...this.config,readonly:e}}if("theme"===e){const e=t??void 0;this.config={...this.config,theme:e},n.themeController?.apply(e??ct.Light)}"paper-size"===e&&(null===t?(n.applyPaperSize(void 0),this.config={...this.config,paperSize:void 0}):ot(t)&&(n.applyPaperSize(t),this.config={...this.config,paperSize:t})),"dir"===e&&this.applyDir("ltr"===t||"rtl"===t?t:void 0,n.contentElement,n.editorWrapper)}applyRuntimeConfig(e,t){void 0!==e.placeholder&&this.applyPlaceholder(e.placeholder,t.contentElement),void 0!==e.readonly&&this.applyReadonly(e.readonly,t.contentElement,t.pluginManager),"paperSize"in e&&t.applyPaperSize(e.paperSize),"dir"in e&&this.applyDir(e.dir,t.contentElement,t.editorWrapper),this.config={...this.config,...e}}applyTheme(e,t){this.config={...this.config,theme:e},t?.apply(e)}getTheme(){return this.config.theme??ct.Light}get isReadOnly(){return this.config.readonly??!1}get markdownShorthand(){return bs(this.config.markdown).shorthand}get pasteMarkdown(){return bs(this.config.markdown).paste}getPaperSize(){return this.config.paperSize}applyPlaceholder(e,t){if(!t)return;const n=t.getAttribute("data-default-placeholder")??"";t.setAttribute("data-placeholder",e??n)}applyReadonly(e,t,n){t&&(t.contentEditable=e?"false":"true",e?t.setAttribute("aria-readonly","true"):t.removeAttribute("aria-readonly"),n?.setReadOnly(e))}applyDir(e,t,n){t&&(e?(n?.setAttribute("dir",e),t.setAttribute("dir",e)):(n?.removeAttribute("dir"),t.removeAttribute("dir")))}},ws=class{listeners=/* @__PURE__ */new Map;log;constructor(e=Qt){this.log=e}setLogger(e=Qt){this.log=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,/* @__PURE__ */new Set),this.listeners.get(e)?.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const n=this.listeners.get(e);if(!n)return;const i=this.log;for(const r of n)try{const n=r(t);this.observeListenerResult(i,e,n)}catch(s){this.reportListenerError(i,e,s)}}observeListenerResult(e,t,n){null===n||"object"!=typeof n&&"function"!=typeof n||Promise.resolve(n).then(void 0,n=>{this.reportListenerError(e,t,n)})}reportListenerError(e,t,n){try{const i=e.error(`[EditorEventEmitter] Listener error on "${String(t)}"`,n);null===i||"object"!=typeof i&&"function"!=typeof i||Promise.resolve(i).then(void 0,()=>{})}catch{}}clear(){this.listeners.clear()}};function Is(e,t,n){if(r(e))return t.selectedLeafIds.has(e.id)?function(e,t){const n=A(e),i=e.id===t.firstBlockId?t.firstOffset:0,s=e.id===t.lastBlockId?t.lastOffset:n;if(0===i&&s===n)return e;const r=f(e,i,s),o=h(r),{htmlId:a,...c}=e;return{...c,children:o}}(e,t):null;const i=a(e),s=[];let o=i.length!==e.children.length;for(const r of i){const e=Is(r,t,n);e?(s.push(e),e!==r&&(o=!0)):o=!0}if(0===s.length)return null;if(!o)return e;const{htmlId:c,...l}=e,d={...l,children:s};return n?.getNodeSpec(e.type)?.transformSelectionSlice?.(e,d)??d}var Ss=class{element;getState;dispatch;schemaRegistry;syncSelection;isReadOnly;handleCopy;handleCut;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.schemaRegistry=t.schemaRegistry,this.syncSelection=t.syncSelection,this.isReadOnly=t.isReadOnly??(()=>!1),this.handleCopy=this.onCopy.bind(this),this.handleCut=this.onCut.bind(this),e.addEventListener("copy",this.handleCopy),e.addEventListener("cut",this.handleCut)}onCopy(e){if(!sn(e,this.element))return;this.syncSelection?.();const t=this.getState(),n=t.selection;if(de(n))return;if(te(n)&&Z(n))return;e.preventDefault();const i=e.clipboardData;i&&(ee(n)?this.writeNodeSelectionToClipboard(i,t):this.writeTextSelectionToClipboard(i,t))}onCut(e){if(!sn(e,this.element))return;if(this.isReadOnly())return;this.syncSelection?.();const t=this.getState(),n=t.selection;if(de(n))return;if(te(n)&&Z(n))return;e.preventDefault();const i=e.clipboardData;if(i)if(ee(n)){this.writeNodeSelectionToClipboard(i,t);const e=He(t,n);e&&this.dispatch(e)}else{this.writeTextSelectionToClipboard(i,t);const e=Ke(t);e&&this.dispatch(e)}}writeNodeSelectionToClipboard(e,t){const n=t.selection;if(!ee(n))return;const i=t.getBlock(n.nodeId);if(!i)return;if(!r(i))return this.schemaRegistry&&e.setData("text/html",vt({children:[i]},this.schemaRegistry)),void e.setData("text/plain",this.plainTextFromBlockTree(i));const s={type:i.type,...i.htmlId?{htmlId:i.htmlId}:{},...i.attrs?{attrs:{...i.attrs}}:{}};e.setData("application/x-notectl-block",JSON.stringify(s));const o=this.schemaRegistry?.getNodeSpec(i.type);o?.toHTML&&e.setData("text/html",St(o.toHTML(i,""),i.htmlId));const a=i.attrs,c="string"==typeof a?.alt?a.alt:"";e.setData("text/plain",c)}plainTextFromBlockTree(e){return r(e)?B(e):a(e).map(e=>this.plainTextFromBlockTree(e)).join("\n")}writeTextSelectionToClipboard(e,t){const n=t.selection;if(ee(n))return;if(de(n))return;if(Z(n))return;if(this.selectionRequiresDocumentSerializer(t))return void this.writeCompositeSelectionToClipboard(e,t);const i=t.getBlockOrder(),s=oe(n,i),r=i.indexOf(s.from.blockId),o=i.indexOf(s.to.blockId),a=[],c=[],l=[];for(let h=r;h<=o;h++){const e=i[h];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const d=A(n),u=h===r?s.from.offset:0,p=h===o?s.to.offset:d,f=this.extractSegmentsForRange(n,u,p),m=this.plainTextFromSegments(f);a.push(m),l.push({block:n,start:u,end:p}),c.push({type:n.type,text:m,...0===u&&p===d&&n.htmlId?{htmlId:n.htmlId}:{},...n.attrs?{attrs:{...n.attrs}}:{},...f.length>0?{segments:f}:{}})}const d=a.join("\n");if(e.setData("text/plain",d),this.schemaRegistry){const n=kt(this.schemaRegistry),a=r!==o,d=c.some(e=>void 0!==e.htmlId||void 0!==e.type&&"paragraph"!==e.type);if(a||this.containsInlineSegments(c)||d){const t=this.serializeBlocksToClipboardHTML(l,n,c);e.setData("text/html",t)}else{const o=i[r],a=o?t.getBlock(o):void 0;if(a){const t=this.serializeBlockRangeToHTML(a,s.from.offset,s.to.offset,n);e.setData("text/html",t)}}}}selectionRequiresDocumentSerializer(e){const t=this.getTextSelection(e);if(!t||Z(t))return!1;const n=e.getBlockOrder(),i=oe(t,n),s=Q(e.doc,i.from.blockId),o=Q(e.doc,i.to.blockId);if(!s||!o)return!1;if(s[0]===o[0]){const t=e.doc.children.find(e=>e.id===s[0]);return!(!t||r(t))}const a=e.doc.children.findIndex(e=>e.id===s[0]),c=e.doc.children.findIndex(e=>e.id===o[0]);for(let l=a;l<=c;l++){const t=e.doc.children[l];if(t){if(!r(t))return!0;if((this.schemaRegistry?.getNodeSpec(t.type))?.isVoid)return!0}}return!1}getTextSelection(e){const t=e.selection;if(te(t))return t}extractPlainTextForRange(e,t,n){return this.plainTextFromSegments(this.extractSegmentsForRange(e,t,n))}plainTextFromSegments(e){return e.map(e=>"inline"===e.kind?"":e.text).join("")}writeCompositeSelectionToClipboard(e,t){const n=this.getTextSelection(t);if(!n)return;const i=t.getBlockOrder(),s=oe(n,i),r=i.indexOf(s.from.blockId),o=i.indexOf(s.to.blockId),a=[];for(let c=r;c<=o;c++){const e=i[c];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const l=c===r?s.from.offset:0,d=c===o?s.to.offset:A(n);a.push(this.extractPlainTextForRange(n,l,d))}if(e.setData("text/plain",a.join("\n")),this.schemaRegistry){const i=function(e,t,n){const i=e.getBlockOrder(),s=oe(t,i),r=i.indexOf(s.from.blockId),o=i.indexOf(s.to.blockId);if(-1===r||-1===o||r>o)return{children:[]};const a=e.getNodePath(s.from.blockId),c=e.getNodePath(s.to.blockId),l=a?.[0],d=c?.[0];if(!l||!d)return{children:[]};const h=e.doc.children.findIndex(e=>e.id===l),u=e.doc.children.findIndex(e=>e.id===d);if(-1===h||-1===u||h>u)return{children:[]};const p={firstBlockId:s.from.blockId,firstOffset:s.from.offset,lastBlockId:s.to.blockId,lastOffset:s.to.offset,selectedLeafIds:new Set(i.slice(r,o+1))},f=[];for(let m=h;m<=u;m++){const t=e.doc.children[m];if(!t)continue;const i=Is(t,p,n);i&&f.push(i)}return{children:f}}(t,n,this.schemaRegistry);if(i.children.length>0){const t=vt(i,this.schemaRegistry);e.setData("text/html",t)}}}serializeBlockRangeToHTML(e,t,n,i){const s=[];return $(e,t,n,{onText:(e,t)=>{this.schemaRegistry&&s.push(It(e,t,this.schemaRegistry,i))},onInline:e=>{const t=this.schemaRegistry?.getInlineNodeSpec(e.inlineType);t?.toHTMLString&&s.push(t.toHTMLString(e))}}),s.join("")}extractSegmentsForRange(e,t,n){const i=[];return $(e,t,n,{onText:(e,t)=>{i.push({text:e,marks:t.map(e=>({type:e.type,...e.attrs?{attrs:{...e.attrs}}:{}}))})},onInline:e=>{i.push({kind:"inline",inlineType:e.inlineType,...Object.keys(e.attrs).length>0?{attrs:{...e.attrs}}:{}})}}),i}containsInlineSegments(e){return e.some(e=>e.segments?.some(e=>"inline"===e.kind))}serializeBlocksToClipboardHTML(e,t,n){const i=[];let s,r=[];const o=()=>{r.length>0&&s&&(i.push(`<${s}>${r.join("")}</${s}>`),r=[],s=void 0)};for(const c of e){const{block:e,start:n,end:a}=c,l=0===n&&a===A(e),{htmlId:d,...h}=e,u={...h,...l&&e.htmlId?{htmlId:e.htmlId}:{}},p=this.serializeBlockRangeToHTML(e,n,a,t),f=this.schemaRegistry?.getNodeSpec(u.type);if(f?.wrapper){const e=f.wrapper(u).tag;s!==e&&(o(),s=e),f.toHTML?r.push(St(f.toHTML(u,p),u.htmlId)):r.push(St(`<li>${p}</li>`,u.htmlId))}else o(),f?.toHTML?i.push(St(f.toHTML(u,p),u.htmlId)):i.push(St(`<p>${p}</p>`,u.htmlId))}o();const a=JSON.stringify(n).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/'/g,"&#39;").replace(/"/g,"&quot;");return i.push(`<span data-notectl-rich="${a}" hidden></span>`),i.join("")}destroy(){this.element.removeEventListener("copy",this.handleCopy),this.element.removeEventListener("cut",this.handleCut)}},xs=class{_composing=!1;_activeBlockId=null;get isComposing(){return this._composing}get activeBlockId(){return this._activeBlockId}start(e){this._composing=!0,this._activeBlockId=e}end(){this._composing=!1,this._activeBlockId=null}};function Rs(e){let t="";for(const n of m(e))t+=v(n)?n.text:"";return t}function Cs(e){const t=/* @__PURE__ */new Set;let n=0;for(const i of m(e))v(i)?n+=i.text.length:(t.add(n),n+=1);return t}var Ms=class e{failureReporter;static silent=new e;constructor(e=()=>{}){this.failureReporter=e}execute(e,t){try{return{ok:!0,value:t()}}catch(n){return this.reportFailure(e,n),{ok:!1}}}executeMaybeAsync(e,t){const n=this.execute(e,t);if(!n.ok)return n;try{return"object"!=typeof(i=n.value)&&"function"!=typeof i||null===i||!("then"in i)||"function"!=typeof i.then?{ok:!0,value:n.value}:Promise.resolve(n.value).then(e=>({ok:!0,value:e}),t=>(this.reportFailure(e,t),{ok:!1}))}catch(s){return this.reportFailure(e,s),{ok:!1}}var i}reportFailure(e,t){try{const n=this.failureReporter({...e,cause:t});null===n||"object"!=typeof n&&"function"!=typeof n||Promise.resolve(n).then(void 0,()=>{})}catch{}}};function Ps(e,t,n){return e>=t&&e<=n?n-e:0}function Es(e,t,n,i){if(!i)return Ts(t,e,n,-1);const{change:s,target:r}=i,o=s.from+s.text.length;if(e>=s.from&&e<=o)return Y(r.blockId,r.from+(e-s.from));if(e<s.from)return Ts(t,e,n,-1);const a=Ts(t,e-s.text.length+(s.to-s.from),n,1);return a&&a.blockId===r.blockId?Y(a.blockId,a.offset+s.text.length-(r.to-r.from)):a}function Ts(e,t,n,i){const s=jt(e,t,n,i);return s?Y(s.blockId,s.from):null}var Bs={kind:"conflict"};function As(e,t){if(null===Os(e,t.blockId)||null===t.mapping)return Bs;const n=Rs(t.baseline),i=function(e,t,n){const i=n.equals??((n,i)=>e.charAt(n)===t.charAt(i)),s=Math.min(e.length,t.length);let r=0;for(;r<s&&i(r,r);)r++;if(r===e.length&&r===t.length)return null;let o=e.length,a=t.length;for(;o>0&&a>0&&i(o-1,a-1);)o--,a--;if(o<r&&e.length<t.length)r-=Ps(n.preferredFrom,o,r),a=r+(a-o),o=r;else if(a<r){const e=o-a;r=function(e,t,n,i){const s=e.preferredDeletionEnd;return void 0!==s&&s-i>=t&&s-i<=n?s-i:n-Ps(e.preferredFrom,t,n)}(n,a,r,e),o=r+e,a=r}return{from:r,to:o,text:t.slice(r,a)}}(n,t.rendered.text,{preferredFrom:t.from,preferredDeletionEnd:t.from===t.to?t.from:void 0,equals:Ls(n,Cs(t.baseline),t.rendered)});if(i&&function(e,t){const n=t.inlineNodeOrigins;if(!n)return e.text.includes("");for(let i=e.from;i<e.from+e.text.length;i++)if(n.has(i))return!0;return!1}(i,t.rendered))return Bs;const s=i?function(t,n,i,s){const r=t.from===t.to?jt(n,t.from,s,1):zt(n,t.from,t.to,s);if(!r)return null;const o=(c=r.blockId,Os(e,c)),a=i.slice(t.from,t.to);var c;return o?.slice(r.from,r.to)!==a?null:{blockId:r.blockId,from:r.from,to:r.to,text:t.text}}(i,t.blockId,n,t.mapping):null;return i&&!s?Bs:{kind:"commit",tr:Ns(e,s?Ds(e,s):null,null===t.rendered.caretOffset?null:Es(t.rendered.caretOffset,t.blockId,t.mapping,i&&s?{change:i,target:s}:null)),changedBlockId:s?.blockId??null}}function Os(e,t){const n=e.getBlock(t);return n&&r(n)?Rs(n):null}function Ds(e,t){const{blockId:n}=t,i=t.text.replaceAll(" "," ");if(i.length>0){const s=e.withSelection(re({blockId:n,offset:t.from},{blockId:n,offset:t.to}));return je(s,i,"input")}return e.transaction("input").deleteTextAt(n,t.from,t.to).setSelection(se(n,t.from)).build()}function Ns(e,t,n){if(null===n)return t;const i=se(n.blockId,n.offset);return t?{...t,selectionAfter:i}:ie(e.selection,i)?null:e.transaction("input").setSelection(i).build()}function Ls(e,t,n){const i=n.inlineNodeOrigins;return(s,r)=>{if(i){if(t.has(s))return i.get(r)===s;if(i.has(r))return!1}const o=e.charAt(s),a=n.text.charAt(r);return o===a||" "===o&&" "===a}}function Hs(e,t){switch(t.type){case"shift":return function(e,t){if(e.blockId!==t.blockId)return[e];const n=t.newLen-(t.to-t.from),i=[];if(e.from<t.from&&i.push({blockId:e.blockId,from:e.from,to:Math.min(e.to,t.from)}),e.to>t.to){const s=Math.max(e.from,t.to)+n;i.push({blockId:e.blockId,from:s,to:e.to+n})}return i}(e,t);case"split":return function(e,t){if(e.blockId!==t.blockId)return[e];const n=[];return e.from<t.offset&&n.push({blockId:e.blockId,from:e.from,to:Math.min(e.to,t.offset)}),e.to>t.offset&&n.push({blockId:t.newBlockId,from:Math.max(e.from,t.offset)-t.offset,to:e.to-t.offset}),n}(e,t);case"merge":return[zs(e,t)];case"blockRemoval":return t.removedBlockIds.has(e.blockId)?[]:[e];case"identity":case"childIndexShift":case"moveNode":return[e]}}function zs(e,t){return e.blockId!==t.sourceBlockId?e:{blockId:t.targetBlockId,from:e.from+t.targetLengthBefore,to:e.to+t.targetLengthBefore}}function _s(e,t,n){if(!n)return null;const i=t.mapping?function({blockId:e,from:t,to:n},i){const s=function(e,t,n,i){let s=t<n?[{blockId:e,from:t,to:n}]:[];for(const r of i.maps)s=s.flatMap(e=>Hs(e,r));return s}(e,t,n,i),r=s[0];if(r)return{at:Y(r.blockId,r.from),replaced:s};const o=jt(e,t,i,1);return o?{at:Y(o.blockId,o.from),replaced:s}:null}(t,t.mapping):null;return i&&function(e,{at:t,replaced:n}){return[{blockId:t.blockId,from:t.offset,to:t.offset},...n].every(t=>{const n=e.getBlock(t.blockId);return void 0!==n&&r(n)&&t.to<=A(n)})}(e,i)?function(e,t,n){const{at:i,replaced:s}=t,r=s[0],o=r?re(i,Y(r.blockId,r.to)):se(i.blockId,i.offset),a=Ue(e.withSelection(o)),c=e.transaction("input");for(const d of[...s].sort((e,t)=>t.from-e.from))c.deleteTextAt(d.blockId,d.from,d.to);const l=i.offset-function(e,t,n){return e.filter(e=>e.blockId===t&&e.to<=n).reduce((e,t)=>e+t.to-t.from,0)}(s,i.blockId,i.offset);return c.insertText(i.blockId,l,n,a),c.setSelection(se(i.blockId,l+n.length)),c.build()}(e,i,n):je(e,n,"input")}var Fs=class{options;anchor=null;stepMaps=[];commitHandled=!1;constructor(e){this.options=e}start(){this.anchor=null;const e=this.options.getState(),t=e.selection;te(t)&&(this.commitHandled=!1,this.stepMaps=[],this.options.tracker.start(t.anchor.blockId),this.anchor=function(e,t){const{anchor:n,head:i}=t;if(n.blockId!==i.blockId)return null;const s=e.getBlock(n.blockId),o=e.getNodePath(n.blockId)?.[0];return s&&r(s)&&void 0!==o?{blockId:n.blockId,rootId:o,from:Math.min(n.offset,i.offset),to:Math.max(n.offset,i.offset),baseline:s}:null}(e,t),this.anchor&&this.options.compositionDOM?.captureBlock(this.anchor.blockId))}observeStateChange(e,t,n){const i=this.anchor;return!(!i||t.getNodePath(i.blockId)?.[0]===i.rootId&&(!this.stepMaps||(0===n.steps.length&&e.doc!==t.doc?(function(e,t,n){const i=e.getBlock(n),s=t.getBlock(n);return!!i&&!!s&&Rs(i)===Rs(s)}(e,t,i.blockId)||(this.stepMaps=null),1):(this.stepMaps.push(...n.mapping.maps),1))))}markCommitHandled(){this.commitHandled=!0}end(e){const t=this.anchor;if(this.anchor=null,this.options.tracker.end(),this.options.isReadOnly())return;if(this.commitHandled)return this.commitHandled=!1,void this.restore(t);const n=this.buildCommit(t,e);n.tr&&this.options.dispatch(n.tr),n.tr&&n.tr.steps.length>0&&!n.restore||this.restore(t)}buildCommit(e,t){const n=this.options.getState();if(!e)return{tr:js(n,t),restore:!1};const i={...e,mapping:this.stepMaps?Lt.from(this.stepMaps):null},s=this.options.compositionDOM?.readBlock(e.blockId)??null;if(null===s)return{tr:_s(n,i,t),restore:!1};const r=As(n,{...i,rendered:s});return"commit"===r.kind?{tr:r.tr,restore:r.changedBlockId!==e.blockId}:{tr:_s(n,i,t),restore:!0}}restore(e){e&&this.options.compositionDOM?.restoreBlock(e.blockId)}};function js(e,t){return t?je(e,t,"input"):null}var $s=class{element;getState;dispatch;syncSelection;inputRuleRegistry;isReadOnly;shouldApplyInputRules;compositionTracker;getTextInputInterceptors;callbackExecutor;resolveTargetRange;composition;pendingBreaks=[];handleBeforeInput;handleCompositionStart;handleCompositionEnd;handleKeydown;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.syncSelection=t.syncSelection,this.inputRuleRegistry=t.inputRuleRegistry,this.isReadOnly=t.isReadOnly??(()=>!1),this.shouldApplyInputRules=t.shouldApplyInputRules??(()=>!0),this.compositionTracker=t.compositionTracker??new xs,this.getTextInputInterceptors=t.getTextInputInterceptors??(()=>[]),this.callbackExecutor=t.callbackExecutor??Ms.silent,this.resolveTargetRange=t.resolveTargetRange,this.composition=new Fs({getState:this.getState,dispatch:this.dispatch,isReadOnly:this.isReadOnly,tracker:this.compositionTracker,compositionDOM:t.compositionDOM}),this.handleBeforeInput=this.onBeforeInput.bind(this),this.handleCompositionStart=this.onCompositionStart.bind(this),this.handleCompositionEnd=this.onCompositionEnd.bind(this),this.handleKeydown=this.onKeydown.bind(this),e.addEventListener("beforeinput",this.handleBeforeInput),e.addEventListener("compositionstart",this.handleCompositionStart),e.addEventListener("compositionend",this.handleCompositionEnd),e.addEventListener("keydown",this.handleKeydown)}onBeforeInput(e){if(!sn(e,this.element))return;if(this.isReadOnly())return;if(this.compositionTracker.isComposing&&"insertCompositionText"===e.inputType)return;if(function(e){switch(e){case"deleteContentBackward":case"deleteContentForward":case"deleteWordBackward":case"deleteWordForward":case"deleteSoftLineBackward":case"deleteSoftLineForward":return!0;default:return!1}}(e.inputType)&&this.isCompositionActive(e))return;if(("insertParagraph"===(t=e.inputType)||"insertLineBreak"===t)&&this.isCompositionActive(e))return e.preventDefault(),void this.pendingBreaks.push(e.inputType);var t;if(!function(e){switch(e){case"insertText":case"insertReplacementText":case"insertFromComposition":case"insertParagraph":case"insertLineBreak":case"deleteContentBackward":case"deleteContentForward":case"deleteWordBackward":case"deleteWordForward":case"deleteSoftLineBackward":case"deleteSoftLineForward":case"deleteByCut":case"insertFromPaste":case"insertFromDrop":case"formatBold":case"formatItalic":case"formatUnderline":case"historyUndo":case"historyRedo":return!0;default:return!1}}(e.inputType))return;const n="insertReplacementText"===e.inputType?function(e){if(e.data)return e.data;const t=e.dataTransfer?.getData("text/plain");return t||null}(e):null,i=n?function(e){return"function"==typeof e.getTargetRanges?e.getTargetRanges()[0]:void 0}(e):void 0,s=i&&this.resolveTargetRange?this.resolveTargetRange(i):null;"insertText"!==e.inputType&&"insertCompositionText"!==e.inputType&&"insertFromComposition"!==e.inputType&&this.syncSelection(),e.preventDefault();const r=this.getState();let o=null;switch(e.inputType){case"insertText":e.data&&(o=this.runTextInputInterceptors(e.data,r)??je(r,e.data,"input"));break;case"insertReplacementText":{if(!n)break;if(this.compositionTracker.isComposing)break;if(i&&!s&&(!te(r.selection)||Z(r.selection)))break;const e=s?r.withSelection(s).withStoredMarks(null):r;o=this.runTextInputInterceptors(n,e)??je(e,n,"input");break}case"insertFromComposition":e.data&&(this.composition.markCommitHandled(),o=this.runTextInputInterceptors(e.data,r)??je(r,e.data,"input"));break;case"insertParagraph":case"insertLineBreak":o=Ks(r,e.inputType);break;case"deleteContentBackward":o=Wn(r);break;case"deleteContentForward":o=Gn(r);break;case"deleteWordBackward":o=function(e){return Un(e,{merge:ze,range:(e,t)=>t>0?[Xe(e,t),t]:null})}(r);break;case"deleteWordForward":o=function(e){return Un(e,{merge:Ve,range:(e,t)=>t<A(e)?[t,Ye(e,t)]:null})}(r);break;case"deleteSoftLineBackward":o=function(e){return Un(e,{merge:ze,range:(e,t)=>t>0?[0,t]:null})}(r);break;case"deleteSoftLineForward":o=function(e){return Un(e,{merge:Ve,range:(e,t)=>{const n=A(e);return t<n?[t,n]:null}})}(r)}o&&(this.dispatch(o),"insertText"!==e.inputType&&"insertReplacementText"!==e.inputType||this.checkInputRules())}isCompositionActive(e){return this.compositionTracker.isComposing||e.isComposing}onCompositionStart(e){sn(e,this.element)&&(this.pendingBreaks=[],this.composition.start())}onCompositionEnd(e){sn(e,this.element)&&this.finishComposition(e.data)}onKeydown(e){this.compositionTracker.isComposing&&!function(e){return e.isComposing||229===e.keyCode||"Process"===e.key}(e)&&sn(e,this.element)&&this.finishComposition("")}abandonComposition(){this.compositionTracker.isComposing&&this.finishComposition("")}finishComposition(e){const t=this.pendingBreaks;this.pendingBreaks=[],this.composition.end(e);for(const n of t){if(this.isReadOnly())break;const e=Ks(this.getState(),n);e&&this.dispatch(e)}}runTextInputInterceptors(e,t){const n=this.getTextInputInterceptors();if(0===n.length)return null;for(const i of n){const n=this.callbackExecutor.execute({pluginId:i.pluginId,name:i.name,kind:"text-input-interceptor"},()=>i.interceptor(e,t));if(n.ok&&n.value)return n.value}return null}checkInputRules(){if(!this.shouldApplyInputRules())return;if(!this.inputRuleRegistry)return;const e=this.inputRuleRegistry.getInputRuleEntries();if(0===e.length)return;const t=this.getState();if(!te(t.selection))return;const{anchor:n}=t.selection,i=t.getBlock(n.blockId);if(!i)return;const s=Rs(i).slice(0,n.offset);for(const r of e){const e=this.callbackExecutor.execute({pluginId:r.pluginId,name:r.name,kind:"input-rule"},()=>{const e=r.rule.pattern.exec(s);if(!e)return null;const n=e.index,i=n+e[0].length;return r.rule.handler(t,e,n,i)});if(e.ok&&e.value)return void this.dispatch(e.value)}}onStateChange(e,t,n){this.composition.observeStateChange(e,t,n)&&queueMicrotask(()=>this.abandonComposition())}destroy(){this.pendingBreaks=[],this.element.removeEventListener("beforeinput",this.handleBeforeInput),this.element.removeEventListener("compositionstart",this.handleCompositionStart),this.element.removeEventListener("compositionend",this.handleCompositionEnd),this.element.removeEventListener("keydown",this.handleKeydown)}};function Ks(e,t){return"insertParagraph"===t?$e(e):qe(e)}var Vs={Period:".",Comma:",",Slash:"/",Semicolon:";",Quote:"'",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Minus:"-",Equal:"=",Backquote:"`"},qs={1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")","`":"~","-":"_","=":"+","[":"{","]":"}","\\":"|",";":":","'":'"',",":"<",".":">","/":"?"},Us=function(){const e=/* @__PURE__ */new Map;for(let t=0;t<26;t++){const n=String.fromCharCode(65+t);e.set(`Key${n}`,n)}for(let t=0;t<=9;t++)e.set(`Digit${t}`,String(t)),e.set(`Numpad${t}`,String(t));for(const[t,n]of Object.entries(Vs))e.set(t,n);return e}();function Ws(e){const t=[];return(e.metaKey||e.ctrlKey)&&t.push("Mod"),e.shiftKey&&t.push("Shift"),e.altKey&&t.push("Alt"),t}function Gs(e){const t=Ws(e);let n=e.key;return" "===n?n="Space":1===n.length&&(n=n.toUpperCase()),t.push(n),t.join("-")}function Js(e){return e.ctrlKey||e.metaKey?e.ctrlKey&&e.altKey&&!e.metaKey?null:Us.get(e.code)??null:null}var Qs={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},Xs=class{element;getState;dispatch;undo;redo;keymapRegistry;isReadOnly;compositionTracker;getTextDirectionFn;navigateFromGapCursorFn;callbackExecutor;handleKeydown;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.undo=t.undo,this.redo=t.redo,this.keymapRegistry=t.keymapRegistry,this.isReadOnly=t.isReadOnly??(()=>!1),this.compositionTracker=t.compositionTracker,this.getTextDirectionFn=t.getTextDirection??(()=>"ltr"),this.navigateFromGapCursorFn=t.navigateFromGapCursor,this.callbackExecutor=t.callbackExecutor??Ms.silent,this.handleKeydown=this.onKeydown.bind(this),e.addEventListener("keydown",this.handleKeydown)}onKeydown(e){if(!sn(e,this.element))return;if(this.compositionTracker?.isComposing)return;if(this.handleNodeSelectionKeys(e))return;if(this.handleGapCursorKeys(e))return;if(this.isReadOnly()){if(this.keymapRegistry){const t=this.keymapRegistry.getKeymapEntriesByPriority();if(this.dispatchKeymaps(e,[t.navigation]))return}return void this.handleEscape(e)}if(this.keymapRegistry){const t=this.keymapRegistry.getKeymapEntriesByPriority(),n=[t.context,t.navigation,t.default,t.fallback];if(this.dispatchKeymaps(e,n))return}if(this.handleGapCursorArrowFallback(e))return;if(this.handleTab(e))return;if(this.handleEscape(e))return;if(!e.metaKey&&!e.ctrlKey)return;let t=this.resolveBuiltinShortcut(e.key.toLowerCase(),e.shiftKey);if(null===t){const n=Js(e);null!==n&&(t=this.resolveBuiltinShortcut(n.toLowerCase(),e.shiftKey))}if(null===t)return;if(e.preventDefault(),"undo"===t)return void this.undo();if("redo"===t)return void this.redo();const n=_e(this.getState());n&&this.dispatch(n)}resolveBuiltinShortcut(e,t){return"z"!==e||t?"z"===e&&t||"y"===e&&!t?"redo":"a"!==e||t?null:"selectAll":"undo"}dispatchKeymaps(e,t){if(this.runDescriptor(e,t,Gs(e)))return!0;for(const n of function(e){const t=Js(e);if(null===t)return[];const n=Ws(e),i=[[...n,t].join("-")];if(e.shiftKey){const e=qs[t];void 0!==e&&i.push([...n,e].join("-"))}return i}(e))if(this.runDescriptor(e,t,n))return!0;return!1}runDescriptor(e,t,n){for(const i of t)for(let t=i.length-1;t>=0;t--){const s=i[t],r=s?.keymap[n];if(!s||!r)continue;const o=this.callbackExecutor.execute({pluginId:s.pluginId,name:`${s.name} (${n})`,kind:"keymap"},r);if(o.ok&&!0===o.value)return e.preventDefault(),!0}return!1}handleNodeSelectionKeys(e){const t=this.getState(),n=t.selection;if(!ee(n))return!1;const i=e.key;if(!("ArrowLeft"!==i&&"ArrowUp"!==i&&"ArrowRight"!==i&&"ArrowDown"!==i||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)){const s=Qs[i];if(!s)return!1;const r=this.isSelectedBlockRtl(n.nodeId),o=Le(t,s,r);return!!o&&(e.preventDefault(),this.dispatch(o),!0)}if("Backspace"===i||"Delete"===i){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const i=He(t,n);return i&&this.dispatch(i),!0}if("Enter"===i){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=$e(t);return n&&this.dispatch(n),!0}if("Escape"===i){e.preventDefault();const n=Le(t,"right");return n&&this.dispatch(n),!0}return!1}handleGapCursorKeys(e){const t=this.getState(),n=t.selection;if(!de(n))return!1;const i=e.key;if("ArrowLeft"===i||"ArrowRight"===i||"ArrowUp"===i||"ArrowDown"===i)return!1;if("Escape"===i||"Tab"===i)return!1;if(e.ctrlKey||e.metaKey||e.altKey)return!1;if("Enter"===i){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=$e(t);return n&&this.dispatch(n),!0}if("Backspace"===i){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const i=We(t,n);return i&&this.dispatch(i),!0}if("Delete"===i){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const i=Fe(t,n);return i&&this.dispatch(i),!0}if(1===i.length){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=je(t,i);return this.dispatch(n),!0}return!1}handleGapCursorArrowFallback(e){const t=this.getState(),n=t.selection;if(!de(n))return!1;const i=e.key;if("ArrowLeft"!==i&&"ArrowRight"!==i&&"ArrowUp"!==i&&"ArrowDown"!==i)return!1;const s=Qs[i];if(!s)return!1;if(!this.navigateFromGapCursorFn)return!1;const r=this.navigateFromGapCursorFn(t,s,this.element);return!(!r||ie(r.selectionAfter,n)||(e.preventDefault(),this.dispatch(r),0))}handleTab(e){if("Tab"!==e.key)return!1;if(e.metaKey||e.ctrlKey||e.altKey)return!1;if(e.preventDefault(),e.shiftKey)return!0;const t=this.getState(),n=je(t,"\t");return this.dispatch(n),!0}handleEscape(e){return"Escape"===e.key&&(this.element.blur(),!0)}isSelectedBlockRtl(e){const t=this.element.querySelector(`[data-block-id="${e}"]`);return t instanceof HTMLElement&&"rtl"===this.getTextDirectionFn(t)}destroy(){this.element.removeEventListener("keydown",this.handleKeydown)}};function Ys(e){const t=e.executor??Ms.silent,n=e.isActive??(()=>!0),i=[...e.files],s=i.map(t=>e.registry.matchFileHandlerEntries(t.type)),r=(o,a,c)=>{let l=o,d=a,h=c;for(;l<i.length;){if(!n())return{handled:h,cancelled:!0};const o=i[l];if(!o){l++,d=0;continue}const a=(s[l]??[])[d];if(!a){l++,d=0;continue}const c=t.executeMaybeAsync({pluginId:a.pluginId,name:a.name,kind:"file-handler"},()=>a.handler(o,e.getPosition(),e.source));if(c instanceof Promise)return c.then(e=>Zs(e,l,d,h,r));c.ok&&!0===c.value?(h=!0,l++,d=0):d++}return n()?{handled:h,cancelled:!1}:{handled:h,cancelled:!0}};return r(0,0,!1)}function Zs(e,t,n,i,s){return e.ok&&!0===e.value?s(t+1,0,!0):s(t,n+1,i)}function er(e,t){return t.isEmpty?e:ee(e)?function(e,t){const n={blockId:e.nodeId,offset:0},i=t.mapResult(n,-1);return i.deleted||i.pos.blockId!==e.nodeId?null:ne(e.nodeId,e.path)}(e,t):de(e)?function(e,t){const n={blockId:e.blockId,offset:0},i=t.mapResult(n,-1);return i.deleted||i.pos.blockId!==e.blockId?null:ae(e.blockId,e.side,e.path)}(e,t):tr(e,t)}function tr(e,t){if(Z(e)){const n=t.map(e.anchor,-1);return n===e.anchor?e:se(n.blockId,n.offset)}const n=t.map(e.anchor,-1),i=t.map(e.head,1);return n===e.anchor&&i===e.head?e:re(n,i)}var nr=/(^|\n) {0,3}(```|~~~)/,ir=/(^|\n)\s*\|?[ :|]*-{3,}[ :|-]*(\n|$)/,sr=/(^|\n) {0,3}(#{1,6} |[-*+] |\d{1,9}[.)] |> )/g;function rr(e,t){if(0===t.blocks.length)return e.transaction("paste").setSelection(e.selection).build();const n=t.blocks[0];return n?1===t.blocks.length&&n.type===he("paragraph")?function(e,t){const n=e.selection;if(ee(n))return e.transaction("paste").setSelection(n).build();if(de(n))return dr(e,n,[t]);const{builder:i,blockId:s,offset:r}=or(e),o=ar(i,s,r,t.segments);return cr(e,i,s,t.attrs),i.setSelection(se(s,o)),i.build()}(e,n):1===t.blocks.length?function(e,t){const n=e.selection;if(ee(n))return e.transaction("paste").setSelection(n).build();if(de(n))return dr(e,n,[t]);const{builder:i,blockId:s,offset:r}=or(e);i.setBlockType(s,t.type,t.attrs);const o=ar(i,s,r,t.segments);return i.setSelection(se(s,o)),i.build()}(e,n):function(e,t){const n=e.selection;if(ee(n))return e.transaction("paste").setSelection(n).build();if(de(n))return dr(e,n,t.blocks);const{builder:i,blockId:s,offset:r,state:o}=or(e),a=Se(o,s),l=o.getBlock(s);if(!a||!l)return i.build();const d=t.blocks[0],u=t.blocks[t.blocks.length-1];if(!d||!u)return i.build();const p=t.blocks.slice(1,-1).map(t=>"paragraph"!==t.type||"list_item"!==l.type?t:{...t,type:l.type,attrs:{...l.attrs,...lr(e,l.type,t.attrs)}}),f=o.getParent(s),m=["paragraph"===d.type?l.type:d.type,...p.map(e=>e.type),"paragraph"===u.type?l.type:u.type];if(f&&m.some(t=>!Ne(e.schema,f.type,t))){const e=Ie(o,s);return e&&hr(i,e.parentPath,e.anchorIndex+1,t.blocks),i.build()}const g=ar(i,s,r,d.segments),y=c();i.splitBlock(s,g,y),d.type!==he("paragraph")?i.setBlockType(s,d.type,d.attrs):cr(e,i,s,d.attrs);let k=a.anchorIndex+1;for(const b of p){const e=L(b.type,h(b.segments),c(),b.attrs);i.insertNode(a.parentPath,k,e),k++}return ar(i,y,0,u.segments),u.type!==he("paragraph")?i.setBlockType(y,u.type,u.attrs):cr(e,i,y,u.attrs),i.setSelection(se(y,ui(u.segments))),i.build()}(e,t):e.transaction("paste").setSelection(e.selection).build()}function or(e){const t=e.transaction("paste");return{builder:t,...rn(e,t)}}function ar(e,t,n,i){let s=n,r=[];const o=()=>{if(0===r.length)return;const n=r.map(e=>"text"===e.kind?e.text:"").join("");n.length>0&&(e.insertText(t,s,n,[],r),s+=n.length),r=[]};for(const a of i)"inline"===a.kind?(o(),e.insertInlineNode(t,s,a.node),s+=1):r.push(a);return o(),s}function cr(e,t,n,i){if(!i||0===Object.keys(i).length)return;const s=e.apply(t.build()),r=s.getBlock(n),o=s.getNodePath(n);if(!r||!o)return;const a=lr(e,r.type,i);Object.keys(a).length>0&&t.setNodeAttr(o,{...r.attrs,...a})}function lr(e,t,n){const i=e.schema.getNodeSpec?.(t),s={};for(const[r,o]of Object.entries(n??{}))i&&!i.attrs?.[r]||(s[r]=o);return s}function dr(e,t,n){const i=function(e,t){const n=Q(e.doc,t.blockId);if(!n)return null;const i=Oe(n),s=ve(e,i),r=De(s,t.blockId);return r<0?null:{parentPath:i,insertIndex:"before"===t.side?r:r+1}}(e,t);if(!i)return e.transaction("paste").setSelection(t).build();const s=e.transaction("paste");return hr(s,i.parentPath,i.insertIndex,n),s.build()}function hr(e,t,n,i){let s,r=n,o=0;for(const a of i){const n=c(),i=L(a.type,h(a.segments),n,a.attrs);e.insertNode(t,r,i),r++,s=n,o=ui(a.segments)}s&&e.setSelection(se(s,o))}function ur(e){const t=[];let n=[];const i=()=>{t.push({...e,segments:n.length>0?n:[H("")]}),n=[]};for(const s of e.segments){if("inline"===s.kind){n.push(s);continue}const e=s.text.split("\n");for(const[t,r]of e.entries())t>0&&i(),r&&n.push(H(r,s.marks))}return i(),t}function pr(e){const t=e.at(-1);if("text"!==t?.kind||!t.text.endsWith("\n"))return e;const n=t.text.slice(0,-1),i=e.slice(0,-1);return n?[...i,H(n,t.marks)]:i}var fr=/* @__PURE__ */new Set(["p","div","h1","h2","h3","h4","h5","h6","blockquote","ul","ol","li","hr","pre","table","thead","tbody","tr"]),mr=/* @__PURE__ */new Set(["STRONG","B","EM","I","U","S","STRIKE","DEL","A","SPAN","BR","SUB","SUP","CODE"]),gr=/^H([1-6])$/;function yr(e){const t=e.style.fontWeight,n=Number.parseInt(t,10);return!("normal"===t||!Number.isNaN(n)&&n<700)&&{}}var kr=/* @__PURE__ */new Map([["STRONG",{markName:"bold",getAttrs:yr}],["B",{markName:"bold",getAttrs:yr}],["EM",{markName:"italic"}],["I",{markName:"italic"}],["U",{markName:"underline"}],["S",{markName:"strikethrough"}],["STRIKE",{markName:"strikethrough"}],["DEL",{markName:"strikethrough"}],["A",{markName:"link",getAttrs:function(e){return{href:n(e.getAttribute("href")??"")}}}]]),br=class{schema;classDeclarations;blockParseRules;markParseRules;inlineParseRules;blockTagHandlers;containsBlockDescendants;constructor(e){this.schema=e.schema,this.classDeclarations=bt(e.schemaRegistry),this.blockParseRules=e.schemaRegistry?.getBlockParseRules()??[],this.markParseRules=e.schemaRegistry?.getMarkParseRules()??[],this.inlineParseRules=e.schemaRegistry?.getInlineParseRules()??[],this.containsBlockDescendants=Ct(this.blockParseRules,this.inlineParseRules,fr),this.blockTagHandlers=this.buildBlockTagHandlers()}parse(e){Tt(e,this.classDeclarations),Pt(e);const t=this.parseContainer(e);return 0===t.length?{blocks:[{type:this.resolveBlockType(he("paragraph")),segments:[H("")]}]}:{blocks:t.flatMap(e=>function(e,t){if("code_block"===e.type||!e.segments.some(e=>"text"===e.kind&&e.text.includes("\n")))return[e];if(!t.getInlineNodeSpec?.("hard_break"))return ur(e);const n=1===e.segments.length?e.segments[0]:void 0;if("text"===n?.kind&&"\n"===n.text)return[{...e,segments:[H("")]}];const i=[];for(const s of e.segments)if("inline"!==s.kind)for(const[e,t]of s.text.split("\n").entries())e>0&&i.push(u(P(pe("hard_break"),{},s.marks))),t&&i.push(H(t,s.marks));else i.push(s);return[{...e,segments:i}]}(e,this.schema))}}buildBlockTagHandlers(){const e=e=>this.parseBlockWithLineBreaks(e,this.resolveBlockType(he("paragraph"))),t=e=>this.parseTableAsParagraphs(e);/* @__PURE__ */
2
+ return new Map([["P",e],["DIV",t=>this.containsBlockDescendants(t)?this.parseContainerWithMarks(t,this.marksFromElement(t),"split"):e(t)],["BLOCKQUOTE",e=>this.parseBlockquote(e)],["UL",e=>this.parseList(e,"bullet",0)],["OL",e=>this.parseList(e,"ordered",0)],["LI",e=>this.parseListItem(e,"bullet",0)],["HR",()=>[{type:this.resolveBlockType(he("horizontal_rule")),segments:[]}]],["PRE",e=>this.parsePreElement(e)],["TABLE",t],["THEAD",t],["TBODY",t],["TR",t]])}parseContainer(e,t="keep"){const n=[];let i=[];for(const s of Array.from(e.childNodes))if(s.nodeType===Node.ELEMENT_NODE){const e=s;this.isBlockElement(e)?(this.flushPendingSegments(n,i,t),i=[],n.push(...this.parseBlockElement(e))):e.children.length>0&&this.containsBlockDescendants(e)?(this.flushPendingSegments(n,i,t),i=[],n.push(...this.parseContainerWithMarks(e,this.marksFromElement(e),t))):i.push(...this.parseInlineNode(s,[]))}else if(s.nodeType===Node.TEXT_NODE){const e=s.textContent??"";e&&i.push(H(e))}return this.flushPendingSegments(n,i,t),n}parseBlockElement(e){const t=gr.exec(e.tagName),n=this.blockTagHandlers.get(e.tagName),i=t?this.parseHeading(e,Number(t[1])):n?n(e):this.parseUnknownBlock(e);return this.applyElementAlignment(i,e)}applyElementAlignment(e,t,n){const i=yt(t);if(!i)return e;const s=n??this.containsBlockDescendants(t);return e.map(e=>this.schema.getNodeSpec&&!this.schema.getNodeSpec(e.type)?.attrs?.align||s&&void 0!==e.attrs?.align?e:{...e,attrs:{...e.attrs,align:i}})}parseHeading(e,t){const n=this.resolveBlockType(he("heading"));return[{type:n,...n===he("heading")?{attrs:{level:t}}:{},segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}parseUnknownBlock(e){const t=this.matchBlockRule(e);return"paragraph"===(t?.type??"paragraph")&&this.containsBlockDescendants(e)?this.parseContainerWithMarks(e,this.marksFromElement(e)):t?[{type:t.type,...t.attrs?{attrs:t.attrs}:{},segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]:[{type:this.resolveBlockType(he("paragraph")),segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}parseBlockquote(e){const t=this.resolveBlockType(he("blockquote"));return this.containsBlockDescendants(e)?this.parseContainer(e).map(e=>({type:t,segments:e.segments})):[{type:t,segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}parseList(e,t,n){const i=[];for(const s of Array.from(e.children)){const e=s;"LI"===e.tagName?i.push(...this.parseListItem(e,t,n)):"UL"===e.tagName?i.push(...this.parseList(e,"bullet",n+1)):"OL"===e.tagName&&i.push(...this.parseList(e,"ordered",n+1))}return i}parseListItem(e,t,n){const i=[],s=this.resolveBlockType(he("list_item")),r=this.hasCheckbox(e),o=r?"checklist":t,a=!!r&&this.isCheckboxChecked(e),c=[],l=[];for(const d of Array.from(e.childNodes))if(d.nodeType===Node.ELEMENT_NODE){const e=d;"UL"===e.tagName||"OL"===e.tagName?l.push(e):"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")||(this.isBlockElement(e)?c.push(...this.parseInlineChildren(e,[])):c.push(...this.parseInlineNode(d,[])))}else if(d.nodeType===Node.TEXT_NODE){const e=d.textContent??"";e&&c.push(H(e))}i.push({type:s,attrs:{listType:o,indent:n,..."checklist"===o?{checked:a}:{}},segments:this.ensureSegments(this.normalizeSegments(c))});for(const d of l){const e="OL"===d.tagName?"ordered":"bullet";i.push(...this.parseList(d,e,n+1))}return i}parseInlineChildren(e,t){const n=[];for(const i of Array.from(e.childNodes))n.push(...this.parseInlineNode(i,t));return this.normalizeSegments(n)}parseInlineNode(e,t){if(e.nodeType===Node.TEXT_NODE){const n=e.textContent??"";return n?[H(n,this.resolveMarks(t))]:[]}if(e.nodeType!==Node.ELEMENT_NODE)return[];const n=e,i=n.tagName;if("BR"===i)return[H("\n",this.resolveMarks(t))];const s=this.matchInlineNodeRule(n);if(s)return[u(s)];if(this.isBlockElement(n)&&!mr.has(i))return this.parseInlineChildren(n,t);const r=this.mergeMarks(t,this.marksFromElement(n));return this.parseInlineChildren(n,r)}matchInlineNodeRule(e){const t=Mt(e,this.inlineParseRules);return t?P(pe(t.type),t.attrs):null}parsePreElement(e){const t=this.resolveBlockType(he("code_block")),n=[H(At(e))];if("code_block"===t){const i=this.matchBlockRule(e);return[{type:t,attrs:i?.type===t?i.attrs:void 0,segments:n}]}return ur({type:t,segments:n})}parseTableAsParagraphs(e){const t=[],n=e.querySelectorAll("td, th");for(const i of Array.from(n)){const e=this.parseInlineChildren(i,[]);e.some(e=>"inline"===e.kind||e.text.length>0)&&t.push({type:this.resolveBlockType(he("paragraph")),segments:this.ensureSegments(e)})}return t}marksFromElement(e){return this.matchMarkRules(e)||this.fallbackMarksFromElement(e)}matchMarkRules(e){const t=Et(e,[],this.markParseRules);return t.length>0?t:null}fallbackMarksFromElement(e){const t=kr.get(e.tagName);if(!t)return[];if(t.getAttrs){const n=t.getAttrs(e);return!1===n?[]:Object.keys(n).length>0?[{type:ue(t.markName),attrs:n}]:[{type:ue(t.markName)}]}return[{type:ue(t.markName)}]}mergeMarks(e,t){const n=[...e];for(const i of t)n.some(e=>e.type===i.type)||n.push(i);return n}resolveMarks(e){return e.filter(e=>ye(this.schema,e.type))}resolveBlockType(e){return ke(this.schema,e)?e:he("paragraph")}normalizeSegments(e){if(0===e.length)return[];const t=[];for(const n of e){if("inline"===n.kind){t.push(n);continue}const e=t[t.length-1];e&&"text"===e.kind&&d(e.marks,n.marks)?t[t.length-1]=H(e.text+n.text,e.marks):n.text.length>0&&t.push(n)}return t}ensureSegments(e){return 0===e.length?[H("")]:e}matchBlockRule(e){const t=Mt(e,this.blockParseRules);return t?{type:he(t.type),...t.attrs?{attrs:t.attrs}:{}}:null}isBlockElement(e){return Ot(e,this.blockParseRules,this.inlineParseRules,fr)}hasCheckbox(e){return null!==e.querySelector('input[type="checkbox"]')}isCheckboxChecked(e){return e.querySelector('input[type="checkbox"]')?.hasAttribute("checked")??!1}parseContainerWithMarks(e,t,n="keep"){const i=this.parseContainer(e,n),s=this.applyElementAlignment(i,e,!0);return 0===t.length?s:s.map(e=>"code_block"===e.type?e:{...e,segments:this.prependMarks(e.segments,t)})}prependMarks(e,t){return e.map(e=>"inline"===e.kind?e:H(e.text,this.mergeMarks(t,e.marks)))}parseBlockWithLineBreaks(e,t){return ur({type:t,segments:this.parseInlineChildren(e,[])})}flushPendingSegments(e,t,n){const i=this.normalizeSegments(t);if(0===i.length)return;if(i.every(e=>"text"===e.kind&&""===e.text.trim()&&!e.text.includes("\n")))return;const s=this.resolveBlockType(he("paragraph"));"keep"!==n?e.push(...ur({type:s,segments:pr(i)})):e.push({type:s,segments:i})}},vr={1:"x-small",2:"small",3:"medium",4:"large",5:"x-large",6:"xx-large",7:"xxx-large"};function wr(e){return e.toLowerCase().includes("font-size")}function Ir(e,t){for(;e.firstChild;)t.appendChild(e.firstChild)}function Sr(e){const t=e.parentNode;if(t){for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}}var xr=["script","style","iframe","object","embed","form","noscript"],Rr=/* @__PURE__ */new Set(["p","div","h1","h2","h3","h4","h5","h6","li","blockquote","table","tr","td","th","pre","figure","hr"]),Cr=class{getState;dispatch;schemaRegistry;tryRichPasteFromJson;constructor(e,t,n,i){this.getState=e,this.dispatch=t,this.schemaRegistry=n,this.tryRichPasteFromJson=i}handleHTMLOrTextPaste(e,t,n){const i=this.stateAtSelection(n),s=e.getData("text/html");s?this.handleHTML(s,i):t&&this.pastePlainText(t,n)}pastePlainText(e,t){if(!e)return;const n=function(e){return{blocks:e.split(/\r?\n/).map(e=>({type:he("paragraph"),segments:[H(e)]}))}}(e);this.dispatch(rr(this.stateAtSelection(t),n))}pasteHTMLString(e,t){return this.handleHTML(e,this.stateAtSelection(t))}handleHTML(e,t){const n=xt(e,{FORBID_TAGS:xr,ADD_TAGS:this.schemaRegistry?this.schemaRegistry.getAllowedTags():[],ADD_ATTR:this.schemaRegistry?this.schemaRegistry.getAllowedAttrs():[],ALLOWED_URI_REGEXP:i,...Rt()},this.schemaRegistry),s=this.extractRichData(n);if(s&&this.tryRichPasteFromJson(s,t))return!0;!function(e){const t=Array.from(e.querySelectorAll("font"));for(const n of t){const e=n.getAttribute("color"),t=n.getAttribute("face"),i=n.getAttribute("size"),s=n.getAttribute("style")??"";if(!(null!==e||null!==t||null!==i||s.length>0)){Sr(n);continue}const r=document.createElement("span"),o=[];if(s&&o.push(s.endsWith(";")?s:`${s};`),e&&o.push(`color: ${e};`),t&&o.push(`font-family: ${t};`),i&&!wr(s)){const e=vr[i];e&&o.push(`font-size: ${e};`)}cn(r,o.join(" ")),Ir(n,r),n.parentNode?.replaceChild(r,n)}}(n);const r=[...this.schemaRegistry?this.schemaRegistry.getAllowedTags():["strong","em","u","b","i","p","br","div","span"],"pre"],o=this.schemaRegistry?this.schemaRegistry.getAllowedAttrs():[],a=xt(n,{ALLOWED_TAGS:r,ALLOWED_ATTR:o,ALLOWED_URI_REGEXP:i,...Rt()},this.schemaRegistry);if(this.schemaRegistry){if(this.requiresDocumentParser(a))return this.handleDocumentPaste(a,t);const e=me(this.schemaRegistry),n=new br({schema:e,schemaRegistry:this.schemaRegistry}),i=null!==a.querySelector("br")||Array.from(a.querySelectorAll("pre")).some(e=>e.textContent?.includes("\n")),s=n.parse(a);return!(!function(e){return e.blocks.some(e=>e.type!==he("paragraph")||e.segments.some(mi))}(s)&&!i||(this.dispatch(rr(t,s)),0))}const c=a.textContent??"";return!!fi(c)&&(this.dispatch(je(t,c,"paste")),!0)}extractRichData(e){const t=e.querySelector("[data-notectl-rich]")?.getAttribute("data-notectl-rich");if(t)return this.decodeHTMLEntities(t)}decodeHTMLEntities(e){return e.replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}requiresDocumentParser(e){return!!this.containsModelledBlockID(e)||!!e.querySelector("table")||!!e.querySelector("blockquote")||!(!e.querySelector("li")||!this.containsMultiBlockListItem(e))||this.containsVoidBlockElements(e)}containsModelledBlockID(e){const t=new Set(this.schemaRegistry?.getBlockParseRules().map(e=>e.rule.tag)??[]);for(const n of Array.from(e.querySelectorAll("[id]"))){const e=n.tagName.toLowerCase();if(Rr.has(e)||t.has(e))return!0}return!1}containsMultiBlockListItem(e){const t=this.schemaRegistry?.getBlockParseRules()??[],n=this.schemaRegistry?.getInlineParseRules()??[],i=/* @__PURE__ */new Set(["PRE","BLOCKQUOTE","TABLE","HR","H1","H2","H3","H4","H5","H6"]);for(const s of Array.from(e.querySelectorAll("li"))){let e=0,r=!1;for(const o of Array.from(s.childNodes))if(o.nodeType===Node.ELEMENT_NODE){const s=o.tagName;if("UL"===s||"OL"===s||"INPUT"===s||"LI"===s)continue;if(i.has(s))return!0;if(Bt(o,t,n))return!0;if("P"===s||"DIV"===s){e++;continue}r=!0}else o.nodeType===Node.TEXT_NODE&&""!==(o.textContent??"").trim()&&(r=!0);if(e>=2||e>=1&&r)return!0}return!1}containsVoidBlockElements(e){if(!this.schemaRegistry)return!1;const t=this.schemaRegistry.getBlockParseRules();for(const n of t){if(!this.schemaRegistry.getNodeSpec(n.type)?.isVoid)continue;const t=e.querySelectorAll(n.rule.tag);for(const e of Array.from(t)){if(!n.rule.getAttrs)return!0;if(!1!==n.rule.getAttrs(e))return!0}}return!1}handleDocumentPaste(e,t){if(!this.schemaRegistry)return!1;const n=Jn(Dt(e,this.schemaRegistry),this.schemaRegistry);if(0===n.children.length)return!1;const i=t.selection,s=t.transaction("paste"),r=rn(t,s),o=r.state,a=r.blockId,l=Ae(o,a,n.children,this.schemaRegistry,i);if(!l)return!1;let d,h,u=l.insertIndex;for(const p of n.children){const e=c(),t=Be(p,e);s.insertNode(l.parentPath,u,t),u++,d=we(t),h=t}if(l.isAnchorEmpty&&!de(i)&&s.removeNode(l.parentPath,l.anchorIndex),d&&h){const e=Ee(h,d),t=e?B(e).length:0;s.setSelection(se(d,t))}return this.dispatch(s.build()),!0}stateAtSelection(e){const t=this.getState();return e?t.withSelection(e):t}},Mr=class{getState;dispatch;schemaRegistry;constructor(e,t,n){this.getState=e,this.dispatch=t,this.schemaRegistry=n}handleBlockPaste(e){let n;try{n=JSON.parse(e)}catch{return}const i=n.type;if(!i)return;const s=this.schemaRegistry?.getNodeSpec(i);if(this.schemaRegistry&&!s)return;const r=Ce(n.attrs,s?.attrs),o=L(he(i),void 0,c(),r,t(n.htmlId)),a=this.getState(),l=a.transaction("paste"),d=rn(a,l),h=Te(d.state,l,d.blockId,[o],a.selection,this.schemaRegistry);h&&(l.setSelection(ne(o.id,[...h,o.id])),this.dispatch(l.build()))}handleRichPasteFromJson(e,t){let n;try{n=JSON.parse(e)}catch{return!1}return!(!Array.isArray(n)||0===n.length)&&this.handleRichPaste(n,t)}handleRichPaste(e,n){if(0===e.length)return!1;const i=[];for(const t of e){const e=xe(t,this.schemaRegistry);e&&i.push(e)}if(0===i.length)return!1;if(!i.some(e=>void 0!==e.htmlId||void 0!==e.type&&"paragraph"!==e.type||e.segments?.some(e=>"inline"===e.kind))&&i.length<=1)return!1;const s=n??this.getState(),r=s.selection,o=Re(r),a=s.getBlock(o),c=s.doc.children.some(e=>e.id===o),l=i.some(e=>t(e.htmlId)),d=i.every(e=>{const t=this.schemaRegistry?.getNodeSpec(e.type)??s.schema.getNodeSpec?.(e.type);return!t?.isVoid&&(!t?.content||t.content.allow.includes("text"))});if(!l&&d&&te(r)&&(i.length>1||Z(r)&&c&&void 0!==a&&A(a)>0))return this.dispatch(rr(s,Pe(i))),!0;const h=s.transaction("paste"),u=rn(s,h);return this.resolveAndInsertRichBlocks(i,h,u,r)}resolveAndInsertRichBlocks(e,t,n,i){const s=e.map(Me),{state:r,blockId:o}=n;if(!Te(r,t,o,s,i,this.schemaRegistry))return!1;const a=s[s.length-1];return a&&t.setSelection(se(a.id,A(a))),this.dispatch(t.build()),!0}};function Pr(e){return""!==e.trim()&&/<\w/.test(e)}var Er=class{element;getState;dispatch;schemaRegistry;fileHandlerRegistry;isReadOnly;getPasteInterceptors;pasteMarkdown;getMarkdownSyntaxExtensions;announce;markdownImportedMessage;callbackExecutor;loadMarkdownParser;handlePaste;htmlHandler;richBlockHandler;pendingBookmarks=/* @__PURE__ */new Set;active=!0;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.schemaRegistry=t.schemaRegistry,this.fileHandlerRegistry=t.fileHandlerRegistry,this.isReadOnly=t.isReadOnly??(()=>!1),this.getPasteInterceptors=t.getPasteInterceptors??(()=>[]),this.pasteMarkdown=t.pasteMarkdown??"auto",this.getMarkdownSyntaxExtensions=t.getMarkdownSyntaxExtensions??(()=>[]),this.announce=t.announce,this.markdownImportedMessage=t.markdownImportedMessage??"Markdown imported",this.callbackExecutor=t.callbackExecutor??Ms.silent,this.loadMarkdownParser=t.loadMarkdownParser??(()=>import("./MarkdownParser-JOfPSvGv.mjs").then(e=>e.t)),this.richBlockHandler=new Mr(t.getState,e=>this.dispatchPasteTransaction(e),t.schemaRegistry),this.htmlHandler=new Cr(t.getState,e=>this.dispatchPasteTransaction(e),t.schemaRegistry,(e,t)=>this.richBlockHandler.handleRichPasteFromJson(e,t)),this.handlePaste=this.onPaste.bind(this),e.addEventListener("paste",this.handlePaste)}onPaste(e){if(!sn(e,this.element))return;if(e.preventDefault(),this.isReadOnly())return;const t=e.clipboardData;if(!t)return;const n=this.captureClipboard(t);if(n.blockJson)return void this.richBlockHandler.handleBlockPaste(n.blockJson);const i=this.createBookmark(),s=function(e,t){if(0===t.length||t.some(e=>!e.type.startsWith("image/")))return!1;if(!Pr(e))return!1;const n=(new DOMParser).parseFromString(e,"text/html").body,i=n.querySelectorAll("img, picture, svg, canvas"),s=i.length>0;for(const r of i)r.remove();return""!==(n.textContent??"").trim()||!s}(n.html,n.files),r=this.fileHandlerRegistry&&n.files.length>0&&!s?Ys({registry:this.fileHandlerRegistry,executor:this.callbackExecutor,files:n.files,source:"paste",getPosition:()=>null,isActive:()=>this.isBookmarkActive(i)}):{handled:!1,cancelled:!1};r instanceof Promise?this.continueAfterFileHandlers(r,n,i):r.handled||r.cancelled?this.releaseBookmark(i):this.processClipboardSnapshot(n,i,s?n.files:[])}processClipboardSnapshot(e,t,n){if(!this.isBookmarkActive(t))return void this.releaseBookmark(t);if(e.plainText&&this.tryPasteInterceptors(e.plainText,e.html,t))return;if(e.plainText&&"never"!==this.pasteMarkdown&&!Pr(e.html)&&function(e){if(0===e.length)return!1;if(nr.test(e))return!0;if(e.includes("|")&&ir.test(e))return!0;const t=e.match(sr);return null!==t&&t.length>=2}(e.plainText))return void this.handleMarkdownPaste(e.plainText,t);const i=this.consumeBookmark(t);i&&(e.html?this.htmlHandler.pasteHTMLString(e.html,i)||this.handleContentlessHTMLFallback(n,e.plainText,i):e.plainText&&this.htmlHandler.pastePlainText(e.plainText,i))}handleContentlessHTMLFallback(e,t,n){const i=this.fileHandlerRegistry;if(!i||0===e.length)return void(this.active&&!this.isReadOnly()&&t&&this.htmlHandler.pastePlainText(t,n));const s=this.createBookmark(n),r=Ys({registry:i,executor:this.callbackExecutor,files:e,source:"paste",getPosition:()=>null,isActive:()=>this.isBookmarkActive(s)});r instanceof Promise?this.continueContentlessHTMLFallback(r,t,s):this.finishContentlessHTMLFallback(r,t,s)}async continueContentlessHTMLFallback(e,t,n){try{this.finishContentlessHTMLFallback(await e,t,n)}catch(i){this.callbackExecutor.reportFailure({pluginId:"core",name:"Deferred file paste",kind:"file-handler"},i),this.releaseBookmark(n)}}finishContentlessHTMLFallback(e,t,n){if(e.handled||e.cancelled||!this.isBookmarkActive(n))return void this.releaseBookmark(n);const i=this.consumeBookmark(n);i&&t&&this.htmlHandler.pastePlainText(t,i)}async handleMarkdownPaste(e,t){const n=await this.callbackExecutor.executeMaybeAsync({pluginId:"core",name:"Markdown conversion",kind:"markdown-paste"},async()=>{const{parseMarkdownToDocument:t}=await this.loadMarkdownParser(),n=t(e,this.schemaRegistry,{syntaxExtensions:this.getMarkdownSyntaxExtensions()});return vt(n,this.schemaRegistry,{includeBlockIds:!1})});if(!this.isBookmarkActive(t))return void this.releaseBookmark(t);const i=this.consumeBookmark(t);if(!i)return;if(!n.ok)return void this.commitMarkdownPlainTextFallback(e,i);const s=this.callbackExecutor.execute({pluginId:"core",name:"Markdown HTML commit",kind:"markdown-paste"},()=>this.htmlHandler.pasteHTMLString(n.value,i));s.ok&&s.value?this.active&&!this.isReadOnly()&&this.callbackExecutor.execute({pluginId:"core",name:"Markdown announcement",kind:"markdown-paste"},()=>this.announce?.(this.markdownImportedMessage)):this.active&&!this.isReadOnly()&&this.commitMarkdownPlainTextFallback(e,i)}commitMarkdownPlainTextFallback(e,t){this.callbackExecutor.execute({pluginId:"core",name:"Markdown plain-text fallback",kind:"markdown-paste"},()=>this.htmlHandler.pastePlainText(e,t))}tryPasteInterceptors(e,t,n){const i=this.getPasteInterceptors(),s=this.getState().withSelection(n.selection);for(const r of i){const i=this.callbackExecutor.execute({pluginId:r.pluginId,name:r.name,kind:"paste-interceptor"},()=>r.interceptor(e,t,s));if(i.ok&&i.value)return this.consumeBookmark(n),this.dispatchPasteTransaction(i.value),!0}return!1}captureClipboard(e){const t=Array.from(e.files);if(0===t.length)for(let n=0;n<e.items.length;n++){const i=e.items[n];if(i&&"file"===i.kind){const e=i.getAsFile();e&&t.push(e)}}return{blockJson:e.getData("application/x-notectl-block"),files:t,plainText:e.getData("text/plain"),html:e.getData("text/html")}}async continueAfterFileHandlers(e,t,n){try{const i=await e;if(i.cancelled||!this.isBookmarkActive(n))return void this.releaseBookmark(n);if(i.handled)return void this.releaseBookmark(n);this.processClipboardSnapshot(t,n,[])}catch(i){this.callbackExecutor.reportFailure({pluginId:"core",name:"File paste continuation",kind:"file-handler"},i),this.releaseBookmark(n)}}onStateChange(e,t,n){for(const i of this.pendingBookmarks){if(e.doc!==t.doc&&0===n.steps.length){i.cancelled=!0,this.pendingBookmarks.delete(i);continue}const s=er(i.selection,n.mapping);s&&Tr(t,s)?i.selection=s:(i.cancelled=!0,this.pendingBookmarks.delete(i))}}createBookmark(e=this.getState().selection){const t={selection:e,cancelled:!1};return this.pendingBookmarks.add(t),t}consumeBookmark(e){return this.isBookmarkActive(e)?(this.pendingBookmarks.delete(e),e.selection):(this.releaseBookmark(e),null)}releaseBookmark(e){this.pendingBookmarks.delete(e)}isBookmarkActive(e){return this.active&&!this.isReadOnly()&&!e.cancelled&&this.pendingBookmarks.has(e)}dispatchPasteTransaction(e){const t=this.getState();if(ie(t.selection,e.selectionBefore))return void this.dispatch(e);const n=er(t.selection,e.mapping);this.dispatch({...e,selectionBefore:t.selection,selectionAfter:n??e.selectionAfter,storedMarksAfter:t.storedMarks})}destroy(){if(this.active){this.active=!1,this.element.removeEventListener("paste",this.handlePaste);for(const e of this.pendingBookmarks)e.cancelled=!0;this.pendingBookmarks.clear()}}};function Tr(e,t){return ee(t)?void 0!==e.getBlock(t.nodeId):de(t)?void 0!==e.getBlock(t.blockId):!!te(t)&&void 0!==e.getBlock(t.anchor.blockId)&&void 0!==e.getBlock(t.head.blockId)}var Br=class{compositionTracker;inputHandler;keyboardHandler;pasteHandler;clipboardHandler;constructor(e,t){this.compositionTracker=new xs,this.inputHandler=new $s(e,{getState:t.getState,dispatch:t.dispatch,syncSelection:t.syncSelection,inputRuleRegistry:t.inputRuleRegistry,isReadOnly:t.isReadOnly,shouldApplyInputRules:t.shouldApplyInputRules,compositionTracker:this.compositionTracker,getTextInputInterceptors:t.getTextInputInterceptors,callbackExecutor:t.callbackExecutor,resolveTargetRange:t.resolveTargetRange,compositionDOM:t.compositionDOM}),this.keyboardHandler=new Xs(e,{getState:t.getState,dispatch:t.dispatch,undo:t.undo,redo:t.redo,keymapRegistry:t.keymapRegistry,isReadOnly:t.isReadOnly,compositionTracker:this.compositionTracker,getTextDirection:t.getTextDirection,navigateFromGapCursor:t.navigateFromGapCursor,callbackExecutor:t.callbackExecutor}),this.pasteHandler=new Er(e,{getState:t.getState,dispatch:t.dispatch,schemaRegistry:t.schemaRegistry,fileHandlerRegistry:t.fileHandlerRegistry,isReadOnly:t.isReadOnly,getPasteInterceptors:t.getPasteInterceptors,pasteMarkdown:t.pasteMarkdown,getMarkdownSyntaxExtensions:t.getMarkdownSyntaxExtensions,announce:t.announce,markdownImportedMessage:t.markdownImportedMessage,callbackExecutor:t.callbackExecutor}),this.clipboardHandler=new Ss(e,{getState:t.getState,dispatch:t.dispatch,schemaRegistry:t.schemaRegistry,syncSelection:t.syncSelection,isReadOnly:t.isReadOnly})}onStateChange(e,t,n){this.inputHandler.onStateChange(e,t,n),this.pasteHandler.onStateChange(e,t,n)}destroy(){this.inputHandler.destroy(),this.keyboardHandler.destroy(),this.pasteHandler.destroy(),this.clipboardHandler.destroy()}},Ar=class{_fileHandlers=[];registerFileHandler(e,t,n){this._fileHandlers.push({pattern:e,handler:t,pluginId:n?.pluginId??"unattributed",name:n?.name??(t.name||e)})}getFileHandlers(){return this._fileHandlers}matchFileHandlers(e){return this.matchFileHandlerEntries(e).map(e=>e.handler)}matchFileHandlerEntries(e){return this._fileHandlers.filter(t=>function(e,t){if("*"===e||"*/*"===e)return!0;if(e===t)return!0;if(e.endsWith("/*")){const n=e.slice(0,-1);return t.startsWith(n)}return!1}(t.pattern,e))}removeFileHandler(e){const t=this._fileHandlers.findIndex(t=>t.handler===e);-1!==t&&this._fileHandlers.splice(t,1)}clear(){this._fileHandlers.length=0}},Or=class{_inputRules=[];registerInputRule(e,t){this._inputRules.push({rule:e,pluginId:t?.pluginId??"unattributed",name:t?.name??(e.handler.name||e.pattern.toString())})}getInputRules(){return this._inputRules.map(e=>e.rule)}getInputRuleEntries(){return this._inputRules}removeInputRule(e){const t=this._inputRules.findIndex(t=>t.rule===e);-1!==t&&this._inputRules.splice(t,1)}clear(){this._inputRules.length=0}},Dr=class{_contextKeymaps=[];_navigationKeymaps=[];_defaultKeymaps=[];_fallbackKeymaps=[];registerKeymap(e,t,n){const i=t?.priority??"default";this.keymapArrayForPriority(i).push({keymap:e,pluginId:n?.pluginId??"unattributed",name:n?.name??(Object.keys(e).join(", ")||"anonymous-keymap")})}getKeymaps(){return[...this._contextKeymaps,...this._navigationKeymaps,...this._defaultKeymaps,...this._fallbackKeymaps].map(e=>e.keymap)}getKeymapsByPriority(){return{context:this._contextKeymaps.map(e=>e.keymap),navigation:this._navigationKeymaps.map(e=>e.keymap),default:this._defaultKeymaps.map(e=>e.keymap),fallback:this._fallbackKeymaps.map(e=>e.keymap)}}getKeymapEntriesByPriority(){return{context:[...this._contextKeymaps],navigation:[...this._navigationKeymaps],default:[...this._defaultKeymaps],fallback:[...this._fallbackKeymaps]}}removeKeymap(e){for(const t of[this._contextKeymaps,this._navigationKeymaps,this._defaultKeymaps,this._fallbackKeymaps]){const n=t.findIndex(t=>t.keymap===e);if(-1!==n)return void t.splice(n,1)}}clear(){this._contextKeymaps.length=0,this._navigationKeymaps.length=0,this._defaultKeymaps.length=0,this._fallbackKeymaps.length=0}keymapArrayForPriority(e){switch(e){case"context":return this._contextKeymaps;case"navigation":return this._navigationKeymaps;case"default":return this._defaultKeymaps;case"fallback":return this._fallbackKeymaps}}},Nr=class{_extensions=[];register(e){this._extensions.push(e)}remove(e){const t=this._extensions.indexOf(e);-1!==t&&this._extensions.splice(t,1)}getExtensions(){return this._extensions}clear(){this._extensions.length=0}};function Lr(e,t){if(function(e){return Li.has(e)}(e))return e;const n=[],i=[];let s=t;for(const r of e.steps){const e=_i(r);n.push(e),i.push(_t(Yi(s,e))),s=Qi(s,e)}return Fi({steps:n,selectionBefore:Hi(e.selectionBefore),selectionAfter:Hi(e.selectionAfter),storedMarksAfter:zi(e.storedMarksAfter),forwardStepMaps:i,metadata:e.metadata})}var Hr=class{_nodeViews=/* @__PURE__ */new Map;registerNodeView(e,t,n={pluginId:"unattributed",name:e}){if(this._nodeViews.has(e))throw new Error(`NodeView for type "${e}" is already registered.`);this._nodeViews.set(e,{...n,factory:t})}getNodeViewFactory(e){return this._nodeViews.get(e)?.factory}getNodeViewEntry(e){return this._nodeViews.get(e)}removeNodeView(e){this._nodeViews.delete(e)}clear(){this._nodeViews.clear()}},zr=class{commands=/* @__PURE__ */new Map;readonlyBypassActive=!1;log;constructor(e=Qt){this.log=Gt(e,"CommandRegistry")}register(e,t,n,i){if(this.commands.has(e)){const t=this.commands.get(e);throw new Error(`Command "${e}" is already registered by plugin "${t?.pluginId}".`)}const s=i?.readonlyAllowed??!1;this.commands.set(e,{name:e,handler:t,pluginId:n,readonlyAllowed:s})}canExecute(e,t){const n=this.commands.get(e);return!(!n||t&&!n.readonlyAllowed)}execute(e,t){const n=this.commands.get(e);if(!n)return!1;if(t&&!n.readonlyAllowed)return!1;const i=t&&n.readonlyAllowed;i&&(this.readonlyBypassActive=!0);try{return n.handler()}catch(s){return this.log.error(`Command "${e}" error`,s),!1}finally{i&&(this.readonlyBypassActive=!1)}}isReadonlyBypassed(){return this.readonlyBypassActive}has(e){return this.commands.has(e)}remove(e){this.commands.delete(e)}clear(){this.commands.clear(),this.readonlyBypassActive=!1}get rawMap(){return this.commands}},_r=class{listeners=/* @__PURE__ */new Map;log;constructor(e=Qt){this.log=Gt(e,"EventBus")}emit(e,t){const n=this.listeners.get(e.id);if(n)for(const s of n)try{s(t)}catch(i){this.log.error(`Listener error on "${e.id}"`,i)}}on(e,t){const n=e.id;this.listeners.has(n)||this.listeners.set(n,/* @__PURE__ */new Set);const i=this.listeners.get(n)??/* @__PURE__ */new Set;return i.add(t),()=>{i.delete(t),0===i.size&&this.listeners.delete(n)}}off(e,t){const n=this.listeners.get(e.id);n&&(n.delete(t),0===n.size&&this.listeners.delete(e.id))}clear(){this.listeners.clear()}},Fr=class{middlewares=[];middlewareSorted=null;pasteInterceptors=[];pasteInterceptorsSorted=null;textInputInterceptors=[];textInputInterceptorsSorted=null;log;constructor(e=Qt){this.log=Gt(e,"MiddlewareChain")}addMiddleware(e){this.middlewares.push(e),this.middlewareSorted=null}removeMiddleware(e){const t=this.middlewares.indexOf(e);-1!==t&&this.middlewares.splice(t,1),this.middlewareSorted=null}invalidateMiddlewareSort(){this.middlewareSorted=null}dispatch(e,t,n){if(0===this.middlewares.length)return void n(e);const i=this.getSortedMiddleware();let s=0,r=!1;const o=e=>{if(s<i.length){const n=i[s++];if(!n)return;let r=!1;const c=e=>{r||(r=!0,o(e))};try{n.middleware(e,t,c)}catch(a){this.log.error(`Middleware "${n.name}" error`,a),c(e)}}else r||(r=!0,n(e))};o(e)}getChain(){return this.getSortedMiddleware().map(e=>({name:e.name,priority:e.priority,pluginId:e.pluginId}))}addPasteInterceptor(e){this.pasteInterceptors.push(e),this.pasteInterceptorsSorted=null}removePasteInterceptor(e){const t=this.pasteInterceptors.indexOf(e);-1!==t&&this.pasteInterceptors.splice(t,1),this.pasteInterceptorsSorted=null}invalidatePasteSort(){this.pasteInterceptorsSorted=null}getPasteInterceptors(){return this.getSortedPasteInterceptors()}addTextInputInterceptor(e){this.textInputInterceptors.push(e),this.textInputInterceptorsSorted=null}removeTextInputInterceptor(e){const t=this.textInputInterceptors.indexOf(e);-1!==t&&this.textInputInterceptors.splice(t,1),this.textInputInterceptorsSorted=null}invalidateTextInputSort(){this.textInputInterceptorsSorted=null}getTextInputInterceptors(){return this.getSortedTextInputInterceptors()}get rawMiddlewares(){return this.middlewares}get rawPasteInterceptors(){return this.pasteInterceptors}get rawTextInputInterceptors(){return this.textInputInterceptors}clear(){this.middlewares.length=0,this.middlewareSorted=null,this.pasteInterceptors.length=0,this.pasteInterceptorsSorted=null,this.textInputInterceptors.length=0,this.textInputInterceptorsSorted=null}getSortedMiddleware(){return this.middlewareSorted||(this.middlewareSorted=[...this.middlewares].sort((e,t)=>e.priority-t.priority)),this.middlewareSorted}getSortedPasteInterceptors(){return this.pasteInterceptorsSorted||(this.pasteInterceptorsSorted=[...this.pasteInterceptors].sort((e,t)=>e.priority-t.priority)),this.pasteInterceptorsSorted}getSortedTextInputInterceptors(){return this.textInputInterceptorsSorted||(this.textInputInterceptorsSorted=[...this.textInputInterceptors].sort((e,t)=>e.priority-t.priority)),this.textInputInterceptorsSorted}},jr=/* @__PURE__ */new WeakSet;function $r(e,t,n,i,s){return{registerCommand:(i,r,o)=>{if(t.has(i)){const e=t.get(i);throw new Error(`Command "${i}" is already registered by plugin "${e?.pluginId}".`)}const a=o?.readonlyAllowed??!1;t.set(i,{name:i,handler:r,pluginId:e,readonlyAllowed:a}),n.commands.push(i),s?.()},executeCommand:i}}function Kr(e,t){return{registerService:(n,i)=>{if(e.has(n.id))throw new Error(`Service "${n.id}" is already registered by another plugin.`);e.set(n.id,i),t.services.push(n.id)},getService:t=>e.get(t.id)}}function Vr(e,t){const{pluginId:n,middlewares:i,pasteInterceptors:s,textInputInterceptors:r,invalidateMiddlewareSort:o,invalidatePasteSort:a,invalidateTextInputSort:c}=e;return{registerMiddleware:(e,s)=>{const r={name:s?.name??(e.name||"anonymous"),pluginId:n,middleware:e,priority:s?.priority??100};i.push(r),t.middlewares.push(r),o()},registerPasteInterceptor:(e,i)=>{const r={name:i?.name??"anonymous",pluginId:n,interceptor:e,priority:i?.priority??100};s.push(r),t.pasteInterceptors.push(r),a()},registerTextInputInterceptor:(e,i)=>{const s={name:i?.name??"anonymous",pluginId:n,interceptor:e,priority:i?.priority??100};r.push(s),t.textInputInterceptors.push(s),c()}}}function qr(e,t){return{registerNodeSpec:n=>{e.schemaRegistry.registerNodeSpec(Ur(n,e.pluginId,e.callbackExecutor)),t.nodeSpecs.push(n.type)},registerNodeSpecExtension:(n,i)=>{const s=t=>{const s=e.callbackExecutor.execute({pluginId:e.pluginId,name:`${n}:extension`,kind:"schema-extension"},()=>i(t));return s.ok?Ur(s.value,e.pluginId,e.callbackExecutor):t};e.schemaRegistry.registerNodeSpecExtension(n,s),t.nodeSpecExtensions.push({type:n,extension:s})},registerMarkSpec:n=>{e.schemaRegistry.registerMarkSpec(function(e,t,n){const i=Gr(e.type,e.parseHTML,t,n),s=e.toDOM,r=jr.has(s)?s:i=>{const r=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>Wr(s(i),`${e.type}.toDOM`));return r.ok?r.value:document.createElement("span")};return jr.add(r),{...e,toDOM:r,parseHTML:i}}(n,e.pluginId,e.callbackExecutor)),t.markSpecs.push(n.type)},registerInlineNodeSpec:n=>{e.schemaRegistry.registerInlineNodeSpec(function(e,t,n){const i=Gr(e.type,e.parseHTML,t,n),s=e.toDOM,r=jr.has(s)?s:i=>{const r=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>Wr(s(i),`${e.type}.toDOM`));if(r.ok)return r.value;const o=document.createElement("span");return o.setAttribute("data-inline-type",i.inlineType),o};return jr.add(r),{...e,toDOM:r,parseHTML:i}}(n,e.pluginId,e.callbackExecutor)),t.inlineNodeSpecs.push(n.type)},registerStyleClass:n=>{e.schemaRegistry.registerStyleClass(n),t.styleClasses.push(n)}}}function Ur(e,t,n){const i=Gr(e.type,e.parseHTML,t,n),s=e.toDOM,r=jr.has(s)?s:i=>{const r=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>Wr(s(i),`${e.type}.toDOM`));if(r.ok)return r.value;const o=document.createElement("div");return o.setAttribute("data-block-id",i.id),o};return jr.add(r),{...e,toDOM:r,parseHTML:i}}function Wr(e,t){if(e instanceof HTMLElement)return e;throw new TypeError(`${t} must return an HTMLElement.`)}function Gr(e,t,n,i){return t?.some(e=>e.getAttrs)?t.map(t=>{const s=t.getAttrs;return s?{...t,getAttrs(r){const o=i.execute({pluginId:n,name:`${e}:${t.tag}`,kind:"schema-parse"},()=>s(r));return!!o.ok&&o.value}}:t}):t}function Jr(e,t,n){return{registerNodeView:(i,s)=>{t.nodeViewRegistry.registerNodeView(i,s,{pluginId:e,name:i}),n.nodeViews.push(i)},registerKeymap:(i,s)=>{t.keymapRegistry.registerKeymap(i,s,{pluginId:e,name:Object.keys(i).join(", ")||"anonymous-keymap"}),n.keymaps.push(i)},registerInputRule:i=>{t.inputRuleRegistry.registerInputRule(i,{pluginId:e,name:i.handler.name||i.pattern.toString()}),n.inputRules.push(i)},registerMarkdownSyntax:i=>{const s=function(e,t,n){const i=e.matchInline,s=e.matchBlock;return{...e,...i?{matchInline(s,r){const o=n.execute({pluginId:t,name:`${e.id}:matchInline`,kind:"markdown-syntax"},()=>function(e,t){const n=Qr(e,"length",t);return n?{type:n.type,attrs:n.attrs,length:n.consumed}:null}(i(s,r),s.length-r));return o.ok?o.value:null}}:{},...s?{matchBlock(i,r){const o=n.execute({pluginId:t,name:`${e.id}:matchBlock`,kind:"markdown-syntax"},()=>function(e,t){const n=Qr(e,"linesConsumed",t);return n?{type:n.type,attrs:n.attrs,linesConsumed:n.consumed}:null}(s(i,r),i.length-r));return o.ok?o.value:null}}:{}}}(i,e,t.callbackExecutor);t.markdownSyntaxRegistry.register(s),n.markdownSyntaxExtensions.push(s)},registerToolbarItem:i=>{t.toolbarRegistry.registerToolbarItem(i,e),n.toolbarItems.push(i.id)},registerBlockTypePickerEntry:e=>{t.blockTypePickerRegistry.registerBlockTypePickerEntry(e),n.blockTypePickerEntries.push(e.id)},registerFileHandler:(i,s)=>{t.fileHandlerRegistry.registerFileHandler(i,s,{pluginId:e,name:s.name||i}),n.fileHandlers.push(s)},registerStyleSheet:e=>{const i=new CSSStyleSheet;i.replaceSync(e),t.pluginStyleSheets.push(i),n.stylesheets.push(i)}}}function Qr(e,t,n){if(null===e)return null;if(!Yr(e))throw new TypeError("Markdown match must be null or an object descriptor.");const i=e.type;if("string"!=typeof i||0===i.trim().length)throw new TypeError("Markdown match type must be a non-empty string.");const s=function(e){if(!Yr(e))throw new TypeError("Markdown match attrs must be an object.");const t=[];for(const[n,i]of Object.entries(e)){if(!Xr(i))throw new TypeError("Markdown match attrs must contain only primitive finite values.");t.push([n,i])}return Object.fromEntries(t)}(e.attrs),r=e[t];if("number"!=typeof r||!Number.isFinite(r)||!Number.isInteger(r)||r<=0||r>n)throw new TypeError(`Markdown match ${t} must be a positive integer within the remaining input.`);return{type:i,attrs:s,consumed:r}}function Xr(e){return"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e)}function Yr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Zr(e){return{getSchemaRegistry:()=>e.schemaRegistry,getKeymapRegistry:()=>e.keymapRegistry,getInputRuleRegistry:()=>e.inputRuleRegistry,getFileHandlerRegistry:()=>e.fileHandlerRegistry,getNodeViewRegistry:()=>e.nodeViewRegistry,getToolbarRegistry:()=>e.toolbarRegistry,getBlockTypePickerRegistry:()=>e.blockTypePickerRegistry}}var eo=class{tracker;plugins=/* @__PURE__ */new Map;initOrder=[];startedInitOrder=[];initialized=!1;initializing=!1;destroying=!1;lifecycleVersion=0;pendingInit=null;pendingDestroy=null;readOnly=!1;log;constructor(e,t=Qt){this.tracker=e,this.log=Gt(t,"PluginLifecycle")}register(e){if(this.initialized||this.initializing||this.destroying)throw new Error(`Cannot register plugin "${e.id}" after initialization.`);if(this.plugins.has(e.id))throw new Error(`Plugin "${e.id}" is already registered.`);this.plugins.set(e.id,e)}get(e){return this.plugins.get(e)}getPluginIds(){return[...this.plugins.keys()]}init(e,t){if(this.destroying)return Promise.reject(/* @__PURE__ */new Error("Cannot initialize plugins while destruction is in progress."));if(this.initialized)return Promise.resolve();if(this.pendingInit)return this.pendingInit;this.initializing=!0;const n=this.lifecycleVersion,i=Promise.resolve().then(()=>this.runInitialization(e,t,n)).finally(()=>{this.pendingInit===i&&(this.pendingInit=null,this.initializing=!1)});return this.pendingInit=i,i}async runInitialization(e,t,n){const i=()=>n!==this.lifecycleVersion||!0===e.isCancelled?.();try{this.initOrder=this.resolveOrder();for(const n of this.initOrder){if(i())return void(await this.rollbackStartedPlugins());const s=this.plugins.get(n);if(!s)continue;this.startedInitOrder.push(n);const r=t(n,e);if(await s.init(r),i())return void(await this.rollbackStartedPlugins())}if(i())return void(await this.rollbackStartedPlugins());if(e.onBeforeReady&&await e.onBeforeReady(),i())return void(await this.rollbackStartedPlugins());for(const e of this.initOrder){if(i())return void(await this.rollbackStartedPlugins());const t=this.plugins.get(e);if(t?.onReady){try{await t.onReady()}catch(s){this.log.error(`Plugin "${e}" error in onReady`,s)}if(i())return void(await this.rollbackStartedPlugins())}}if(i())return void(await this.rollbackStartedPlugins());this.initialized=!0}catch(s){throw await this.rollbackStartedPlugins(),s}}destroy(){if(this.pendingDestroy)return this.pendingDestroy;this.destroying=!0,this.lifecycleVersion+=1;const e=this.pendingInit,t=Promise.resolve().then(()=>this.runDestruction(e)).finally(()=>{this.pendingDestroy===t&&(this.pendingDestroy=null,this.destroying=!1)});return this.pendingDestroy=t,t}async runDestruction(e){if(e)try{await e}catch{}const t=[...this.startedInitOrder].reverse();for(const n of t)await this.destroyPlugin(n);this.plugins.clear(),this.initOrder=[],this.startedInitOrder=[],this.initialized=!1,this.initializing=!1}notifyStateChange(e,t,n){for(const s of this.initOrder){const r=this.plugins.get(s);if(r?.onStateChange)try{r.onStateChange(e,t,n)}catch(i){this.log.error(`Plugin "${s}" error in onStateChange`,i)}}}collectDecorations(e,t){let n=Ut.empty;for(const s of this.initOrder){const r=this.plugins.get(s);if(r?.decorations)try{const i=r.decorations(e,t).withWidgetOwner(s);i.isEmpty||(n=n.merge(i))}catch(i){this.log.error(`Plugin "${s}" error in decorations()`,i)}}return n}configurePlugin(e,t){const n=this.plugins.get(e);if(!n)throw new Error(`Plugin "${e}" not found.`);if(n.onConfigure)try{n.onConfigure(t)}catch(i){this.log.error(`Plugin "${e}" error in onConfigure`,i)}}isReadOnly(){return this.readOnly}setReadOnly(e){if(this.readOnly!==e){this.readOnly=e;for(const n of this.initOrder){const i=this.plugins.get(n);if(i?.onReadOnlyChange)try{i.onReadOnlyChange(e)}catch(t){this.log.error(`Plugin "${n}" error in onReadOnlyChange`,t)}}}}get rawPlugins(){return this.plugins}get isInitialized(){return this.initialized}async destroyPlugin(e){const t=this.plugins.get(e);if(t?.destroy)try{await t.destroy()}catch(n){this.log.error(`Plugin "${e}" error in destroy`,n)}this.tracker.cleanup(e)}async rollbackStartedPlugins(){const e=[...this.startedInitOrder].reverse();for(const t of e)await this.destroyPlugin(t);this.startedInitOrder=[],this.initOrder=[],this.initialized=!1}resolveOrder(){const e=[...this.plugins.keys()];for(const r of e){const e=this.plugins.get(r);if(e)for(const t of e.dependencies??[])if(!this.plugins.has(t))throw new Error(`Plugin "${r}" depends on "${t}", which is not registered.`)}const t=/* @__PURE__ */new Map,n=/* @__PURE__ */new Map;for(const r of e)t.set(r,0),n.set(r,[]);for(const r of e){const e=this.plugins.get(r)?.dependencies??[];t.set(r,e.length);for(const t of e){const e=n.get(t);e&&e.push(r)}}const i=[];for(const[r,o]of t)0===o&&i.push(r);const s=[];for(;i.length>0;){i.sort((e,t)=>(this.plugins.get(e)?.priority??100)-(this.plugins.get(t)?.priority??100));const e=i.shift();if(!e)break;s.push(e);for(const s of n.get(e)??[]){const e=(t.get(s)??0)-1;t.set(s,e),0===e&&i.push(s)}}if(s.length!==e.length){const t=e.filter(e=>!s.includes(e));throw new Error(`Circular dependency detected among plugins: ${t.join(", ")}`)}return s}},to=class{deps;registrations=/* @__PURE__ */new Map;pluginStyleSheets=[];constructor(e){this.deps=e}track(e,t){this.registrations.set(e,t)}cleanup(e){const t=this.registrations.get(e);if(t){for(const e of t.commands)this.deps.commandRegistry.remove(e);for(const e of t.services)this.deps.serviceRegistry.remove(e);for(const e of t.middlewares)this.deps.middlewareChain.removeMiddleware(e);for(const e of t.pasteInterceptors)this.deps.middlewareChain.removePasteInterceptor(e);for(const e of t.textInputInterceptors)this.deps.middlewareChain.removeTextInputInterceptor(e);for(const e of t.unsubscribers)e();for(const{type:e,extension:n}of t.nodeSpecExtensions)this.deps.schemaRegistry.removeNodeSpecExtension(e,n);for(const e of t.nodeSpecs)this.deps.schemaRegistry.removeNodeSpec(e);for(const e of t.markSpecs)this.deps.schemaRegistry.removeMarkSpec(e);for(const e of t.inlineNodeSpecs)this.deps.schemaRegistry.removeInlineNodeSpec(e);for(const e of t.styleClasses)this.deps.schemaRegistry.removeStyleClass(e);for(const e of t.nodeViews)this.deps.nodeViewRegistry.removeNodeView(e);for(const e of t.keymaps)this.deps.keymapRegistry.removeKeymap(e);for(const e of t.inputRules)this.deps.inputRuleRegistry.removeInputRule(e);for(const e of t.markdownSyntaxExtensions)this.deps.markdownSyntaxRegistry.remove(e);for(const e of t.toolbarItems)this.deps.toolbarRegistry.removeToolbarItem(e);for(const e of t.fileHandlers)this.deps.fileHandlerRegistry.removeFileHandler(e);for(const e of t.blockTypePickerEntries)this.deps.blockTypePickerRegistry.removeBlockTypePickerEntry(e);for(const e of t.stylesheets){const t=this.pluginStyleSheets.indexOf(e);-1!==t&&this.pluginStyleSheets.splice(t,1)}this.registrations.delete(e)}}clear(){this.registrations.clear(),this.pluginStyleSheets.length=0}get rawStyleSheets(){return this.pluginStyleSheets}},no=class{services=/* @__PURE__ */new Map;register(e,t){if(this.services.has(e.id))throw new Error(`Service "${e.id}" is already registered.`);this.services.set(e.id,t)}get(e){return this.services.get(e.id)}has(e){return this.services.has(e)}remove(e){this.services.delete(e)}clear(){this.services.clear()}get rawMap(){return this.services}},io=class{container;getState;composition;elements=/* @__PURE__ */new Map;destroyed=!1;ready=!1;onFocus=()=>{this.restoreSelection()};constructor(e,t,n){this.container=e,this.getState=t,this.composition=n,e.addEventListener("focus",this.onFocus)}start(){this.ready=!0}register(e){if(this.destroyed)return()=>{};this.elements.set(e,(this.elements.get(e)??0)+1);let t=!0;return()=>{if(!t)return;t=!1;const n=this.elements.get(e)??0;n>1?this.elements.set(e,n-1):this.elements.delete(e)}}contains(e){let t=e;for(;t;){if(t===this.container||[...this.elements.keys()].some(e=>e.contains(t)))return!0;t=t.parentNode??(t instanceof ShadowRoot?t.host:null)}return!1}focus(e){return!(this.destroyed||this.composition().isComposing||!e.isConnected||!this.contains(e))&&(e.focus({preventScroll:!0}),this.activeElement()===e)}focusEditor(){return!(this.destroyed||!this.container.isConnected||this.composition().isComposing)&&(this.container.focus({preventScroll:!0}),this.restoreSelection(),this.activeElement()===this.container)}shouldSyncSelection(){const e=this.activeElement();return!e||e===this.container.ownerDocument.body||this.container.contains(e)}destroy(){this.destroyed=!0,this.container.removeEventListener("focus",this.onFocus),this.elements.clear()}activeElement(){let e=this.container.ownerDocument.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e}restoreSelection(){!this.ready||this.destroyed||this.composition().isComposing||kn(this.container,this.getState().selection)}};function so(e){const{x:t,y:n,top:i,right:s,bottom:r,left:o,width:a,height:c}=e;return Object.freeze({x:t,y:n,top:i,right:s,bottom:r,left:o,width:a,height:c})}function ro(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&e.height>0}function oo(e,t,n){if(!e.length||!t||!n)return null;const i=Math.min(...e.map(e=>e.left)),s=Math.min(...e.map(e=>e.top)),r=Math.max(...e.map(e=>e.right)),o=Math.max(...e.map(e=>e.bottom));return Object.freeze({bounds:so({x:i,y:s,left:i,top:s,right:r,bottom:o,width:r-i,height:o-s}),rects:Object.freeze(e.map(so)),anchor:so(t),focus:so(n)})}function ao(e,t){const n=e.querySelector(`[data-block-id="${CSS.escape(t)}"]`)?.getBoundingClientRect();return n&&ro(n)?so(n):null}function co(e,t){let n=e;for(;n instanceof Element&&!vn(n);)n=t?n.firstChild:n.lastChild;if(!vn(n)||n.hasAttribute("data-widget")||n instanceof HTMLBRElement)return null;const i=n.getBoundingClientRect();if(!ro(i))return null;const s=t!==un(n.parentElement??n)?i.left:i.right;return so(new DOMRect(s,i.y,0,i.height))}function lo(e,t){const n=e.ownerDocument.createRange();n.setStart(t.node,t.offset),n.collapse(!0);const i=Array.from(n.getClientRects()).find(ro);if(i)return so(i);if(t.node instanceof Element){const e=t.node.childNodes[t.offset],n=t.node.childNodes[t.offset-1],i=e??(n instanceof HTMLBRElement&&"false"!==n.getAttribute("contenteditable")?n:void 0);if(i instanceof HTMLBRElement){const e=i.getBoundingClientRect();if(ro(e))return so(e)}return co(e,!0)??co(n,!1)}return null}var ho=class{container;measure;reportError;listeners=/* @__PURE__ */new Set;cleanups=[];frame=null;destroyed=!1;previous="";constructor(e,t,n){this.container=e,this.measure=t,this.reportError=n}subscribe(e){return this.destroyed?()=>{}:(this.listeners.add(e),1===this.listeners.size&&this.observe(),this.deliver(e,this.measure()),()=>{this.listeners.delete(e),this.listeners.size||this.stop()})}invalidate=()=>{!this.destroyed&&this.listeners.size&&null===this.frame&&(this.frame=requestAnimationFrame(()=>{this.frame=null;const e=this.measure(),t=JSON.stringify(e);if(t!==this.previous){this.previous=t;for(const t of[...this.listeners])this.listeners.has(t)&&this.deliver(t,e)}}))};destroy(){this.destroyed=!0,this.listeners.clear(),this.stop()}deliver(e,t){try{e(t)}catch(n){this.reportError(n)}}observe(){const e=this.container.ownerDocument,t=e.defaultView,n=(e,t)=>{e.addEventListener(t,this.invalidate,!0),this.cleanups.push(()=>e.removeEventListener(t,this.invalidate,!0))};let i=this.container;const s="undefined"==typeof ResizeObserver?null:new ResizeObserver(this.invalidate),r=new MutationObserver(this.invalidate);for(;i;)i instanceof Element&&(s?.observe(i),r.observe(i,{attributes:!0,attributeFilter:["class","style","dir","hidden"]})),(i instanceof ShadowRoot||i instanceof Document)&&n(i,"scroll"),i=i instanceof ShadowRoot?i.host:i.parentNode;const o=new MutationObserver(this.invalidate);n(e,"scroll"),o.observe(this.container,{subtree:!0,childList:!0,characterData:!0,attributes:!0}),this.cleanups.push(()=>s?.disconnect(),()=>r.disconnect(),()=>o.disconnect()),n(this.container,"load"),n(this.container,"compositionend"),t&&n(t,"resize"),t?.visualViewport&&(n(t.visualViewport,"resize"),n(t.visualViewport,"scroll")),e.fonts&&n(e.fonts,"loadingdone"),this.invalidate()}stop(){for(const e of this.cleanups)e();this.cleanups=[],null!==this.frame&&cancelAnimationFrame(this.frame),this.frame=null,this.previous=""}},uo=class{activePopup=null;activePopupButton=null;activeHandle=null;getActiveElement;locale;popupManager=null;constructor(e,t=On){this.getActiveElement=e,this.locale=t}setPopupManager(e){this.popupManager=e}isOpen(){return null!==this.activePopup}toggle(e,t,n){this.activePopup?this.close():this.open(t,n,{anchor:e,restoreFocusTo:e,trigger:e})}close(){if(this.activeHandle){const e=this.activeHandle;return this.activeHandle=null,this.clearButtonState(),void e.close()}this.clearButtonState(),this.activePopup&&(this.activePopup.remove(),this.activePopup=null)}closeAndRestoreFocus(){const e=this.activePopupButton;this.close(),e?.focus()}destroy(){this.close()}open(e,t,n){if(!this.popupManager)return null;this.close();const i=n.trigger;this.activePopupButton=i??null,i?.classList.add("notectl-toolbar-btn--popup-open"),i?.setAttribute("aria-expanded","true");const s=this.popupManager.open({anchor:n.anchor,className:"notectl-toolbar-popup",referenceNode:t.getContainer(),restoreFocusTo:n.restoreFocusTo??i??t.getContainer(),position:"below-start",onClose:()=>{this.activeHandle=null,this.clearButtonState(),this.activePopup=null,n.onClose?.()},content:(n,i)=>{this.activePopup=n,this.renderPopupContent(n,e,t,i),n.addEventListener("keydown",e=>this.handlePopupKeydown(e))}});return this.activeHandle=this.activePopup?s:null,this.activeHandle}renderPopupContent(e,t,n,i){const s=()=>{i({restoreFocusTo:null}),n.getContainer().focus()};switch(t.popupType){case"gridPicker":Hn(e,t.popupConfig,s,this.locale);break;case"dropdown":Ln(e,t.popupConfig,e=>n.executeCommand(e),s);break;case"custom":case"combobox":t.renderPopup(e,n,i)}}clearButtonState(){this.activePopupButton&&(this.activePopupButton.classList.remove("notectl-toolbar-btn--popup-open"),this.activePopupButton.setAttribute("aria-expanded","false"),this.activePopupButton=null)}handlePopupKeydown(e){if(!this.activePopup||e.defaultPrevented||e.isComposing)return;if("Escape"===e.key)return e.preventDefault(),e.stopPropagation(),void this.closeAndRestoreFocus();if("Tab"===e.key&&!this.activePopup.querySelector("input, textarea, select"))return e.preventDefault(),void this.closeAndRestoreFocus();if(e.target instanceof HTMLElement&&(e.target.matches("input, textarea, select")||e.target.isContentEditable))return;const t=this.activePopup.querySelectorAll('[role="menuitem"]');t.length>0?this.handleDropdownKeydown(e,t):null===this.activePopup.querySelector(".notectl-grid-picker__cell")?this.handleCustomPopupKeydown(e):this.handleGridKeydown(e)}handleDropdownKeydown(e,t){const n=Array.from(t),i=n.indexOf(this.getActiveElement());switch(e.key){case"ArrowDown":e.preventDefault(),n[_n(n,i,1)]?.focus();break;case"ArrowUp":e.preventDefault(),n[_n(n,i,-1)]?.focus();break;case"Enter":case" ":{e.preventDefault();const t=n[i];t&&t.click();break}}}handleGridKeydown(e){const t=this.getActiveElement(),n=Number(t?.getAttribute("data-row")??1),i=Number(t?.getAttribute("data-col")??1),s=this.activePopup?.querySelector(".notectl-grid-picker__grid")??null;if(!s)return;const r=s.querySelector(".notectl-grid-picker__cell:last-child"),o=Number(r?.getAttribute("data-col")??1),a=Number(r?.getAttribute("data-row")??1);if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key)){e.preventDefault();const[t,r]=Fn(n,i,a,o,e.key,!!this.activePopup&&un(this.activePopup));s.querySelector(`.notectl-grid-picker__cell[data-row="${t}"][data-col="${r}"]`)?.focus(),An(s,t,r);const c=this.activePopup?.querySelector(".notectl-grid-picker__label")??null;c&&(c.textContent=this.locale.gridPickerLabel(t,r))}"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),t?.click())}handleCustomPopupKeydown(e){if(!this.activePopup)return;const t=Array.from(this.activePopup.querySelectorAll("button"));if(0===t.length)return;const n=this.getActiveElement(),i=t.indexOf(n);switch(e.key){case"ArrowDown":e.preventDefault(),t[_n(t,i,1)]?.focus();break;case"ArrowUp":e.preventDefault(),t[_n(t,i,-1)]?.focus();break;case"Enter":case" ":e.preventDefault(),t[i]?.click()}}},po=Object.freeze([]),fo=Object.freeze({type:"text",collapsed:!0,geometry:null}),mo=class{context;canExecute;logger;interaction;popups;geometry;listeners=/* @__PURE__ */new Set;unsubscribeRegistry;onComposition=()=>{queueMicrotask(()=>this.refresh())};actions=po;controller=null;activeAction=null;ready=!1;destroyed=!1;constructor(e,t,n){this.context=e,this.canExecute=t,this.logger=n;const i=e.getContainer();this.interaction=new io(i,e.getState,e.getCompositionState),this.popups=new Xt(i,e=>this.registerInteraction(e)),this.geometry=new ho(i,()=>this.getSelection(),e=>this.report(e)),this.unsubscribeRegistry=e.getToolbarRegistry().subscribe(()=>this.refresh()),e.registerStyleSheet(".notectl-toolbar-popup{background:var(--notectl-surface-overlay);border:1px solid var(--notectl-border);box-shadow:0 4px 12px var(--notectl-shadow);border-radius:6px;overflow:hidden}.notectl-grid-picker__cell:focus-visible{outline:2px solid var(--notectl-focus-ring);outline-offset:-1px}.notectl-grid-picker__cell--highlighted{background:var(--notectl-primary-muted);border-color:var(--notectl-primary)}.notectl-dropdown{min-width:160px;padding:4px 0}.notectl-dropdown__item{text-align:start;cursor:pointer;width:100%;color:var(--notectl-fg);white-space:nowrap;background:0 0;border:none;align-items:center;padding:8px 12px;font-family:inherit;font-size:14px;line-height:1.4;display:flex}@media (hover:hover){.notectl-dropdown__item:hover{background:var(--notectl-hover-bg)}}.notectl-dropdown__item:focus-visible{background:var(--notectl-hover-bg);outline:none}.notectl-dropdown__item-icon{width:28px;color:var(--notectl-fg-muted);flex-shrink:0;justify-content:center;align-items:center;font-weight:600;display:inline-flex}.notectl-dropdown__item-label{flex:1}.notectl-dropdown__item:disabled{opacity:.4;cursor:not-allowed}@media (hover:hover){.notectl-dropdown__item:disabled:hover{background:0 0}}.notectl-dropdown__item--active{color:var(--notectl-accent-fg)}.notectl-dropdown__item-icon svg{fill:currentColor;width:16px;height:16px;display:block}.notectl-dropdown__separator{background:var(--notectl-border);height:1px;margin:4px 0}"),e.registerService(jn,this),e.registerService(Jt,this.popups),i.addEventListener("compositionstart",this.onComposition),i.addEventListener("compositionend",this.onComposition)}async start(){const e=await Zt(this.context,void 0,On,Nn);this.destroyed||(this.controller=new uo(()=>Tn(this.context.getContainer()),e),this.controller.setPopupManager(this.popups),this.ready=!0,this.interaction.start(),this.refresh())}getActions(){return this.actions}subscribeActions(e){return this.destroyed?()=>{}:(this.listeners.add(e),this.deliver(e),()=>{this.listeners.delete(e)})}refresh(){if(!this.ready||this.destroyed)return;const e=this.context.getToolbarRegistry().getToolbarItems().map(e=>this.snapshot(e));if(this.activeAction&&!e.find(e=>e.id===this.activeAction)?.enabled&&this.closePopup(),JSON.stringify(e)!==JSON.stringify(this.actions)){this.actions=Object.freeze(e);for(const e of[...this.listeners])this.listeners.has(e)&&this.deliver(e)}this.geometry.invalidate()}executeAction(e){const t=this.availableItem(e);return!(!t||t.popupType)&&this.context.executeCommand(t.command)}openAction(e,t={}){const n=this.availableItem(e);if(!n?.popupType||!this.controller)return null;const i=t.anchor??this.createSelectionAnchor();if("getRect"in i&&!i.getRect())return null;this.closePopup(),this.activeAction=e;try{return this.controller.open(n,this.context,{...t,anchor:i,onClose:()=>{this.activeAction=null}})}catch(s){return this.closePopup(),this.report(s),null}}closePopup(){this.activeAction=null,this.controller?.close()}isPopupOpen(){return this.controller?.isOpen()??!1}getSelection(){if(!this.ready||this.destroyed)return fo;const e=this.context.getService(Bn)?.getSelectedCellIds()??[];return function(e,t,n=[],i=!1){const s=n.length?"cell":ee(t)?"node":de(t)?"gap":"text",r="gap"===s||"text"===s&&Z(t);let o=null;if(e.isConnected&&e.getClientRects().length&&!i)try{"visible"===getComputedStyle(e).visibility&&(o=function(e,t,n){if(n.length){const t=n.map(t=>ao(e,t));if(t.some(e=>null===e))return null;const i=t.filter(e=>null!==e);return oo(i,i[0]??null,i.at(-1)??null)}if(ee(t)||de(t)){let n=ao(e,ee(t)?t.nodeId:t.blockId);if(n&&de(t)){const e="before"===t.side?n.top:n.bottom;n=so({...n,y:e,top:e,bottom:e+1,height:1})}return n?oo([n],n,n):null}const i=Mn(e,t.anchor),s=Mn(e,t.head);if(!i||!s)return null;const r=e.ownerDocument.createRange();r.setStart(i.node,i.offset),r.collapse(!0);const o=e.ownerDocument.createRange();o.setStart(s.node,s.offset),o.collapse(!0);const a=r.compareBoundaryPoints(Range.START_TO_START,o)>0,c=e.ownerDocument.createRange(),l=a?s:i,d=a?i:s;c.setStart(l.node,l.offset),c.setEnd(d.node,d.offset);const h=lo(e,i),u=lo(e,s),p=Array.from(c.getClientRects()).filter(ro);return!p.length&&h&&Z(t)&&p.push(new DOMRect(h.x,h.y,h.width,h.height)),oo(p,h,u)}(e,t,n))}catch{}return Object.freeze({type:s,collapsed:r,geometry:o})}(this.context.getContainer(),this.context.getState().selection,e,this.context.getCompositionState().isComposing)}subscribeSelection(e){return this.geometry.subscribe(e)}invalidateGeometry(){this.geometry.invalidate()}createSelectionAnchor(e="bounds"){let t;return Object.freeze({getRect:()=>this.destroyed?null:(t??this.getSelection()).geometry?.[e]??null,subscribe:e=>{const n=this.subscribeSelection(n=>{t=n,e()});return()=>{n(),t=void 0}}})}registerInteraction(e){return this.interaction.register(e)}focus(e){return this.ready&&this.interaction.focus(e)}focusEditor(){return this.ready&&this.interaction.focusEditor()}destroy(){this.destroyed||(this.destroyed=!0,this.ready=!1,this.listeners.clear(),this.unsubscribeRegistry(),this.context.getContainer().removeEventListener("compositionstart",this.onComposition),this.context.getContainer().removeEventListener("compositionend",this.onComposition),this.geometry.destroy(),this.interaction.destroy(),this.popups.destroy(),this.controller?.destroy(),this.controller=null,this.actions=po)}availableItem(e){if(!this.ready||this.destroyed||this.context.getCompositionState().isComposing)return null;const t=this.context.getToolbarRegistry().getToolbarItem(e);return t&&this.snapshot(t).enabled?t:null}snapshot(e){const t=this.context.getState();let n=!1,i=!1,s=e.icon??"",r=null;try{n=(e.command?this.canExecute(e.command):!!e.popupType&&!this.context.isReadOnly())&&(e.isEnabled?.(t)??!0)&&!this.context.getCompositionState().isComposing,i=e.isActive?.(t)??!1,s=e.getIcon?.(t)??s,r="combobox"===e.popupType?e.getLabel(t):null}catch(o){n=!1,this.report(o)}return Object.freeze({id:e.id,group:e.group,label:e.label,tooltip:e.tooltip??e.label,icon:s,value:r,active:i,enabled:n,popupType:e.popupType??null})}deliver(e){try{e(this.actions)}catch(t){this.report(t)}}report(e){this.logger.error("[EditorUI] callback failed",e)}},go=class{schemaRegistry=new fn;keymapRegistry=new Dr;inputRuleRegistry=new Or;markdownSyntaxRegistry=new Nr;fileHandlerRegistry=new Ar;nodeViewRegistry=new Hr;toolbarRegistry=new Dn;blockTypePickerRegistry=new $n;logger;commandRegistry;serviceRegistry=new no;middlewareChain;eventBus;registrationTracker;lifecycle;callbackExecutor;pendingDestroy=null;ui=null;uiInit=null;constructor(e={}){this.logger=e.logger??Qt,this.callbackExecutor=new Ms(e=>{this.logger.error(`[PluginCallback] Plugin "${e.pluginId}" ${e.kind} "${e.name}" error`,e.cause)}),this.commandRegistry=new zr(this.logger),this.middlewareChain=new Fr(this.logger),this.eventBus=new _r(this.logger),this.registrationTracker=new to({commandRegistry:this.commandRegistry,serviceRegistry:this.serviceRegistry,middlewareChain:this.middlewareChain,schemaRegistry:this.schemaRegistry,keymapRegistry:this.keymapRegistry,inputRuleRegistry:this.inputRuleRegistry,markdownSyntaxRegistry:this.markdownSyntaxRegistry,nodeViewRegistry:this.nodeViewRegistry,toolbarRegistry:this.toolbarRegistry,fileHandlerRegistry:this.fileHandlerRegistry,blockTypePickerRegistry:this.blockTypePickerRegistry}),this.lifecycle=new eo(this.registrationTracker,this.logger)}registerService(e,t){this.serviceRegistry.register(e,t)}register(e){if("core-ui"===e.id)throw new Error('Plugin id "core-ui" is reserved for editor services.');if(this.pendingDestroy)throw new Error(`Cannot register plugin "${e.id}" while destruction is in progress.`);this.lifecycle.register(e)}init(e){if(this.pendingDestroy)return Promise.reject(/* @__PURE__ */new Error("Cannot initialize PluginManager while destruction is in progress."));if(this.uiInit)return this.uiInit;const t={...e,onBeforeReady:async()=>{this.schemaRegistry.finalize(),await(e.onBeforeReady?.()),e.isCancelled?.()||await(this.ui?.start())}};return this.ui??=new mo(this.createContext("core-ui",e),e=>this.canExecuteCommand(e),this.logger),this.uiInit=this.lifecycle.init(t,(e,t)=>this.createContext(e,t)).then(()=>{e.isCancelled?.()&&this.disposeUI()}).catch(e=>{throw this.disposeUI(),e}),this.uiInit}notifyStateChange(e,t,n){this.lifecycle.notifyStateChange(e,t,n),this.ui?.refresh()}collectDecorations(e,t){return this.lifecycle.collectDecorations(e,t)}dispatchWithMiddleware(e,t,n){this.middlewareChain.dispatch(e,t,e=>{n(Lr(e,t.doc))})}canExecuteCommand(e){return this.commandRegistry.canExecute(e,this.lifecycle.isReadOnly())}executeCommand(e){return this.commandRegistry.execute(e,this.lifecycle.isReadOnly())}isReadonlyBypassed(){return this.commandRegistry.isReadonlyBypassed()}configurePlugin(e,t){this.lifecycle.configurePlugin(e,t)}isReadOnly(){return this.lifecycle.isReadOnly()}setReadOnly(e){this.lifecycle.setReadOnly(e),e&&this.ui?.popups.closeAll(),this.ui?.refresh()}shouldSyncSelection(){return this.ui?.interaction.shouldSyncSelection()??!0}getPluginIds(){return this.lifecycle.getPluginIds()}getMiddlewareChain(){return this.middlewareChain.getChain()}getPasteInterceptors(){return this.middlewareChain.getPasteInterceptors()}getTextInputInterceptors(){return this.middlewareChain.getTextInputInterceptors()}getCallbackExecutor(){return this.callbackExecutor}get(e){return this.lifecycle.get(e)}getService(e){return this.serviceRegistry.get(e)}onEvent(e,t){return this.eventBus.on(e,t)}getPluginStyleSheets(){return this.registrationTracker.rawStyleSheets}destroy(){if(this.pendingDestroy)return this.pendingDestroy;this.ui?.destroy();const e=this.lifecycle.destroy().then(()=>this.clearRegistries()).finally(()=>{this.pendingDestroy===e&&(this.pendingDestroy=null)});return this.pendingDestroy=e,e}clearRegistries(){this.ui=null,this.uiInit=null,this.commandRegistry.clear(),this.serviceRegistry.clear(),this.middlewareChain.clear(),this.registrationTracker.clear(),this.eventBus.clear(),this.schemaRegistry.clear(),this.keymapRegistry.clear(),this.inputRuleRegistry.clear(),this.markdownSyntaxRegistry.clear(),this.fileHandlerRegistry.clear(),this.nodeViewRegistry.clear(),this.toolbarRegistry.clear(),this.blockTypePickerRegistry.clear()}disposeUI(){this.ui?.destroy(),this.ui=null,this.uiInit=null,this.registrationTracker.cleanup("core-ui")}createContext(e,t){const n=t.getCompositionState??(()=>yo),i={pluginId:e,logger:this.logger,getState:t.getState,dispatch:t.dispatch,getContainer:t.getContainer,getPluginContainer:t.getPluginContainer,announce:t.announce,hasAnnouncement:t.hasAnnouncement,commands:this.commandRegistry.rawMap,services:this.serviceRegistry.rawMap,middlewares:this.middlewareChain.rawMiddlewares,pasteInterceptors:this.middlewareChain.rawPasteInterceptors,textInputInterceptors:this.middlewareChain.rawTextInputInterceptors,pluginStyleSheets:this.registrationTracker.rawStyleSheets,plugins:this.lifecycle.rawPlugins,eventBus:this.eventBus,callbackExecutor:this.callbackExecutor,schemaRegistry:this.schemaRegistry,keymapRegistry:this.keymapRegistry,inputRuleRegistry:this.inputRuleRegistry,markdownSyntaxRegistry:this.markdownSyntaxRegistry,toolbarRegistry:this.toolbarRegistry,blockTypePickerRegistry:this.blockTypePickerRegistry,fileHandlerRegistry:this.fileHandlerRegistry,nodeViewRegistry:this.nodeViewRegistry,getCompositionState:n,isReadOnly:()=>this.lifecycle.isReadOnly(),invalidateMiddlewareSort:()=>this.middlewareChain.invalidateMiddlewareSort(),invalidatePasteSort:()=>this.middlewareChain.invalidatePasteSort(),invalidateTextInputSort:()=>this.middlewareChain.invalidateTextInputSort(),executeCommand:e=>this.executeCommand(e),onCommandsChanged:()=>this.ui?.refresh()},{context:s,registrations:r}=function(e){const t={commands:[],services:[],middlewares:[],pasteInterceptors:[],textInputInterceptors:[],unsubscribers:[],nodeSpecs:[],nodeSpecExtensions:[],markSpecs:[],inlineNodeSpecs:[],styleClasses:[],nodeViews:[],keymaps:[],inputRules:[],markdownSyntaxExtensions:[],toolbarItems:[],fileHandlers:[],blockTypePickerEntries:[],stylesheets:[]},n=function(e,t){return{emit:(t,n)=>e.emit(t,n),on:(n,i)=>{const s=e.on(n,i);return t.unsubscribers.push(s),s},off:(t,n)=>e.off(t,n)}}(e.eventBus,t);return{context:{getState:e.getState,dispatch:e.dispatch,getContainer:e.getContainer,getPluginContainer:e.getPluginContainer,isReadOnly:e.isReadOnly,getEventBus:()=>n,...$r(e.pluginId,e.commands,t,e.executeCommand,e.onCommandsChanged),...Kr(e.services,t),...Vr(e,t),...qr(e,t),...Jr(e.pluginId,e,t),...Zr(e),updateConfig:t=>{const n=e.plugins.get(e.pluginId);if(n?.onConfigure)try{n.onConfigure(t)}catch(i){const t=`[PluginContext] Plugin "${e.pluginId}" error in onConfigure`;e.logger.error(t,i)}},announce:t=>{e.announce?.(t)},hasAnnouncement:()=>e.hasAnnouncement?.()??!1,getCompositionState:()=>e.getCompositionState()},registrations:t}}(i);return this.registrationTracker.track(e,r),s}},yo={isComposing:!1,activeBlockId:null},ko=class{undoStack=[];redoStack=[];groupTimeoutMs;maxDepth;lastOrigin=null;constructor(e){this.groupTimeoutMs=e?.groupTimeoutMs??500,this.maxDepth=e?.maxDepth??100}push(e){if("history"===e.metadata.origin)return;if(!e.steps.some(e=>"setStoredMarks"!==e.type))return void(this.lastOrigin=null);const t=e.metadata.timestamp,n=this.undoStack[this.undoStack.length-1];for(n&&"input"===e.metadata.origin&&"input"===this.lastOrigin&&t-n.timestamp<this.groupTimeoutMs&&this.isSameInputType(n.transactions,e)&&n?this.undoStack[this.undoStack.length-1]={...n,transactions:[...n.transactions,e],timestamp:t}:this.undoStack.push({transactions:[e],timestamp:t,interveningMapping:Lt.empty}),this.lastOrigin=e.metadata.origin,this.redoStack=[];this.undoStack.length>this.maxDepth;)this.undoStack.shift()}recordIntervening(e){e.isEmpty||(this.lastOrigin=null,Io(this.undoStack,e),Io(this.redoStack,e))}undo(e){const t=this.undoStack.pop();if(!t)return null;const n=bo(t,e,"undo");return null===n?(this.lastOrigin=null,null):(this.redoStack.push({transactions:[n.transaction],timestamp:Date.now(),interveningMapping:Lt.empty}),this.lastOrigin=null,{state:n.newState,transaction:n.transaction})}redo(e){const t=this.redoStack.pop();if(!t)return null;const n=bo(t,e,"redo");return null===n?(this.lastOrigin=null,null):(this.undoStack.push({transactions:[n.transaction],timestamp:Date.now(),interveningMapping:Lt.empty}),this.lastOrigin=null,{state:n.newState,transaction:n.transaction})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.lastOrigin=null}isSameInputType(e,t){const n=e[e.length-1];return!!n&&n.steps[0]?.type===t.steps[0]?.type}};function bo(e,t,n){let i=e.interveningMapping,s=t.doc;const r=[],o=[];for(let h=e.transactions.length-1;h>=0;h--){const t=e.transactions[h];if(t)for(let e=t.steps.length-1;e>=0;e--){const n=t.steps[e],a=t.forwardStepMaps[e];if(!n||!a)continue;const c=Zi(Xi(n),i,s);if(null===c)return null;const l=vo(s,c);if(null===l)return null;const d=Yi(s,c);r.push(c),o.push(d),s=l,i=wo(a,i,d)}}const a=function(e){const t=e.transactions[0];return t?Bi(t):null}(e),c=Lr({steps:r,selectionBefore:t.selection,selectionAfter:t.selection,storedMarksAfter:a,mapping:Lt.from(o),forwardStepMaps:o,metadata:{origin:"history",timestamp:Date.now(),historyDirection:n}},t.doc);let l=t.apply(c);const d=e.transactions[0];if(d){const e=er(d.selectionBefore,i);null!==e&&(l=l.withSelection(e))}return{newState:l,transaction:Fi({steps:c.steps,selectionBefore:c.selectionBefore,selectionAfter:Hi(l.selection),storedMarksAfter:c.storedMarksAfter,forwardStepMaps:c.forwardStepMaps,metadata:c.metadata})}}function vo(e,t){try{return Qi(e,t)}catch(n){if(n instanceof wi)return null;throw n}}function wo(e,t,n){return t.isEmpty&&Nt(Wt(e),n)?t:Lt.from([e]).appendMapping(t).appendMap(n)}function Io(e,t){for(let n=0;n<e.length;n++){const i=e[n];i&&(e[n]={...i,interveningMapping:i.interveningMapping.appendMapping(t)})}}function So(e){for(const t of e.steps)if("setStoredMarks"!==t.type)return!1;return!0}function xo(e){return!!e.metadata.readonlyAllowed||So(e)}function Ro(e,t){if(t){const n=t.getMarkSpec(e.type);if(n)return n.rank??100}switch(e.type){case"bold":return 0;case"italic":return 1;case"underline":return 2;default:return 100}}function Co(e,t,n){if(0===t.length)return e;const i=[...t].sort((e,t)=>Ro(e,n)-Ro(t,n));let s=e;for(let r=i.length-1;r>=0;r--){const e=i[r];if(!e)continue;const t=Mo(e,n);t.appendChild(s),s=t}return s}function Mo(e,t){if(t){const n=t.getMarkSpec(e.type);if(n)return n.toDOM(e)}switch(e.type){case"bold":return document.createElement("strong");case"italic":return document.createElement("em");case"underline":return document.createElement("u");default:return document.createElement("span")}}var Po=class{wrapperElement=null;container;registry;constructor(e,t){this.container=e,this.registry=t}get isActive(){return null!==this.wrapperElement}onCompositionStart(e){this.cleanup();const t=e.storedMarks;if(!t||0===t.length)return;const n=e.selection;if(!te(n))return;if(!Z(n))return;const i=document.createElement("span");i.setAttribute(In,"");const s=document.createTextNode("​"),r=Co(s,t,this.registry);i.appendChild(r);const o=Cn();if(!o||0===o.rangeCount)return;let a;const c=wn(this.container,o);if(c){const e=document.createRange();try{e.setStart(c.anchorNode,c.anchorOffset),e.setEnd(c.focusNode,c.focusOffset)}catch{return}a=e}else a=o.getRangeAt(0);a.insertNode(i);try{o.collapse(s,s.length)}catch{}this.wrapperElement=i}cleanup(){this.wrapperElement&&(this.wrapperElement.remove(),this.wrapperElement=null)}};function Eo(e){return e.shiftKey||e.ctrlKey||e.altKey||e.metaKey}function To(e,t){return Math.abs(t.clientX-e.clientX)>4||Math.abs(t.clientY-e.clientY)>4}var Bo=class{deps;handleSelectionChange;handleMousedown;handleMousemove;handleMouseup;handleDragover;handleDrop;handleCompositionStart;handleCompositionEnd;pendingNodeSelectionClear=!1;pendingGapCursorClear=!1;pendingBelowContentPress=null;pendingDropBookmarks=/* @__PURE__ */new Set;callbackExecutor;active=!0;constructor(e){this.deps=e,this.callbackExecutor=e.callbackExecutor??Ms.silent,this.handleCompositionStart=t=>{sn(t,e.contentElement)&&e.cursorWrapper.onCompositionStart(e.getState())},this.handleCompositionEnd=t=>{sn(t,e.contentElement)&&e.cursorWrapper.cleanup()},e.contentElement.addEventListener("compositionstart",this.handleCompositionStart),e.contentElement.addEventListener("compositionend",this.handleCompositionEnd),this.handleSelectionChange=this.onSelectionChange.bind(this),document.addEventListener("selectionchange",this.handleSelectionChange),this.handleMousedown=this.onMousedown.bind(this),e.contentElement.addEventListener("mousedown",this.handleMousedown),this.handleMousemove=this.onMousemove.bind(this),this.handleMouseup=this.onMouseup.bind(this),document.addEventListener("mouseup",this.handleMouseup),this.handleDragover=this.onDragover.bind(this),e.contentElement.addEventListener("dragover",this.handleDragover),this.handleDrop=this.onDrop.bind(this),e.contentElement.addEventListener("drop",this.handleDrop)}syncSelectionFromDOM(){if(this.deps.compositionState.isComposing)return;this.deps.cursorWrapper.isActive&&this.deps.cursorWrapper.cleanup();const e=this.deps.getState();if(ee(e.selection)&&!this.pendingNodeSelectionClear)return;if(de(e.selection)&&!this.pendingGapCursorClear)return;this.pendingNodeSelectionClear=!1,this.pendingGapCursorClear=!1;const t=xn(this.deps.contentElement);if(!t)return;if(ie(t,e.selection))return;const n=e.transaction("input").setSelection(t).setStoredMarks(null,e.storedMarks).build(),i=e.apply(n);this.deps.applyUpdate(i,n,!0)}destroy(){if(!this.active)return;this.active=!1;const e=this.deps.contentElement;e.removeEventListener("compositionstart",this.handleCompositionStart),e.removeEventListener("compositionend",this.handleCompositionEnd),document.removeEventListener("selectionchange",this.handleSelectionChange),document.removeEventListener("mouseup",this.handleMouseup),e.removeEventListener("mousedown",this.handleMousedown),this.clearBelowContentPress(),e.removeEventListener("dragover",this.handleDragover),e.removeEventListener("drop",this.handleDrop);for(const t of this.pendingDropBookmarks)t.cancelled=!0;this.pendingDropBookmarks.clear()}onStateChange(e,t,n){e.doc!==t.doc&&(this.clearBelowContentPress(),this.pendingNodeSelectionClear=!1,this.pendingGapCursorClear=!1),ee(t.selection)||(this.pendingNodeSelectionClear=!1),de(t.selection)||(this.pendingGapCursorClear=!1);for(const i of this.pendingDropBookmarks){if(!i.position)continue;if(e.doc!==t.doc&&0===n.steps.length){i.cancelled=!0,this.pendingDropBookmarks.delete(i);continue}const s=n.mapping.mapResult(i.position,-1);!s.deleted&&t.getBlock(s.pos.blockId)?i.position=s.pos:(i.cancelled=!0,this.pendingDropBookmarks.delete(i))}}onSelectionChange(){if(this.deps.isUpdating())return;const e=this.deps.contentElement.getRootNode(),t="activeElement"in e?e.activeElement:document.activeElement;(this.deps.contentElement.contains(t)||t===this.deps.contentElement)&&nn(t,this.deps.contentElement)&&this.syncSelectionFromDOM()}onMousedown(e){if(this.clearBelowContentPress(),this.deps.isUpdating())return;if(!sn(e,this.deps.contentElement))return;this.deps.onMousedown?.();const t=e.target;if(!(t instanceof HTMLElement))return;const n=t.closest("[data-block-id]");if(!(n instanceof HTMLElement&&this.deps.contentElement.contains(n)))return void((this.deps.contentElement.contains(t)||t===this.deps.contentElement)&&this.trackBelowContentPress(e));if(!n.hasAttribute("data-void")&&!n.hasAttribute("data-selectable"))return void this.markPendingSelectionClear();if(n.querySelector("[data-content-dom]")?.contains(t))return void this.markPendingSelectionClear();e.preventDefault(),this.deps.contentElement.focus();const i=fe(n.getAttribute("data-block-id")??""),s=gn(this.deps.contentElement,n),r=ne(i,s),o=this.deps.getState(),a=o.transaction("input").setSelection(r).setStoredMarks(null,o.storedMarks).build(),c=o.apply(a);this.deps.applyUpdate(c,a)}trackBelowContentPress(e){this.deps.isReadOnly()||e.defaultPrevented||0!==e.button||Eo(e)||this.isBelowLastRootBlock(e.clientY)&&(this.markPendingSelectionClear(),this.pendingBelowContentPress={clientX:e.clientX,clientY:e.clientY,dragged:!1},document.addEventListener("mousemove",this.handleMousemove))}onMousemove(e){const t=this.pendingBelowContentPress;t&&(1&e.buttons?To(t,e)&&(t.dragged=!0,document.removeEventListener("mousemove",this.handleMousemove)):this.clearBelowContentPress())}onMouseup(e){const t=this.clearBelowContentPress();t&&(this.deps.isUpdating()||e.defaultPrevented||0!==e.button||0!==e.buttons||Eo(e)||t.dragged||To(t,e)||this.isBelowLastRootBlock(e.clientY)&&this.handleClickBelowContent())}clearBelowContentPress(){const e=this.pendingBelowContentPress;return this.pendingBelowContentPress=null,document.removeEventListener("mousemove",this.handleMousemove),e}isBelowLastRootBlock(e){const t=this.deps.getState(),n=t.doc.children[t.doc.children.length-1];if(!n)return!1;const i=this.deps.contentElement.querySelector(`[data-block-id="${n.id}"]`);return!!i&&e>i.getBoundingClientRect().bottom}handleClickBelowContent(){if(this.deps.isReadOnly())return;const e=this.deps.getState(),t=e.doc.children[e.doc.children.length-1];if(!t)return;const n=t.id,i=e.getBlock(n);if("paragraph"===i?.type&&0===A(i)){const t=e.transaction("input").setSelection(se(n,0)).build();return void this.deps.dispatch(t)}this.deps.contentElement.focus();const s=c(),r=e.transaction("input").insertNode([],e.doc.children.length,E(s)).setSelection(se(s,0)).build();this.deps.dispatch(r)}onDragover(e){this.deps.fileHandlerRegistry&&e.dataTransfer&&e.dataTransfer.types.includes("Files")&&e.preventDefault()}onDrop(e){if(this.deps.isReadOnly())return;if(!this.deps.fileHandlerRegistry)return;if(!e.dataTransfer)return;const t=Array.from(e.dataTransfer.files);if(0===t.length)return;const n={position:this.getPositionFromPoint(e.clientX,e.clientY),cancelled:!1};this.pendingDropBookmarks.add(n);const i=Ys({registry:this.deps.fileHandlerRegistry,executor:this.callbackExecutor,files:t,source:"drop",getPosition:()=>n.position,isActive:()=>this.active&&!this.deps.isReadOnly()&&!n.cancelled});if(i instanceof Promise)return e.preventDefault(),void this.finishAsyncFileDrop(i,n);this.pendingDropBookmarks.delete(n),i.handled&&e.preventDefault()}async finishAsyncFileDrop(e,t){try{await e}catch(n){this.callbackExecutor.reportFailure({pluginId:"core",name:"File drop continuation",kind:"file-handler"},n)}finally{this.pendingDropBookmarks.delete(t)}}getPositionFromPoint(e,t){const n=this.deps.contentElement.getRootNode(),i=Qe(n,e,t);return i&&this.deps.contentElement.contains(i.node)?Pn(this.deps.contentElement,i.node,i.offset):null}markPendingSelectionClear(){const e=this.deps.getState();ee(e.selection)&&(this.pendingNodeSelectionClear=!0),de(e.selection)&&(this.pendingGapCursorClear=!0)}},Ao=class{deps;navigationKeymap=null;goalColumn=null;preserveGoalColumn=!1;constructor(e){this.deps=e,this.registerKeymaps()}resetAfterUpdate(){this.preserveGoalColumn||(this.goalColumn=null)}clearGoalColumn(){this.goalColumn=null}destroy(){this.navigationKeymap&&this.deps.keymapRegistry&&(this.deps.keymapRegistry.removeKeymap(this.navigationKeymap),this.navigationKeymap=null)}registerKeymaps(){if(!this.deps.keymapRegistry)return;const e={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},t={};for(const[n,i]of Object.entries(e))t[n]=()=>this.handleArrow(i);this.navigationKeymap=t,this.deps.keymapRegistry.registerKeymap(t,{priority:"navigation"})}handleArrow(e){const t=this.deps.getState();return!ee(t.selection)&&!de(t.selection)&&!!Z(t.selection)&&("left"===e||"right"===e?this.handleHorizontalArrow(e):this.handleVerticalArrow(e))}handleHorizontalArrow(e){this.goalColumn=null;const t=this.deps.getState(),n=this.resolveLogicalDirection(t,e),i=tt(t,n);if(i)return this.deps.dispatch(i),this.validateSelectionAfterInlineSkip(),!0;if(!Je(this.deps.contentElement,t,e))return!1;const s=Ze(t,n);return!!s&&(this.deps.dispatch(s),!0)}resolveLogicalDirection(e,t){const n=e.selection;if(!te(n))return t;const i=this.deps.contentElement.querySelector(`[data-block-id="${n.anchor.blockId}"]`);return i instanceof HTMLElement&&"rtl"===pn(i)?"left"===t?"right":"left":t}handleVerticalArrow(e){const t=this.deps.getState(),n=this.deps.contentElement.ownerDocument.getSelection?.()??null,i=n?it(n,this.deps.contentElement):null;if(!Je(this.deps.contentElement,t,e,i))return!1;null===this.goalColumn&&i&&(this.goalColumn=i.left),this.preserveGoalColumn=!0;const s=et(this.deps.contentElement,t,e,this.goalColumn);return s?(this.deps.dispatch(s),this.preserveGoalColumn=!1,!0):(this.preserveGoalColumn=!1,!1)}validateSelectionAfterInlineSkip(){const e=this.deps.getState(),t=xn(this.deps.contentElement);t&&ie(t,e.selection)||kn(this.deps.contentElement,e.selection)}};function Oo(e,t,n){if(!t)return;const i=/* @__PURE__ */new Set,s=n?.includeRoot??!0,r=(e,o)=>{for(const t of a(e))r(t,!1);if(o&&!s)return;const c=t.get(e.id);c&&(n?.ownerDOM&&c.dom!==n.ownerDOM&&!n.ownerDOM.contains(c.dom)||(Do(t,c),i.has(c)||(i.add(c),c.destroy?.())))};r(e,!0)}function Do(e,t){for(const[n,i]of e)i===t&&e.delete(n)}function No(e,t){const n=[];let i=null,s=[];for(const r of e){const e=t.getNodeSpec(r.type)?.wrapper?.(r);e&&i&&e.key===i.key?s.push(r.id):e?(i&&s.length>0&&n.push({spec:i,blockIds:s}),i=e,s=[r.id]):(i&&s.length>0&&n.push({spec:i,blockIds:s}),i=null,s=[])}return i&&s.length>0&&n.push({spec:i,blockIds:s}),n}function Lo(e,t){if(t.className&&e.className!==t.className&&(e.className=t.className),t.attrs)for(const[n,i]of Object.entries(t.attrs))e.getAttribute(n)!==i&&e.setAttribute(n,i)}function Ho(e){const t=document.createElement(e.tag);if(t.setAttribute("data-block-wrapper",e.key),e.className&&(t.className=e.className),e.attrs)for(const[n,i]of Object.entries(e.attrs))t.setAttribute(n,i);return t}function zo(e,t,n){t!==(n?n.nextSibling:e.firstChild)&&(n||t.parentNode!==e||t!==e.firstChild)&&(n?n.after(t):e.insertBefore(t,e.firstChild))}function _o(e,t,n){for(let s=0;s<t.length;s++){const i=t[s];if(!i)continue;const r=n.querySelector(`[data-block-id="${i}"]`);if(!r)continue;const o=e.children[s]??null;r!==o&&(o?e.insertBefore(r,o):e.appendChild(r))}const i=new Set(t);for(const s of Array.from(e.children)){const t=s.getAttribute("data-block-id");t&&!i.has(t)&&n.insertBefore(s,e)}}function Fo(e,t,n){if(!n)return;const i=No(t,n);for(const s of i){const t=e.querySelector(`[data-block-id="${s.blockIds[0]}"]`);if(!t)continue;const n=Ho(s.spec);t.before(n);for(const i of s.blockIds){const t=e.querySelector(`[data-block-id="${i}"]`);t&&n.appendChild(t)}}}function jo(e){e.parentElement?.removeChild(e)}function $o(e,t,n){const i=e.parentElement;i?i.replaceChild(t,e):n.replaceChild(t,e)}function Ko(e,t,n){if(t?.parentElement){const e=t.parentElement;return void(t.nextSibling?e.insertBefore(n,t.nextSibling):e.appendChild(n))}e.firstChild?e.insertBefore(n,e.firstChild):e.appendChild(n)}function Vo(e,t){if(t){const n=t.getInlineNodeSpec(e.inlineType);if(n){const t=n.toDOM(e);return t.setAttribute("contenteditable","false"),t}}const n=document.createElement("span");return n.setAttribute("data-inline-type",e.inlineType),n.setAttribute("contenteditable","false"),n}function qo(e){let t=e.replace(/ {2}/g,"  ");return t.endsWith(" ")&&(t=`${t.slice(0,-1)} `),t.startsWith(" ")&&(t=` ${t.slice(1)}`),t}var Uo=/* @__PURE__ */new WeakMap;function Wo(e){const t=/* @__PURE__ */new Map;for(const n of e.querySelectorAll("[data-decoration-widget][data-widget-key][data-widget-block-id]")){const e=n.getAttribute("data-widget-block-id"),i=n.getAttribute("data-widget-key");if(null===e||null===i)continue;const s=fe(e),r=t.get(s)??/* @__PURE__ */new Map,o=r.get(i)??[];o.push(n),r.set(i,o),t.set(s,r)}return t}function Go(e,t,n,i){let s;if(void 0!==e.key&&(s=function(e,t,n){if(!e||void 0===t)return;const i=e.get(t),s=i?.get(n),r=s?.shift();return 0===s?.length&&i?.delete(n),0===i?.size&&e.delete(t),r}(i?.pool,i?.blockId,e.key),!s)){const t=n.get(e.key);s=t?.shift(),0===t?.length&&n.delete(e.key)}return s??=function(e,t=Ms.silent){const n=Vt(e)??{pluginId:"unattributed",name:"widget"},i=t.execute({pluginId:n.pluginId,name:`${n.name}:toDOM`,kind:"widget-render"},()=>{const t=e.toDOM();if(!(t instanceof HTMLElement))throw new TypeError("WidgetDecoration.toDOM must return an HTMLElement.");return t});if(i.ok)return i.value;const s=document.createElement("span");return s.setAttribute("data-widget-render-fallback","true"),s}(e,i?.callbackExecutor),s.setAttribute("data-widget","true"),s.setAttribute("data-decoration-widget","true"),s.setAttribute("data-widget-offset",String(t)),s.setAttribute("data-widget-side",String(e.side)),s.setAttribute("contenteditable","false"),void 0===e.key?s.removeAttribute("data-widget-key"):s.setAttribute("data-widget-key",e.key),i&&s.setAttribute("data-widget-block-id",i.blockId),s}function Jo(e){const t=e.nodeName??"span",n=document.createElement(t);if(n.setAttribute("data-decoration","true"),e.class)for(const i of e.class.split(" "))i&&n.classList.add(i);e.style&&cn(n,e.style);for(const[i,s]of Object.entries(e))"class"!==i&&"style"!==i&&"nodeName"!==i&&void 0!==s&&n.setAttribute(i,s);return n}function Qo(e,t,n){Xo(e,t,n)}function Xo(e,t,n){const i=n?.decorations?.findNode(t)??[],s=Uo.get(e);if(s&&$t(s.decorations,i))return;Zo(e,s);const r=/* @__PURE__ */new Set,o=/* @__PURE__ */new Map;for(const d of i){for(const e of d.attrs.class?.split(/\s+/)??[])e&&r.add(e);for(const[e,t]of ea(d.attrs.style??""))o.set(e,t)}if(0===r.size&&0===o.size)return void Uo.delete(e);const a=/* @__PURE__ */new Set;for(const d of r)e.classList.contains(d)?a.add(d):e.classList.add(d);const c=ea(ln(e)),l=/* @__PURE__ */new Map;for(const[d,h]of o)l.set(d,c.get(d)??null),c.set(d,h);o.size>0&&cn(e,na(c)),Uo.set(e,{decorations:[...i],managed:r,preexisting:a,previousStyles:l})}function Yo(e){Zo(e,Uo.get(e)),Uo.delete(e)}function Zo(e,t){if(!t)return;for(const i of t.managed)t.preexisting.has(i)||e.classList.remove(i);if(0===t.previousStyles.size)return;const n=ea(ln(e));for(const[i,s]of t.previousStyles)null===s?n.delete(i):n.set(i,s);cn(e,na(n))}function ea(e){const t=/* @__PURE__ */new Map;for(const n of e.split(";")){const e=n.trim();if(!e)continue;const i=e.indexOf(":");if(i<=0)continue;const s=ta(e.slice(0,i)),r=e.slice(i+1).trim();s&&r&&t.set(s,r)}return t}function ta(e){const t=e.trim();return t.startsWith("--")?t:t.includes("-")?t.toLowerCase():t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`).toLowerCase()}function na(e){return[...e.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}: ${t}`).join("; ")}var ia=/* @__PURE__ */new WeakSet;function sa(e,t){if(e instanceof HTMLElement)return e;throw new TypeError(`${t} must be an HTMLElement.`)}var ra=/* @__PURE__ */new WeakMap;function oa(e,t,n,i){const s=i?.decorations?.findInline(e.id),o=i?.decorations?.findWidget(e.id),a=i?.nodeViewRegistry;if(a&&t&&n&&i?.getState&&i?.dispatch){const c=a.getNodeViewEntry(e.type);if(c){const a=function(e,t,n,i,s=Ms.silent){const r=s.execute({pluginId:e.pluginId,name:`${e.name}:factory`,kind:"node-view"},()=>function(e,t,n){if("object"!=typeof t&&"function"!=typeof t||null===t)throw new TypeError(`${e.name} NodeView factory must return a NodeView object.`);const i=sa(t.dom,`${e.name}.dom`),s=t.contentDOM;if(null!==s&&!(s instanceof HTMLElement))throw new TypeError(`${e.name}.contentDOM must be an HTMLElement or null.`);const r=s,o=t.getContentDOM,a=t.update,c=t.destroy,l=t.selectNode,d=t.deselectNode;return{dom:i,contentDOM:r,...o?{getContentDOM(i){const s=n.execute({pluginId:e.pluginId,name:`${e.name}:getContentDOM`,kind:"node-view"},()=>{const n=o.call(t,i);return null===n?null:sa(n,`${e.name}.getContentDOM`)});return s.ok?s.value:null}}:{},...a?{update(i){const s=n.execute({pluginId:e.pluginId,name:`${e.name}:update`,kind:"node-view"},()=>{const n=a.call(t,i);if("boolean"!=typeof n)throw new TypeError(`${e.name}.update must return a boolean.`);return n});return!!s.ok&&s.value}}:{},...c?{destroy(){ia.has(t)||(ia.add(t),n.execute({pluginId:e.pluginId,name:`${e.name}:destroy`,kind:"node-view"},()=>c.call(t)))}}:{},...l?{selectNode(){n.execute({pluginId:e.pluginId,name:`${e.name}:selectNode`,kind:"node-view"},()=>l.call(t)).ok||i.classList.add("notectl-node-selected")}}:{},...d?{deselectNode(){n.execute({pluginId:e.pluginId,name:`${e.name}:deselectNode`,kind:"node-view"},()=>d.call(t)).ok||i.classList.remove("notectl-node-selected")}}:{}}}(e,e.factory(t,n,i),s));return r.ok?r.value:null}(c,e,i.getState,i.dispatch,i.callbackExecutor);if(!a)return aa(e,t,n,i);const l=t.getNodeSpec(e.type);return l?.isVoid&&a.dom.setAttribute("data-void","true"),l?.selectable&&a.dom.setAttribute("data-selectable","true"),a.contentDOM&&a.contentDOM!==a.dom&&a.contentDOM.setAttribute("data-content-dom","true"),r(e)&&a.contentDOM?la(a.contentDOM,e,t,s,o,i?.widgetDOMPool,i?.callbackExecutor):pa(e,e=>a.getContentDOM?.(e.id)??a.contentDOM,t,n,i),ca(a.dom,e),a.dom.setAttribute("data-block-type",e.type),Qo(a.dom,e.id,i),function(e,t,n){const i=e.get(t);i&&i!==n&&(Do(e,i),i.destroy?.()),e.set(t,n)}(n,e.id,a),a.dom}}return aa(e,t,n,i)}function aa(e,t,n,i){const s=i?.decorations?.findInline(e.id),o=i?.decorations?.findWidget(e.id);if(t){const a=t.getNodeSpec(e.type);if(a){const c=a.toDOM(e);return a.isVoid&&c.setAttribute("data-void","true"),a.selectable&&c.setAttribute("data-selectable","true"),a.isVoid||(r(e)?la(c,e,t,s,o,i?.widgetDOMPool,i?.callbackExecutor):pa(e,()=>c,t,n,i)),ca(c,e),c.setAttribute("data-block-type",e.type),Qo(c,e.id,i),c}}return function(e,t,n,i,s,r){const o=mn("p",e.id);return ca(o,e),o.setAttribute("data-block-type",e.type),la(o,e,t,n,i,s,r),o}(e,t,s,o,i?.widgetDOMPool,i?.callbackExecutor)}function ca(e,n,i){const s=t(n.htmlId);if(s)return void e.setAttribute("id",s);const r=t(i?.htmlId);r&&e.getAttribute("id")===r&&e.removeAttribute("id")}function la(e,t,n,i,s,r,o){const a=[...i??[],...s??[]];(function(e,t,n,i,s=[],r){const o=t.reduce((e,t)=>e+(U(t)?1:t.text.length),0),a=function(e,t){const n=/* @__PURE__ */new Map;for(let s=0;s<e.length;s++){const i=e[s];if(!i)continue;const r=Number.isFinite(i.offset)?i.offset:0,o=Math.max(0,Math.min(t,Math.trunc(r))),a=n.get(o)??[];a.push({decoration:i,index:s}),n.set(o,a)}const i=/* @__PURE__ */new Map;for(const[s,r]of n)r.sort((e,t)=>e.decoration.side-t.decoration.side||e.index-t.index),i.set(s,r.map(e=>e.decoration));return i}(s,o),c=r?.pool?/* @__PURE__ */new Map:function(e){const t=/* @__PURE__ */new Map;for(const n of Array.from(e.children)){if(!(n instanceof HTMLElement&&n.hasAttribute("data-decoration-widget")))continue;const e=n.getAttribute("data-widget-key");if(null===e)continue;const i=t.get(e)??[];i.push(n),t.set(e,i)}return t}(e);e.replaceChildren();const l=t=>{const n=a.get(t);if(n)for(const i of n)e.appendChild(Go(i,t,c,r))};if(1===t.length&&!U(t[0])&&""===t[0]?.text)return l(0),void e.appendChild(document.createElement("br"));let d=0;for(const u of t){if(U(u)){l(d),e.appendChild(Co(Vo(u,i),u.marks,i)),d+=1;continue}const t=d,s=d+u.text.length;if(0===u.text.length){d=s;continue}const r=/* @__PURE__ */new Set;r.add(t),r.add(s);for(const e of n){const n=Math.max(t,e.from),i=Math.min(s,e.to);n>t&&n<s&&r.add(n),i>t&&i<s&&r.add(i)}for(const e of a.keys())e>t&&e<s&&r.add(e);const o=[...r].sort((e,t)=>e-t);for(let a=0;a<o.length-1;a++){const s=o[a],r=o[a+1];if(void 0===s||void 0===r||s>=r)continue;l(s);const c=s-t,d=r-t,h=u.text.slice(c,d),p=[];for(const e of n)e.from<=s&&e.to>=r&&p.push(e);let f=Co(document.createTextNode(qo(h)),u.marks,i);for(const e of p){const t=Jo(e.attrs);t.appendChild(f),f=t}e.appendChild(f)}d=s}l(o);const h=t[t.length-1];h&&U(h)&&"hard_break"===h.inlineType&&e.appendChild(document.createElement("br"))})(e,m(t),i??[],n,s??[],{blockId:t.id,pool:r,callbackExecutor:o}),ra.set(e,a)}function da(e,t,n,i,s,r){const o=[...i,...s],a=ra.get(e);a&&$t(a,o)||la(e,t,n,i,s,void 0,r)}function ha(e,t){const n=/* @__PURE__ */new Set;e.contentDOM&&n.add(e.contentDOM);for(const i of a(t)){const t=e.getContentDOM?.(i.id);t&&n.add(t)}return[...n]}function ua(e,t,n,i,s,r){const o=/* @__PURE__ */new Set([...n,...ha(e,t)]);for(const a of o)a.replaceChildren();pa(t,t=>e.getContentDOM?.(t.id)??e.contentDOM,i,s,r)}function pa(e,t,n,i,s){const r=/* @__PURE__ */new Map;for(const o of a(e)){const e=t(o);if(!e)continue;e.appendChild(oa(o,n,i,s));const a=r.get(e)??[];a.push(o),r.set(e,a)}for(const[o,a]of r)Fo(o,a,n)}function fa(e,t,n,i){const s=t?.doc.children??[],o=n.doc.children,a=i?.registry,c=i?.nodeViews,l={...i,widgetDOMPool:Wo(e)},d=/* @__PURE__ */new Map;for(const r of s)d.set(r.id,r);const h=null!=i?.compositionBlockId,u=function(e,t,n){if(!n||!e)return;const i=t.getNodePath(n)?.[0];return void 0!==i&&i===e.getNodePath(n)?.[0]?i:void 0}(t,n,i?.compositionBlockId),p=/* @__PURE__ */new Map;for(const r of function(e){const t=[];for(const n of Array.from(e.children))if(n instanceof HTMLElement)if(n.hasAttribute("data-block-id"))t.push(n);else if(n.hasAttribute("data-block-wrapper"))for(const e of Array.from(n.children))e instanceof HTMLElement&&e.hasAttribute("data-block-id")&&t.push(e);return t}(e)){const e=r.getAttribute("data-block-id");e&&p.set(fe(e),r)}const f=new Set(o.map(e=>e.id));for(const[r,k]of p)if(!f.has(r)){const e=d.get(r);e?Oo(e,c,{ownerDOM:k}):((c?.get(r))?.destroy?.(),c?.delete(r)),jo(k),p.delete(r)}let m=null;const g=i?.selectedNodeId,y=i?.previousSelectedNodeId;for(const k of o){const t=p.get(k.id),n=d.get(k.id);if(u===k.id&&t)m=t;else{if(t&&n&&!ga(n,k))m=t;else if(t){const s=c?.get(k.id);let o=!1;if(s&&n){const e=ha(s,n);if(Yo(s.dom),s.update?.(k)){ca(s.dom,k,n);const d=ya(n,k);if(d&&Oo(n,c,{includeRoot:!1,ownerDOM:t}),r(k)&&s.contentDOM){if(!r(n))for(const n of e)n.replaceChildren();const t=i?.decorations?.findInline(k.id),o=i?.decorations?.findWidget(k.id);la(s.contentDOM,k,a,t,o,l.widgetDOMPool,l.callbackExecutor)}else d&&ua(s,k,e,a,c,l);m=s.dom,o=!0}}if(!o){n?Oo(n,c,{ownerDOM:t}):s&&(s.destroy?.(),c?.delete(k.id));const i=oa(k,a,c,l);$o(t,i,e),m=i}}else{const t=oa(k,a,c,l);Ko(e,m,t),m=t}if(g===k.id){const e=c?.get(k.id);if(e)e.selectNode?.();else{const e=p.get(k.id)??m;e instanceof HTMLElement&&e.classList.add("notectl-node-selected")}}else if(y===k.id){const e=c?.get(k.id);if(e)e.deselectNode?.();else{const e=p.get(k.id)??m;e instanceof HTMLElement&&e.classList.remove("notectl-node-selected")}}}}if(y&&y!==g){const e=c?.get(y);e&&!f.has(y)&&e.deselectNode?.()}if(g&&!f.has(g)){const e=c?.get(g);e&&e.selectNode?.()}!h&&a&&function(e,t,n){const i=No(t,n),s=function(e,t){const n=[],i=/* @__PURE__ */new Set;for(const r of t)for(const e of r.blockIds)i.add(e);let s=0;for(const r of e){if(!i.has(r.id)){n.push({type:"bare",blockId:r.id});continue}const e=t[s];e&&e.blockIds[0]===r.id&&(n.push({type:"wrapper",key:e.spec.key,blockIds:e.blockIds}),s++)}return n}(t,i),r=function(e){const t=[];for(const n of Array.from(e.children))if(n instanceof HTMLElement)if(n.hasAttribute("data-block-wrapper")){const e=n.getAttribute("data-block-wrapper")??"",i=[];for(const t of Array.from(n.children)){if(!(t instanceof HTMLElement))continue;const e=t.getAttribute("data-block-id");e&&i.push(fe(e))}t.push({type:"wrapper",element:n,key:e,blockIds:i})}else if(n.hasAttribute("data-block-id")){const e=n.getAttribute("data-block-id")??"";t.push({type:"bare",element:n,blockId:fe(e)})}return t}(e);if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const i=e[n],s=t[n];if(!i||!s)return!1;if(i.type!==s.type)return!1;if("bare"===i.type&&"bare"===s.type){if(i.blockId!==s.blockId)return!1}else if("wrapper"===i.type&&"wrapper"===s.type){if(i.key!==s.key)return!1;if(i.blockIds.length!==s.blockIds.length)return!1;for(let e=0;e<i.blockIds.length;e++)if(i.blockIds[e]!==s.blockIds[e])return!1}}return!0}(s,r)){let e=0;for(const t of r)if("wrapper"===t.type){const n=i[e];n&&Lo(t.element,n.spec),e++}return}const o=/* @__PURE__ */new Map;for(const d of r){if("wrapper"!==d.type)continue;let e=o.get(d.key);e||(e=[],o.set(d.key,e)),e.push(d.element)}const a=/* @__PURE__ */new Set;let c=null,l=0;for(const d of s){if("bare"===d.type){const t=e.querySelector(`[data-block-id="${d.blockId}"]`);if(!t)continue;t.parentNode!==e?c?c.after(t):e.insertBefore(t,e.firstChild):zo(e,t,c),c=t;continue}const t=i[l];if(!t)continue;l++;const n=o.get(d.key);let s=null;if(n&&n.length>0){const e=n.shift();e&&(s=e.tagName.toLowerCase()===t.spec.tag?e:Ho(t.spec))}s||(s=Ho(t.spec)),a.add(s),Lo(s,t.spec),s.parentNode!==e?c?c.after(s):e.insertBefore(s,e.firstChild):zo(e,s,c),_o(s,d.blockIds,e),c=s}for(const d of r)if("wrapper"===d.type&&!a.has(d.element)){for(;d.element.firstChild;)e.insertBefore(d.element.firstChild,d.element);d.element.remove()}}(e,o,a);for(const k of e.querySelectorAll("[data-block-id]")){const e=k.getAttribute("data-block-id");if(!e)continue;const t=fe(e);Xo(k,t,i);const s=n.getBlock(t);if(!s||!r(s))continue;if(i?.compositionBlockId===t)continue;const o=ma(k,s,a,c);o&&da(o,s,a,i?.decorations?.findInline(t)??[],i?.decorations?.findWidget(t)??[],i?.callbackExecutor)}}function ma(e,t,n,i){const s=i?.get(t.id);return s?s.contentDOM:n?.getNodeSpec(t.type)?.isVoid?null:e}function ga(e,t){return e.id!==t.id||e.type!==t.type||e.htmlId!==t.htmlId||e.children.length!==t.children.length||!z(e.attrs,t.attrs)||ya(e,t)}function ya(e,t){if(e.children.length!==t.children.length)return!0;for(let n=0;n<e.children.length;n++){const i=e.children[n],s=t.children[n];if(!i||!s)return!0;if(ka(i,s))return!0}return!1}function ka(e,t){return v(e)&&v(t)?e.text!==t.text||!d(e.marks,t.marks):U(e)&&U(t)?e.inlineType!==t.inlineType||!function(e,t){const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const s of n)if(e[s]!==t[s])return!1;return!0}(e.attrs,t.attrs)||!d(e.marks,t.marks):!!(v(e)||v(t)||U(e)||U(t))||ga(e,t)}function ba(e,t){const n=e.querySelector(`[data-block-id="${t}"]`);return n?Rn(n):null}function*va(e){const t=En(e,{includeCursorWrapper:!0});for(let n=t.nextNode();n;n=t.nextNode())yield{node:n,data:n.nodeType===Node.TEXT_NODE?n.textContent??"":"",inWrapper:Ia(n,e)}}function wa(e){return e.inWrapper?e.data.replaceAll("​",""):e.data}function Ia(e,t){for(let n=e.parentElement;n&&n!==t;n=n.parentElement)if(bn(n))return!0;return!1}var Sa=class{state;contentElement;history;stateChangeCallbacks=[];isUpdating=!1;schemaRegistry;nodeViewRegistry;callbackExecutor;nodeViews=/* @__PURE__ */new Map;decorations=Ut.empty;compositionOrigins;compositionContainer;getDecorations;isReadOnly;isReadonlyBypassed;shouldSyncSelection;compositionState;cursorWrapper;navigation;events;constructor(e,t){this.state=t.state,this.contentElement=e,this.schemaRegistry=t.schemaRegistry,this.nodeViewRegistry=t.nodeViewRegistry,this.callbackExecutor=t.callbackExecutor??Ms.silent,this.getDecorations=t.getDecorations,this.isReadOnly=t.isReadOnly??(()=>!1),this.isReadonlyBypassed=t.isReadonlyBypassed??(()=>!1),this.shouldSyncSelection=t.shouldSyncSelection??(()=>!0),this.compositionState=t.compositionState??{isComposing:!1,activeBlockId:null},this.history=new ko({maxDepth:t.maxHistoryDepth??100}),t.onStateChange&&this.stateChangeCallbacks.push(t.onStateChange),this.cursorWrapper=new Po(e,this.schemaRegistry),this.navigation=new Ao({contentElement:e,getState:()=>this.state,dispatch:e=>this.dispatch(e),keymapRegistry:t.keymapRegistry}),this.events=new Bo({contentElement:e,getState:()=>this.state,dispatch:e=>this.dispatch(e),applyUpdate:(e,t,n)=>this.applyUpdate(e,t,{skipSelectionSync:n}),isUpdating:()=>this.isUpdating,compositionState:this.compositionState,cursorWrapper:this.cursorWrapper,isReadOnly:this.isReadOnly,fileHandlerRegistry:t.fileHandlerRegistry,callbackExecutor:this.callbackExecutor,onMousedown:()=>this.navigation.clearGoalColumn()}),this.decorations=this.getDecorations?.(this.state)??Ut.empty,fa(e,null,this.state,{...this.reconcileOptions(),decorations:this.decorations}),this.shouldSyncSelection()&&kn(e,this.state.selection)}getState(){return this.state}applyUpdate(e,t,n){if(!this.isUpdating){this.isUpdating=!0;try{const i=this.state,s=Lr(t,i.doc);this.state=e,this.events.onStateChange(i,e,s),this.cursorWrapper.isActive&&!e.storedMarks?.length&&this.cursorWrapper.cleanup(),(n?.pushHistory&&"history"!==s.metadata.origin||So(s))&&this.history.push(s);const r=this.getDecorations?.(e,s)??Ut.empty;this.reconcileAndSync(i,e,r,n?.skipSelectionSync);for(const t of this.stateChangeCallbacks)t(i,e,s);this.navigation.resetAfterUpdate()}finally{this.isUpdating=!1}}}dispatch(e){const t=Lr(e,this.state.doc);if(this.isReadOnly()&&!xo(t)&&!this.isReadonlyBypassed())return;const n=this.state.apply(t);this.applyUpdate(n,t,{pushHistory:!0})}undo(){if(this.isUpdating||this.isReadOnly())return;const e=this.history.undo(this.state);e&&this.applyUpdate(e.state,e.transaction)}redo(){if(this.isUpdating||this.isReadOnly())return;const e=this.history.redo(this.state);e&&this.applyUpdate(e.state,e.transaction)}onStateChange(e){return this.stateChangeCallbacks.push(e),()=>{const t=this.stateChangeCallbacks.indexOf(e);-1!==t&&this.stateChangeCallbacks.splice(t,1)}}replaceState(e){if(!this.isUpdating){this.isUpdating=!0;try{const t=this.state,n=e.withSelection(t.selection);this.state=n,this.history.clear(),!this.cursorWrapper.isActive||n.storedMarks?.length||this.compositionState.isComposing||this.cursorWrapper.cleanup();const i=Fi({steps:[],selectionBefore:t.selection,selectionAfter:n.selection,storedMarksAfter:n.storedMarks,forwardStepMaps:[],metadata:{origin:"api",timestamp:Date.now()}});this.events.onStateChange(t,n,i);const s=this.getDecorations?.(n,i)??Ut.empty;this.reconcileAndSync(t,n,s);for(const e of this.stateChangeCallbacks)e(t,n,i);this.navigation.resetAfterUpdate()}finally{this.isUpdating=!1}}}syncSelection(){this.events.syncSelectionFromDOM()}resolveDOMRange(e){return Sn(this.contentElement,e)}captureCompositionBlock(e){this.compositionOrigins=function(e,t){const n=/* @__PURE__ */new WeakMap,i=ba(e,t);if(!i)return n;let s=0;for(const r of va(i))r.node instanceof Element&&n.set(r.node,s),s+=wa(r).length;return n}(this.contentElement,e);const t=this.state.getNodePath(e)?.[0];this.compositionContainer=void 0!==t&&t!==e?this.state.getBlock(t):void 0}readCompositionSnapshot(e){return function(e,t,n){const i=ba(e,t);return i?function(e,t,n){let i="",s=t?0:null;const r=n?/* @__PURE__ */new Map:void 0;for(const o of va(e)){const{node:e,data:a}=o;if(t?.isPointInRange(e,0)){const n=t.endContainer===e?a.slice(0,t.endOffset):a;s=i.length+wa({...o,data:n}).length}e instanceof Element&&r?.set(i.length,n?.get(e)??null),i+=wa(o)}return r?{text:i,caretOffset:s,inlineNodeOrigins:r}:{text:i,caretOffset:s}}(i,function(e,t){const n=Cn(),i=n&&yn(e,n);if(!i)return null;const{anchorNode:s,anchorOffset:r,focusNode:o,focusOffset:a}=i;if(s!==o||r!==a||!t.contains(s))return null;const c=document.createRange();return c.setStart(t,0),c.setEnd(s,r),c}(e,i),n):null}(this.contentElement,e,this.compositionOrigins)}restoreBlock(e){this.cursorWrapper.cleanup();const t={...this.reconcileOptions(),decorations:this.decorations},n=this.compositionContainer;this.compositionContainer=void 0,n&&this.state.getBlock(n.id)!==n?function(e,t,n,i){const s=n.getBlock(t.id),r=e.querySelector(`[data-block-id="${t.id}"]`);s&&r&&(Oo(t,i.nodeViews,{ownerDOM:r}),$o(r,oa(s,i.registry,i.nodeViews,{...i,widgetDOMPool:Wo(e)}),e))}(this.contentElement,n,this.state,t):function(e,t,n,i){const s=t.getBlock(n);if(!s||!r(s))return;const o=e.querySelector(`[data-block-id="${n}"]`);if(!o)return;const a=ma(o,s,i.registry,i.nodeViews);a&&la(a,s,i.registry,i.decorations?.findInline(n),i.decorations?.findWidget(n),void 0,i.callbackExecutor)}(this.contentElement,this.state,e,t),!this.compositionState.isComposing&&this.shouldSyncSelection()&&kn(this.contentElement,this.state.selection)}reconcileAndSync(e,t,n,i){const s=this.decorations;this.decorations=n,fa(this.contentElement,e,t,{...this.reconcileOptions(e.selection),decorations:n,oldDecorations:s,compositionBlockId:this.compositionState.isComposing?this.compositionState.activeBlockId??void 0:void 0}),this.compositionState.isComposing||i||!this.shouldSyncSelection()||kn(this.contentElement,t.selection)}reconcileOptions(e){const t=ee(this.state.selection)?this.state.selection.nodeId:void 0,n=e&&ee(e)?e.nodeId:void 0;return{registry:this.schemaRegistry,nodeViewRegistry:this.nodeViewRegistry,nodeViews:this.nodeViews,getState:()=>this.state,dispatch:e=>this.dispatch(e),callbackExecutor:this.callbackExecutor,selectedNodeId:t,previousSelectedNodeId:n}}destroy(){this.cursorWrapper.cleanup(),this.events.destroy(),this.navigation.destroy(),function(e){const t=/* @__PURE__ */new Set;for(const n of e.values())t.has(n)||(t.add(n),n.destroy?.());e.clear()}(this.nodeViews)}},xa={paragraph:"Paragraph",heading:"Heading",code_block:"Code Block",blockquote:"Block Quote",list_item:"List Item",horizontal_rule:"Horizontal Rule",image:"Image",table:"Table"};function Ra(e,t){return"heading"===e&&t?.level?`Heading ${t.level}`:xa[e]??e}function Ca(e){e.registerNodeSpec({type:"paragraph",group:"block",content:{allow:["text"]},toDOM:e=>mn("p",e.id),toHTML:(e,t)=>`<p>${t||"<br>"}</p>`,parseHTML:[{tag:"p"},{tag:"div",priority:10}],sanitize:{tags:["p"]}})}var Ma={ariaLabel:"Rich text editor",ariaDescription:"Press Escape to exit the editor",defaultPlaceholder:"Start typing...",markdownImported:"Markdown imported"},Pa=/* #__PURE__ */Object.assign({"./locales/ar.ts":()=>import("./ar-eOA3UmiE.mjs"),"./locales/de.ts":()=>import("./de-DRbhnS4T.mjs"),"./locales/es.ts":()=>import("./es-BQ9dox_E.mjs"),"./locales/fr.ts":()=>import("./fr-NVOinLyF.mjs"),"./locales/hi.ts":()=>import("./hi-DrC2H81d.mjs"),"./locales/nl.ts":()=>import("./nl-BEmzpzKO.mjs"),"./locales/pt.ts":()=>import("./pt-CFrcl1v_.mjs"),"./locales/ru.ts":()=>import("./ru-gxbzqLL8.mjs"),"./locales/zh.ts":()=>import("./zh-BFZOM3lF.mjs")}),Ea=['@property --notectl-bg{syntax:"<color>";inherits:true;initial-value:#fff}@property --notectl-fg{syntax:"<color>";inherits:true;initial-value:#1f2328}@property --notectl-fg-muted{syntax:"<color>";inherits:true;initial-value:#6e7781}@property --notectl-border{syntax:"<color>";inherits:true;initial-value:#d0d7de}@property --notectl-border-focus{syntax:"<color>";inherits:true;initial-value:#0969da}@property --notectl-primary{syntax:"<color>";inherits:true;initial-value:#0969da}@property --notectl-primary-fg{syntax:"<color>";inherits:true;initial-value:#fff}@property --notectl-accent-fg{syntax:"<color>";inherits:true;initial-value:#0969da}@property --notectl-focus-ring{syntax:"<color>";inherits:true;initial-value:#0969da4d}:host{color:var(--notectl-fg);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:16px;line-height:1.6;display:block}.notectl-editor{border:1px solid var(--notectl-border);border-radius:var(--notectl-border-radius,6px);background:var(--notectl-bg);box-sizing:border-box;flex-direction:column;height:100%;min-height:0;display:flex;overflow:hidden}.notectl-editor:focus-within{border-color:var(--notectl-border-focus);box-shadow:0 0 0 2px var(--notectl-focus-ring)}.notectl-content{min-height:var(--notectl-content-min-height,400px);max-height:var(--notectl-content-max-height,none);cursor:text;white-space:pre-wrap;word-wrap:break-word;-webkit-user-select:text;-moz-user-select:text;user-select:text;-moz-tab-size:4;tab-size:4;outline:none;flex:1;padding:12px 16px;position:relative;overflow-y:auto}.notectl-content p{min-height:1.6em;margin:0;padding:2px 0}.notectl-content p+p{margin-top:0}.notectl-content hr{border:none;border-top:1px solid var(--notectl-border);cursor:default;-webkit-user-select:none;-moz-user-select:none;user-select:none;margin:8px 0;padding:0}.notectl-content.notectl-content--empty:before{content:attr(data-placeholder);color:var(--notectl-fg-muted);pointer-events:none;top:12px;position:absolute;inset-inline-start:16px}.notectl-plugin-container--bottom{border-top:1px solid var(--notectl-border);flex-shrink:0}.notectl-sr-only{clip:rect(0, 0, 0, 0);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.notectl-node-selected{outline:2px solid var(--notectl-primary);outline-offset:2px}@media (forced-colors:active){.notectl-editor{border-color:canvastext}.notectl-editor:focus-within{border-color:highlight;box-shadow:0 0 0 2px highlight}.notectl-content{color:canvastext}.notectl-plugin-container--top,.notectl-plugin-container--bottom{border-color:canvastext}.notectl-node-selected{outline-color:highlight}}',"@media (prefers-reduced-motion:reduce){.notectl-toolbar-btn,.notectl-image__resize-handle,.notectl-image__size-indicator,.notectl-color-picker__swatch,.notectl-font-picker__item,.notectl-heading-picker__item,.notectl-font-size-picker__item,.ntbl-handle,.ntbl-handle-delete,.ntbl-insert-line,.ntbl-insert-btn,.ntbl-add-zone,.ntbl-add-icon,.ntbl-col-bar,.ntbl-row-bar,.ntbl-delete-table-btn,.notectl-code-block__copy{transition:none!important}}",'\n/* Paper viewport: scroll container with centered gray background */\n.notectl-paper-viewport {\n\tflex: 1;\n\toverflow-y: auto;\n\toverflow-x: hidden;\n\tbackground: var(--notectl-paper-viewport-bg, #e8e8e8);\n\tpadding: 24px 0;\n}\n\n/* Paper surface: white page with shadow, centered */\n.notectl-paper-surface {\n\tmargin: 0 auto;\n\tbackground: var(--notectl-bg);\n\tborder-radius: 2px;\n\tbox-shadow: 0 2px 8px var(--notectl-shadow, rgba(0, 0, 0, 0.15));\n\ttransform-origin: top center;\n\ttransition: transform 0.15s ease-out;\n}\n\n/* Content overrides in paper mode: wider document margins */\n.notectl-editor[data-paper-mode] .notectl-content {\n\tflex: none;\n\tpadding: 48px 56px;\n\tmin-height: auto;\n}\n\n/* Placeholder position override for paper mode */\n.notectl-editor[data-paper-mode] .notectl-content.notectl-content--empty::before {\n\ttop: 48px;\n\tinset-inline-start: 56px;\n}\n\n/* Dark mode: darker viewport background */\n:host([theme="dark"]) .notectl-paper-viewport {\n\t--notectl-paper-viewport-bg: #181825;\n}\n\n@media (prefers-reduced-motion: reduce) {\n\t.notectl-paper-surface {\n\t\ttransition: none !important;\n\t}\n}\n'].join("\n"),Ta=null,Ba=class{themeStyleSheet=new CSSStyleSheet;systemThemeQuery=null;systemThemeHandler=null;pluginSheets=[];runtimeSheets=[];shadow;constructor(e){this.shadow=e}apply(e){if(this.cleanupSystemThemeListener(),e===ct.System){this.setupSystemThemeListener();const e=mt(this.getSystemTheme());this.setThemeStyleSheet(e)}else this.setThemeStyleSheet(mt(e))}setPluginStyleSheets(e){this.pluginSheets=e,this.refreshAdoptedStyleSheets()}setRuntimeStyleSheets(e){this.runtimeSheets=e,this.refreshAdoptedStyleSheets()}destroy(){this.cleanupSystemThemeListener()}setThemeStyleSheet(e){this.themeStyleSheet.replaceSync(pt(e)),this.refreshAdoptedStyleSheets()}refreshAdoptedStyleSheets(){this.shadow.adoptedStyleSheets=[this.themeStyleSheet,(Ta||(Ta=new CSSStyleSheet).replaceSync(Ea),Ta),...this.pluginSheets,...this.runtimeSheets]}setupSystemThemeListener(){this.systemThemeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.systemThemeHandler=e=>{const t=mt(this.getSystemTheme());this.setThemeStyleSheet(t)},this.systemThemeQuery.addEventListener("change",this.systemThemeHandler)}cleanupSystemThemeListener(){this.systemThemeQuery&&this.systemThemeHandler&&this.systemThemeQuery.removeEventListener("change",this.systemThemeHandler),this.systemThemeQuery=null,this.systemThemeHandler=null}getSystemTheme(){return(this.systemThemeQuery??window.matchMedia("(prefers-color-scheme: dark)")).matches?ct.Dark:ct.Light}},Aa=class{wrapper;content;viewport=null;surface=null;viewportObserver=null;surfaceObserver=null;currentSize=null;currentPaperWidthPx=0;currentPaperHeightPx=0;currentScale=1;compensationFrameId=null;constructor(e,t){this.wrapper=e,this.content=t}apply(e){if(null===e)return void this.disable();const t=ht(e);this.currentPaperWidthPx=t.widthPx,this.currentPaperHeightPx=t.heightPx,this.currentSize=e,this.viewport||this.enable(),this.updateSurfaceDimensions(),this.wrapper.setAttribute("data-paper-mode",e)}destroy(){this.disable()}getPaperSize(){return this.currentSize}enable(){this.viewport=document.createElement("div"),this.viewport.className="notectl-paper-viewport",this.surface=document.createElement("div"),this.surface.className="notectl-paper-surface",this.wrapper.removeChild(this.content),this.surface.appendChild(this.content),this.viewport.appendChild(this.surface);const e=this.wrapper.querySelector(".notectl-plugin-container--bottom");e?this.wrapper.insertBefore(this.viewport,e):this.wrapper.appendChild(this.viewport),this.viewportObserver=new ResizeObserver(e=>{for(const t of e)this.onViewportResize(t.contentRect.width)}),this.viewportObserver.observe(this.viewport),this.surfaceObserver=new ResizeObserver(e=>{for(const t of e)this.onSurfaceResize(t.contentRect.height)}),this.surfaceObserver.observe(this.surface)}disable(){if(null!==this.compensationFrameId&&(cancelAnimationFrame(this.compensationFrameId),this.compensationFrameId=null),this.viewportObserver?.disconnect(),this.viewportObserver=null,this.surfaceObserver?.disconnect(),this.surfaceObserver=null,this.viewport&&this.surface){this.surface.removeChild(this.content);const e=this.wrapper.querySelector(".notectl-plugin-container--bottom");e?this.wrapper.insertBefore(this.content,e):this.wrapper.appendChild(this.content),this.wrapper.removeChild(this.viewport)}this.viewport=null,this.surface=null,this.currentSize=null,this.currentPaperWidthPx=0,this.currentPaperHeightPx=0,this.currentScale=1,this.wrapper.removeAttribute("data-paper-mode")}updateSurfaceDimensions(){this.surface&&(an(this.surface,"width",`${this.currentPaperWidthPx}px`),an(this.surface,"minHeight",`${this.currentPaperHeightPx}px`))}onViewportResize(e){if(!this.surface||0===this.currentPaperWidthPx)return;const t=e-48,n=Math.min(1,t/this.currentPaperWidthPx);this.currentScale=n,an(this.surface,"transform",n<1?`scale(${n})`:""),this.scheduleHeightCompensation(n)}onSurfaceResize(e){this.surface&&this.viewport&&this.scheduleHeightCompensation(this.currentScale)}scheduleHeightCompensation(e){null!==this.compensationFrameId&&cancelAnimationFrame(this.compensationFrameId),this.compensationFrameId=requestAnimationFrame(()=>{this.compensationFrameId=null,this.updateHeightCompensation(e)})}updateHeightCompensation(e){if(!this.surface)return;if(e>=1)return void an(this.surface,"marginBottom","");const t=this.surface.scrollHeight,n=t*e-t;an(this.surface,"marginBottom",`${n}px`)}};function Oa(e){return!Array.isArray(e)}function Da(e){if(Array.isArray(e))return{plugins:e,label:void 0};const t=e;return{plugins:t.plugins,label:t.label}}var Na=class{deps;cfg;themeController=null;styleLease=null;domElements=null;paperLayout=null;pluginManager=null;inputManager=null;view=null;locale=Ma;domEventTarget=null;autofocusFrameId=null;cleanedUp=!1;handleFocus=()=>this.deps.events.emit("focus",void 0);handleBlur=()=>this.deps.events.emit("blur",void 0);constructor(e){this.deps=e,this.cfg=e.config}announce(e){const t=this.domElements?.announcer;t&&(t.textContent=e)}async run(){try{if(this.setupTheme(),this.isCancelled())return this.abort();const e=await async function(e){const t=new Yt(e.locale??"browser").getLocale();return"en"===t?Ma:await async function(e){return en(Pa,e,Ma)}(t)}(this.cfg);return this.isCancelled()?this.abort():(this.locale=e,this.setupDOM(e),this.setupPlugins(),await this.initPluginsAndView(),!this.isCancelled()&&this.view&&this.inputManager&&this.pluginManager&&this.domElements&&this.themeController&&this.styleLease?(this.finalizeSetup(this.pluginManager,this.domElements),this.release()):this.abort())}catch(e){throw await this.cleanup(),e}}setupTheme(){this.themeController=new Ba(this.deps.shadow),this.styleLease=this.deps.styleCoordinator.setup(this.deps.shadow,this.cfg.styleNonce,this.themeController),this.themeController.apply(this.cfg.theme??ct.Light)}setupDOM(e){this.domElements=function(e){const t=e.locale??Ma,n=t.defaultPlaceholder,i=document.createElement("div");i.className="notectl-editor",i.setAttribute("part","editor");const s=document.createElement("div");s.className="notectl-plugin-container--top",s.setAttribute("part","plugin-container plugin-container-top"),s.setAttribute("data-notectl-no-print","");const r=document.createElement("div");r.className="notectl-content",r.setAttribute("part","content"),r.contentEditable=e.readonly?"false":"true",r.setAttribute("role","textbox"),r.setAttribute("aria-multiline","true"),r.setAttribute("aria-label",t.ariaLabel),e.readonly&&r.setAttribute("aria-readonly","true"),r.setAttribute("aria-description",t.ariaDescription),r.setAttribute("data-default-placeholder",n),r.setAttribute("data-placeholder",e.placeholder??n),e.dir&&(i.setAttribute("dir",e.dir),r.setAttribute("dir",e.dir));const o=document.createElement("div");o.className="notectl-plugin-container--bottom",o.setAttribute("part","plugin-container plugin-container-bottom"),o.setAttribute("data-notectl-no-print","");const a=document.createElement("div");return a.className="notectl-sr-only",a.setAttribute("data-notectl-no-print",""),a.setAttribute("aria-live","polite"),a.setAttribute("aria-atomic","true"),i.appendChild(s),i.appendChild(r),i.appendChild(o),i.appendChild(a),{wrapper:i,content:r,topPluginContainer:s,bottomPluginContainer:o,announcer:a}}({readonly:this.cfg.readonly,placeholder:this.cfg.placeholder,dir:this.cfg.dir??this.deps.hostDir,locale:e}),this.deps.shadow.appendChild(this.domElements.wrapper),this.cfg.paperSize&&(this.paperLayout=new Aa(this.domElements.wrapper,this.domElements.content),this.paperLayout.apply(this.cfg.paperSize))}setupPlugins(){if(this.domElements){this.pluginManager=new go({logger:this.cfg.logger}),this.pluginManager.registerService(tn,new Yt(this.cfg.locale??"browser")),Ca(this.pluginManager.schemaRegistry),function(e,t){if(!t)return;const n=Oa(t)?t.groups:t,i=Oa(t)?t.overflow:void 0,s=[];for(const o of n){const{plugins:t,label:n}=Da(o),i=[];for(const s of t)i.push(s.id),e.register(s);s.push(void 0!==n?{plugins:i,label:n}:i)}const r={groups:s,overflow:i};e.register(new zn(r))}(this.pluginManager,this.cfg.toolbar);for(const e of this.cfg.plugins??[])this.pluginManager.register(e);for(const e of this.deps.preInitPlugins)this.pluginManager.register(e);e=this.pluginManager,t=this.cfg.features,function(e,t){if(void 0!==e.get("text-formatting"))return;const n={bold:t?.bold??!0,italic:t?.italic??!0,underline:t?.underline??!0};e.register(new qn(n))}(e,t),function(e){void 0===e.get("caret-navigation")&&e.register(new st)}(e),function(e){void 0===e.get("gap-cursor")&&e.register(new Vn)}(e),this.domEventTarget=this.domElements.content,this.domEventTarget.addEventListener("focus",this.handleFocus),this.domEventTarget.addEventListener("blur",this.handleBlur)}var e,t}async initPluginsAndView(){if(!this.pluginManager||!this.domElements||!this.themeController)return;const e=this.domElements,t=this.pluginManager,n=this.themeController;await t.init({isCancelled:()=>this.isCancelled(),getState:()=>{if(!this.view)throw new Error("View not initialized");return this.view.getState()},dispatch:e=>this.dispatch(e),getContainer:()=>e.content,getPluginContainer:t=>"top"===t?e.topPluginContainer:e.bottomPluginContainer,announce:e=>this.announce(e),hasAnnouncement:()=>!!e.announcer?.textContent,getCompositionState:()=>{const e=this.inputManager?.compositionTracker;return e||La},onBeforeReady:()=>this.createInputAndView(e,t,n)})}createInputAndView(e,t,n){if(this.isCancelled()||!this.pluginManager||!this.themeController)return;const i=me(t.schemaRegistry),s=is.create({schema:i}),r=this.deps.configController.markdownShorthand;this.inputManager=new Br(e.content,{getState:()=>{if(!this.view)throw new Error("View not initialized");return this.view.getState()},dispatch:e=>this.dispatch(e),syncSelection:()=>this.view?.syncSelection(),undo:()=>this.view?.undo(),redo:()=>this.view?.redo(),schemaRegistry:t.schemaRegistry,keymapRegistry:t.keymapRegistry,inputRuleRegistry:t.inputRuleRegistry,fileHandlerRegistry:t.fileHandlerRegistry,isReadOnly:()=>this.deps.configController.isReadOnly,shouldApplyInputRules:()=>r,getPasteInterceptors:()=>t.getPasteInterceptors(),pasteMarkdown:this.deps.configController.pasteMarkdown,getMarkdownSyntaxExtensions:()=>t.markdownSyntaxRegistry.getExtensions(),getTextInputInterceptors:()=>t.getTextInputInterceptors(),getTextDirection:pn,navigateFromGapCursor:Kn,announce:e=>this.announce(e),markdownImportedMessage:this.locale.markdownImported,callbackExecutor:t.getCallbackExecutor(),resolveTargetRange:e=>this.view?.resolveDOMRange(e)??null,compositionDOM:{captureBlock:e=>this.view?.captureCompositionBlock(e),readBlock:e=>this.view?.readCompositionSnapshot(e)??null,restoreBlock:e=>this.view?.restoreBlock(e)}}),this.view=new Sa(e.content,{state:s,schemaRegistry:t.schemaRegistry,keymapRegistry:t.keymapRegistry,fileHandlerRegistry:t.fileHandlerRegistry,callbackExecutor:t.getCallbackExecutor(),nodeViewRegistry:t.nodeViewRegistry,maxHistoryDepth:this.cfg.maxHistoryDepth,getDecorations:(e,n)=>t.collectDecorations(e,n)??Ut.empty,onStateChange:(n,i,s)=>{this.inputManager?.onStateChange(n,i,s),function(e,t,n,i,s,r){const o=i.announcer;if(o&&(o.textContent=""),s.notifyStateChange(e,t,n),Ha(i.content,t.doc),r.emit("stateChange",{oldState:e,newState:t,transaction:n}),ie(e.selection,t.selection)||r.emit("selectionChange",{selection:t.selection}),!o?.textContent){const i=function(e,t,n){if("undo"===n.metadata.historyDirection)return"Undo";if("redo"===n.metadata.historyDirection)return"Redo";for(const i of n.steps)if("setBlockType"===i.type)return Ra(i.nodeType,i.attrs);for(const i of t.schema.markTypes){const n=ue(i),s=Ge(e,n),r=Ge(t,n);if(s!==r)return`${i} ${r?"on":"off"}`}return null}(e,t,n);i&&o&&(o.textContent=i)}}(n,i,s,e,t,this.deps.events)},isReadOnly:()=>this.deps.configController.isReadOnly,isReadonlyBypassed:()=>t.isReadonlyBypassed(),shouldSyncSelection:()=>t.shouldSyncSelection(),compositionState:this.inputManager.compositionTracker}),Ha(e.content,this.view.getState().doc);const o=t.getPluginStyleSheets();o.length>0&&n.setPluginStyleSheets(o)}finalizeSetup(e,t){if(this.cfg.readonly&&e.setReadOnly(!0),e.onEvent(ut,e=>{!e.options.paperSize&&this.deps.configController.getPaperSize()&&(e.options={...e.options,paperSize:this.deps.configController.getPaperSize()})}),this.cfg.autofocus){const e=t.content;this.autofocusFrameId=requestAnimationFrame(()=>{this.autofocusFrameId=null,this.cleanedUp||e.focus()})}}dispatch(e){this.view&&this.pluginManager&&this.pluginManager.dispatchWithMiddleware(e,this.view.getState(),e=>this.view?.dispatch(e))}isCancelled(){return this.deps.isCancelled?.()??!1}release(){const e=this.view,t=this.inputManager,n=this.pluginManager,i=this.domElements,s=this.themeController,r=this.styleLease;if(!(e&&t&&n&&i&&s&&r))throw new Error("Cannot release an incomplete editor initialization session.");return{view:e,pluginManager:n,domElements:i,themeController:s,paperLayout:this.paperLayout,announce:e=>this.announce(e),markdownImportedMessage:this.locale.markdownImported,dispose:()=>this.cleanup()}}async abort(){return await this.cleanup(),null}async cleanup(){if(this.cleanedUp)return;this.cleanedUp=!0,null!==this.autofocusFrameId&&(cancelAnimationFrame(this.autofocusFrameId),this.autofocusFrameId=null),this.domEventTarget?.removeEventListener("focus",this.handleFocus),this.domEventTarget?.removeEventListener("blur",this.handleBlur),this.domEventTarget=null;const e=this.view;this.view=null,this.paperLayout?.destroy(),this.paperLayout=null,this.deps.styleCoordinator.teardown(this.styleLease),this.styleLease=null,this.themeController?.destroy(),this.themeController=null,this.inputManager?.destroy(),this.inputManager=null,e?.destroy();const t=this.pluginManager;this.pluginManager=null;const n=t?.destroy()??Promise.resolve();this.domElements?.wrapper.remove(),this.domElements=null,await n}},La={isComposing:!1,activeBlockId:null};function Ha(e,t){e.classList.toggle("notectl-content--empty",gs(t))}var za=class extends Error{constructor(){super("Editor initialization was aborted because the editor was destroyed."),this.name="AbortError"}},_a=class{state="idle";readyPromiseResolve=null;readyPromiseReject=null;readyPromise;preInitPlugins=[];constructor(){this.readyPromise=this.createReadyPromise()}isInitialized(){return"initializing"===this.state||"ready"===this.state}markInitialized(){return"initializing"!==this.state&&"ready"!==this.state&&("failed"===this.state&&(this.readyPromise=this.createReadyPromise()),this.state="initializing",!0)}whenReady(){return this.readyPromise}resolveReady(){"initializing"===this.state&&(this.state="ready",this.readyPromiseResolve?.(),this.readyPromiseResolve=null,this.readyPromiseReject=null)}failReady(e){"initializing"===this.state&&(this.state="failed",this.readyPromiseReject?.(e),this.readyPromiseResolve=null,this.readyPromiseReject=null)}registerPreInitPlugin(e){if("initializing"===this.state||"ready"===this.state)throw new Error("Cannot register plugins after initialization. Register before calling init() or adding to DOM.");this.preInitPlugins.push(e)}consumePreInitPlugins(){const e=this.preInitPlugins;return this.preInitPlugins=[],e}restorePreInitPlugins(e){0!==e.length&&(this.preInitPlugins=[...e,...this.preInitPlugins])}reset(){this.readyPromiseReject?.(new za),this.state="idle",this.preInitPlugins=[],this.readyPromise=this.createReadyPromise()}createReadyPromise(){const e=new Promise((e,t)=>{this.readyPromiseResolve=e,this.readyPromiseReject=t});return e.catch(()=>{}),e}},Fa=class{runtimeStyleSheet=null;activeLease=null;setup(e,t,n){this.activeLease?this.release(this.activeLease):hn(e),this.runtimeStyleSheet=dn();const i={id:Symbol("notectl-style-lease"),shadow:e,themeController:n};return this.activeLease=i,n?.setRuntimeStyleSheets(this.runtimeStyleSheet?[this.runtimeStyleSheet]:[]),on(e,{nonce:t,sheet:this.runtimeStyleSheet}),i}teardown(e){e&&this.activeLease===e&&this.release(e)}release(e){hn(e.shadow),this.runtimeStyleSheet=null,e.themeController?.setRuntimeStyleSheets([]),this.activeLease===e&&(this.activeLease=null)}},ja=class extends HTMLElement{view=null;pluginManager=null;domElements=null;configController=new vs;events=new ws;lifecycle=new _a;styleCoordinator=new Fa;themeController=null;paperLayout=null;activeInitResult=null;pendingInitPromise=null;pendingDestroyPromise=null;cancelPendingInit=null;autoInitToken=0;autoInitQueued=!1;initVersion=0;destroyVersion=0;announce=null;markdownImportedMessage="Markdown imported";static get observedAttributes(){return["placeholder","readonly","theme","paper-size","dir"]}connectedCallback(){at(this)||this.lifecycle.isInitialized()||this.scheduleAutoInit()}disconnectedCallback(){setTimeout(()=>{this.isConnected||this.destroy()},0)}attributeChangedCallback(e,t,n){this.configController.applyAttribute(e,n,this.getConfigDeps())}registerPlugin(e){this.lifecycle.registerPreInitPlugin(e)}async init(e){if(at(this))throw gt();this.cancelAutoInit();const t=this.destroyVersion,n=this.pendingDestroyPromise;if(n&&(await n,t!==this.destroyVersion))throw new za;const i=this.pendingInitPromise;if(i){if(await i,e)throw new Error("Cannot apply init config while another initialization is in progress. Await the active init, then destroy and initialize a new generation.");return}if(!this.lifecycle.markInitialized()){if(e)throw new Error("Cannot apply init config after the editor is initialized. Use configure() for runtime options or destroy() before re-initializing.");return}let s;e&&this.configController.setConfig(e),this.events.setLogger(this.configController.getConfig().logger);try{s=this.ensureFreshShadowRoot()}catch(d){throw this.lifecycle.failReady(d),d}const r=++this.initVersion;let o=!1;this.cancelPendingInit=()=>{o=!0};const a=this.lifecycle.consumePreInitPlugins(),c=async function(e){return new Na(e).run()}({shadow:s,config:this.configController.getConfig(),hostDir:this.getAttribute("dir")??void 0,configController:this.configController,styleCoordinator:this.styleCoordinator,events:this.events,preInitPlugins:a,isCancelled:()=>o||r!==this.initVersion}),l=this.completeInitialization(c,r,()=>o||r!==this.initVersion,a);this.pendingInitPromise=l;try{await l}finally{this.pendingInitPromise===l&&(this.pendingInitPromise=null,this.cancelPendingInit=null)}}async completeInitialization(e,t,n,i){let s=null;try{const i=await e;if(!i){if(n())throw new za;throw new Error("Editor initialization completed without a result.")}if(t!==this.initVersion)throw await i.dispose(),new za;if(this.activeInitResult=i,s=i,this.view=i.view,this.pluginManager=i.pluginManager,this.domElements=i.domElements,this.themeController=i.themeController,this.paperLayout=i.paperLayout,this.announce=i.announce,this.markdownImportedMessage=i.markdownImportedMessage,this.lifecycle.resolveReady(),this.events.emit("ready",void 0),t!==this.initVersion)throw new za}catch(r){throw s&&this.activeInitResult===s&&(this.activeInitResult=null,this.clearPublishedRuntime(),await s.dispose()),t===this.initVersion&&(this.lifecycle.restorePreInitPlugins(i),this.lifecycle.failReady(r)),r}}get isReadOnly(){return this.configController.isReadOnly}getJSON(){if(!this.view)throw new Error("Editor not initialized");return e=this.view.getState(),R(e.doc);var e}setJSON(e){this.assertInitialized(),cs(e,this.pluginManager?.schemaRegistry,e=>this.replaceState(e))}async getContentHTML(t){if(!this.view)throw new Error("Editor not initialized");return function(t,n,i){const s=t.doc;if("classes"===i?.cssMode){const t=wt(s,n,i);return i.pretty?{html:e(t.html),css:t.css,styleMap:t.styleMap}:t}const r=vt(s,n,i);return i?.pretty?e(r):r}(this.view.getState(),this.pluginManager?.schemaRegistry,t)}async setContentHTML(e,t){return this.assertInitialized(),function(e,t,n,i){cs(Dt(e,t,i),t,n)}(e,this.pluginManager?.schemaRegistry,e=>this.replaceState(e),t)}async getContentMarkdown(e){if(!this.view)throw new Error("Editor not initialized");return async function(e,t,n){const{serializeDocumentToMarkdown:i}=await import("./MarkdownSerializer-Y6saYClE.mjs").then(e=>e.t);return i(e.doc,t,n)}(this.view.getState(),this.pluginManager?.schemaRegistry,e)}async setContentMarkdown(e,t){this.assertInitialized();const n=this.view,i=this.pluginManager,s=this.announce,r=this.markdownImportedMessage;if(!n)return;const o=this.initVersion,a=i?.markdownSyntaxRegistry.getExtensions(),c={...t,syntaxExtensions:t?.syntaxExtensions??a};let l=!1;await async function(e,t,n,i,s){const{parseMarkdownToDocument:r}=await import("./MarkdownParser-JOfPSvGv.mjs").then(e=>e.t);i(ds(ss(ls(r(e,n,s),n),t.doc),n))}(e,n.getState(),i?.schemaRegistry,e=>{o===this.initVersion&&this.view===n&&this.pluginManager===i&&(n.replaceState(e),l=!0)},c),l&&o===this.initVersion&&this.view===n&&this.pluginManager===i&&this.announce===s&&s?.(r)}getText(){if(!this.view)throw new Error("Editor not initialized");return fs(this.view.getState())}setText(e){this.assertInitialized(),this.view&&function(e,t,n,i){e!==fs(t)&&i(ds(ss({children:e.split("\n").map(e=>L(he("paragraph"),[I(e)]))},t.doc),n))}(e,this.view.getState(),this.pluginManager?.schemaRegistry,e=>this.replaceState(e))}isEmpty(){return!this.view||gs(this.view.getState().doc)}commands={toggleBold:()=>this.executeCommand("toggleBold"),toggleItalic:()=>this.executeCommand("toggleItalic"),toggleUnderline:()=>this.executeCommand("toggleUnderline"),undo:()=>{this.configController.isReadOnly||this.view?.undo()},redo:()=>{this.configController.isReadOnly||this.view?.redo()},selectAll:()=>{if(!this.view)return;const e=_e(this.view.getState());this.dispatch(e)}};can(){const e=this.view?.getState().schema,t=this.configController.isReadOnly;return{toggleBold:()=>!t&&!!e&&ye(e,"bold"),toggleItalic:()=>!t&&!!e&&ye(e,"italic"),toggleUnderline:()=>!t&&!!e&&ye(e,"underline"),undo:()=>!t&&(this.view?.history.canUndo()??!1),redo:()=>!t&&(this.view?.history.canRedo()??!1),selectAll:()=>this.canExecuteCommand("selectAll")}}canExecuteCommand(e){return this.pluginManager?.canExecuteCommand(e)??!1}executeCommand(e){return this.pluginManager?.executeCommand(e)??!1}configurePlugin(e,t){this.pluginManager?.configurePlugin(e,t)}getService(e){return this.pluginManager?.getService(e)}onPluginEvent(e,t){return this.pluginManager?.onEvent(e,t)??(()=>{})}getState(){if(!this.view)throw new Error("Editor not initialized");return this.view.getState()}dispatch(e){this.view&&this.pluginManager&&this.pluginManager.dispatchWithMiddleware(e,this.view.getState(),e=>this.view?.dispatch(e))}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}whenReady(){return at(this)?Promise.reject(gt()):this.lifecycle.whenReady()}configure(e){this.configController.applyRuntimeConfig(e,this.getConfigDeps()),"logger"in e&&this.events.setLogger(e.logger)}setTheme(e){this.configController.applyTheme(e,this.themeController)}getTheme(){return this.configController.getTheme()}getPaperSize(){return this.configController.getPaperSize()}destroy(){if(this.cancelAutoInit(),this.pendingDestroyPromise)return this.destroyVersion++,this.initVersion++,this.cancelPendingInit?.(),this.lifecycle.reset(),this.pendingDestroyPromise;this.destroyVersion++,this.initVersion++,this.cancelPendingInit?.(),this.cancelPendingInit=null;const e=this.pendingInitPromise?.then(()=>{},()=>{})??Promise.resolve();this.pendingInitPromise=null;const t=this.activeInitResult;this.activeInitResult=null,this.clearPublishedRuntime(),this.lifecycle.reset(),this.events.clear();const n=Promise.resolve().then(()=>{const n=t?.dispose()??Promise.resolve();return Promise.all([n,e]).then(()=>{})}).finally(()=>{this.pendingDestroyPromise===n&&(this.pendingDestroyPromise=null)});return this.pendingDestroyPromise=n,n}clearPublishedRuntime(){this.view=null,this.pluginManager=null,this.domElements=null,this.themeController=null,this.paperLayout=null,this.announce=null}ensureFreshShadowRoot(){const e=this.shadowRoot;return e?(e.replaceChildren(),e):this.attachShadow({mode:"open"})}getConfigDeps(){return{contentElement:this.domElements?.content??null,editorWrapper:this.domElements?.wrapper??null,pluginManager:this.pluginManager,themeController:this.themeController,applyPaperSize:e=>this.applyPaperSize(e)}}scheduleAutoInit(){const e=++this.autoInitToken;this.autoInitQueued=!0,queueMicrotask(()=>{this.isConnected&&this.autoInitQueued&&this.autoInitToken===e&&(this.autoInitQueued=!1,this.lifecycle.isInitialized()||this.init().catch(()=>{}))})}cancelAutoInit(){this.autoInitToken++,this.autoInitQueued=!1}applyPaperSize(e){this.domElements&&(e?(this.paperLayout||(this.paperLayout=new Aa(this.domElements.wrapper,this.domElements.content)),this.paperLayout.apply(e)):this.paperLayout?.apply(null))}replaceState(e){this.view&&this.view.replaceState(e)}assertInitialized(){if(!this.view)throw new Error("Editor not initialized")}};async function $a(e){const t=document.createElement("notectl-editor");return await t.init(e),t}function Ka(){"undefined"==typeof customElements||customElements.get("notectl-editor")||customElements.define("notectl-editor",ja)}Ka();export{Gn as A,is as C,Xi as D,Yi as E,es as O,Ss as S,Qi as T,Br as _,Ca as a,Gs as b,xo as c,go as d,_r as f,Ar as g,Or as h,za as i,Wn as k,So as l,Dr as m,ja as n,Ra as o,Hr as p,$a as r,Po as s,Ka as t,ko as u,er as v,ts as w,xs as x,tr as y};
3
+ //# sourceMappingURL=register-DSRtHVkk.mjs.map