@notectl/core 2.3.6 → 2.4.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 (401) hide show
  1. package/dist/chunks/AlignmentPlugin-Cp7HYGaH.mjs +2 -0
  2. package/dist/chunks/AlignmentPlugin-Cp7HYGaH.mjs.map +1 -0
  3. package/dist/chunks/{AttrRegistry-CtNhf2EF.mjs → AttrRegistry-Di936wMv.mjs} +2 -2
  4. package/dist/chunks/{AttrRegistry-CtNhf2EF.mjs.map → AttrRegistry-Di936wMv.mjs.map} +1 -1
  5. package/dist/chunks/{AttributedMarkCommands-B3MQdob_.mjs → AttributedMarkCommands-DKHuhZA7.mjs} +2 -2
  6. package/dist/chunks/{AttributedMarkCommands-B3MQdob_.mjs.map → AttributedMarkCommands-DKHuhZA7.mjs.map} +1 -1
  7. package/dist/chunks/BidiIsolationPlugin-GWukKdgJ.mjs +2 -0
  8. package/dist/chunks/{BidiIsolationPlugin-cOLlL3Y9.mjs.map → BidiIsolationPlugin-GWukKdgJ.mjs.map} +1 -1
  9. package/dist/chunks/BlockAlignment-BqyBQ4uV.mjs +2 -0
  10. package/dist/chunks/BlockAlignment-BqyBQ4uV.mjs.map +1 -0
  11. package/dist/chunks/{BlockInsertion-O5pAFKid.mjs → BlockInsertion-CxKdCKJd.mjs} +2 -2
  12. package/dist/chunks/{BlockInsertion-O5pAFKid.mjs.map → BlockInsertion-CxKdCKJd.mjs.map} +1 -1
  13. package/dist/chunks/BlockquotePlugin-CSL_7Yit.mjs +2 -0
  14. package/dist/chunks/BlockquotePlugin-CSL_7Yit.mjs.map +1 -0
  15. package/dist/chunks/CSSValueEquivalence-DeyUKPQ7.mjs +2 -0
  16. package/dist/chunks/CSSValueEquivalence-DeyUKPQ7.mjs.map +1 -0
  17. package/dist/chunks/{CaretNavigationPlugin-DEZU09LJ.mjs → CaretNavigationPlugin-BxWjR7SN.mjs} +2 -2
  18. package/dist/chunks/{CaretNavigationPlugin-DEZU09LJ.mjs.map → CaretNavigationPlugin-BxWjR7SN.mjs.map} +1 -1
  19. package/dist/chunks/CodeBlockPlugin-BIrkK4ER.mjs +2 -0
  20. package/dist/chunks/{CodeBlockPlugin-BandNM3t.mjs.map → CodeBlockPlugin-BIrkK4ER.mjs.map} +1 -1
  21. package/dist/chunks/{ColorGrid-D0vLHsG6.mjs → ColorGrid-DAs0--ty.mjs} +2 -2
  22. package/dist/chunks/{ColorGrid-D0vLHsG6.mjs.map → ColorGrid-DAs0--ty.mjs.map} +1 -1
  23. package/dist/chunks/ColorPickerPopup-B6340f3p.mjs +2 -0
  24. package/dist/chunks/{ColorPickerPopup-_C5JZhki.mjs.map → ColorPickerPopup-B6340f3p.mjs.map} +1 -1
  25. package/dist/chunks/{ColorValidation-B9d_umnf.mjs → ColorValidation-ZBKZ_gTr.mjs} +2 -2
  26. package/dist/chunks/ColorValidation-ZBKZ_gTr.mjs.map +1 -0
  27. package/dist/chunks/Commands-DBBCAYBn.mjs +2 -0
  28. package/dist/chunks/Commands-DBBCAYBn.mjs.map +1 -0
  29. package/dist/chunks/{ContentModel-Bzmzeqwg.mjs → ContentModel-BLC3Tez8.mjs} +2 -2
  30. package/dist/chunks/{ContentModel-Bzmzeqwg.mjs.map → ContentModel-BLC3Tez8.mjs.map} +1 -1
  31. package/dist/chunks/{CursorMarks-dx51OGBf.mjs → CursorMarks-CqHLzGNI.mjs} +2 -2
  32. package/dist/chunks/{CursorMarks-dx51OGBf.mjs.map → CursorMarks-CqHLzGNI.mjs.map} +1 -1
  33. package/dist/chunks/{Decoration-BwhoA4MU.mjs → Decoration-BoFcdSXk.mjs} +2 -2
  34. package/dist/chunks/{Decoration-BwhoA4MU.mjs.map → Decoration-BoFcdSXk.mjs.map} +1 -1
  35. package/dist/chunks/{DirectionDetection-ZrkMhyaL.mjs → DirectionDetection-a-1iksmh.mjs} +2 -2
  36. package/dist/chunks/{DirectionDetection-ZrkMhyaL.mjs.map → DirectionDetection-a-1iksmh.mjs.map} +1 -1
  37. package/dist/chunks/{Document-D_2cIBJG.mjs → Document-ssR6hBzG.mjs} +2 -2
  38. package/dist/chunks/{Document-D_2cIBJG.mjs.map → Document-ssR6hBzG.mjs.map} +1 -1
  39. package/dist/chunks/DocumentParser-BKUrtgw1.mjs +2 -0
  40. package/dist/chunks/DocumentParser-BKUrtgw1.mjs.map +1 -0
  41. package/dist/chunks/FontPlugin-BcXNFqqO.mjs +2 -0
  42. package/dist/chunks/FontPlugin-BcXNFqqO.mjs.map +1 -0
  43. package/dist/chunks/FontSizePlugin-BQ9Aj8cT.mjs +2 -0
  44. package/dist/chunks/FontSizePlugin-BQ9Aj8cT.mjs.map +1 -0
  45. package/dist/chunks/FormulaPlugin-Bw_sO_lq.mjs +2 -0
  46. package/dist/chunks/FormulaPlugin-Bw_sO_lq.mjs.map +1 -0
  47. package/dist/chunks/GapCursorPlugin-QDGwnaRR.mjs +2 -0
  48. package/dist/chunks/GapCursorPlugin-QDGwnaRR.mjs.map +1 -0
  49. package/dist/chunks/HTMLUtils-DTpsjZyK.mjs +2 -0
  50. package/dist/chunks/HTMLUtils-DTpsjZyK.mjs.map +1 -0
  51. package/dist/chunks/{HardBreakPlugin-CC4rntSX.mjs → HardBreakPlugin-svNnJ9Xj.mjs} +2 -2
  52. package/dist/chunks/{HardBreakPlugin-CC4rntSX.mjs.map → HardBreakPlugin-svNnJ9Xj.mjs.map} +1 -1
  53. package/dist/chunks/HeadingPlugin-B7EfynaH.mjs +2 -0
  54. package/dist/chunks/HeadingPlugin-B7EfynaH.mjs.map +1 -0
  55. package/dist/chunks/HighlightPlugin-LdO0INtJ.mjs +2 -0
  56. package/dist/chunks/HighlightPlugin-LdO0INtJ.mjs.map +1 -0
  57. package/dist/chunks/HorizontalRulePlugin-CQ5NT2Mo.mjs +2 -0
  58. package/dist/chunks/{HorizontalRulePlugin-CxmUMM34.mjs.map → HorizontalRulePlugin-CQ5NT2Mo.mjs.map} +1 -1
  59. package/dist/chunks/ImagePlugin-BzLvPXGo.mjs +2 -0
  60. package/dist/chunks/ImagePlugin-BzLvPXGo.mjs.map +1 -0
  61. package/dist/chunks/InlineCodePlugin-Bu9-rE4B.mjs +2 -0
  62. package/dist/chunks/InlineCodePlugin-Bu9-rE4B.mjs.map +1 -0
  63. package/dist/chunks/InlineStyleMarkSpec-BhfGgfH9.mjs +2 -0
  64. package/dist/chunks/InlineStyleMarkSpec-BhfGgfH9.mjs.map +1 -0
  65. package/dist/chunks/{LinkPlugin-BwXDGHPe.mjs → LinkPlugin-BuzrXo2c.mjs} +2 -2
  66. package/dist/chunks/{LinkPlugin-BwXDGHPe.mjs.map → LinkPlugin-BuzrXo2c.mjs.map} +1 -1
  67. package/dist/chunks/ListPlugin-DTgpvBEt.mjs +2 -0
  68. package/dist/chunks/{ListPlugin-DSFPSWQC.mjs.map → ListPlugin-DTgpvBEt.mjs.map} +1 -1
  69. package/dist/chunks/MarkCommands-C0ps9h0z.mjs +2 -0
  70. package/dist/chunks/MarkCommands-C0ps9h0z.mjs.map +1 -0
  71. package/dist/chunks/MarkdownHTMLRegistry-BunUDiza.mjs +2 -0
  72. package/dist/chunks/{MarkdownHTMLRegistry-CISsC0lH.mjs.map → MarkdownHTMLRegistry-BunUDiza.mjs.map} +1 -1
  73. package/dist/chunks/{MarkdownParser-D1d9zB0R.mjs → MarkdownParser-CvYOvU3d.mjs} +2 -2
  74. package/dist/chunks/{MarkdownParser-D1d9zB0R.mjs.map → MarkdownParser-CvYOvU3d.mjs.map} +1 -1
  75. package/dist/chunks/MarkdownSerializer-CdUBWWGI.mjs +2 -0
  76. package/dist/chunks/MarkdownSerializer-CdUBWWGI.mjs.map +1 -0
  77. package/dist/chunks/NavigationQueries-CaKfccu7.mjs +2 -0
  78. package/dist/chunks/NavigationQueries-CaKfccu7.mjs.map +1 -0
  79. package/dist/chunks/NodeResolver-F4RtpoEd.mjs +2 -0
  80. package/dist/chunks/NodeResolver-F4RtpoEd.mjs.map +1 -0
  81. package/dist/chunks/{NodeSelectionCommands-DK3iEh18.mjs → NodeSelectionCommands-B0Sb4ux4.mjs} +2 -2
  82. package/dist/chunks/{NodeSelectionCommands-DK3iEh18.mjs.map → NodeSelectionCommands-B0Sb4ux4.mjs.map} +1 -1
  83. package/dist/chunks/PluginHelpers-B3gk3VB3.mjs +2 -0
  84. package/dist/chunks/{PluginHelpers-WG1Lzzh3.mjs.map → PluginHelpers-B3gk3VB3.mjs.map} +1 -1
  85. package/dist/chunks/{PrintPlugin-BQ7LWbEB.mjs → PrintPlugin-BxNlFk2c.mjs} +2 -2
  86. package/dist/chunks/{PrintPlugin-BQ7LWbEB.mjs.map → PrintPlugin-BxNlFk2c.mjs.map} +1 -1
  87. package/dist/chunks/{RangeIterator-DDOxTQIf.mjs → RangeIterator-sJ_c9MNr.mjs} +2 -2
  88. package/dist/chunks/{RangeIterator-DDOxTQIf.mjs.map → RangeIterator-sJ_c9MNr.mjs.map} +1 -1
  89. package/dist/chunks/Schema-BSM4YLNT.mjs +2 -0
  90. package/dist/chunks/Schema-BSM4YLNT.mjs.map +1 -0
  91. package/dist/chunks/SchemaRegistry-Cs7rxafF.mjs +2 -0
  92. package/dist/chunks/SchemaRegistry-Cs7rxafF.mjs.map +1 -0
  93. package/dist/chunks/SelectionSync-BkjCwGp-.mjs +2 -0
  94. package/dist/chunks/SelectionSync-BkjCwGp-.mjs.map +1 -0
  95. package/dist/chunks/{SelectionTransactions-DNCzsl_b.mjs → SelectionTransactions-mQ1NfMEg.mjs} +2 -2
  96. package/dist/chunks/{SelectionTransactions-DNCzsl_b.mjs.map → SelectionTransactions-mQ1NfMEg.mjs.map} +1 -1
  97. package/dist/chunks/SimpleMark-D6vz3Nfd.mjs +2 -0
  98. package/dist/chunks/{SimpleMark-CTDtEIMV.mjs.map → SimpleMark-D6vz3Nfd.mjs.map} +1 -1
  99. package/dist/chunks/{SmartPastePlugin-CjExbE9Q.mjs → SmartPastePlugin-C3SVKkWK.mjs} +2 -2
  100. package/dist/chunks/{SmartPastePlugin-CjExbE9Q.mjs.map → SmartPastePlugin-C3SVKkWK.mjs.map} +1 -1
  101. package/dist/chunks/{StrikethroughPlugin-d-EW2YYx.mjs → StrikethroughPlugin-v-VJZzUZ.mjs} +2 -2
  102. package/dist/chunks/{StrikethroughPlugin-d-EW2YYx.mjs.map → StrikethroughPlugin-v-VJZzUZ.mjs.map} +1 -1
  103. package/dist/chunks/StyleClassNames-BsAx7k5T.mjs +2 -0
  104. package/dist/chunks/StyleClassNames-BsAx7k5T.mjs.map +1 -0
  105. package/dist/chunks/{SuperSubPlugin-C-kvFQyx.mjs → SuperSubPlugin-x1iPnZyt.mjs} +2 -2
  106. package/dist/chunks/{SuperSubPlugin-C-kvFQyx.mjs.map → SuperSubPlugin-x1iPnZyt.mjs.map} +1 -1
  107. package/dist/chunks/TableDimensions-BSEOEox2.mjs +2 -0
  108. package/dist/chunks/TableDimensions-BSEOEox2.mjs.map +1 -0
  109. package/dist/chunks/TablePlugin-WPwp902E.mjs +2 -0
  110. package/dist/chunks/TablePlugin-WPwp902E.mjs.map +1 -0
  111. package/dist/chunks/TextColorPlugin-Bnl9of9E.mjs +2 -0
  112. package/dist/chunks/TextColorPlugin-Bnl9of9E.mjs.map +1 -0
  113. package/dist/chunks/{TextDirectionAutoPlugin-LVDkKdDX.mjs → TextDirectionAutoPlugin-DOH5cfyy.mjs} +2 -2
  114. package/dist/chunks/{TextDirectionAutoPlugin-LVDkKdDX.mjs.map → TextDirectionAutoPlugin-DOH5cfyy.mjs.map} +1 -1
  115. package/dist/chunks/{TextDirectionPlugin-CtGwof7i.mjs → TextDirectionPlugin-JwlR-R-b.mjs} +2 -2
  116. package/dist/chunks/{TextDirectionPlugin-CtGwof7i.mjs.map → TextDirectionPlugin-JwlR-R-b.mjs.map} +1 -1
  117. package/dist/chunks/TextDirectionService-BcX07mw2.mjs +2 -0
  118. package/dist/chunks/{TextDirectionService-OFOU6r_s.mjs.map → TextDirectionService-BcX07mw2.mjs.map} +1 -1
  119. package/dist/chunks/{TextFormattingPlugin-DlS0SeW7.mjs → TextFormattingPlugin-Kc_UNoOz.mjs} +2 -2
  120. package/dist/chunks/{TextFormattingPlugin-DlS0SeW7.mjs.map → TextFormattingPlugin-Kc_UNoOz.mjs.map} +1 -1
  121. package/dist/chunks/ToolbarPlugin-DmVI7MN9.mjs +2 -0
  122. package/dist/chunks/ToolbarPlugin-DmVI7MN9.mjs.map +1 -0
  123. package/dist/chunks/VideoPlugin-D3zGQ6QV.mjs +2 -0
  124. package/dist/chunks/VideoPlugin-D3zGQ6QV.mjs.map +1 -0
  125. package/dist/chunks/color-picker-D6HrTsDM.mjs +2 -0
  126. package/dist/chunks/color-picker-D6HrTsDM.mjs.map +1 -0
  127. package/dist/chunks/full-BiQ93ERr.mjs +2 -0
  128. package/dist/chunks/{full-Cshz7aTP.mjs.map → full-BiQ93ERr.mjs.map} +1 -1
  129. package/dist/chunks/minimal-DO7LiFTa.mjs +2 -0
  130. package/dist/chunks/{minimal-7XqMY9kC.mjs.map → minimal-DO7LiFTa.mjs.map} +1 -1
  131. package/dist/chunks/register-Cb1YTAN4.mjs +3 -0
  132. package/dist/chunks/register-Cb1YTAN4.mjs.map +1 -0
  133. package/dist/commands/Commands.d.ts.map +1 -1
  134. package/dist/commands/CompositionCommands.d.ts +47 -0
  135. package/dist/commands/CompositionCommands.d.ts.map +1 -0
  136. package/dist/commands/CompositionRebase.d.ts +24 -0
  137. package/dist/commands/CompositionRebase.d.ts.map +1 -0
  138. package/dist/commands/PasteCommand.d.ts.map +1 -1
  139. package/dist/commands/SelectionDeletion.d.ts +15 -5
  140. package/dist/commands/SelectionDeletion.d.ts.map +1 -1
  141. package/dist/fonts/math.mjs +1 -1
  142. package/dist/fonts.mjs +1 -1
  143. package/dist/full.mjs +1 -1
  144. package/dist/html.mjs +1 -1
  145. package/dist/index.d.ts +1 -0
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/input/CompositionController.d.ts +78 -0
  148. package/dist/input/CompositionController.d.ts.map +1 -0
  149. package/dist/input/HTMLParser.d.ts +15 -2
  150. package/dist/input/HTMLParser.d.ts.map +1 -1
  151. package/dist/input/InputHandler.d.ts +34 -1
  152. package/dist/input/InputHandler.d.ts.map +1 -1
  153. package/dist/input/InputManager.d.ts +3 -0
  154. package/dist/input/InputManager.d.ts.map +1 -1
  155. package/dist/input/PasteHTMLHandler.d.ts.map +1 -1
  156. package/dist/markdown.mjs +1 -1
  157. package/dist/model/BlockAlignment.d.ts +6 -0
  158. package/dist/model/BlockAlignment.d.ts.map +1 -1
  159. package/dist/model/BlockOffsetText.d.ts +11 -0
  160. package/dist/model/BlockOffsetText.d.ts.map +1 -0
  161. package/dist/model/CompositionState.d.ts +14 -0
  162. package/dist/model/CompositionState.d.ts.map +1 -1
  163. package/dist/model/HTMLUtils.d.ts +16 -3
  164. package/dist/model/HTMLUtils.d.ts.map +1 -1
  165. package/dist/model/MarkSpec.d.ts +5 -3
  166. package/dist/model/MarkSpec.d.ts.map +1 -1
  167. package/dist/model/NodeResolver.d.ts +2 -0
  168. package/dist/model/NodeResolver.d.ts.map +1 -1
  169. package/dist/model/NodeSpec.d.ts +2 -1
  170. package/dist/model/NodeSpec.d.ts.map +1 -1
  171. package/dist/model/Schema.d.ts +2 -0
  172. package/dist/model/Schema.d.ts.map +1 -1
  173. package/dist/model/SchemaRegistry.d.ts +26 -1
  174. package/dist/model/SchemaRegistry.d.ts.map +1 -1
  175. package/dist/model/StyleClass.d.ts +45 -0
  176. package/dist/model/StyleClass.d.ts.map +1 -0
  177. package/dist/model/StyleClassRegistry.d.ts +28 -0
  178. package/dist/model/StyleClassRegistry.d.ts.map +1 -0
  179. package/dist/model/TextChange.d.ts +40 -0
  180. package/dist/model/TextChange.d.ts.map +1 -0
  181. package/dist/notectl-core.mjs +1 -1
  182. package/dist/notectl-core.umd.js +1 -1
  183. package/dist/notectl-core.umd.js.map +1 -1
  184. package/dist/plugins/Plugin.d.ts +11 -0
  185. package/dist/plugins/Plugin.d.ts.map +1 -1
  186. package/dist/plugins/PluginContextFactory.d.ts +2 -0
  187. package/dist/plugins/PluginContextFactory.d.ts.map +1 -1
  188. package/dist/plugins/RegistrationTracker.d.ts.map +1 -1
  189. package/dist/plugins/alignment/AlignmentPlugin.d.ts +17 -0
  190. package/dist/plugins/alignment/AlignmentPlugin.d.ts.map +1 -1
  191. package/dist/plugins/alignment.mjs +1 -1
  192. package/dist/plugins/bidi-isolation.mjs +1 -1
  193. package/dist/plugins/blockquote.mjs +1 -1
  194. package/dist/plugins/caret-navigation.mjs +1 -1
  195. package/dist/plugins/code-block.mjs +1 -1
  196. package/dist/plugins/font/FontPlugin.d.ts +13 -0
  197. package/dist/plugins/font/FontPlugin.d.ts.map +1 -1
  198. package/dist/plugins/font-size/FontSizeOperations.d.ts +2 -0
  199. package/dist/plugins/font-size/FontSizeOperations.d.ts.map +1 -1
  200. package/dist/plugins/font-size/FontSizePlugin.d.ts +11 -0
  201. package/dist/plugins/font-size/FontSizePlugin.d.ts.map +1 -1
  202. package/dist/plugins/font-size.mjs +1 -1
  203. package/dist/plugins/font.mjs +1 -1
  204. package/dist/plugins/formula/FormulaPlugin.d.ts.map +1 -1
  205. package/dist/plugins/formula/latex/LatexParser.d.ts.map +1 -1
  206. package/dist/plugins/formula/latex/LatexSymbols.d.ts.map +1 -1
  207. package/dist/plugins/formula/latex/LookupOwn.d.ts +6 -0
  208. package/dist/plugins/formula/latex/LookupOwn.d.ts.map +1 -0
  209. package/dist/plugins/formula/latex/handlers/Accents.d.ts.map +1 -1
  210. package/dist/plugins/formula/latex/handlers/Delimiters.d.ts.map +1 -1
  211. package/dist/plugins/formula/latex/handlers/Environments.d.ts.map +1 -1
  212. package/dist/plugins/formula/latex/handlers/Fonts.d.ts.map +1 -1
  213. package/dist/plugins/formula/latex/handlers/Spacing.d.ts.map +1 -1
  214. package/dist/plugins/formula.mjs +1 -1
  215. package/dist/plugins/gap-cursor/GapCursorPlugin.d.ts.map +1 -1
  216. package/dist/plugins/gap-cursor.mjs +1 -1
  217. package/dist/plugins/hard-break.mjs +1 -1
  218. package/dist/plugins/heading.mjs +1 -1
  219. package/dist/plugins/highlight/HighlightPlugin.d.ts +11 -0
  220. package/dist/plugins/highlight/HighlightPlugin.d.ts.map +1 -1
  221. package/dist/plugins/highlight.mjs +1 -1
  222. package/dist/plugins/horizontal-rule.mjs +1 -1
  223. package/dist/plugins/image.mjs +1 -1
  224. package/dist/plugins/inline-code/InlineCodePlugin.d.ts.map +1 -1
  225. package/dist/plugins/inline-code.mjs +1 -1
  226. package/dist/plugins/link/LinkPlugin.d.ts.map +1 -1
  227. package/dist/plugins/link.mjs +1 -1
  228. package/dist/plugins/list/ListPlugin.d.ts +2 -1
  229. package/dist/plugins/list/ListPlugin.d.ts.map +1 -1
  230. package/dist/plugins/list.mjs +1 -1
  231. package/dist/plugins/print.mjs +1 -1
  232. package/dist/plugins/shared/ColorGrid.d.ts.map +1 -1
  233. package/dist/plugins/shared/ColorPickerPopup.d.ts.map +1 -1
  234. package/dist/plugins/shared/ColorValidation.d.ts +12 -4
  235. package/dist/plugins/shared/ColorValidation.d.ts.map +1 -1
  236. package/dist/plugins/shared/InlineStyleMarkSpec.d.ts +10 -0
  237. package/dist/plugins/shared/InlineStyleMarkSpec.d.ts.map +1 -1
  238. package/dist/plugins/shared/StyleClassNames.d.ts +10 -0
  239. package/dist/plugins/shared/StyleClassNames.d.ts.map +1 -0
  240. package/dist/plugins/shared.mjs +1 -1
  241. package/dist/plugins/smart-paste.mjs +1 -1
  242. package/dist/plugins/strikethrough.mjs +1 -1
  243. package/dist/plugins/super-sub.mjs +1 -1
  244. package/dist/plugins/table/TableBorderColor.d.ts.map +1 -1
  245. package/dist/plugins/table.mjs +1 -1
  246. package/dist/plugins/text-color/TextColorPlugin.d.ts +11 -0
  247. package/dist/plugins/text-color/TextColorPlugin.d.ts.map +1 -1
  248. package/dist/plugins/text-color.mjs +1 -1
  249. package/dist/plugins/text-direction-auto.mjs +1 -1
  250. package/dist/plugins/text-direction.mjs +1 -1
  251. package/dist/plugins/text-formatting.mjs +1 -1
  252. package/dist/plugins/toolbar/ToolbarOverflowController.d.ts.map +1 -1
  253. package/dist/plugins/toolbar/ToolbarPlugin.d.ts.map +1 -1
  254. package/dist/plugins/toolbar.mjs +1 -1
  255. package/dist/plugins/video.mjs +1 -1
  256. package/dist/presets/full.mjs +1 -1
  257. package/dist/presets/minimal.mjs +1 -1
  258. package/dist/presets.mjs +1 -1
  259. package/dist/register.mjs +1 -1
  260. package/dist/serialization/AlignmentHTML.d.ts +43 -0
  261. package/dist/serialization/AlignmentHTML.d.ts.map +1 -0
  262. package/dist/serialization/CSSClassCollector.d.ts +20 -17
  263. package/dist/serialization/CSSClassCollector.d.ts.map +1 -1
  264. package/dist/serialization/CSSValueEquivalence.d.ts +24 -0
  265. package/dist/serialization/CSSValueEquivalence.d.ts.map +1 -0
  266. package/dist/serialization/DocumentParser.d.ts +2 -1
  267. package/dist/serialization/DocumentParser.d.ts.map +1 -1
  268. package/dist/serialization/DocumentSerializer.d.ts +0 -4
  269. package/dist/serialization/DocumentSerializer.d.ts.map +1 -1
  270. package/dist/serialization/FirstTagAttributes.d.ts +16 -0
  271. package/dist/serialization/FirstTagAttributes.d.ts.map +1 -0
  272. package/dist/serialization/HTMLParseRules.d.ts +32 -0
  273. package/dist/serialization/HTMLParseRules.d.ts.map +1 -0
  274. package/dist/serialization/HTMLParseSession.d.ts +21 -0
  275. package/dist/serialization/HTMLParseSession.d.ts.map +1 -0
  276. package/dist/serialization/MarkSerializer.d.ts.map +1 -1
  277. package/dist/serialization/StyleClassHTML.d.ts +37 -0
  278. package/dist/serialization/StyleClassHTML.d.ts.map +1 -0
  279. package/dist/serialization/StyleRehydration.d.ts +16 -0
  280. package/dist/serialization/StyleRehydration.d.ts.map +1 -0
  281. package/dist/serialization/TableDimensions.d.ts.map +1 -1
  282. package/dist/serialization/index.d.ts +2 -1
  283. package/dist/serialization/index.d.ts.map +1 -1
  284. package/dist/serialization/markdown/InlineSerializers.d.ts.map +1 -1
  285. package/dist/state/EditorState.d.ts.map +1 -1
  286. package/dist/state/History.d.ts +2 -1
  287. package/dist/state/History.d.ts.map +1 -1
  288. package/dist/state/NavigationQueries.d.ts.map +1 -1
  289. package/dist/state/SelectionValidation.d.ts +12 -0
  290. package/dist/state/SelectionValidation.d.ts.map +1 -0
  291. package/dist/state/StepMapping.d.ts.map +1 -1
  292. package/dist/state/TransactionBuilder.d.ts +7 -1
  293. package/dist/state/TransactionBuilder.d.ts.map +1 -1
  294. package/dist/test/PluginTestUtils.d.ts +25 -0
  295. package/dist/test/PluginTestUtils.d.ts.map +1 -1
  296. package/dist/test/TestUtils.d.ts.map +1 -1
  297. package/dist/view/CursorWrapper.d.ts.map +1 -1
  298. package/dist/view/EditorView.d.ts +25 -1
  299. package/dist/view/EditorView.d.ts.map +1 -1
  300. package/dist/view/InlineContentDOM.d.ts +44 -0
  301. package/dist/view/InlineContentDOM.d.ts.map +1 -0
  302. package/dist/view/Reconciler.d.ts +20 -1
  303. package/dist/view/Reconciler.d.ts.map +1 -1
  304. package/dist/view/RenderedBlockText.d.ts +27 -0
  305. package/dist/view/RenderedBlockText.d.ts.map +1 -0
  306. package/dist/view/SelectionSync.d.ts.map +1 -1
  307. package/package.json +3 -2
  308. package/dist/chunks/AlignmentPlugin-DIwrRsHd.mjs +0 -2
  309. package/dist/chunks/AlignmentPlugin-DIwrRsHd.mjs.map +0 -1
  310. package/dist/chunks/BidiIsolationPlugin-cOLlL3Y9.mjs +0 -2
  311. package/dist/chunks/BlockquotePlugin-D-jRWLQB.mjs +0 -2
  312. package/dist/chunks/BlockquotePlugin-D-jRWLQB.mjs.map +0 -1
  313. package/dist/chunks/CodeBlockPlugin-BandNM3t.mjs +0 -2
  314. package/dist/chunks/ColorPickerPopup-_C5JZhki.mjs +0 -2
  315. package/dist/chunks/ColorValidation-B9d_umnf.mjs.map +0 -1
  316. package/dist/chunks/Commands-D-0UXYvo.mjs +0 -2
  317. package/dist/chunks/Commands-D-0UXYvo.mjs.map +0 -1
  318. package/dist/chunks/DocumentParser-i-CreJ48.mjs +0 -2
  319. package/dist/chunks/DocumentParser-i-CreJ48.mjs.map +0 -1
  320. package/dist/chunks/FontPlugin-C_ScWZ0P.mjs +0 -2
  321. package/dist/chunks/FontPlugin-C_ScWZ0P.mjs.map +0 -1
  322. package/dist/chunks/FontSizePlugin-DB_0njtC.mjs +0 -2
  323. package/dist/chunks/FontSizePlugin-DB_0njtC.mjs.map +0 -1
  324. package/dist/chunks/FormulaPlugin-CI0r4X1o.mjs +0 -2
  325. package/dist/chunks/FormulaPlugin-CI0r4X1o.mjs.map +0 -1
  326. package/dist/chunks/GapCursorPlugin-NozsEK9J.mjs +0 -2
  327. package/dist/chunks/GapCursorPlugin-NozsEK9J.mjs.map +0 -1
  328. package/dist/chunks/HTMLUtils-B0nGyFLb.mjs +0 -2
  329. package/dist/chunks/HTMLUtils-B0nGyFLb.mjs.map +0 -1
  330. package/dist/chunks/HeadingPlugin-LK8Pg4h0.mjs +0 -2
  331. package/dist/chunks/HeadingPlugin-LK8Pg4h0.mjs.map +0 -1
  332. package/dist/chunks/HighlightPlugin-B4WlZawl.mjs +0 -2
  333. package/dist/chunks/HighlightPlugin-B4WlZawl.mjs.map +0 -1
  334. package/dist/chunks/HorizontalRulePlugin-CxmUMM34.mjs +0 -2
  335. package/dist/chunks/ImagePlugin-C5ESNNsA.mjs +0 -2
  336. package/dist/chunks/ImagePlugin-C5ESNNsA.mjs.map +0 -1
  337. package/dist/chunks/InlineCodePlugin-C1SqGfv5.mjs +0 -2
  338. package/dist/chunks/InlineCodePlugin-C1SqGfv5.mjs.map +0 -1
  339. package/dist/chunks/InlineStyleMarkSpec-Cx3goc3W.mjs +0 -2
  340. package/dist/chunks/InlineStyleMarkSpec-Cx3goc3W.mjs.map +0 -1
  341. package/dist/chunks/ListPlugin-DSFPSWQC.mjs +0 -2
  342. package/dist/chunks/MarkCommands-CJvLGL5G.mjs +0 -2
  343. package/dist/chunks/MarkCommands-CJvLGL5G.mjs.map +0 -1
  344. package/dist/chunks/MarkdownHTMLRegistry-CISsC0lH.mjs +0 -2
  345. package/dist/chunks/MarkdownSerializer-Oex2RzNw.mjs +0 -2
  346. package/dist/chunks/MarkdownSerializer-Oex2RzNw.mjs.map +0 -1
  347. package/dist/chunks/NavigationQueries-Bt4zZ17v.mjs +0 -2
  348. package/dist/chunks/NavigationQueries-Bt4zZ17v.mjs.map +0 -1
  349. package/dist/chunks/NodeResolver-BtIknXqD.mjs +0 -2
  350. package/dist/chunks/NodeResolver-BtIknXqD.mjs.map +0 -1
  351. package/dist/chunks/PluginHelpers-WG1Lzzh3.mjs +0 -2
  352. package/dist/chunks/SchemaRegistry-acc6q_5x.mjs +0 -2
  353. package/dist/chunks/SchemaRegistry-acc6q_5x.mjs.map +0 -1
  354. package/dist/chunks/SelectionSync-CwOHMMfI.mjs +0 -2
  355. package/dist/chunks/SelectionSync-CwOHMMfI.mjs.map +0 -1
  356. package/dist/chunks/SimpleMark-CTDtEIMV.mjs +0 -2
  357. package/dist/chunks/TableDimensions-BcARMxQB.mjs +0 -2
  358. package/dist/chunks/TableDimensions-BcARMxQB.mjs.map +0 -1
  359. package/dist/chunks/TablePlugin-C4WMYGWN.mjs +0 -2
  360. package/dist/chunks/TablePlugin-C4WMYGWN.mjs.map +0 -1
  361. package/dist/chunks/TextColorPlugin-D_MhNJT6.mjs +0 -2
  362. package/dist/chunks/TextColorPlugin-D_MhNJT6.mjs.map +0 -1
  363. package/dist/chunks/TextDirectionService-OFOU6r_s.mjs +0 -2
  364. package/dist/chunks/ToolbarPlugin-O7TirXQP.mjs +0 -2
  365. package/dist/chunks/ToolbarPlugin-O7TirXQP.mjs.map +0 -1
  366. package/dist/chunks/VideoPlugin-C9z4JfP_.mjs +0 -2
  367. package/dist/chunks/VideoPlugin-C9z4JfP_.mjs.map +0 -1
  368. package/dist/chunks/color-picker-DJ05ey9o.mjs +0 -2
  369. package/dist/chunks/color-picker-DJ05ey9o.mjs.map +0 -1
  370. package/dist/chunks/full-Cshz7aTP.mjs +0 -2
  371. package/dist/chunks/minimal-7XqMY9kC.mjs +0 -2
  372. package/dist/chunks/register-BVvV0Vl_.mjs +0 -3
  373. package/dist/chunks/register-BVvV0Vl_.mjs.map +0 -1
  374. package/dist/editor/styles/base.d.ts +0 -3
  375. package/dist/editor/styles/base.d.ts.map +0 -1
  376. package/dist/editor/styles/color-picker.d.ts +0 -3
  377. package/dist/editor/styles/color-picker.d.ts.map +0 -1
  378. package/dist/editor/styles/font-select.d.ts +0 -3
  379. package/dist/editor/styles/font-select.d.ts.map +0 -1
  380. package/dist/editor/styles/font-size-select.d.ts +0 -3
  381. package/dist/editor/styles/font-size-select.d.ts.map +0 -1
  382. package/dist/editor/styles/heading-select.d.ts +0 -3
  383. package/dist/editor/styles/heading-select.d.ts.map +0 -1
  384. package/dist/editor/styles/image.d.ts +0 -3
  385. package/dist/editor/styles/image.d.ts.map +0 -1
  386. package/dist/editor/styles/reduced-motion.d.ts +0 -3
  387. package/dist/editor/styles/reduced-motion.d.ts.map +0 -1
  388. package/dist/editor/styles/table.d.ts +0 -3
  389. package/dist/editor/styles/table.d.ts.map +0 -1
  390. package/dist/editor/styles/toolbar.d.ts +0 -3
  391. package/dist/editor/styles/toolbar.d.ts.map +0 -1
  392. package/dist/plugins/blockquote/BlockquoteStyles.d.ts +0 -3
  393. package/dist/plugins/blockquote/BlockquoteStyles.d.ts.map +0 -1
  394. package/dist/plugins/formula/FormulaStyles.d.ts +0 -12
  395. package/dist/plugins/formula/FormulaStyles.d.ts.map +0 -1
  396. package/dist/plugins/image/ImagePopupStyles.d.ts +0 -3
  397. package/dist/plugins/image/ImagePopupStyles.d.ts.map +0 -1
  398. package/dist/plugins/video/VideoPopupStyles.d.ts +0 -3
  399. package/dist/plugins/video/VideoPopupStyles.d.ts.map +0 -1
  400. package/dist/plugins/video/VideoStyles.d.ts +0 -3
  401. package/dist/plugins/video/VideoStyles.d.ts.map +0 -1
@@ -0,0 +1,3 @@
1
+ import{a as e,c as t,l as n,n as s}from"./HTMLUtils-DTpsjZyK.mjs";import{A as r,B as i,C as o,D as a,E as l,G as c,H as d,K as h,L as u,M as p,O as m,P as f,R as g,S as y,T as k,U as w,V as b,W as v,_ as I,a as S,b as x,c as R,d as M,f as C,g as P,h as E,i as T,j as B,k as A,l as O,m as N,o as D,p as L,q as H,r as z,s as F,t as j,u as $,v as _,w as K,x as V,y as W,z as q}from"./Document-ssR6hBzG.mjs";import{c as U,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 se,n as re,o as ie,p as oe,r as ae,s as le,t as ce,u as de}from"./Selection-DC6AOGgF.mjs";import{a as he,i as ue,r as pe,t as me}from"./TypeBrands-Ch9856Gb.mjs";import{a as fe,i as ge,n as ye,r as ke,t as we}from"./Schema-BSM4YLNT.mjs";import{C as be,S as ve,a as Ie,d as Se,f as xe,g as Re,h as Me,i as Ce,m as Pe,n as Ee,p as Te,r as Be,t as Ae,u as Oe,w as Ne,x as De,y as Le}from"./BlockInsertion-CxKdCKJd.mjs";import{i as He,t as ze}from"./NodeSelectionCommands-B0Sb4ux4.mjs";import{a as Fe,c as je,i as $e,l as _e,n as Ke,o as Ve,r as We,s as qe,t as Ue,u as Ge}from"./Commands-DBBCAYBn.mjs";import{t as Je}from"./MarkCommands-C0ps9h0z.mjs";import{A as Qe,F as Xe,I as Ye,L as Ze,M as et,N as tt,P as nt,R as st,j as rt,t as it,z as ot}from"./CaretNavigationPlugin-BxWjR7SN.mjs";import{_ as at,b as lt,c as ct,d as dt,f as ht,g as ut,i as pt,n as mt,p as ft,u as gt,y as yt}from"./ThemeEngine-kIXtSRkI.mjs";import{T as kt,_ as wt,h as bt,m as vt,p as It,v as St,y as xt}from"./TableDimensions-BSEOEox2.mjs";import{n as Rt,t as Mt}from"./HTMLSanitization-Ce9dVT1q.mjs";import{a as Ct,c as Pt,i as Et,n as Tt,o as Bt,r as At,s as Ot,t as Nt}from"./DocumentParser-BKUrtgw1.mjs";import{_ as Dt,c as Lt,d as Ht,f as zt,g as Ft,l as jt,m as $t,n as _t,p as Kt,r as Vt,s as Wt,t as qt,u as Ut}from"./Decoration-BoFcdSXk.mjs";import{c as Gt,l as Jt,u as Qt}from"./PluginHelpers-B3gk3VB3.mjs";import{n as Xt,t as Yt}from"./EditorEventBoundary-zpYRxryo.mjs";import{a as Zt,c as en,l as tn,r as nn,t as sn,u as rn}from"./StyleRuntime-C0RSqKzG.mjs";import{t as on}from"./Platform-ByobkiCc.mjs";import{t as an}from"./SchemaRegistry-Cs7rxafF.mjs";import{t as ln}from"./BlockTypePickerRegistry-BTET9jM-.mjs";import{o as cn,t as dn}from"./ToolbarPlugin-DmVI7MN9.mjs";import{n as hn,t as un}from"./DomUtils-Bf7JLFlx.mjs";import{a as pn,c as mn,d as fn,i as gn,l as yn,n as kn,o as wn,r as bn,s as vn,t as In,u as Sn}from"./SelectionSync-BkjCwGp-.mjs";import{n as xn,t as Rn}from"./GapCursorPlugin-QDGwnaRR.mjs";import{t as Mn}from"./TextFormattingPlugin-Kc_UNoOz.mjs";function Cn(e,t){const n=e.selection;if(ee(n))return ze(e,n);if(de(n))return null;if(!Z(n))return Ke(e);const s=e.getBlock(n.anchor.blockId);if(!s)return null;const r=t.range(s,n.anchor.offset);if(!r)return t.merge(e);const[i,o]=r;return e.transaction("input").deleteTextAt(s.id,i,o).setSelection(re(s.id,i)).build()}function Pn(e){return Cn(e,{merge:Fe,range:(e,t)=>{if(t<=0)return null;if("inline"===p(e,t-1)?.kind)return[t-1,t];const n=B(e),s=T(e,t);return[t-(ot(n,s)||1),t]}})}function En(e){return Cn(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),s=T(e,t);return[t,t+(st(n,s)||1)]}})}function Tn(e,t){return{children:e.children.map(e=>Bn(e,t))}}function Bn(e,t){const n=t.getNodeSpec(e.type);let s=e;if(n?.content&&n.content.allow.some(e=>"text"!==e)){const r=n.content.allow.includes("text");if(i(e)){if(!r&&(0!==e.children.length||0!==n.content.min)){const t=e.children.length>0?e.children:void 0,n=L(he("paragraph"),t);s=L(e.type,[n],e.id,e.attrs,e.htmlId)}}else{const n=function(e,t){const n=[];let s=[];const r=()=>{0!==s.length&&(n.push(L(he("paragraph"),s)),s=[])};for(const i of e)b(i)||q(i)?s.push(i):(r(),n.push(Bn(i,t)));return r(),n}(e.children,t);s=L(e.type,n,e.id,e.attrs,e.htmlId)}}const r=n?.normalizeAttrs?.(s);if(n?.normalizeAttrs&&!z(s.attrs,r)){const{attrs:e,...t}=s;s={...t,...r?{attrs:r}:{}}}return n?.normalizeNode?.(s)??s}function An(e,t,n){if(ee(n))return G(e,n.nodeId)?n:On(e,t)??n;if(de(n))return G(e,n.blockId)?n:On(e,t)??n;const s=Nn(e,t,n.anchor),r=Nn(e,t,n.head);return s.blockId===r.blockId&&function(e,t,n){const s=G(e,n);return void 0!==s&&ge(t,s.type)}(e,t,s.blockId)?Hn(e,s.blockId):s===n.anchor&&r===n.head?n:ie(s,r)}function On(e,t){const n=Dn(e.children,t);return n?ge(t,n.type)?Hn(e,n.id):re(n.id,0):null}function Nn(e,t,n){const s=G(e,n.blockId);if(s&&i(s))return function(e,t){const n=A(e),s=Number.isFinite(t.offset)?Math.trunc(t.offset):0,r=Math.max(0,Math.min(n,s));return r===t.offset?t:Y(t.blockId,r,t.path)}(s,n);const r=Dn(s?s.children:e.children,t)??(s?Dn(e.children,t):null);return r?Y(r.id,0):n}function Dn(e,t){return Ln(e,e=>!ge(t,e.type))??Ln(e,()=>!0)}function Ln(e,t){for(const n of e){if(!g(n))continue;if(i(n)){if(t(n))return n;continue}const e=Ln(n.children,t);if(e)return e}return null}function Hn(e,t){const n=Q(e,t)??[];return ne(t,n)}function zn(e,t,n){return{children:Fn(e.children,t,n)}}function Fn(e,t,n){let s=!1;const r=e.map(e=>{if(!g(e))return e;if(e.id===t)return s=!0,n(e);const r=Fn(e.children,t,n);return r===e.children?e:(s=!0,{...e,children:r})});return s?r:e}function jn(e,t,n){if(0===t.length)return e;const s=t[0];return s?{children:e.children.map(e=>g(e)&&e.id===s?1===t.length?n(e):$n(e,t,1,n):e)}:e}function $n(e,t,n,s){const r=t[n];if(!r)return e;const i=e.children.map(e=>g(e)&&e.id===r?n===t.length-1?s(e):$n(e,t,n+1,s):e);return{...e,children:i}}function _n(e,t,n){if(t(e))return n(e);let s=!1;const r=e.map(e=>{if(!g(e))return e;const r=_n(e.children,t,n);return r?(s=!0,{...e,children:r}):e});return s?r:null}function Kn(e,t,n){const s=[];let r=0,i=!1;for(const o of e){if(q(o)){i||t!==r||(s.push(...n()),i=!0),s.push(o),r+=1;continue}const e=r+o.text.length;if(!i&&t>=r&&t<=e){const e=t-r,a=o.text.slice(0,e),l=o.text.slice(e);a&&s.push(I(a,o.marks)),s.push(...n()),l&&s.push(I(l,o.marks)),i=!0}else s.push(o);r=e}return i||s.push(...n()),s}function Vn(e,t,n){const s=[];let r=0;for(const i of e){if(q(i)){const e=r+1;e>t&&r<n&&s.push(i),r=e;continue}const e=r+i.text.length;if(e<=t||r>=n);else{const e=Math.max(0,t-r),o=Math.min(i.text.length,n-r),a=i.text.slice(e,o);a.length>0&&s.push(I(a,i.marks))}r=e}return 0===s.length&&s.push(I("")),s}function Wn(e,t,n,s,r){const i=[];let o=0;for(const a of e){if(q(a)){i.push(a),o+=1;continue}const e=o+a.text.length;if(e<=t||o>=n)i.push(a);else if(o>=t&&e<=n){const e=r?j(a.marks,s):c(a.marks,s.type);i.push(I(a.text,e))}else{const e=Math.max(0,t-o),l=Math.min(a.text.length,n-o),d=a.text.slice(0,e),h=a.text.slice(e,l),u=a.text.slice(l);if(d&&i.push(I(d,a.marks)),h){const e=r?j(a.marks,s):c(a.marks,s.type);i.push(I(h,e))}u&&i.push(I(u,a.marks))}o=e}return i}function qn(e,t){if(e.every(e=>b(e)||q(e)))return t;const n=e.filter(e=>!b(e)&&!q(e));return[...t,...n]}function Un(e){return e.reduce((e,t)=>e+("inline"===t.kind?1:t.text.length),0)}var Gn=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Jn(e){return e.replace(Gn,"").length>0}function Qn(e){return"inline"===e.kind||Jn(e.text)}function Xn(e){return es(e.fromParentPath,e.toParentPath)&&e.toIndex>e.fromIndex?e.toIndex-1:e.toIndex}function Yn(e){return es(e.fromParentPath,e.toParentPath)&&Xn(e)===e.fromIndex}function Zn(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 s=0===t.toParentPath.length?e.children.length:U(e,t.toParentPath)?.children.length??null;if(null===s||!Number.isInteger(t.toIndex)||t.toIndex<0||t.toIndex>s)return null;const r=es(t.fromParentPath,t.toParentPath),i=Xn(t);return i<0||i>s-(r?1:0)?null:{movedNode:n,destinationIndex:i}}function es(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function ts(e){return e.segments?Un(e.segments):e.text.length}function ns(e,t,n,s=!0){return zn(e,t,e=>{const t=n(f(e));return{...e,children:qn(e.children,s?v(t):t)}})}function ss(e,t){if(0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,0,t.node),{children:n}}return jn(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,0,t.node),{...e,children:n}})}function rs(e,t){if(0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,1),{children:n}}return jn(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,1),{...e,children:n}})}function is(e){return e.path?{path:e.path}:{}}function os(e){for(const t of e.steps)if("setStoredMarks"===t.type)return t.previousMarks;return e.storedMarksAfter}function as(e,t,n){return n?e!==t?{}:{path:n}:{}}function ls(e,t,n){if(0===e.length)return!0;for(const s of e){const e=t.mapResult({blockId:s,offset:0},-1);if(e.deleted)return!1;if(e.pos.blockId!==s)return!1}return void 0!==U(n,e)}function cs(e,t){return t.blockId===e.blockId&&t.from===e.from&&t.to===e.to}function ds(e,t,n){const s=zt(e,t,t+1,n);return s?s.to-s.from!==1?null:s:null}var hs=/* @__PURE__ */new WeakSet;function us(e){return le(ce(e))}function ps(e){if(!e)return null;const t=M(e);return k(t),t}function ms(e){switch(e.type){case"insertText":return Object.freeze({...e,marks:ps(e.marks)??Object.freeze([]),...e.segments?{segments:vs(e.segments)}:{},...e.path?{path:Is(e.path)}:{}});case"deleteText":return Object.freeze({...e,deletedMarks:ps(e.deletedMarks)??Object.freeze([]),deletedSegments:vs(e.deletedSegments),...e.path?{path:Is(e.path)}:{}});case"splitBlock":return Object.freeze({...e,...e.newBlockAttrs?{newBlockAttrs:ys(e.newBlockAttrs)}:{},...e.path?{path:Is(e.path)}:{}});case"mergeBlocks":return Object.freeze({...e,...e.sourceAttrs?{sourceAttrs:ys(e.sourceAttrs)}:{},...e.path?{path:Is(e.path)}:{}});case"addMark":case"removeMark":return Object.freeze({...e,mark:gs(e.mark),...e.path?{path:Is(e.path)}:{}});case"setStoredMarks":return Object.freeze({...e,marks:ps(e.marks),previousMarks:ps(e.previousMarks)});case"setBlockType":return Object.freeze({...e,...e.attrs?{attrs:ys(e.attrs)}:{},...e.previousAttrs?{previousAttrs:ys(e.previousAttrs)}:{},...e.path?{path:Is(e.path)}:{}});case"insertNode":return Object.freeze({...e,parentPath:Is(e.parentPath),node:ws(e.node)});case"removeNode":return Object.freeze({...e,parentPath:Is(e.parentPath),removedNode:ws(e.removedNode)});case"moveNode":return Object.freeze({...e,fromParentPath:Is(e.fromParentPath),toParentPath:Is(e.toParentPath),movedNode:ws(e.movedNode)});case"setNodeAttr":return Object.freeze({...e,path:Is(e.path),...e.attrs?{attrs:ys(e.attrs)}:{},...e.previousAttrs?{previousAttrs:ys(e.previousAttrs)}:{}});case"insertInlineNode":return Object.freeze({...e,node:bs(e.node),...e.path?{path:Is(e.path)}:{}});case"removeInlineNode":return Object.freeze({...e,removedNode:bs(e.removedNode),...e.path?{path:Is(e.path)}:{}});case"setInlineNodeAttr":return Object.freeze({...e,attrs:ks(e.attrs),previousAttrs:ks(e.previousAttrs),...e.path?{path:Is(e.path)}:{}})}}function fs(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&&hs.add(n),n}function gs(e){const t=$(e);return K(t),t}function ys(e){const t=S(e);return W(t),t}function ks(e){return Object.freeze({...e})}function ws(e){const t=D(e);return x(t),t}function bs(e){const t=O(e);return o(t),t}function vs(e){const t=F(e);return V(t),t}function Is(e){return Object.freeze([...e])}var Ss={insertText:{apply:function(e,t){return ns(e,t.blockId,e=>{return t.segments?(n=e,s=t.offset,r=t.segments,Kn(n,s,()=>r.map(C))):function(e,t,n,s){return Kn(e,t,()=>[I(n,s)])}(e,t.offset,t.text,t.marks);var n,s,r})},invert:function(e){return{type:"deleteText",blockId:e.blockId,from:e.offset,to:e.offset+ts(e),deletedText:e.text,deletedMarks:e.marks,deletedSegments:e.segments??[H(e.text,[...e.marks])],...is(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.offset,to:t.offset,newLen:ts(t)}},map:function(e,t,n){const s=$t(e.blockId,e.offset,t,-1);return s?s.blockId===e.blockId&&s.from===e.offset?e:{type:"insertText",blockId:s.blockId,offset:s.from,text:e.text,marks:e.marks,...e.segments?{segments:e.segments}:{},...as(e.blockId,s.blockId,e.path)}:null}},deleteText:{apply:function(e,t){return ns(e,t.blockId,e=>function(e,t,n){const s=[];let r=0;for(const i of e){if(q(i)){const e=r+1;(e<=t||r>=n)&&s.push(i),r=e;continue}const e=r+i.text.length;if(e<=t||r>=n)s.push(i);else{const e=Math.max(0,t-r),o=Math.min(i.text.length,n-r),a=i.text.slice(0,e)+i.text.slice(o);a.length>0&&s.push(I(a,i.marks))}r=e}return s}(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,...is(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 s=zt(e.blockId,e.from,e.to,t);if(!s)return null;if(cs({blockId:e.blockId,from:e.from,to:e.to},s))return e;const i=G(n,s.blockId);if(!i)return null;const o=B(i).slice(s.from,s.to),a=r(i,s.from),l=m(i,s.from,s.to);return{type:"deleteText",blockId:s.blockId,from:s.from,to:s.to,deletedText:o,deletedMarks:a,deletedSegments:l,...as(e.blockId,s.blockId,e.path)}}},splitBlock:{apply:function(e,t){const n=_n(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 s=e[n],r=f(s),i=A(s),o=Vn(r,0,t.offset),a=Vn(r,t.offset,i),l={...s,children:v(o)},c=void 0!==t.newBlockType,d=t.newBlockType??s.type,h=c?t.newBlockAttrs:s.attrs,u=L(d,v(a),t.newBlockId,h,t.newBlockHTMLId),p=[...e];return p.splice(n,1,l,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}:{},...is(e)}},getMap:function(e,t){return{type:"split",blockId:t.blockId,offset:t.offset,newBlockId:t.newBlockId}},map:function(e,t,n){const s=$t(e.blockId,e.offset,t,-1);return s?s.blockId===e.blockId&&s.from===e.offset?e:{type:"splitBlock",blockId:s.blockId,offset:s.from,newBlockId:e.newBlockId,...void 0!==e.newBlockType?{newBlockType:e.newBlockType}:{},...e.newBlockAttrs?{newBlockAttrs:e.newBlockAttrs}:{},...void 0!==e.newBlockHTMLId?{newBlockHTMLId:e.newBlockHTMLId}:{},...as(e.blockId,s.blockId,e.path)}:null}},mergeBlocks:{apply:function(e,t){const n=_n(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),s=e.findIndex(e=>g(e)&&e.id===t.sourceBlockId);if(-1===n||-1===s)return e;const r=e[n],i=e[s],o=f(r),a=f(i),l=v([...o,...a]),c={...r,children:l};return e.filter(e=>!g(e)||e.id!==t.sourceBlockId).map(e=>g(e)&&e.id===t.targetBlockId?c: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}:{},...is(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 s=t.mapResult({blockId:e.targetBlockId,offset:0},-1),r=t.mapResult({blockId:e.sourceBlockId,offset:0},-1);if(s.deleted||r.deleted)return null;const i=s.pos.blockId,o=r.pos.blockId;if(i===o)return null;const a=G(n,i);if(!a)return null;const l=A(a);return i===e.targetBlockId&&o===e.sourceBlockId&&l===e.targetLengthBefore?e:{type:"mergeBlocks",targetBlockId:i,sourceBlockId:o,targetLengthBefore:l,...void 0!==e.sourceType?{sourceType:e.sourceType}:{},...e.sourceAttrs?{sourceAttrs:e.sourceAttrs}:{},...void 0!==e.sourceHTMLId?{sourceHTMLId:e.sourceHTMLId}:{},...as(e.targetBlockId,i,e.path)}}},addMark:{apply:function(e,t){return ns(e,t.blockId,e=>Wn(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,...is(e)}},getMap:function(e,t){return Wt},map:function(e,t,n){const s=zt(e.blockId,e.from,e.to,t);return s?cs({blockId:e.blockId,from:e.from,to:e.to},s)?e:{type:"addMark",blockId:s.blockId,from:s.from,to:s.to,mark:e.mark,...as(e.blockId,s.blockId,e.path)}:null}},removeMark:{apply:function(e,t){return ns(e,t.blockId,e=>Wn(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,...is(e)}},getMap:function(e,t){return Wt},map:function(e,t,n){const s=zt(e.blockId,e.from,e.to,t);return s?cs({blockId:e.blockId,from:e.from,to:e.to},s)?e:{type:"removeMark",blockId:s.blockId,from:s.from,to:s.to,mark:e.mark,...as(e.blockId,s.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 Wt},map:function(e,t,n){return e}},setBlockType:{apply:function(e,t){return zn(e,t.blockId,e=>{const{attrs:n,...s}=e;return{...s,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,...is(e)}},getMap:function(e,t){return Wt},map:function(e,t,n){if(t.isEmpty)return e;const s=t.mapResult({blockId:e.blockId,offset:0},-1);if(s.deleted)return null;const r=s.pos.blockId,i=G(n,r);return i?r===e.blockId&&i.type===e.previousNodeType&&z(i.attrs,e.previousAttrs)?e:{type:"setBlockType",blockId:r,nodeType:e.nodeType,...e.attrs?{attrs:e.attrs}:{},previousNodeType:i.type,...i.attrs?{previousAttrs:i.attrs}:{},...as(e.blockId,r,e.path)}:null}},insertNode:{apply:ss,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:jt(t.node)}},map:function(e,t,n){if(!ls(e.parentPath,t,n))return null;const s=Kt(e.parentPath,e.index,t);return s===e.index?e:{type:"insertNode",parentPath:e.parentPath,index:s,node:e.node}}},removeNode:{apply:rs,invert:function(e){return{type:"insertNode",parentPath:e.parentPath,index:e.index,node:e.removedNode}},getMap:function(e,t){return{type:"blockRemoval",removedBlockIds:jt(t.removedNode),parentPath:t.parentPath,index:t.index}},map:function(e,t,n){if(!ls(e.parentPath,t,n))return null;const s=t.mapResult({blockId:e.removedNode.id,offset:0},-1);if(s.deleted)return null;if(s.pos.blockId!==e.removedNode.id)return null;const r=Ht(e.parentPath,e.index,t);if(null===r)return null;const i=X(n,e.parentPath,r);return i?i.id!==e.removedNode.id?null:r===e.index&&i===e.removedNode?e:{type:"removeNode",parentPath:e.parentPath,index:r,removedNode:i}:null}},moveNode:{apply:function(e,t){const n=Zn(e,t);return!n||Yn(t)?e:ss(rs(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=Xn(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=Zn(e,t);return!n||Yn(t)?Wt:{type:"moveNode",movedNodeId:t.movedNode.id,fromParentPath:t.fromParentPath,fromIndex:t.fromIndex,toParentPath:t.toParentPath,destinationIndex:n.destinationIndex}},map:function(e,t,n){if(!ls(e.fromParentPath,t,n))return null;if(!ls(e.toParentPath,t,n))return null;const s=t.mapResult({blockId:e.movedNode.id,offset:0},-1);if(s.deleted||s.pos.blockId!==e.movedNode.id)return null;const r=Ht(e.fromParentPath,e.fromIndex,t);if(null===r)return null;const i=Kt(e.toParentPath,e.toIndex,t),o=X(n,e.fromParentPath,r);if(!o||o.id!==e.movedNode.id)return null;const a={type:"moveNode",fromParentPath:e.fromParentPath,fromIndex:r,toParentPath:e.toParentPath,toIndex:i,movedNode:o};return Zn(n,a)?r===e.fromIndex&&i===e.toIndex&&o===e.movedNode?e:a:null}},setNodeAttr:{apply:function(e,t){const n=t.path[t.path.length-1];return n?zn(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 Wt},map:function(e,t,n){if(t.isEmpty)return e;if(!ls(e.path,t,n))return null;const s=U(n,e.path);return s?{type:"setNodeAttr",path:e.path,attrs:e.attrs,...s.attrs?{previousAttrs:s.attrs}:{}}:null}},insertInlineNode:{apply:function(e,t){return ns(e,t.blockId,e=>function(e,t,n){const s=[];let r=0,i=!1;for(const o of e){if(q(o)){i||t!==r||(s.push(n),i=!0),s.push(o),r+=1;continue}const e=r+o.text.length;if(!i&&t>=r&&t<=e){const e=t-r,a=o.text.slice(0,e),l=o.text.slice(e);a&&s.push(I(a,o.marks)),s.push(n),l&&s.push(I(l,o.marks)),i=!0}else s.push(o);r=e}return i||s.push(n),s}(e,t.offset,t.node))},invert:function(e){return{type:"removeInlineNode",blockId:e.blockId,offset:e.offset,removedNode:e.node,...is(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 s=$t(e.blockId,e.offset,t,-1);return s?s.blockId===e.blockId&&s.from===e.offset?e:{type:"insertInlineNode",blockId:s.blockId,offset:s.from,node:e.node,...as(e.blockId,s.blockId,e.path)}:null}},removeInlineNode:{apply:function(e,t){return ns(e,t.blockId,e=>function(e,t){const n=[];let s=0;for(const r of e)q(r)?(s!==t&&n.push(r),s+=1):(n.push(r),s+=r.text.length);return n}(e,t.offset))},invert:function(e){return{type:"insertInlineNode",blockId:e.blockId,offset:e.offset,node:e.removedNode,...is(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 s=ds(e.blockId,e.offset,t);if(!s)return null;const r=G(n,s.blockId);if(!r)return null;const i=p(r,s.from);return i&&"inline"===i.kind&&q(i.node)?(o=e.removedNode)===(a=i.node)||o.inlineType===a.inlineType&&z(o.attrs,a.attrs)?s.blockId===e.blockId&&s.from===e.offset?e:{type:"removeInlineNode",blockId:s.blockId,offset:s.from,removedNode:i.node,...as(e.blockId,s.blockId,e.path)}:null:null;var o,a}},setInlineNodeAttr:{apply:function(e,t){return ns(e,t.blockId,e=>function(e,t,n){const s=[];let r=0;for(const i of e)q(i)?(r===t?s.push({...i,attrs:n}):s.push(i),r+=1):(s.push(i),r+=i.text.length);return s}(e,t.offset,t.attrs),!1)},invert:function(e){return{type:"setInlineNodeAttr",blockId:e.blockId,offset:e.offset,attrs:e.previousAttrs,previousAttrs:e.attrs,...is(e)}},getMap:function(e,t){return Wt},map:function(e,t,n){const s=ds(e.blockId,e.offset,t);if(!s)return null;if(s.blockId===e.blockId&&s.from===e.offset)return e;const r=G(n,s.blockId);if(!r)return null;const i=p(r,s.from);return i&&"inline"===i.kind&&q(i.node)?{type:"setInlineNodeAttr",blockId:s.blockId,offset:s.from,attrs:e.attrs,previousAttrs:i.node.attrs,...as(e.blockId,s.blockId,e.path)}:null}}};function xs(e){return Ss[e.type]}function Rs(e,t){return xs(t).apply(e,t)}function Ms(e){return xs(e).invert(e)}function Cs(e,t){return xs(t).getMap(e,t)}function Ps(e,t,n){return t.isEmpty?e:xs(e).map(e,t,n)}function Es(e){const t=e.steps.map(Ms).reverse().map(ms);return fs({steps:t,selectionBefore:us(e.selectionAfter),selectionAfter:us(e.selectionBefore),storedMarksAfter:ps(os(e)),forwardStepMaps:t.map(()=>Wt),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",s){const r=us(e);this.selection=r,this.selectionBefore=r,this.storedMarks=ps(t),this.origin=n,this.workingDoc=s??null}insertText(e,t,n,s,r){const i={type:"insertText",blockId:e,offset:t,text:n,marks:s,...r?{segments:r}:{}};return this.appendStep(i),this}deleteText(e,t,n,s,r,i){let o;if(i)o=i;else if(this.workingDoc){const i=G(this.workingDoc,e);o=i?m(i,t,n):[H(s,[...r])]}else o=[H(s,[...r])];const a={type:"deleteText",blockId:e,from:t,to:n,deletedText:s,deletedMarks:r,deletedSegments:o};return this.appendStep(a),this}deleteTextAt(e,t,n){const s=this.requireDoc("deleteTextAt"),i=this.requireBlock(s,e),o=B(i).slice(t,n),a=r(i,t),l=m(i,t,n);return this.deleteText(e,t,n,o,a,l)}splitBlock(e,t,n){const s={type:"splitBlock",blockId:e,offset:t,newBlockId:n};return this.appendStep(s),this}mergeBlocks(e,t,n,s,r,i){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!==s?{sourceType:s}:{},...r?{sourceAttrs:r}:{},...void 0!==i?{sourceHTMLId:i}:{}};return this.appendStep(o),this}mergeBlocksAt(e,t){const n=this.requireDoc("mergeBlocksAt"),s=this.requireBlock(n,e),r=this.requireBlock(n,t),i=A(s);return this.mergeBlocks(e,t,i,r.type,r.attrs,r.htmlId)}addMark(e,t,n,s){const r=this.tryGetBlock(e);if(!r){const r={type:"addMark",blockId:e,from:t,to:n,mark:s};return this.appendStep(r),this}const i=function(e,t,n,s){const r=[];if(t>=n)return r;let i=null,o=0;const a=()=>{i&&(r.push(i),i=null)};for(const l of e){const e=o+(q(l)?1:l.text.length);if(e<=t||o>=n){o=e;continue}const r=Math.max(o,t),c=Math.min(e,n);q(l)?i&&(i.to=c):l.marks.some(e=>e.type===s)?a():i?i.to=c:i={from:r,to:c},o=e}return a(),r}(f(r),t,n,s.type);for(const o of i){const t={type:"addMark",blockId:e,from:o.from,to:o.to,mark:s};this.appendStep(t)}return this}removeMark(e,t,n,s){const r=this.tryGetBlock(e);if(!r){const r={type:"removeMark",blockId:e,from:t,to:n,mark:s};return this.appendStep(r),this}const i=function(e,t,n,s){const r=[];if(t>=n)return r;let i=null,o=0;const a=()=>{i&&(r.push(i),i=null)};for(const l of e){const e=o+(q(l)?1:l.text.length);if(e<=t||o>=n){o=e;continue}const r=Math.max(o,t),c=Math.min(e,n);if(q(l))i&&(i.to=c);else{const e=l.marks.find(e=>e.type===s);e?i&&w(i.mark,e)?i.to=c:(a(),i={from:r,to:c,mark:e}):a()}o=e}return a(),r}(f(r),t,n,s.type);for(const o of i){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 s=this.requireDoc("setBlockType"),r=this.requireBlock(s,e),i={type:"setBlockType",blockId:e,nodeType:t,...n?{attrs:n}:{},previousNodeType:r.type,...r.attrs?{previousAttrs:r.attrs}:{}};return this.appendStep(i),this}insertNode(e,t,n){const s={type:"insertNode",parentPath:e,index:t,node:n};return this.appendStep(s),this}removeNode(e,t){const n=this.requireDoc("removeNode"),s=X(n,e,t);if(!s)throw new Error(`Node at index ${t} not found under parent path [${e.join(", ")}].`);const r={type:"removeNode",parentPath:e,index:t,removedNode:s};return this.appendStep(r),this}moveNode(e,t,n,s){const r=this.requireDoc("moveNode"),i=X(r,e,t);if(!i)throw new Error(`Node at index ${t} not found under source path [${e.join(", ")}].`);if(n.includes(i.id))throw new Error(`Cannot move node "${i.id}" into its own subtree.`);const o=0===n.length?r.children.length:U(r,n)?.children.length??-1;if(!Number.isInteger(s)||s<0||s>o)throw new Error(`Invalid destination index ${s} under path [${n.join(", ")}].`);const a={type:"moveNode",fromParentPath:e,fromIndex:t,toParentPath:n,toIndex:s,movedNode:i};return Yn(a)||this.appendStep(a),this}setNodeAttr(e,t){const n=this.requireDoc("setNodeAttr"),s=U(n,e);if(!s)throw new Error(`Node not found at path [${e.join(", ")}].`);const r={type:"setNodeAttr",path:e,attrs:t,...s.attrs?{previousAttrs:s.attrs}:{}};return this.appendStep(r),this}insertInlineNode(e,t,n){const s={type:"insertInlineNode",blockId:e,offset:t,node:n};return this.appendStep(s),this}removeInlineNode(e,t){const n=this.requireDoc("removeInlineNode"),s=this.requireBlock(n,e),r=p(s,t);if(!r||"inline"!==r.kind)throw new Error(`No InlineNode at offset ${t} in block "${e}".`);const i={type:"removeInlineNode",blockId:e,offset:t,removedNode:r.node};return this.appendStep(i),this}setInlineNodeAttr(e,t,n){const s=this.requireDoc("setInlineNodeAttr"),r=this.requireBlock(s,e),i=f(r);let o=0;for(const a of i){if(q(a)&&o===t){const s={type:"setInlineNodeAttr",blockId:e,offset:t,attrs:n,previousAttrs:a.attrs};return this.appendStep(s),this}o+=q(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=us(e),this}setNodeSelection(e,t){return this.selection=us(ne(e,t)),this}setStoredMarks(e,t){return this.appendStep({type:"setStoredMarks",marks:e,previousMarks:t}),this.storedMarks=ps(e),this}build(){return fs({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=ms(e);this.steps.push(t),this.advanceDoc(t)}advanceDoc(e){const t=this.workingDoc??Bs;this.stepMaps.push(Ft(Cs(t,e))),this.workingDoc&&(this.workingDoc=Rs(this.workingDoc,e))}},Bs={children:[]},As=class e{doc;selection;storedMarks;schema;_blockMap=null;_blockOrder=null;constructor(e,t,n,s){if(this.doc=y(e),this.selection=le(t),n){const e=M(n);k(e),this.storedMarks=e}else this.storedMarks=null;this.schema=s}static create(t){const n=t?.schema??we(),s=t?.doc?R(t.doc):N(),r=t?.selection?An(s,n,ce(t.selection)):On(s,n)??re(me(""),0);return new e(s,r,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=Rs(n,e);const s=An(n,this.schema,ce(t.selectionAfter));return new e(n,s,t.storedMarksAfter,this.schema)}getBlock(e){return this._blockMap??=function(e){const t=/* @__PURE__ */new Map;return function e(n){for(const s of n)g(s)&&(t.set(s.id,s),e(s.children))}(e.children),t}(this.doc),this._blockMap.get(e)}getBlockOrder(){return this._blockOrder??=function(e){const t=[];return function e(n){for(const s of n)g(s)&&(i(s)?t.push(s.id):e(s.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=An(this.doc,this.schema,ce(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:ce(this.selection)}}static fromJSON(t,n){return e.create({doc:t.doc,selection:t.selection,schema:n})}};function Os(e,t,n){const s=function(e){const t=Ls(e.children,Ds);return t===e.children?e:{children:t}}(function(e){const t=Ls(e.children,Ns);return t===e.children?e:{children:t}}(e)),r=R(s),i=t?Tn(r,t):r,o=t?fe(t):void 0;n(As.create({doc:i,schema:o}))}function Ns(e){const n=Ls(e.children,e=>b(e)||q(e)?e:Ns(e)),s=e.htmlId,r=t(s),i=Object.prototype.hasOwnProperty.call(e,"htmlId"),o=s===r&&(void 0!==r||!i);if(n===e.children&&o)return e;const{htmlId:a,...l}=e;return{...l,...r?{htmlId:r}:{},children:n}}function Ds(e){if(!e.children)return e;const t=Ls(e.children,e=>b(e)||q(e)?e.marks?e:{...e,marks:[]}:Ds(e));return t===e.children?e:{...e,children:t}}function Ls(e,t){let n=!1;const s=e.map(e=>{const s=t(e);return s!==e&&(n=!0),s});return n?s:e}function Hs(e){return e.doc.children.map(zs).join("\n")}function zs(e){return i(e)?B(e):a(e).map(zs).join("\n")}function Fs(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 js={shorthand:!0,paste:"auto"},$s={shorthand:!1,paste:"never"};function _s(e){return void 0===e||!0===e?js:!1===e?$s:{shorthand:e.shorthand??!0,paste:e.paste??"auto"}}var Ks=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}):at(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 _s(this.config.markdown).shorthand}get pasteMarkdown(){return _s(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")))}},Vs={error(e,t){void 0===t?console.error(e):console.error(e,t)},warn(e,t){void 0===t?console.warn(e):console.warn(e,t)},info(e,t){void 0===t?console.info(e):console.info(e,t)},debug(e,t){void 0===t?console.debug(e):console.debug(e,t)}},Ws={error(){},warn(){},info(){},debug(){}};function qs(e,t){const n=`[${t}]`;return{error(t,s){Us(()=>e.error(`${n} ${t}`,s))},warn(t,s){Us(()=>e.warn(`${n} ${t}`,s))},info(t,s){Us(()=>e.info(`${n} ${t}`,s))},debug(t,s){Us(()=>e.debug(`${n} ${t}`,s))}}}function Us(e){try{const t=e();null===t||"object"!=typeof t&&"function"!=typeof t||Promise.resolve(t).then(void 0,()=>{})}catch{}}var Gs=class{listeners=/* @__PURE__ */new Map;log;constructor(e=Vs){this.log=e}setLogger(e=Vs){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 s=this.log;for(const i of n)try{const n=i(t);this.observeListenerResult(s,e,n)}catch(r){this.reportListenerError(s,e,r)}}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 s=e.error(`[EditorEventEmitter] Listener error on "${String(t)}"`,n);null===s||"object"!=typeof s&&"function"!=typeof s||Promise.resolve(s).then(void 0,()=>{})}catch{}}clear(){this.listeners.clear()}};function Js(e,t,n){if(i(e))return t.selectedLeafIds.has(e.id)?function(e,t){const n=A(e),s=e.id===t.firstBlockId?t.firstOffset:0,r=e.id===t.lastBlockId?t.lastOffset:n;if(0===s&&r===n)return e;const i=m(e,s,r),o=h(i),{htmlId:a,...l}=e;return{...l,children:o}}(e,t):null;const s=a(e),r=[];let o=s.length!==e.children.length;for(const i of s){const e=Js(i,t,n);e?(r.push(e),e!==i&&(o=!0)):o=!0}if(0===r.length)return null;if(!o)return e;const{htmlId:l,...c}=e,d={...c,children:r};return n?.getNodeSpec(e.type)?.transformSelectionSlice?.(e,d)??d}var Qs=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(!Yt(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 s=e.clipboardData;s&&(ee(n)?this.writeNodeSelectionToClipboard(s,t):this.writeTextSelectionToClipboard(s,t))}onCut(e){if(!Yt(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 s=e.clipboardData;if(s)if(ee(n)){this.writeNodeSelectionToClipboard(s,t);const e=ze(t,n);e&&this.dispatch(e)}else{this.writeTextSelectionToClipboard(s,t);const e=Ke(t);e&&this.dispatch(e)}}writeNodeSelectionToClipboard(e,t){const n=t.selection;if(!ee(n))return;const s=t.getBlock(n.nodeId);if(!s)return;if(!i(s))return this.schemaRegistry&&e.setData("text/html",vt({children:[s]},this.schemaRegistry)),void e.setData("text/plain",this.plainTextFromBlockTree(s));const r={type:s.type,...s.htmlId?{htmlId:s.htmlId}:{},...s.attrs?{attrs:{...s.attrs}}:{}};e.setData("application/x-notectl-block",JSON.stringify(r));const o=this.schemaRegistry?.getNodeSpec(s.type);o?.toHTML&&e.setData("text/html",xt(o.toHTML(s,""),s.htmlId));const a=s.attrs,l="string"==typeof a?.alt?a.alt:"";e.setData("text/plain",l)}plainTextFromBlockTree(e){return i(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 s=t.getBlockOrder(),r=oe(n,s),i=s.indexOf(r.from.blockId),o=s.indexOf(r.to.blockId),a=[],l=[],c=[];for(let h=i;h<=o;h++){const e=s[h];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const d=A(n),u=h===i?r.from.offset:0,p=h===o?r.to.offset:d,m=this.extractSegmentsForRange(n,u,p),f=this.plainTextFromSegments(m);a.push(f),c.push({block:n,start:u,end:p}),l.push({type:n.type,text:f,...0===u&&p===d&&n.htmlId?{htmlId:n.htmlId}:{},...n.attrs?{attrs:{...n.attrs}}:{},...m.length>0?{segments:m}:{}})}const d=a.join("\n");if(e.setData("text/plain",d),this.schemaRegistry){const n=wt(this.schemaRegistry),a=i!==o,d=l.some(e=>void 0!==e.htmlId||void 0!==e.type&&"paragraph"!==e.type);if(a||this.containsInlineSegments(l)||d){const t=this.serializeBlocksToClipboardHTML(c,n,l);e.setData("text/html",t)}else{const o=s[i],a=o?t.getBlock(o):void 0;if(a){const t=this.serializeBlockRangeToHTML(a,r.from.offset,r.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(),s=oe(t,n),r=Q(e.doc,s.from.blockId),o=Q(e.doc,s.to.blockId);if(!r||!o)return!1;if(r[0]===o[0]){const t=e.doc.children.find(e=>e.id===r[0]);return!(!t||i(t))}const a=e.doc.children.findIndex(e=>e.id===r[0]),l=e.doc.children.findIndex(e=>e.id===o[0]);for(let c=a;c<=l;c++){const t=e.doc.children[c];if(t){if(!i(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 s=t.getBlockOrder(),r=oe(n,s),i=s.indexOf(r.from.blockId),o=s.indexOf(r.to.blockId),a=[];for(let l=i;l<=o;l++){const e=s[l];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const c=l===i?r.from.offset:0,d=l===o?r.to.offset:A(n);a.push(this.extractPlainTextForRange(n,c,d))}if(e.setData("text/plain",a.join("\n")),this.schemaRegistry){const s=function(e,t,n){const s=e.getBlockOrder(),r=oe(t,s),i=s.indexOf(r.from.blockId),o=s.indexOf(r.to.blockId);if(-1===i||-1===o||i>o)return{children:[]};const a=e.getNodePath(r.from.blockId),l=e.getNodePath(r.to.blockId),c=a?.[0],d=l?.[0];if(!c||!d)return{children:[]};const h=e.doc.children.findIndex(e=>e.id===c),u=e.doc.children.findIndex(e=>e.id===d);if(-1===h||-1===u||h>u)return{children:[]};const p={firstBlockId:r.from.blockId,firstOffset:r.from.offset,lastBlockId:r.to.blockId,lastOffset:r.to.offset,selectedLeafIds:new Set(s.slice(i,o+1))},m=[];for(let f=h;f<=u;f++){const t=e.doc.children[f];if(!t)continue;const s=Js(t,p,n);s&&m.push(s)}return{children:m}}(t,n,this.schemaRegistry);if(s.children.length>0){const t=vt(s,this.schemaRegistry);e.setData("text/html",t)}}}serializeBlockRangeToHTML(e,t,n,s){const r=[];return _(e,t,n,{onText:(e,t)=>{this.schemaRegistry&&r.push(St(e,t,this.schemaRegistry,s))},onInline:e=>{const t=this.schemaRegistry?.getInlineNodeSpec(e.inlineType);t?.toHTMLString&&r.push(t.toHTMLString(e))}}),r.join("")}extractSegmentsForRange(e,t,n){const s=[];return _(e,t,n,{onText:(e,t)=>{s.push({text:e,marks:t.map(e=>({type:e.type,...e.attrs?{attrs:{...e.attrs}}:{}}))})},onInline:e=>{s.push({kind:"inline",inlineType:e.inlineType,...Object.keys(e.attrs).length>0?{attrs:{...e.attrs}}:{}})}}),s}containsInlineSegments(e){return e.some(e=>e.segments?.some(e=>"inline"===e.kind))}serializeBlocksToClipboardHTML(e,t,n){const s=[];let r,i=[];const o=()=>{i.length>0&&r&&(s.push(`<${r}>${i.join("")}</${r}>`),i=[],r=void 0)};for(const l of e){const{block:e,start:n,end:a}=l,c=0===n&&a===A(e),{htmlId:d,...h}=e,u={...h,...c&&e.htmlId?{htmlId:e.htmlId}:{}},p=this.serializeBlockRangeToHTML(e,n,a,t),m=this.schemaRegistry?.getNodeSpec(u.type);if(m?.wrapper){const e=m.wrapper(u).tag;r!==e&&(o(),r=e),m.toHTML?i.push(xt(m.toHTML(u,p),u.htmlId)):i.push(xt(`<li>${p}</li>`,u.htmlId))}else o(),m?.toHTML?s.push(xt(m.toHTML(u,p),u.htmlId)):s.push(xt(`<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 s.push(`<span data-notectl-rich="${a}" hidden></span>`),s.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 Ys(e){let t="";for(const n of f(e))t+=b(n)?n.text:"";return t}function Zs(e){const t=/* @__PURE__ */new Set;let n=0;for(const s of f(e))b(s)?n+=s.text.length:(t.add(n),n+=1);return t}var er=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(s=n.value)&&"function"!=typeof s||null===s||!("then"in s)||"function"!=typeof s.then?{ok:!0,value:n.value}:Promise.resolve(n.value).then(e=>({ok:!0,value:e}),t=>(this.reportFailure(e,t),{ok:!1}))}catch(r){return this.reportFailure(e,r),{ok:!1}}var s}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 tr(e,t,n){return e>=t&&e<=n?n-e:0}function nr(e,t,n,s){const r=$t(e,t,n,s);return r&&r.blockId===e?r.from:null}var sr={kind:"conflict"};function rr(e,t){const n=e.getBlock(t.blockId);if(!n||!i(n)||null===t.mapping)return sr;const s=Ys(t.baseline),r=function(e,t,n){const s=n.equals??((n,s)=>e.charAt(n)===t.charAt(s)),r=Math.min(e.length,t.length);let i=0;for(;i<r&&s(i,i);)i++;if(i===e.length&&i===t.length)return null;let o=e.length,a=t.length;for(;o>0&&a>0&&s(o-1,a-1);)o--,a--;if(o<i&&e.length<t.length)i-=tr(n.preferredFrom,o,i),a=i+(a-o),o=i;else if(a<i){const e=o-a;i=function(e,t,n,s){const r=e.preferredDeletionEnd;return void 0!==r&&r-s>=t&&r-s<=n?r-s:n-tr(e.preferredFrom,t,n)}(n,a,i,e),o=i+e,a=i}return{from:i,to:o,text:t.slice(i,a)}}(s,t.rendered.text,{preferredFrom:t.from,preferredDeletionEnd:t.from===t.to?t.from:void 0,equals:or(s,Zs(t.baseline),t.rendered)});if(r&&function(e,t){const n=t.inlineNodeOrigins;if(!n)return e.text.includes("");for(let s=e.from;s<e.from+e.text.length;s++)if(n.has(s))return!0;return!1}(r,t.rendered))return sr;const o=r?function(e,t,n,s,r){const i=e.from===e.to?$t(t,e.from,r,1):zt(t,e.from,e.to,r);if(!i||i.blockId!==t)return null;const o=n.slice(e.from,e.to);return s.slice(i.from,i.to)!==o?null:{from:i.from,to:i.to,text:e.text}}(r,t.blockId,s,Ys(n),t.mapping):null;if(r&&!o)return sr;const a=o?function(e,t,n){const s=n.text.replaceAll(" "," ");if(s.length>0){const r=e.withSelection(ie({blockId:t,offset:n.from},{blockId:t,offset:n.to}));return $e(r,s,"input")}return e.transaction("input").deleteTextAt(t,n.from,n.to).setSelection(re(t,n.from)).build()}(e,t.blockId,o):null,l=null===t.rendered.caretOffset?null:function(e,t,n,s){if(!s)return nr(t,e,n,-1);const{change:r,target:i}=s,o=r.from+r.text.length;if(e>=r.from&&e<=o)return i.from+(e-r.from);if(e<r.from)return nr(t,e,n,-1);const a=nr(t,e-r.text.length+(r.to-r.from),n,1);return null===a?null:a+r.text.length-(i.to-i.from)}(t.rendered.caretOffset,t.blockId,t.mapping,r&&o?{change:r,target:o}:null);return{kind:"commit",tr:ir(e,a,t.blockId,l)}}function ir(e,t,n,s){if(null===s)return t;const r=re(n,s);return t?{...t,selectionAfter:r}:se(e.selection,r)?null:e.transaction("input").setSelection(r).build()}function or(e,t,n){const s=n.inlineNodeOrigins;return(r,i)=>{if(s){if(t.has(r))return s.get(i)===r;if(s.has(i))return!1}const o=e.charAt(r),a=n.text.charAt(i);return o===a||" "===o&&" "===a}}var ar=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:s}=t;if(n.blockId!==s.blockId)return null;const r=e.getBlock(n.blockId),o=e.getNodePath(n.blockId)?.[0];return r&&i(r)&&void 0!==o?{blockId:n.blockId,rootId:o,from:Math.min(n.offset,s.offset),to:Math.max(n.offset,s.offset),baseline:r}:null}(e,t),this.anchor&&this.options.compositionDOM?.captureBlock(this.anchor.blockId))}observeStateChange(e,t,n){const s=this.anchor;return!(!s||t.getNodePath(s.blockId)?.[0]===s.rootId&&(!this.stepMaps||(0===n.steps.length&&e.doc!==t.doc?(function(e,t,n){const s=e.getBlock(n),r=t.getBlock(n);return!!s&&!!r&&Ys(s)===Ys(r)}(e,t,s.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(),s=e?this.options.compositionDOM?.readBlock(e.blockId)??null:null;if(e&&null!==s){const r=rr(n,{...e,rendered:s,mapping:this.stepMaps?Lt.from(this.stepMaps):null});return"commit"===r.kind?{tr:r.tr,restore:!1}:{tr:lr(n,t),restore:!0}}return{tr:lr(n,t),restore:!1}}restore(e){e&&this.options.compositionDOM?.restoreBlock(e.blockId)}};function lr(e,t){return t?$e(e,t,"input"):null}var cr=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??er.silent,this.resolveTargetRange=t.resolveTargetRange,this.composition=new ar({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(!Yt(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,s=n?function(e){return"function"==typeof e.getTargetRanges?e.getTargetRanges()[0]:void 0}(e):void 0,r=s&&this.resolveTargetRange?this.resolveTargetRange(s):null;"insertText"!==e.inputType&&"insertCompositionText"!==e.inputType&&"insertFromComposition"!==e.inputType&&this.syncSelection(),e.preventDefault();const i=this.getState();let o=null;switch(e.inputType){case"insertText":e.data&&(o=this.runTextInputInterceptors(e.data,i)??$e(i,e.data,"input"));break;case"insertReplacementText":{if(!n)break;if(this.compositionTracker.isComposing)break;if(s&&!r&&(!te(i.selection)||Z(i.selection)))break;const e=r?i.withSelection(r).withStoredMarks(null):i;o=this.runTextInputInterceptors(n,e)??$e(e,n,"input");break}case"insertFromComposition":e.data&&(this.composition.markCommitHandled(),o=this.runTextInputInterceptors(e.data,i)??$e(i,e.data,"input"));break;case"insertParagraph":case"insertLineBreak":o=dr(i,e.inputType);break;case"deleteContentBackward":o=Pn(i);break;case"deleteContentForward":o=En(i);break;case"deleteWordBackward":o=function(e){return Cn(e,{merge:Fe,range:(e,t)=>t>0?[Ye(e,t),t]:null})}(i);break;case"deleteWordForward":o=function(e){return Cn(e,{merge:Ve,range:(e,t)=>t<A(e)?[t,Ze(e,t)]:null})}(i);break;case"deleteSoftLineBackward":o=function(e){return Cn(e,{merge:Fe,range:(e,t)=>t>0?[0,t]:null})}(i);break;case"deleteSoftLineForward":o=function(e){return Cn(e,{merge:Ve,range:(e,t)=>{const n=A(e);return t<n?[t,n]:null}})}(i)}o&&(this.dispatch(o),"insertText"!==e.inputType&&"insertReplacementText"!==e.inputType||this.checkInputRules())}isCompositionActive(e){return this.compositionTracker.isComposing||e.isComposing}onCompositionStart(e){Yt(e,this.element)&&(this.pendingBreaks=[],this.composition.start())}onCompositionEnd(e){Yt(e,this.element)&&this.finishComposition(e.data)}onKeydown(e){this.compositionTracker.isComposing&&!function(e){return e.isComposing||229===e.keyCode||"Process"===e.key}(e)&&Yt(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=dr(this.getState(),n);e&&this.dispatch(e)}}runTextInputInterceptors(e,t){const n=this.getTextInputInterceptors();if(0===n.length)return null;for(const s of n){const n=this.callbackExecutor.execute({pluginId:s.pluginId,name:s.name,kind:"text-input-interceptor"},()=>s.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,s=t.getBlock(n.blockId);if(!s)return;const r=Ys(s).slice(0,n.offset);for(const i of e){const e=this.callbackExecutor.execute({pluginId:i.pluginId,name:i.name,kind:"input-rule"},()=>{const e=i.rule.pattern.exec(r);if(!e)return null;const n=e.index,s=n+e[0].length;return i.rule.handler(t,e,n,s)});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 dr(e,t){return"insertParagraph"===t?je(e):We(e)}var hr={Period:".",Comma:",",Slash:"/",Semicolon:";",Quote:"'",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Minus:"-",Equal:"=",Backquote:"`"},ur={1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")","`":"~","-":"_","=":"+","[":"{","]":"}","\\":"|",";":":","'":'"',",":"<",".":">","/":"?"},pr=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(hr))e.set(t,n);return e}();function mr(e){const t=[];return(e.metaKey||e.ctrlKey)&&t.push("Mod"),e.shiftKey&&t.push("Shift"),e.altKey&&t.push("Alt"),t}function fr(e){const t=mr(e);let n=e.key;return" "===n?n="Space":1===n.length&&(n=n.toUpperCase()),t.push(n),t.join("-")}function gr(e){return e.ctrlKey||e.metaKey?e.ctrlKey&&e.altKey&&!e.metaKey?null:pr.get(e.code)??null:null}var yr={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},kr=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??er.silent,this.handleKeydown=this.onKeydown.bind(this),e.addEventListener("keydown",this.handleKeydown)}onKeydown(e){if(!Yt(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=gr(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=qe(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,fr(e)))return!0;for(const n of function(e){const t=gr(e);if(null===t)return[];const n=mr(e),s=[[...n,t].join("-")];if(e.shiftKey){const e=ur[t];void 0!==e&&s.push([...n,e].join("-"))}return s}(e))if(this.runDescriptor(e,t,n))return!0;return!1}runDescriptor(e,t,n){for(const s of t)for(let t=s.length-1;t>=0;t--){const r=s[t],i=r?.keymap[n];if(!r||!i)continue;const o=this.callbackExecutor.execute({pluginId:r.pluginId,name:`${r.name} (${n})`,kind:"keymap"},i);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 s=e.key;if(!("ArrowLeft"!==s&&"ArrowUp"!==s&&"ArrowRight"!==s&&"ArrowDown"!==s||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)){const r=yr[s];if(!r)return!1;const i=this.isSelectedBlockRtl(n.nodeId),o=He(t,r,i);return!!o&&(e.preventDefault(),this.dispatch(o),!0)}if("Backspace"===s||"Delete"===s){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const s=ze(t,n);return s&&this.dispatch(s),!0}if("Enter"===s){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=je(t);return n&&this.dispatch(n),!0}if("Escape"===s){e.preventDefault();const n=He(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 s=e.key;if("ArrowLeft"===s||"ArrowRight"===s||"ArrowUp"===s||"ArrowDown"===s)return!1;if("Escape"===s||"Tab"===s)return!1;if(e.ctrlKey||e.metaKey||e.altKey)return!1;if("Enter"===s){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=je(t);return n&&this.dispatch(n),!0}if("Backspace"===s){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const s=_e(t,n);return s&&this.dispatch(s),!0}if("Delete"===s){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const s=Ge(t,n);return s&&this.dispatch(s),!0}if(1===s.length){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=$e(t,s);return this.dispatch(n),!0}return!1}handleGapCursorArrowFallback(e){const t=this.getState(),n=t.selection;if(!de(n))return!1;const s=e.key;if("ArrowLeft"!==s&&"ArrowRight"!==s&&"ArrowUp"!==s&&"ArrowDown"!==s)return!1;const r=yr[s];if(!r)return!1;if(!this.navigateFromGapCursorFn)return!1;const i=this.navigateFromGapCursorFn(t,r,this.element);return!(!i||se(i.selectionAfter,n)||(e.preventDefault(),this.dispatch(i),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=$e(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 wr(e){const t=e.executor??er.silent,n=e.isActive??(()=>!0),s=[...e.files],r=s.map(t=>e.registry.matchFileHandlerEntries(t.type)),i=(o,a,l)=>{let c=o,d=a,h=l;for(;c<s.length;){if(!n())return{handled:h,cancelled:!0};const o=s[c];if(!o){c++,d=0;continue}const a=(r[c]??[])[d];if(!a){c++,d=0;continue}const l=t.executeMaybeAsync({pluginId:a.pluginId,name:a.name,kind:"file-handler"},()=>a.handler(o,e.getPosition()));if(l instanceof Promise)return l.then(e=>br(e,c,d,h,i));l.ok&&!0===l.value?(h=!0,c++,d=0):d++}return n()?{handled:h,cancelled:!1}:{handled:h,cancelled:!0}};return i(0,0,!1)}function br(e,t,n,s,r){return e.ok&&!0===e.value?r(t+1,0,!0):r(t,n+1,s)}function vr(e,t){return t.isEmpty?e:ee(e)?function(e,t){const n={blockId:e.nodeId,offset:0},s=t.mapResult(n,-1);return s.deleted||s.pos.blockId!==e.nodeId?null:ne(e.nodeId,e.path)}(e,t):de(e)?function(e,t){const n={blockId:e.blockId,offset:0},s=t.mapResult(n,-1);return s.deleted||s.pos.blockId!==e.blockId?null:ae(e.blockId,e.side,e.path)}(e,t):Ir(e,t)}function Ir(e,t){if(Z(e)){const n=t.map(e.anchor,-1);return n===e.anchor?e:re(n.blockId,n.offset)}const n=t.map(e.anchor,-1),s=t.map(e.head,1);return n===e.anchor&&s===e.head?e:ie(n,s)}var Sr=/(^|\n) {0,3}(```|~~~)/,xr=/(^|\n)\s*\|?[ :|]*-{3,}[ :|-]*(\n|$)/,Rr=/(^|\n) {0,3}(#{1,6} |[-*+] |\d{1,9}[.)] |> )/g;function Mr(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 Tr(e,n,[t]);const{builder:s,insertBlockId:r,insertOffset:i}=Cr(e,n),o=Pr(s,r,i,t.segments);return Er(e,s,r,t.attrs),s.setSelection(re(r,o)),s.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 Tr(e,n,[t]);const{builder:s,insertBlockId:r,insertOffset:i}=Cr(e,n);s.setBlockType(r,t.type,t.attrs);const o=Pr(s,r,i,t.segments);return s.setSelection(re(r,o)),s.build()}(e,n):function(e,t){const n=e.selection;if(ee(n))return e.transaction("paste").setSelection(n).build();if(de(n))return Tr(e,n,t.blocks);const{builder:s,landingId:r,resolved:i,insertBlockId:o,insertOffset:a}=Cr(e,n),c=e.getBlockOrder();let d;if(r){const t=Q(e.doc,i.blockId)?.[0];d=t?e.doc.children.findIndex(e=>e.id===t):0}else d=c.indexOf(o);const u=t.blocks[0],p=t.blocks[t.blocks.length-1];if(!u||!p)return s.build();const m=t.blocks.slice(1,-1),f=Pr(s,o,a,u.segments),g=l();s.splitBlock(o,f,g),u.type!==he("paragraph")?s.setBlockType(o,u.type,u.attrs):Er(e,s,o,u.attrs);let y=d+1;for(const k of m){const e=L(k.type,h(k.segments),l(),k.attrs);s.insertNode([],y,e),y++}return Pr(s,g,0,p.segments),p.type!==he("paragraph")?s.setBlockType(g,p.type,p.attrs):Er(e,s,g,p.attrs),s.setSelection(re(g,Un(p.segments))),s.build()}(e,t):e.transaction("paste").setSelection(e.selection).build()}function Cr(e,t){const n=e.transaction("paste");let s;Z(t)||(s=Ue(e,n));const r=Ne(t,e.getBlockOrder());return{builder:n,landingId:s,resolved:r,insertBlockId:s??r.blockId,insertOffset:s?0:r.offset}}function Pr(e,t,n,s){let r=n,i=[];const o=()=>{if(0===i.length)return;const n=i.map(e=>"text"===e.kind?e.text:"").join("");n.length>0&&(e.insertText(t,r,n,[],i),r+=n.length),i=[]};for(const a of s)"inline"===a.kind?(o(),e.insertInlineNode(t,r,a.node),r+=1):i.push(a);return o(),r}function Er(e,t,n,s){if(!s||0===Object.keys(s).length)return;const r=e.apply(t.build()),i=r.getBlock(n),o=r.getNodePath(n);if(!i||!o)return;const a=e.schema.getNodeSpec?.(i.type),l={};for(const[c,d]of Object.entries(s))a&&!a.attrs?.[c]||(l[c]=d);Object.keys(l).length>0&&t.setNodeAttr(o,{...i.attrs,...l})}function Tr(e,t,n){const s=function(e,t){const n=Q(e.doc,t.blockId);if(!n)return null;const s=Le(n),r=be(e,s),i=ve(r,t.blockId);return i<0?null:{parentPath:s,insertIndex:"before"===t.side?i:i+1}}(e,t);if(!s)return e.transaction("paste").setSelection(t).build();const r=e.transaction("paste");let i,o=s.insertIndex,a=0;for(const c of n){const e=l(),t=L(c.type,h(c.segments),e,c.attrs);r.insertNode(s.parentPath,o,t),o++,i=e,a=Un(c.segments)}return i&&r.setSelection(re(i,a)),r.build()}var Br=/* @__PURE__ */new Set(["p","div","h1","h2","h3","h4","h5","h6","blockquote","ul","ol","li","hr","pre","table","thead","tbody","tr"]),Ar=/* @__PURE__ */new Set(["STRONG","B","EM","I","U","S","STRIKE","DEL","A","SPAN","BR","SUB","SUP","CODE"]),Or=/^H([1-6])$/;function Nr(e){const t=e.style.fontWeight,n=Number.parseInt(t,10);return!("normal"===t||!Number.isNaN(n)&&n<700)&&{}}var Dr=/* @__PURE__ */new Map([["STRONG",{markName:"bold",getAttrs:Nr}],["B",{markName:"bold",getAttrs:Nr}],["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")??"")}}}]]),Lr=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=Et(this.blockParseRules,this.inlineParseRules,Br),this.blockTagHandlers=this.buildBlockTagHandlers()}parse(e){Tt(e,this.classDeclarations),At(e);const t=this.parseContainer(e);return 0===t.length?{blocks:[{type:this.resolveBlockType(he("paragraph")),segments:[H("")]}]}:{blocks:t}}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=>[{type:this.resolveBlockType(he("paragraph")),segments:this.ensureSegments(this.parsePreContent(e))}]],["TABLE",t],["THEAD",t],["TBODY",t],["TR",t]])}parseContainer(e,t="keep"){const n=[];let s=[];for(const r of Array.from(e.childNodes))if(r.nodeType===Node.ELEMENT_NODE){const e=r;this.isBlockElement(e)?(this.flushPendingSegments(n,s,t),s=[],n.push(...this.parseBlockElement(e))):e.children.length>0&&this.containsBlockDescendants(e)?(this.flushPendingSegments(n,s,t),s=[],n.push(...this.parseContainerWithMarks(e,this.marksFromElement(e),t))):s.push(...this.parseInlineNode(r,[]))}else if(r.nodeType===Node.TEXT_NODE){const e=r.textContent??"";e&&s.push(H(e))}return this.flushPendingSegments(n,s,t),n}parseBlockElement(e){const t=Or.exec(e.tagName),n=this.blockTagHandlers.get(e.tagName),s=t?this.parseHeading(e,Number(t[1])):n?n(e):this.parseUnknownBlock(e);return this.applyElementAlignment(s,e)}applyElementAlignment(e,t,n){const s=kt(t);if(!s)return e;const r=n??this.containsBlockDescendants(t);return e.map(e=>this.schema.getNodeSpec&&!this.schema.getNodeSpec(e.type)?.attrs?.align||r&&void 0!==e.attrs?.align?e:{...e,attrs:{...e.attrs,align:s}})}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 s=[];for(const r of Array.from(e.children)){const e=r;"LI"===e.tagName?s.push(...this.parseListItem(e,t,n)):"UL"===e.tagName?s.push(...this.parseList(e,"bullet",n+1)):"OL"===e.tagName&&s.push(...this.parseList(e,"ordered",n+1))}return s}parseListItem(e,t,n){const s=[],r=this.resolveBlockType(he("list_item")),i=this.hasCheckbox(e),o=i?"checklist":t,a=!!i&&this.isCheckboxChecked(e),l=[],c=[];for(const d of Array.from(e.childNodes))if(d.nodeType===Node.ELEMENT_NODE){const e=d;"UL"===e.tagName||"OL"===e.tagName?c.push(e):"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")||(this.isBlockElement(e)?l.push(...this.parseInlineChildren(e,[])):l.push(...this.parseInlineNode(d,[])))}else if(d.nodeType===Node.TEXT_NODE){const e=d.textContent??"";e&&l.push(H(e))}s.push({type:r,attrs:{listType:o,indent:n,..."checklist"===o?{checked:a}:{}},segments:this.ensureSegments(this.normalizeSegments(l))});for(const d of c){const e="OL"===d.tagName?"ordered":"bullet";s.push(...this.parseList(d,e,n+1))}return s}parseInlineChildren(e,t){const n=[];for(const s of Array.from(e.childNodes))n.push(...this.parseInlineNode(s,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,s=n.tagName;if("BR"===s)return[H("\n",this.resolveMarks(t))];const r=this.matchInlineNodeRule(n);if(r)return[u(r)];if(this.isBlockElement(n)&&!Ar.has(s))return this.parseInlineChildren(n,t);const i=this.mergeMarks(t,this.marksFromElement(n));return this.parseInlineChildren(n,i)}matchInlineNodeRule(e){const t=Ot(e,this.inlineParseRules);return t?P(pe(t.type),t.attrs):null}parsePreContent(e){const t=e.textContent??"";return t?[H(t)]:[]}parseTableAsParagraphs(e){const t=[],n=e.querySelectorAll("td, th");for(const s of Array.from(n)){const e=this.parseInlineChildren(s,[]);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=Pt(e,[],this.markParseRules);return t.length>0?t:null}fallbackMarksFromElement(e){const t=Dr.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 s of t)n.some(e=>e.type===s.type)||n.push(s);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=Ot(e,this.blockParseRules);return t?{type:he(t.type),...t.attrs?{attrs:t.attrs}:{}}:null}isBlockElement(e){return Bt(e,this.blockParseRules,this.inlineParseRules,Br)}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 s=this.parseContainer(e,n),r=this.applyElementAlignment(s,e,!0);return 0===t.length?r:r.map(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 this.splitAtLineBreaks(this.parseInlineChildren(e,[]),t)}splitAtLineBreaks(e,t){if(!e.some(e=>"text"===e.kind&&e.text.includes("\n")))return[{type:t,segments:this.ensureSegments(e)}];const n=[];let s=[];for(const r of e){if("inline"===r.kind){s.push(r);continue}const e=r.text.split("\n");for(let i=0;i<e.length;i++){i>0&&(n.push({type:t,segments:this.ensureSegments(this.normalizeSegments(s))}),s=[]);const o=e[i]??"";o&&s.push(H(o,r.marks))}}return n.push({type:t,segments:this.ensureSegments(this.normalizeSegments(s))}),n}flushPendingSegments(e,t,n){const s=this.normalizeSegments(t);if(0===s.length)return;if(s.every(e=>"text"===e.kind&&""===e.text.trim()))return;const r=this.resolveBlockType(he("paragraph"));"keep"!==n?e.push(...this.splitAtLineBreaks(function(e){const t=e.at(-1);if("text"!==t?.kind||!t.text.endsWith("\n"))return e;const n=t.text.slice(0,-1),s=e.slice(0,-1);return n?[...s,H(n,t.marks)]:s}(s),r)):e.push({type:r,segments:s})}},Hr={1:"x-small",2:"small",3:"medium",4:"large",5:"x-large",6:"xx-large",7:"xxx-large"};function zr(e){return e.toLowerCase().includes("font-size")}function Fr(e,t){for(;e.firstChild;)t.appendChild(e.firstChild)}function jr(e){const t=e.parentNode;if(t){for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}}var $r=["script","style","iframe","object","embed","form","noscript"],_r=/* @__PURE__ */new Set(["p","div","h1","h2","h3","h4","h5","h6","li","blockquote","table","tr","td","th","pre","figure","hr"]),Kr=class{getState;dispatch;schemaRegistry;tryRichPasteFromJson;constructor(e,t,n,s){this.getState=e,this.dispatch=t,this.schemaRegistry=n,this.tryRichPasteFromJson=s}handleHTMLOrTextPaste(e,t,n){const s=this.stateAtSelection(n),r=e.getData("text/html");r?this.handleHTML(r,s):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(Mr(this.stateAtSelection(t),n))}pasteHTMLString(e,t){return this.handleHTML(e,this.stateAtSelection(t))}handleHTML(e,t){const n=Rt(e,{FORBID_TAGS:$r,ADD_TAGS:this.schemaRegistry?this.schemaRegistry.getAllowedTags():[],ADD_ATTR:this.schemaRegistry?this.schemaRegistry.getAllowedAttrs():[],ALLOWED_URI_REGEXP:s,...Mt()},this.schemaRegistry),r=this.extractRichData(n);if(r&&this.tryRichPasteFromJson(r,t))return!0;const i=document.createElement("template");i.innerHTML=n,function(e){const t=Array.from(e.querySelectorAll("font"));for(const n of t){const e=n.getAttribute("color"),t=n.getAttribute("face"),s=n.getAttribute("size"),r=n.getAttribute("style")??"";if(!(null!==e||null!==t||null!==s||r.length>0)){jr(n);continue}const i=document.createElement("span"),o=[];if(r&&o.push(r.endsWith(";")?r:`${r};`),e&&o.push(`color: ${e};`),t&&o.push(`font-family: ${t};`),s&&!zr(r)){const e=Hr[s];e&&o.push(`font-size: ${e};`)}tn(i,o.join(" ")),Fr(n,i),n.parentNode?.replaceChild(i,n)}}(i.content);const o=i.innerHTML,a=this.schemaRegistry?this.schemaRegistry.getAllowedTags():["strong","em","u","b","i","p","br","div","span"],l=this.schemaRegistry?this.schemaRegistry.getAllowedAttrs():[],c=Rt(o,{ALLOWED_TAGS:a,ALLOWED_ATTR:l,ALLOWED_URI_REGEXP:s,...Mt()},this.schemaRegistry);if(this.schemaRegistry){const e=document.createElement("template");if(e.innerHTML=c,this.requiresDocumentParser(c,e.content))return this.handleDocumentPaste(c,t);const n=fe(this.schemaRegistry),s=new Lr({schema:n,schemaRegistry:this.schemaRegistry}),r=null!==e.content.querySelector("br"),i=s.parse(e.content);return!(!function(e){return e.blocks.some(e=>e.type!==he("paragraph")||e.segments.some(Qn))}(i)&&!r||(this.dispatch(Mr(t,i)),0))}const d=this.extractTextFromHTML(c);return!!Jn(d)&&(this.dispatch($e(t,d,"paste")),!0)}extractRichData(e){const t=document.createElement("template");t.innerHTML=e;const n=t.content.querySelector("[data-notectl-rich]")?.getAttribute("data-notectl-rich");if(n)return this.decodeHTMLEntities(n)}decodeHTMLEntities(e){return e.replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}requiresDocumentParser(e,t){return!!this.containsModelledBlockID(t)||!!/<table[\s>]/i.test(e)||!!/<blockquote[\s>]/i.test(e)||!(!/<li[\s>]/i.test(e)||!this.containsMultiBlockListItem(t))||this.containsVoidBlockElements(t)}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(_r.has(e)||t.has(e))return!0}return!1}containsMultiBlockListItem(e){const t=this.schemaRegistry?.getBlockParseRules()??[],n=this.schemaRegistry?.getInlineParseRules()??[],s=/* @__PURE__ */new Set(["PRE","BLOCKQUOTE","TABLE","HR","H1","H2","H3","H4","H5","H6"]);for(const r of Array.from(e.querySelectorAll("li"))){let e=0,i=!1;for(const o of Array.from(r.childNodes))if(o.nodeType===Node.ELEMENT_NODE){const r=o.tagName;if("UL"===r||"OL"===r||"INPUT"===r||"LI"===r)continue;if(s.has(r))return!0;if(Ct(o,t,n))return!0;if("P"===r||"DIV"===r){e++;continue}i=!0}else o.nodeType===Node.TEXT_NODE&&""!==(o.textContent??"").trim()&&(i=!0);if(e>=2||e>=1&&i)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=Tn(Nt(e,this.schemaRegistry),this.schemaRegistry);if(0===n.children.length)return!1;const s=t.selection,r=t.transaction("paste");let i;te(s)&&!Z(s)&&(i=Ue(t,r));const o=i??(ee(s)?s.nodeId:de(s)?s.blockId:s.anchor.blockId),a=Te(t,o,this.schemaRegistry);if(!a)return!1;const c=a.parentPath[a.parentPath.length-1],d=c?t.getBlock(c)?.type:void 0,h=Ae(this.schemaRegistry,d,n.children)?a:xe(t,o);if(!h)return!1;const u=de(s)&&"before"===s.side?0:1;let p,m,f=h.anchorIndex+u;for(const g of n.children){const e=l(),t=Ee(g,e);r.insertNode(h.parentPath,f,t),f++,p=De(t),m=t}if(h.isAnchorEmpty&&!de(s)&&r.removeNode(h.parentPath,h.anchorIndex),p&&m){const e=Ce(m,p),t=e?B(e).length:0;r.setSelection(re(p,t))}return this.dispatch(r.build()),!0}extractTextFromHTML(e){const t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}stateAtSelection(e){const t=this.getState();return e?t.withSelection(e):t}},Vr=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 s=n.type;if(!s)return;const r=this.schemaRegistry?.getNodeSpec(s);if(this.schemaRegistry&&!r)return;const i=this.getState(),o=i.selection,a=Oe(o),c=l(),d=Me(n.attrs,r?.attrs),h=L(he(s),void 0,c,d,t(n.htmlId)),u=Ie(i,a);if(u){const e=i.getBlock(u);if(this.cellRejects(e,[h])){const e=xe(i,a);if(!e)return;return void this.dispatchNodeInsert(i,e.parentPath,e.anchorIndex+1,h)}const t=Se(i,a,u,this.schemaRegistry);if(!t||!e)return;return void this.dispatchNodeInsert(i,t.parentPath,e.children.length,h)}const p=Te(i,a,this.schemaRegistry);if(!p)return;const m=de(o)&&"before"===o.side?0:1;this.dispatchNodeInsert(i,p.parentPath,p.anchorIndex+m,h)}dispatchNodeInsert(e,t,n,s){const r=e.transaction("paste");r.insertNode(t,n,s),r.setSelection(ne(s.id,[...t,s.id])),this.dispatch(r.build())}cellRejects(e,t){return!(!e||!this.schemaRegistry||Ae(this.schemaRegistry,e.type,t))}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 s=[];for(const t of e){const e=Re(t,this.schemaRegistry);e&&s.push(e)}if(0===s.length)return!1;if(!s.some(e=>void 0!==e.htmlId||void 0!==e.type&&"paragraph"!==e.type||e.segments?.some(e=>"inline"===e.kind))&&s.length<=1)return!1;let r=n??this.getState();const i=r.selection,o=Oe(i),a=r.getBlock(o),l=r.doc.children.some(e=>e.id===o);if(!s.some(e=>t(e.htmlId))&&te(i)&&Z(i)&&l&&void 0!==a&&A(a)>0)return this.dispatch(Mr(r,Pe(s))),!0;if(te(i)&&!Z(i)){const e=r.transaction("paste"),t=Ue(r,e),n=e.build();if(this.dispatch(n),r=r.apply(n),t)return this.resolveAndInsertRichBlocks(s,r,t)}return this.resolveAndInsertRichBlocks(s,r,o)}resolveAndInsertRichBlocks(e,t,n){const s=e.map(Be),r=t.selection,i=Ie(t,n);if(i){const e=t.getBlock(i);if(this.cellRejects(e,s)){const e=xe(t,n);return!!e&&this.insertNodes(s,t,e,e.anchorIndex+1,!1)}const r=Se(t,n,i,this.schemaRegistry);if(!r)return!1;const o=r.anchorIndex>=0?r.anchorIndex+1:e?.children.length??0;return this.insertNodes(s,t,r,o,!0)}const o=Te(t,n,this.schemaRegistry);if(!o)return!1;const a=de(r)&&"before"===r.side?0:1;return this.insertNodes(s,t,o,o.anchorIndex+a,!de(r))}insertNodes(e,t,n,s,r){const i=t.transaction("paste");let o,a=s;for(const l of e)i.insertNode(n.parentPath,a,l),a++,o=l;return r&&n.isAnchorEmpty&&n.anchorIndex>=0&&i.removeNode(n.parentPath,n.anchorIndex),o&&i.setSelection(re(o.id,A(o))),this.dispatch(i.build()),!0}};function Wr(e){return""!==e.trim()&&/<\w/.test(e)}var qr=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??er.silent,this.loadMarkdownParser=t.loadMarkdownParser??(()=>import("./MarkdownParser-CvYOvU3d.mjs").then(e=>e.t)),this.richBlockHandler=new Vr(t.getState,e=>this.dispatchPasteTransaction(e),t.schemaRegistry),this.htmlHandler=new Kr(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(!Yt(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 s=this.createBookmark(),r=function(e,t){if(0===t.length||t.some(e=>!e.type.startsWith("image/")))return!1;if(!Wr(e))return!1;const n=(new DOMParser).parseFromString(e,"text/html").body,s=n.querySelectorAll("img, picture, svg, canvas"),r=s.length>0;for(const i of s)i.remove();return""!==(n.textContent??"").trim()||!r}(n.html,n.files),i=this.fileHandlerRegistry&&n.files.length>0&&!r?wr({registry:this.fileHandlerRegistry,executor:this.callbackExecutor,files:n.files,getPosition:()=>null,isActive:()=>this.isBookmarkActive(s)}):{handled:!1,cancelled:!1};i instanceof Promise?this.continueAfterFileHandlers(i,n,s):i.handled||i.cancelled?this.releaseBookmark(s):this.processClipboardSnapshot(n,s,r?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&&!Wr(e.html)&&function(e){if(0===e.length)return!1;if(Sr.test(e))return!0;if(e.includes("|")&&xr.test(e))return!0;const t=e.match(Rr);return null!==t&&t.length>=2}(e.plainText))return void this.handleMarkdownPaste(e.plainText,t);const s=this.consumeBookmark(t);s&&(e.html?this.htmlHandler.pasteHTMLString(e.html,s)||this.handleContentlessHTMLFallback(n,e.plainText,s):e.plainText&&this.htmlHandler.pastePlainText(e.plainText,s))}handleContentlessHTMLFallback(e,t,n){const s=this.fileHandlerRegistry;if(!s||0===e.length)return void(this.active&&!this.isReadOnly()&&t&&this.htmlHandler.pastePlainText(t,n));const r=this.createBookmark(n),i=wr({registry:s,executor:this.callbackExecutor,files:e,getPosition:()=>null,isActive:()=>this.isBookmarkActive(r)});i instanceof Promise?this.continueContentlessHTMLFallback(i,t,r):this.finishContentlessHTMLFallback(i,t,r)}async continueContentlessHTMLFallback(e,t,n){try{this.finishContentlessHTMLFallback(await e,t,n)}catch(s){this.callbackExecutor.reportFailure({pluginId:"core",name:"Deferred file paste",kind:"file-handler"},s),this.releaseBookmark(n)}}finishContentlessHTMLFallback(e,t,n){if(e.handled||e.cancelled||!this.isBookmarkActive(n))return void this.releaseBookmark(n);const s=this.consumeBookmark(n);s&&t&&this.htmlHandler.pastePlainText(t,s)}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 s=this.consumeBookmark(t);if(!s)return;if(!n.ok)return void this.commitMarkdownPlainTextFallback(e,s);const r=this.callbackExecutor.execute({pluginId:"core",name:"Markdown HTML commit",kind:"markdown-paste"},()=>this.htmlHandler.pasteHTMLString(n.value,s));r.ok&&r.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,s)}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 s=this.getPasteInterceptors(),r=this.getState().withSelection(n.selection);for(const i of s){const s=this.callbackExecutor.execute({pluginId:i.pluginId,name:i.name,kind:"paste-interceptor"},()=>i.interceptor(e,t,r));if(s.ok&&s.value)return this.consumeBookmark(n),this.dispatchPasteTransaction(s.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 s=e.items[n];if(s&&"file"===s.kind){const e=s.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 s=await e;if(s.cancelled||!this.isBookmarkActive(n))return void this.releaseBookmark(n);if(s.handled)return void this.releaseBookmark(n);this.processClipboardSnapshot(t,n,[])}catch(s){this.callbackExecutor.reportFailure({pluginId:"core",name:"File paste continuation",kind:"file-handler"},s),this.releaseBookmark(n)}}onStateChange(e,t,n){for(const s of this.pendingBookmarks){if(e.doc!==t.doc&&0===n.steps.length){s.cancelled=!0,this.pendingBookmarks.delete(s);continue}const r=vr(s.selection,n.mapping);r&&Ur(t,r)?s.selection=r:(s.cancelled=!0,this.pendingBookmarks.delete(s))}}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(se(t.selection,e.selectionBefore))return void this.dispatch(e);const n=vr(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 Ur(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 Gr=class{compositionTracker;inputHandler;keyboardHandler;pasteHandler;clipboardHandler;constructor(e,t){this.compositionTracker=new Xs,this.inputHandler=new cr(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 kr(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 qr(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 Qs(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()}},Jr=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}},Qr=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}},Xr=class{_contextKeymaps=[];_navigationKeymaps=[];_defaultKeymaps=[];_fallbackKeymaps=[];registerKeymap(e,t,n){const s=t?.priority??"default";this.keymapArrayForPriority(s).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}}},Yr=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 Zr(e,t){if(function(e){return hs.has(e)}(e))return e;const n=[],s=[];let r=t;for(const i of e.steps){const e=ms(i);n.push(e),s.push(Ft(Cs(r,e))),r=Rs(r,e)}return fs({steps:n,selectionBefore:us(e.selectionBefore),selectionAfter:us(e.selectionAfter),storedMarksAfter:ps(e.storedMarksAfter),forwardStepMaps:s,metadata:e.metadata})}var ei=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()}},ti=class{commands=/* @__PURE__ */new Map;readonlyBypassActive=!1;log;constructor(e=Vs){this.log=qs(e,"CommandRegistry")}register(e,t,n,s){if(this.commands.has(e)){const t=this.commands.get(e);throw new Error(`Command "${e}" is already registered by plugin "${t?.pluginId}".`)}const r=s?.readonlyAllowed??!1;this.commands.set(e,{name:e,handler:t,pluginId:n,readonlyAllowed:r})}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 s=t&&n.readonlyAllowed;s&&(this.readonlyBypassActive=!0);try{return n.handler()}catch(r){return this.log.error(`Command "${e}" error`,r),!1}finally{s&&(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}},ni=class{listeners=/* @__PURE__ */new Map;log;constructor(e=Vs){this.log=qs(e,"EventBus")}emit(e,t){const n=this.listeners.get(e.id);if(n)for(const r of n)try{r(t)}catch(s){this.log.error(`Listener error on "${e.id}"`,s)}}on(e,t){const n=e.id;this.listeners.has(n)||this.listeners.set(n,/* @__PURE__ */new Set);const s=this.listeners.get(n)??/* @__PURE__ */new Set;return s.add(t),()=>{s.delete(t),0===s.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()}},si=class{middlewares=[];middlewareSorted=null;pasteInterceptors=[];pasteInterceptorsSorted=null;textInputInterceptors=[];textInputInterceptorsSorted=null;log;constructor(e=Vs){this.log=qs(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 s=this.getSortedMiddleware();let r=0,i=!1;const o=e=>{if(r<s.length){const n=s[r++];if(!n)return;let i=!1;const l=e=>{i||(i=!0,o(e))};try{n.middleware(e,t,l)}catch(a){this.log.error(`Middleware "${n.name}" error`,a),l(e)}}else i||(i=!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}},ri=/* @__PURE__ */new WeakSet;function ii(e,t,n,s){return{registerCommand:(s,r,i)=>{if(t.has(s)){const e=t.get(s);throw new Error(`Command "${s}" is already registered by plugin "${e?.pluginId}".`)}const o=i?.readonlyAllowed??!1;t.set(s,{name:s,handler:r,pluginId:e,readonlyAllowed:o}),n.commands.push(s)},executeCommand:s}}function oi(e,t){return{registerService:(n,s)=>{if(e.has(n.id))throw new Error(`Service "${n.id}" is already registered by another plugin.`);e.set(n.id,s),t.services.push(n.id)},getService:t=>e.get(t.id)}}function ai(e,t){const{pluginId:n,middlewares:s,pasteInterceptors:r,textInputInterceptors:i,invalidateMiddlewareSort:o,invalidatePasteSort:a,invalidateTextInputSort:l}=e;return{registerMiddleware:(e,r)=>{const i={name:r?.name??(e.name||"anonymous"),pluginId:n,middleware:e,priority:r?.priority??100};s.push(i),t.middlewares.push(i),o()},registerPasteInterceptor:(e,s)=>{const i={name:s?.name??"anonymous",pluginId:n,interceptor:e,priority:s?.priority??100};r.push(i),t.pasteInterceptors.push(i),a()},registerTextInputInterceptor:(e,s)=>{const r={name:s?.name??"anonymous",pluginId:n,interceptor:e,priority:s?.priority??100};i.push(r),t.textInputInterceptors.push(r),l()}}}function li(e,t){return{registerNodeSpec:n=>{e.schemaRegistry.registerNodeSpec(ci(n,e.pluginId,e.callbackExecutor)),t.nodeSpecs.push(n.type)},registerNodeSpecExtension:(n,s)=>{const r=t=>{const r=e.callbackExecutor.execute({pluginId:e.pluginId,name:`${n}:extension`,kind:"schema-extension"},()=>s(t));return r.ok?ci(r.value,e.pluginId,e.callbackExecutor):t};e.schemaRegistry.registerNodeSpecExtension(n,r),t.nodeSpecExtensions.push({type:n,extension:r})},registerMarkSpec:n=>{e.schemaRegistry.registerMarkSpec(function(e,t,n){const s=hi(e.type,e.parseHTML,t,n),r=e.toDOM,i=ri.has(r)?r:s=>{const i=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>di(r(s),`${e.type}.toDOM`));return i.ok?i.value:document.createElement("span")};return ri.add(i),{...e,toDOM:i,parseHTML:s}}(n,e.pluginId,e.callbackExecutor)),t.markSpecs.push(n.type)},registerInlineNodeSpec:n=>{e.schemaRegistry.registerInlineNodeSpec(function(e,t,n){const s=hi(e.type,e.parseHTML,t,n),r=e.toDOM,i=ri.has(r)?r:s=>{const i=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>di(r(s),`${e.type}.toDOM`));if(i.ok)return i.value;const o=document.createElement("span");return o.setAttribute("data-inline-type",s.inlineType),o};return ri.add(i),{...e,toDOM:i,parseHTML:s}}(n,e.pluginId,e.callbackExecutor)),t.inlineNodeSpecs.push(n.type)},registerStyleClass:n=>{e.schemaRegistry.registerStyleClass(n),t.styleClasses.push(n)}}}function ci(e,t,n){const s=hi(e.type,e.parseHTML,t,n),r=e.toDOM,i=ri.has(r)?r:s=>{const i=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>di(r(s),`${e.type}.toDOM`));if(i.ok)return i.value;const o=document.createElement("div");return o.setAttribute("data-block-id",s.id),o};return ri.add(i),{...e,toDOM:i,parseHTML:s}}function di(e,t){if(e instanceof HTMLElement)return e;throw new TypeError(`${t} must return an HTMLElement.`)}function hi(e,t,n,s){return t?.some(e=>e.getAttrs)?t.map(t=>{const r=t.getAttrs;return r?{...t,getAttrs(i){const o=s.execute({pluginId:n,name:`${e}:${t.tag}`,kind:"schema-parse"},()=>r(i));return!!o.ok&&o.value}}:t}):t}function ui(e,t,n){return{registerNodeView:(s,r)=>{t.nodeViewRegistry.registerNodeView(s,r,{pluginId:e,name:s}),n.nodeViews.push(s)},registerKeymap:(s,r)=>{t.keymapRegistry.registerKeymap(s,r,{pluginId:e,name:Object.keys(s).join(", ")||"anonymous-keymap"}),n.keymaps.push(s)},registerInputRule:s=>{t.inputRuleRegistry.registerInputRule(s,{pluginId:e,name:s.handler.name||s.pattern.toString()}),n.inputRules.push(s)},registerMarkdownSyntax:s=>{const r=function(e,t,n){const s=e.matchInline,r=e.matchBlock;return{...e,...s?{matchInline(r,i){const o=n.execute({pluginId:t,name:`${e.id}:matchInline`,kind:"markdown-syntax"},()=>function(e,t){const n=pi(e,"length",t);return n?{type:n.type,attrs:n.attrs,length:n.consumed}:null}(s(r,i),r.length-i));return o.ok?o.value:null}}:{},...r?{matchBlock(s,i){const o=n.execute({pluginId:t,name:`${e.id}:matchBlock`,kind:"markdown-syntax"},()=>function(e,t){const n=pi(e,"linesConsumed",t);return n?{type:n.type,attrs:n.attrs,linesConsumed:n.consumed}:null}(r(s,i),s.length-i));return o.ok?o.value:null}}:{}}}(s,e,t.callbackExecutor);t.markdownSyntaxRegistry.register(r),n.markdownSyntaxExtensions.push(r)},registerToolbarItem:s=>{t.toolbarRegistry.registerToolbarItem(s,e),n.toolbarItems.push(s.id)},registerBlockTypePickerEntry:e=>{t.blockTypePickerRegistry.registerBlockTypePickerEntry(e),n.blockTypePickerEntries.push(e.id)},registerFileHandler:(s,r)=>{t.fileHandlerRegistry.registerFileHandler(s,r,{pluginId:e,name:r.name||s}),n.fileHandlers.push(r)},registerStyleSheet:e=>{const s=new CSSStyleSheet;s.replaceSync(e),t.pluginStyleSheets.push(s),n.stylesheets.push(s)}}}function pi(e,t,n){if(null===e)return null;if(!fi(e))throw new TypeError("Markdown match must be null or an object descriptor.");const s=e.type;if("string"!=typeof s||0===s.trim().length)throw new TypeError("Markdown match type must be a non-empty string.");const r=function(e){if(!fi(e))throw new TypeError("Markdown match attrs must be an object.");const t=[];for(const[n,s]of Object.entries(e)){if(!mi(s))throw new TypeError("Markdown match attrs must contain only primitive finite values.");t.push([n,s])}return Object.fromEntries(t)}(e.attrs),i=e[t];if("number"!=typeof i||!Number.isFinite(i)||!Number.isInteger(i)||i<=0||i>n)throw new TypeError(`Markdown match ${t} must be a positive integer within the remaining input.`);return{type:s,attrs:r,consumed:i}}function mi(e){return"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e)}function fi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gi(e){return{getSchemaRegistry:()=>e.schemaRegistry,getKeymapRegistry:()=>e.keymapRegistry,getInputRuleRegistry:()=>e.inputRuleRegistry,getFileHandlerRegistry:()=>e.fileHandlerRegistry,getNodeViewRegistry:()=>e.nodeViewRegistry,getToolbarRegistry:()=>e.toolbarRegistry,getBlockTypePickerRegistry:()=>e.blockTypePickerRegistry}}var yi=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=Vs){this.tracker=e,this.log=qs(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,s=Promise.resolve().then(()=>this.runInitialization(e,t,n)).finally(()=>{this.pendingInit===s&&(this.pendingInit=null,this.initializing=!1)});return this.pendingInit=s,s}async runInitialization(e,t,n){const s=()=>n!==this.lifecycleVersion||!0===e.isCancelled?.();try{this.initOrder=this.resolveOrder();for(const n of this.initOrder){if(s())return void(await this.rollbackStartedPlugins());const r=this.plugins.get(n);if(!r)continue;this.startedInitOrder.push(n);const i=t(n,e);if(await r.init(i),s())return void(await this.rollbackStartedPlugins())}if(s())return void(await this.rollbackStartedPlugins());if(e.onBeforeReady&&await e.onBeforeReady(),s())return void(await this.rollbackStartedPlugins());for(const e of this.initOrder){if(s())return void(await this.rollbackStartedPlugins());const t=this.plugins.get(e);if(t?.onReady){try{await t.onReady()}catch(r){this.log.error(`Plugin "${e}" error in onReady`,r)}if(s())return void(await this.rollbackStartedPlugins())}}if(s())return void(await this.rollbackStartedPlugins());this.initialized=!0}catch(r){throw await this.rollbackStartedPlugins(),r}}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 r of this.initOrder){const i=this.plugins.get(r);if(i?.onStateChange)try{i.onStateChange(e,t,n)}catch(s){this.log.error(`Plugin "${r}" error in onStateChange`,s)}}}collectDecorations(e,t){let n=qt.empty;for(const r of this.initOrder){const i=this.plugins.get(r);if(i?.decorations)try{const s=i.decorations(e,t).withWidgetOwner(r);s.isEmpty||(n=n.merge(s))}catch(s){this.log.error(`Plugin "${r}" error in decorations()`,s)}}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(s){this.log.error(`Plugin "${e}" error in onConfigure`,s)}}isReadOnly(){return this.readOnly}setReadOnly(e){if(this.readOnly!==e){this.readOnly=e;for(const n of this.initOrder){const s=this.plugins.get(n);if(s?.onReadOnlyChange)try{s.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 i of e){const e=this.plugins.get(i);if(e)for(const t of e.dependencies??[])if(!this.plugins.has(t))throw new Error(`Plugin "${i}" depends on "${t}", which is not registered.`)}const t=/* @__PURE__ */new Map,n=/* @__PURE__ */new Map;for(const i of e)t.set(i,0),n.set(i,[]);for(const i of e){const e=this.plugins.get(i)?.dependencies??[];t.set(i,e.length);for(const t of e){const e=n.get(t);e&&e.push(i)}}const s=[];for(const[i,o]of t)0===o&&s.push(i);const r=[];for(;s.length>0;){s.sort((e,t)=>(this.plugins.get(e)?.priority??100)-(this.plugins.get(t)?.priority??100));const e=s.shift();if(!e)break;r.push(e);for(const r of n.get(e)??[]){const e=(t.get(r)??0)-1;t.set(r,e),0===e&&s.push(r)}}if(r.length!==e.length){const t=e.filter(e=>!r.includes(e));throw new Error(`Circular dependency detected among plugins: ${t.join(", ")}`)}return r}},ki=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}},wi=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}},bi=class{schemaRegistry=new an;keymapRegistry=new Xr;inputRuleRegistry=new Qr;markdownSyntaxRegistry=new Yr;fileHandlerRegistry=new Jr;nodeViewRegistry=new ei;toolbarRegistry=new cn;blockTypePickerRegistry=new ln;logger;commandRegistry;serviceRegistry=new wi;middlewareChain;eventBus;registrationTracker;lifecycle;callbackExecutor;pendingDestroy=null;constructor(e={}){this.logger=e.logger??Vs,this.callbackExecutor=new er(e=>{this.logger.error(`[PluginCallback] Plugin "${e.pluginId}" ${e.kind} "${e.name}" error`,e.cause)}),this.commandRegistry=new ti(this.logger),this.middlewareChain=new si(this.logger),this.eventBus=new ni(this.logger),this.registrationTracker=new ki({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 yi(this.registrationTracker,this.logger)}registerService(e,t){this.serviceRegistry.register(e,t)}register(e){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."));const t={...e,onBeforeReady:async()=>{this.schemaRegistry.finalize(),await(e.onBeforeReady?.())}};return this.lifecycle.init(t,(e,t)=>this.createContext(e,t))}notifyStateChange(e,t,n){this.lifecycle.notifyStateChange(e,t,n)}collectDecorations(e,t){return this.lifecycle.collectDecorations(e,t)}dispatchWithMiddleware(e,t,n){this.middlewareChain.dispatch(e,t,e=>{n(Zr(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)}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;const e=this.lifecycle.destroy().then(()=>this.clearRegistries()).finally(()=>{this.pendingDestroy===e&&(this.pendingDestroy=null)});return this.pendingDestroy=e,e}clearRegistries(){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()}createContext(e,t){const n=t.getCompositionState??(()=>vi),s={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)},{context:r,registrations:i}=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,s)=>{const r=e.on(n,s);return t.unsubscribers.push(r),r},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,...ii(e.pluginId,e.commands,t,e.executeCommand),...oi(e.services,t),...ai(e,t),...li(e,t),...ui(e.pluginId,e,t),...gi(e),updateConfig:t=>{const n=e.plugins.get(e.pluginId);if(n?.onConfigure)try{n.onConfigure(t)}catch(s){const t=`[PluginContext] Plugin "${e.pluginId}" error in onConfigure`;e.logger.error(t,s)}},announce:t=>{e.announce?.(t)},hasAnnouncement:()=>e.hasAnnouncement?.()??!1,getCompositionState:()=>e.getCompositionState()},registrations:t}}(s);return this.registrationTracker.track(e,i),r}},vi={isComposing:!1,activeBlockId:null},Ii=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,Ri(this.undoStack,e),Ri(this.redoStack,e))}undo(e){const t=this.undoStack.pop();if(!t)return null;const n=Si(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=Si(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 Si(e,t,n){let s=e.interveningMapping,r=t.doc;const i=[],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 l=Ps(Ms(n),s,r);if(null===l)return null;const c=Cs(r,l);i.push(l),o.push(c),r=Rs(r,l),s=xi(a,s,c)}}const a=function(e){const t=e.transactions[0];return t?os(t):null}(e),l=Zr({steps:i,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 c=t.apply(l);const d=e.transactions[0];if(d){const e=vr(d.selectionBefore,s);null!==e&&(c=c.withSelection(e))}return{newState:c,transaction:fs({steps:l.steps,selectionBefore:l.selectionBefore,selectionAfter:us(c.selection),storedMarksAfter:l.storedMarksAfter,forwardStepMaps:l.forwardStepMaps,metadata:l.metadata})}}function xi(e,t,n){return t.isEmpty&&Dt(Ut(e),n)?t:Lt.from([e]).appendMapping(t).appendMap(n)}function Ri(e,t){for(let n=0;n<e.length;n++){const s=e[n];s&&(e[n]={...s,interveningMapping:s.interveningMapping.appendMapping(t)})}}function Mi(e){for(const t of e.steps)if("setStoredMarks"!==t.type)return!1;return!0}function Ci(e){return!!e.metadata.readonlyAllowed||Mi(e)}function Pi(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 Ei(e,t,n){if(0===t.length)return e;const s=[...t].sort((e,t)=>Pi(e,n)-Pi(t,n));let r=e;for(let i=s.length-1;i>=0;i--){const e=s[i];if(!e)continue;const t=Ti(e,n);t.appendChild(r),r=t}return r}function Ti(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 Bi=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 s=document.createElement("span");s.setAttribute(mn,"");const r=document.createTextNode("​"),i=Ei(r,t,this.registry);s.appendChild(i);const o=bn();if(!o||0===o.rangeCount)return;let a;const l=gn(this.container,o);if(l){const e=document.createRange();try{e.setStart(l.anchorNode,l.anchorOffset),e.setEnd(l.focusNode,l.focusOffset)}catch{return}a=e}else a=o.getRangeAt(0);a.insertNode(s);try{o.collapse(r,r.length)}catch{}this.wrapperElement=s}cleanup(){this.wrapperElement&&(this.wrapperElement.remove(),this.wrapperElement=null)}};function Ai(e){return e.shiftKey||e.ctrlKey||e.altKey||e.metaKey}function Oi(e,t){return Math.abs(t.clientX-e.clientX)>4||Math.abs(t.clientY-e.clientY)>4}var Ni=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??er.silent,this.handleCompositionStart=t=>{Yt(t,e.contentElement)&&e.cursorWrapper.onCompositionStart(e.getState())},this.handleCompositionEnd=t=>{Yt(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=wn(this.deps.contentElement);if(!t)return;if(se(t,e.selection))return;const n=e.transaction("input").setSelection(t).setStoredMarks(null,e.storedMarks).build(),s=e.apply(n);this.deps.applyUpdate(s,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 s of this.pendingDropBookmarks){if(!s.position)continue;if(e.doc!==t.doc&&0===n.steps.length){s.cancelled=!0,this.pendingDropBookmarks.delete(s);continue}const r=n.mapping.mapResult(s.position,-1);!r.deleted&&t.getBlock(r.pos.blockId)?s.position=r.pos:(s.cancelled=!0,this.pendingDropBookmarks.delete(s))}}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)&&Xt(t,this.deps.contentElement)&&this.syncSelectionFromDOM()}onMousedown(e){if(this.clearBelowContentPress(),this.deps.isUpdating())return;if(!Yt(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 s=me(n.getAttribute("data-block-id")??""),r=un(this.deps.contentElement,n),i=ne(s,r),o=this.deps.getState(),a=o.transaction("input").setSelection(i).setStoredMarks(null,o.storedMarks).build(),l=o.apply(a);this.deps.applyUpdate(l,a)}trackBelowContentPress(e){this.deps.isReadOnly()||e.defaultPrevented||0!==e.button||Ai(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?Oi(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||Ai(e)||t.dragged||Oi(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 s=this.deps.contentElement.querySelector(`[data-block-id="${n.id}"]`);return!!s&&e>s.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,s=e.getBlock(n);if("paragraph"===s?.type&&0===A(s)){const t=e.transaction("input").setSelection(re(n,0)).build();return void this.deps.dispatch(t)}this.deps.contentElement.focus();const r=l(),i=e.transaction("input").insertNode([],e.doc.children.length,E(r)).setSelection(re(r,0)).build();this.deps.dispatch(i)}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 s=wr({registry:this.deps.fileHandlerRegistry,executor:this.callbackExecutor,files:t,getPosition:()=>n.position,isActive:()=>this.active&&!this.deps.isReadOnly()&&!n.cancelled});if(s instanceof Promise)return e.preventDefault(),void this.finishAsyncFileDrop(s,n);this.pendingDropBookmarks.delete(n),s.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(),s=Xe(n,e,t);return s&&this.deps.contentElement.contains(s.node)?In(this.deps.contentElement,s.node,s.offset):null}markPendingSelectionClear(){const e=this.deps.getState();ee(e.selection)&&(this.pendingNodeSelectionClear=!0),de(e.selection)&&(this.pendingGapCursorClear=!0)}},Di=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,s]of Object.entries(e))t[n]=()=>this.handleArrow(s);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),s=nt(t,n);if(s)return this.deps.dispatch(s),this.validateSelectionAfterInlineSkip(),!0;if(!Qe(this.deps.contentElement,t,e))return!1;const r=et(t,n);return!!r&&(this.deps.dispatch(r),!0)}resolveLogicalDirection(e,t){const n=e.selection;if(!te(n))return t;const s=this.deps.contentElement.querySelector(`[data-block-id="${n.anchor.blockId}"]`);return s instanceof HTMLElement&&"rtl"===on(s)?"left"===t?"right":"left":t}handleVerticalArrow(e){const t=this.deps.getState(),n=this.deps.contentElement.ownerDocument.getSelection?.()??null,s=n?rt(n,this.deps.contentElement):null;if(!Qe(this.deps.contentElement,t,e,s))return!1;null===this.goalColumn&&s&&(this.goalColumn=s.left),this.preserveGoalColumn=!0;const r=tt(this.deps.contentElement,t,e,this.goalColumn);return r?(this.deps.dispatch(r),this.preserveGoalColumn=!1,!0):(this.preserveGoalColumn=!1,!1)}validateSelectionAfterInlineSkip(){const e=this.deps.getState(),t=wn(this.deps.contentElement);t&&se(t,e.selection)||vn(this.deps.contentElement,e.selection)}};function Li(e,t,n){if(!t)return;const s=/* @__PURE__ */new Set,r=n?.includeRoot??!0,i=(e,o)=>{for(const t of a(e))i(t,!1);if(o&&!r)return;const l=t.get(e.id);l&&(n?.ownerDOM&&l.dom!==n.ownerDOM&&!n.ownerDOM.contains(l.dom)||(Hi(t,l),s.has(l)||(s.add(l),l.destroy?.())))};i(e,!0)}function Hi(e,t){for(const[n,s]of e)s===t&&e.delete(n)}function zi(e,t){const n=[];let s=null,r=[];for(const i of e){const e=t.getNodeSpec(i.type)?.wrapper?.(i);e&&s&&e.key===s.key?r.push(i.id):e?(s&&r.length>0&&n.push({spec:s,blockIds:r}),s=e,r=[i.id]):(s&&r.length>0&&n.push({spec:s,blockIds:r}),s=null,r=[])}return s&&r.length>0&&n.push({spec:s,blockIds:r}),n}function Fi(e,t){if(t.className&&e.className!==t.className&&(e.className=t.className),t.attrs)for(const[n,s]of Object.entries(t.attrs))e.getAttribute(n)!==s&&e.setAttribute(n,s)}function ji(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,s]of Object.entries(e.attrs))t.setAttribute(n,s);return t}function $i(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 _i(e,t,n){for(let r=0;r<t.length;r++){const s=t[r];if(!s)continue;const i=n.querySelector(`[data-block-id="${s}"]`);if(!i)continue;const o=e.children[r]??null;i!==o&&(o?e.insertBefore(i,o):e.appendChild(i))}const s=new Set(t);for(const r of Array.from(e.children)){const t=r.getAttribute("data-block-id");t&&!s.has(t)&&n.insertBefore(r,e)}}function Ki(e,t,n){if(!n)return;const s=zi(t,n);for(const r of s){const t=e.querySelector(`[data-block-id="${r.blockIds[0]}"]`);if(!t)continue;const n=ji(r.spec);t.before(n);for(const s of r.blockIds){const t=e.querySelector(`[data-block-id="${s}"]`);t&&n.appendChild(t)}}}function Vi(e){e.parentElement?.removeChild(e)}function Wi(e,t,n){const s=e.parentElement;s?s.replaceChild(t,e):n.replaceChild(t,e)}function qi(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 Ui(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 Gi(e){let t=e.replace(/ {2}/g,"  ");return t.endsWith(" ")&&(t=`${t.slice(0,-1)} `),t.startsWith(" ")&&(t=` ${t.slice(1)}`),t}var Ji=/* @__PURE__ */new WeakMap;function Qi(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"),s=n.getAttribute("data-widget-key");if(null===e||null===s)continue;const r=me(e),i=t.get(r)??/* @__PURE__ */new Map,o=i.get(s)??[];o.push(n),i.set(s,o),t.set(r,i)}return t}function Xi(e,t,n,s){let r;if(void 0!==e.key&&(r=function(e,t,n){if(!e||void 0===t)return;const s=e.get(t),r=s?.get(n),i=r?.shift();return 0===r?.length&&s?.delete(n),0===s?.size&&e.delete(t),i}(s?.pool,s?.blockId,e.key),!r)){const t=n.get(e.key);r=t?.shift(),0===t?.length&&n.delete(e.key)}return r??=function(e,t=er.silent){const n=Vt(e)??{pluginId:"unattributed",name:"widget"},s=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(s.ok)return s.value;const r=document.createElement("span");return r.setAttribute("data-widget-render-fallback","true"),r}(e,s?.callbackExecutor),r.setAttribute("data-widget","true"),r.setAttribute("data-decoration-widget","true"),r.setAttribute("data-widget-offset",String(t)),r.setAttribute("data-widget-side",String(e.side)),r.setAttribute("contenteditable","false"),void 0===e.key?r.removeAttribute("data-widget-key"):r.setAttribute("data-widget-key",e.key),s&&r.setAttribute("data-widget-block-id",s.blockId),r}function Yi(e){const t=e.nodeName??"span",n=document.createElement(t);if(n.setAttribute("data-decoration","true"),e.class)for(const s of e.class.split(" "))s&&n.classList.add(s);e.style&&tn(n,e.style);for(const[s,r]of Object.entries(e))"class"!==s&&"style"!==s&&"nodeName"!==s&&void 0!==r&&n.setAttribute(s,r);return n}function Zi(e,t,n){eo(e,t,n)}function eo(e,t,n){const s=n?.decorations?.findNode(t)??[],r=Ji.get(e);if(r&&_t(r.decorations,s))return;no(e,r);const i=/* @__PURE__ */new Set,o=/* @__PURE__ */new Map;for(const d of s){for(const e of d.attrs.class?.split(/\s+/)??[])e&&i.add(e);for(const[e,t]of so(d.attrs.style??""))o.set(e,t)}if(0===i.size&&0===o.size)return void Ji.delete(e);const a=/* @__PURE__ */new Set;for(const d of i)e.classList.contains(d)?a.add(d):e.classList.add(d);const l=so(nn(e)),c=/* @__PURE__ */new Map;for(const[d,h]of o)c.set(d,l.get(d)??null),l.set(d,h);o.size>0&&tn(e,io(l)),Ji.set(e,{decorations:[...s],managed:i,preexisting:a,previousStyles:c})}function to(e){no(e,Ji.get(e)),Ji.delete(e)}function no(e,t){if(!t)return;for(const s of t.managed)t.preexisting.has(s)||e.classList.remove(s);if(0===t.previousStyles.size)return;const n=so(nn(e));for(const[s,r]of t.previousStyles)null===r?n.delete(s):n.set(s,r);tn(e,io(n))}function so(e){const t=/* @__PURE__ */new Map;for(const n of e.split(";")){const e=n.trim();if(!e)continue;const s=e.indexOf(":");if(s<=0)continue;const r=ro(e.slice(0,s)),i=e.slice(s+1).trim();r&&i&&t.set(r,i)}return t}function ro(e){const t=e.trim();return t.startsWith("--")?t:t.includes("-")?t.toLowerCase():t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`).toLowerCase()}function io(e){return[...e.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}: ${t}`).join("; ")}var oo=/* @__PURE__ */new WeakSet;function ao(e,t){if(e instanceof HTMLElement)return e;throw new TypeError(`${t} must be an HTMLElement.`)}var lo=/* @__PURE__ */new WeakMap;function co(e,t,n,s){const r=s?.decorations?.findInline(e.id),o=s?.decorations?.findWidget(e.id),a=s?.nodeViewRegistry;if(a&&t&&n&&s?.getState&&s?.dispatch){const l=a.getNodeViewEntry(e.type);if(l){const a=function(e,t,n,s,r=er.silent){const i=r.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 s=ao(t.dom,`${e.name}.dom`),r=t.contentDOM;if(null!==r&&!(r instanceof HTMLElement))throw new TypeError(`${e.name}.contentDOM must be an HTMLElement or null.`);const i=r,o=t.getContentDOM,a=t.update,l=t.destroy,c=t.selectNode,d=t.deselectNode;return{dom:s,contentDOM:i,...o?{getContentDOM(s){const r=n.execute({pluginId:e.pluginId,name:`${e.name}:getContentDOM`,kind:"node-view"},()=>{const n=o.call(t,s);return null===n?null:ao(n,`${e.name}.getContentDOM`)});return r.ok?r.value:null}}:{},...a?{update(s){const r=n.execute({pluginId:e.pluginId,name:`${e.name}:update`,kind:"node-view"},()=>{const n=a.call(t,s);if("boolean"!=typeof n)throw new TypeError(`${e.name}.update must return a boolean.`);return n});return!!r.ok&&r.value}}:{},...l?{destroy(){oo.has(t)||(oo.add(t),n.execute({pluginId:e.pluginId,name:`${e.name}:destroy`,kind:"node-view"},()=>l.call(t)))}}:{},...c?{selectNode(){n.execute({pluginId:e.pluginId,name:`${e.name}:selectNode`,kind:"node-view"},()=>c.call(t)).ok||s.classList.add("notectl-node-selected")}}:{},...d?{deselectNode(){n.execute({pluginId:e.pluginId,name:`${e.name}:deselectNode`,kind:"node-view"},()=>d.call(t)).ok||s.classList.remove("notectl-node-selected")}}:{}}}(e,e.factory(t,n,s),r));return i.ok?i.value:null}(l,e,s.getState,s.dispatch,s.callbackExecutor);if(!a)return ho(e,t,n,s);const c=t.getNodeSpec(e.type);return c?.isVoid&&a.dom.setAttribute("data-void","true"),c?.selectable&&a.dom.setAttribute("data-selectable","true"),a.contentDOM&&a.contentDOM!==a.dom&&a.contentDOM.setAttribute("data-content-dom","true"),i(e)&&a.contentDOM?po(a.contentDOM,e,t,r,o,s?.widgetDOMPool,s?.callbackExecutor):yo(e,e=>a.getContentDOM?.(e.id)??a.contentDOM,t,n,s),uo(a.dom,e),a.dom.setAttribute("data-block-type",e.type),Zi(a.dom,e.id,s),function(e,t,n){const s=e.get(t);s&&s!==n&&(Hi(e,s),s.destroy?.()),e.set(t,n)}(n,e.id,a),a.dom}}return ho(e,t,n,s)}function ho(e,t,n,s){const r=s?.decorations?.findInline(e.id),o=s?.decorations?.findWidget(e.id);if(t){const a=t.getNodeSpec(e.type);if(a){const l=a.toDOM(e);return a.isVoid&&l.setAttribute("data-void","true"),a.selectable&&l.setAttribute("data-selectable","true"),a.isVoid||(i(e)?po(l,e,t,r,o,s?.widgetDOMPool,s?.callbackExecutor):yo(e,()=>l,t,n,s)),uo(l,e),l.setAttribute("data-block-type",e.type),Zi(l,e.id,s),l}}return function(e,t,n,s,r,i){const o=hn("p",e.id);return uo(o,e),o.setAttribute("data-block-type",e.type),po(o,e,t,n,s,r,i),o}(e,t,r,o,s?.widgetDOMPool,s?.callbackExecutor)}function uo(e,n,s){const r=t(n.htmlId);if(r)return void e.setAttribute("id",r);const i=t(s?.htmlId);i&&e.getAttribute("id")===i&&e.removeAttribute("id")}function po(e,t,n,s,r,i,o){const a=[...s??[],...r??[]];(function(e,t,n,s,r=[],i){const o=t.reduce((e,t)=>e+(q(t)?1:t.text.length),0),a=function(e,t){const n=/* @__PURE__ */new Map;for(let r=0;r<e.length;r++){const s=e[r];if(!s)continue;const i=Number.isFinite(s.offset)?s.offset:0,o=Math.max(0,Math.min(t,Math.trunc(i))),a=n.get(o)??[];a.push({decoration:s,index:r}),n.set(o,a)}const s=/* @__PURE__ */new Map;for(const[r,i]of n)i.sort((e,t)=>e.decoration.side-t.decoration.side||e.index-t.index),s.set(r,i.map(e=>e.decoration));return s}(r,o),l=i?.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 s=t.get(e)??[];s.push(n),t.set(e,s)}return t}(e);e.replaceChildren();const c=t=>{const n=a.get(t);if(n)for(const s of n)e.appendChild(Xi(s,t,l,i))};if(1===t.length&&!q(t[0])&&""===t[0]?.text)return c(0),void e.appendChild(document.createElement("br"));let d=0;for(const u of t){if(q(u)){c(d),e.appendChild(Ei(Ui(u,s),u.marks,s)),d+=1;continue}const t=d,r=d+u.text.length;if(0===u.text.length){d=r;continue}const i=/* @__PURE__ */new Set;i.add(t),i.add(r);for(const e of n){const n=Math.max(t,e.from),s=Math.min(r,e.to);n>t&&n<r&&i.add(n),s>t&&s<r&&i.add(s)}for(const e of a.keys())e>t&&e<r&&i.add(e);const o=[...i].sort((e,t)=>e-t);for(let a=0;a<o.length-1;a++){const r=o[a],i=o[a+1];if(void 0===r||void 0===i||r>=i)continue;c(r);const l=r-t,d=i-t,h=u.text.slice(l,d),p=[];for(const e of n)e.from<=r&&e.to>=i&&p.push(e);let m=Ei(document.createTextNode(Gi(h)),u.marks,s);for(const e of p){const t=Yi(e.attrs);t.appendChild(m),m=t}e.appendChild(m)}d=r}c(o);const h=t[t.length-1];h&&q(h)&&"hard_break"===h.inlineType&&e.appendChild(document.createElement("br"))})(e,f(t),s??[],n,r??[],{blockId:t.id,pool:i,callbackExecutor:o}),lo.set(e,a)}function mo(e,t,n,s,r,i){const o=[...s,...r],a=lo.get(e);a&&_t(a,o)||po(e,t,n,s,r,void 0,i)}function fo(e,t){const n=/* @__PURE__ */new Set;e.contentDOM&&n.add(e.contentDOM);for(const s of a(t)){const t=e.getContentDOM?.(s.id);t&&n.add(t)}return[...n]}function go(e,t,n,s,r,i){const o=/* @__PURE__ */new Set([...n,...fo(e,t)]);for(const a of o)a.replaceChildren();yo(t,t=>e.getContentDOM?.(t.id)??e.contentDOM,s,r,i)}function yo(e,t,n,s,r){const i=/* @__PURE__ */new Map;for(const o of a(e)){const e=t(o);if(!e)continue;e.appendChild(co(o,n,s,r));const a=i.get(e)??[];a.push(o),i.set(e,a)}for(const[o,a]of i)Ki(o,a,n)}function ko(e,t,n,s){const r=t?.doc.children??[],o=n.doc.children,a=s?.registry,l=s?.nodeViews,c={...s,widgetDOMPool:Qi(e)},d=/* @__PURE__ */new Map;for(const i of r)d.set(i.id,i);const h=null!=s?.compositionBlockId,u=function(e,t,n){if(!n||!e)return;const s=t.getNodePath(n)?.[0];return void 0!==s&&s===e.getNodePath(n)?.[0]?s:void 0}(t,n,s?.compositionBlockId),p=/* @__PURE__ */new Map;for(const i 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=i.getAttribute("data-block-id");e&&p.set(me(e),i)}const m=new Set(o.map(e=>e.id));for(const[i,k]of p)if(!m.has(i)){const e=d.get(i);e?Li(e,l,{ownerDOM:k}):((l?.get(i))?.destroy?.(),l?.delete(i)),Vi(k),p.delete(i)}let f=null;const g=s?.selectedNodeId,y=s?.previousSelectedNodeId;for(const k of o){const t=p.get(k.id),n=d.get(k.id);if(u===k.id&&t)f=t;else{if(t&&n&&!bo(n,k))f=t;else if(t){const r=l?.get(k.id);let o=!1;if(r&&n){const e=fo(r,n);if(to(r.dom),r.update?.(k)){uo(r.dom,k,n);const d=vo(n,k);if(d&&Li(n,l,{includeRoot:!1,ownerDOM:t}),i(k)&&r.contentDOM){if(!i(n))for(const n of e)n.replaceChildren();const t=s?.decorations?.findInline(k.id),o=s?.decorations?.findWidget(k.id);po(r.contentDOM,k,a,t,o,c.widgetDOMPool,c.callbackExecutor)}else d&&go(r,k,e,a,l,c);f=r.dom,o=!0}}if(!o){n?Li(n,l,{ownerDOM:t}):r&&(r.destroy?.(),l?.delete(k.id));const s=co(k,a,l,c);Wi(t,s,e),f=s}}else{const t=co(k,a,l,c);qi(e,f,t),f=t}if(g===k.id){const e=l?.get(k.id);if(e)e.selectNode?.();else{const e=p.get(k.id)??f;e instanceof HTMLElement&&e.classList.add("notectl-node-selected")}}else if(y===k.id){const e=l?.get(k.id);if(e)e.deselectNode?.();else{const e=p.get(k.id)??f;e instanceof HTMLElement&&e.classList.remove("notectl-node-selected")}}}}if(y&&y!==g){const e=l?.get(y);e&&!m.has(y)&&e.deselectNode?.()}if(g&&!m.has(g)){const e=l?.get(g);e&&e.selectNode?.()}!h&&a&&function(e,t,n){const s=zi(t,n),r=function(e,t){const n=[],s=/* @__PURE__ */new Set;for(const i of t)for(const e of i.blockIds)s.add(e);let r=0;for(const i of e){if(!s.has(i.id)){n.push({type:"bare",blockId:i.id});continue}const e=t[r];e&&e.blockIds[0]===i.id&&(n.push({type:"wrapper",key:e.spec.key,blockIds:e.blockIds}),r++)}return n}(t,s),i=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")??"",s=[];for(const t of Array.from(n.children)){if(!(t instanceof HTMLElement))continue;const e=t.getAttribute("data-block-id");e&&s.push(me(e))}t.push({type:"wrapper",element:n,key:e,blockIds:s})}else if(n.hasAttribute("data-block-id")){const e=n.getAttribute("data-block-id")??"";t.push({type:"bare",element:n,blockId:me(e)})}return t}(e);if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(!s||!r)return!1;if(s.type!==r.type)return!1;if("bare"===s.type&&"bare"===r.type){if(s.blockId!==r.blockId)return!1}else if("wrapper"===s.type&&"wrapper"===r.type){if(s.key!==r.key)return!1;if(s.blockIds.length!==r.blockIds.length)return!1;for(let e=0;e<s.blockIds.length;e++)if(s.blockIds[e]!==r.blockIds[e])return!1}}return!0}(r,i)){let e=0;for(const t of i)if("wrapper"===t.type){const n=s[e];n&&Fi(t.element,n.spec),e++}return}const o=/* @__PURE__ */new Map;for(const d of i){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 l=null,c=0;for(const d of r){if("bare"===d.type){const t=e.querySelector(`[data-block-id="${d.blockId}"]`);if(!t)continue;t.parentNode!==e?l?l.after(t):e.insertBefore(t,e.firstChild):$i(e,t,l),l=t;continue}const t=s[c];if(!t)continue;c++;const n=o.get(d.key);let r=null;if(n&&n.length>0){const e=n.shift();e&&(r=e.tagName.toLowerCase()===t.spec.tag?e:ji(t.spec))}r||(r=ji(t.spec)),a.add(r),Fi(r,t.spec),r.parentNode!==e?l?l.after(r):e.insertBefore(r,e.firstChild):$i(e,r,l),_i(r,d.blockIds,e),l=r}for(const d of i)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=me(e);eo(k,t,s);const r=n.getBlock(t);if(!r||!i(r))continue;if(s?.compositionBlockId===t)continue;const o=wo(k,r,a,l);o&&mo(o,r,a,s?.decorations?.findInline(t)??[],s?.decorations?.findWidget(t)??[],s?.callbackExecutor)}}function wo(e,t,n,s){const r=s?.get(t.id);return r?r.contentDOM:n?.getNodeSpec(t.type)?.isVoid?null:e}function bo(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)||vo(e,t)}function vo(e,t){if(e.children.length!==t.children.length)return!0;for(let n=0;n<e.children.length;n++){const s=e.children[n],r=t.children[n];if(!s||!r)return!0;if(Io(s,r))return!0}return!1}function Io(e,t){return b(e)&&b(t)?e.text!==t.text||!d(e.marks,t.marks):q(e)&&q(t)?e.inlineType!==t.inlineType||!function(e,t){const n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return!1;for(const r of n)if(e[r]!==t[r])return!1;return!0}(e.attrs,t.attrs)||!d(e.marks,t.marks):!!(b(e)||b(t)||q(e)||q(t))||bo(e,t)}function So(e,t){const n=e.querySelector(`[data-block-id="${t}"]`);return n?fn(n):null}function*xo(e){const t=yn(e,{includeCursorWrapper:!0});for(let n=t.nextNode();n;n=t.nextNode())yield{node:n,data:n.nodeType===Node.TEXT_NODE?n.textContent??"":"",inWrapper:Mo(n,e)}}function Ro(e){return e.inWrapper?e.data.replaceAll("​",""):e.data}function Mo(e,t){for(let n=e.parentElement;n&&n!==t;n=n.parentElement)if(Sn(n))return!0;return!1}var Co=class{state;contentElement;history;stateChangeCallbacks=[];isUpdating=!1;schemaRegistry;nodeViewRegistry;callbackExecutor;nodeViews=/* @__PURE__ */new Map;decorations=qt.empty;compositionOrigins;compositionContainer;getDecorations;isReadOnly;isReadonlyBypassed;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??er.silent,this.getDecorations=t.getDecorations,this.isReadOnly=t.isReadOnly??(()=>!1),this.isReadonlyBypassed=t.isReadonlyBypassed??(()=>!1),this.compositionState=t.compositionState??{isComposing:!1,activeBlockId:null},this.history=new Ii({maxDepth:t.maxHistoryDepth??100}),t.onStateChange&&this.stateChangeCallbacks.push(t.onStateChange),this.cursorWrapper=new Bi(e,this.schemaRegistry),this.navigation=new Di({contentElement:e,getState:()=>this.state,dispatch:e=>this.dispatch(e),keymapRegistry:t.keymapRegistry}),this.events=new Ni({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)??qt.empty,ko(e,null,this.state,{...this.reconcileOptions(),decorations:this.decorations}),vn(e,this.state.selection)}getState(){return this.state}applyUpdate(e,t,n){if(!this.isUpdating){this.isUpdating=!0;try{const s=this.state,r=Zr(t,s.doc);this.state=e,this.events.onStateChange(s,e,r),this.cursorWrapper.isActive&&!e.storedMarks?.length&&this.cursorWrapper.cleanup(),(n?.pushHistory&&"history"!==r.metadata.origin||Mi(r))&&this.history.push(r);const i=this.getDecorations?.(e,r)??qt.empty;this.reconcileAndSync(s,e,i,n?.skipSelectionSync);for(const t of this.stateChangeCallbacks)t(s,e,r);this.navigation.resetAfterUpdate()}finally{this.isUpdating=!1}}}dispatch(e){const t=Zr(e,this.state.doc);if(this.isReadOnly()&&!Ci(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 s=fs({steps:[],selectionBefore:t.selection,selectionAfter:n.selection,storedMarksAfter:n.storedMarks,forwardStepMaps:[],metadata:{origin:"api",timestamp:Date.now()}});this.events.onStateChange(t,n,s);const r=this.getDecorations?.(n,s)??qt.empty;this.reconcileAndSync(t,n,r);for(const e of this.stateChangeCallbacks)e(t,n,s);this.navigation.resetAfterUpdate()}finally{this.isUpdating=!1}}}syncSelection(){this.events.syncSelectionFromDOM()}resolveDOMRange(e){return kn(this.contentElement,e)}captureCompositionBlock(e){this.compositionOrigins=function(e,t){const n=/* @__PURE__ */new WeakMap,s=So(e,t);if(!s)return n;let r=0;for(const i of xo(s))i.node instanceof Element&&n.set(i.node,r),r+=Ro(i).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 s=So(e,t);return s?function(e,t,n){let s="",r=t?0:null;const i=n?/* @__PURE__ */new Map:void 0;for(const o of xo(e)){const{node:e,data:a}=o;if(t?.isPointInRange(e,0)){const n=t.endContainer===e?a.slice(0,t.endOffset):a;r=s.length+Ro({...o,data:n}).length}e instanceof Element&&i?.set(s.length,n?.get(e)??null),s+=Ro(o)}return i?{text:s,caretOffset:r,inlineNodeOrigins:i}:{text:s,caretOffset:r}}(s,function(e,t){const n=bn(),s=n&&pn(e,n);if(!s)return null;const{anchorNode:r,anchorOffset:i,focusNode:o,focusOffset:a}=s;if(r!==o||i!==a||!t.contains(r))return null;const l=document.createRange();return l.setStart(t,0),l.setEnd(r,i),l}(e,s),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,s){const r=n.getBlock(t.id),i=e.querySelector(`[data-block-id="${t.id}"]`);r&&i&&(Li(t,s.nodeViews,{ownerDOM:i}),Wi(i,co(r,s.registry,s.nodeViews,{...s,widgetDOMPool:Qi(e)}),e))}(this.contentElement,n,this.state,t):function(e,t,n,s){const r=t.getBlock(n);if(!r||!i(r))return;const o=e.querySelector(`[data-block-id="${n}"]`);if(!o)return;const a=wo(o,r,s.registry,s.nodeViews);a&&po(a,r,s.registry,s.decorations?.findInline(n),s.decorations?.findWidget(n),void 0,s.callbackExecutor)}(this.contentElement,this.state,e,t),this.compositionState.isComposing||vn(this.contentElement,this.state.selection)}reconcileAndSync(e,t,n,s){const r=this.decorations;this.decorations=n,ko(this.contentElement,e,t,{...this.reconcileOptions(e.selection),decorations:n,oldDecorations:r,compositionBlockId:this.compositionState.isComposing?this.compositionState.activeBlockId??void 0:void 0}),this.compositionState.isComposing||s||vn(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)}},Po={paragraph:"Paragraph",heading:"Heading",code_block:"Code Block",blockquote:"Block Quote",list_item:"List Item",horizontal_rule:"Horizontal Rule",image:"Image",table:"Table"};function Eo(e,t){return"heading"===e&&t?.level?`Heading ${t.level}`:Po[e]??e}function To(e){e.registerNodeSpec({type:"paragraph",group:"block",content:{allow:["text"]},toDOM:e=>hn("p",e.id),toHTML:(e,t)=>`<p>${t||"<br>"}</p>`,parseHTML:[{tag:"p"},{tag:"div",priority:10}],sanitize:{tags:["p"]}})}var Bo={ariaLabel:"Rich text editor",ariaDescription:"Press Escape to exit the editor",defaultPlaceholder:"Start typing...",markdownImported:"Markdown imported"},Ao=/* #__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/pt.ts":()=>import("./pt-CFrcl1v_.mjs"),"./locales/ru.ts":()=>import("./ru-gxbzqLL8.mjs"),"./locales/zh.ts":()=>import("./zh-BFZOM3lF.mjs")}),Oo=['@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"),No=null,Do=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=gt(this.getSystemTheme());this.setThemeStyleSheet(e)}else this.setThemeStyleSheet(gt(e))}setPluginStyleSheets(e){this.pluginSheets=e,this.refreshAdoptedStyleSheets()}setRuntimeStyleSheets(e){this.runtimeSheets=e,this.refreshAdoptedStyleSheets()}destroy(){this.cleanupSystemThemeListener()}setThemeStyleSheet(e){this.themeStyleSheet.replaceSync(mt(e)),this.refreshAdoptedStyleSheets()}refreshAdoptedStyleSheets(){this.shadow.adoptedStyleSheets=[this.themeStyleSheet,(No||(No=new CSSStyleSheet).replaceSync(Oo),No),...this.pluginSheets,...this.runtimeSheets]}setupSystemThemeListener(){this.systemThemeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.systemThemeHandler=e=>{const t=gt(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}},Lo=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=ut(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&&(en(this.surface,"width",`${this.currentPaperWidthPx}px`),en(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,en(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 en(this.surface,"marginBottom","");const t=this.surface.scrollHeight,n=t*e-t;en(this.surface,"marginBottom",`${n}px`)}};function Ho(e){return!Array.isArray(e)}function zo(e){if(Array.isArray(e))return{plugins:e,label:void 0};const t=e;return{plugins:t.plugins,label:t.label}}var Fo=class{deps;cfg;themeController=null;styleLease=null;domElements=null;paperLayout=null;pluginManager=null;inputManager=null;view=null;locale=Bo;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 Jt(e.locale??"browser").getLocale();return"en"===t?Bo:await async function(e){return Gt(Ao,e,Bo)}(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 Do(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??Bo,n=t.defaultPlaceholder,s=document.createElement("div");s.className="notectl-editor",s.setAttribute("part","editor");const r=document.createElement("div");r.className="notectl-plugin-container--top",r.setAttribute("part","plugin-container plugin-container-top"),r.setAttribute("data-notectl-no-print","");const i=document.createElement("div");i.className="notectl-content",i.setAttribute("part","content"),i.contentEditable=e.readonly?"false":"true",i.setAttribute("role","textbox"),i.setAttribute("aria-multiline","true"),i.setAttribute("aria-label",t.ariaLabel),e.readonly&&i.setAttribute("aria-readonly","true"),i.setAttribute("aria-description",t.ariaDescription),i.setAttribute("data-default-placeholder",n),i.setAttribute("data-placeholder",e.placeholder??n),e.dir&&(s.setAttribute("dir",e.dir),i.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"),s.appendChild(r),s.appendChild(i),s.appendChild(o),s.appendChild(a),{wrapper:s,content:i,topPluginContainer:r,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 Lo(this.domElements.wrapper,this.domElements.content),this.paperLayout.apply(this.cfg.paperSize))}setupPlugins(){if(this.domElements){this.pluginManager=new bi({logger:this.cfg.logger}),this.pluginManager.registerService(Qt,new Jt(this.cfg.locale??"browser")),To(this.pluginManager.schemaRegistry),function(e,t){if(!t)return;const n=Ho(t)?t.groups:t,s=Ho(t)?t.overflow:void 0,r=[];for(const o of n){const{plugins:t,label:n}=zo(o),s=[];for(const r of t)s.push(r.id),e.register(r);r.push(void 0!==n?{plugins:s,label:n}:s)}const i={groups:r,overflow:s};e.register(new dn(i))}(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 Mn(n))}(e,t),function(e){void 0===e.get("caret-navigation")&&e.register(new it)}(e),function(e){void 0===e.get("gap-cursor")&&e.register(new Rn)}(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||jo},onBeforeReady:()=>this.createInputAndView(e,t,n)})}createInputAndView(e,t,n){if(this.isCancelled()||!this.pluginManager||!this.themeController)return;const s=fe(t.schemaRegistry),r=As.create({schema:s}),i=this.deps.configController.markdownShorthand;this.inputManager=new Gr(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:()=>i,getPasteInterceptors:()=>t.getPasteInterceptors(),pasteMarkdown:this.deps.configController.pasteMarkdown,getMarkdownSyntaxExtensions:()=>t.markdownSyntaxRegistry.getExtensions(),getTextInputInterceptors:()=>t.getTextInputInterceptors(),getTextDirection:on,navigateFromGapCursor:xn,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 Co(e.content,{state:r,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)??qt.empty,onStateChange:(n,s,r)=>{this.inputManager?.onStateChange(n,s,r),function(e,t,n,s,r,i){const o=s.announcer;if(o&&(o.textContent=""),r.notifyStateChange(e,t,n),$o(s.content,t.doc),i.emit("stateChange",{oldState:e,newState:t,transaction:n}),se(e.selection,t.selection)||i.emit("selectionChange",{selection:t.selection}),!o?.textContent){const s=function(e,t,n){if("undo"===n.metadata.historyDirection)return"Undo";if("redo"===n.metadata.historyDirection)return"Redo";for(const s of n.steps)if("setBlockType"===s.type)return Eo(s.nodeType,s.attrs);for(const s of t.schema.markTypes){const n=ue(s),r=Je(e,n),i=Je(t,n);if(r!==i)return`${s} ${i?"on":"off"}`}return null}(e,t,n);s&&o&&(o.textContent=s)}}(n,s,r,e,t,this.deps.events)},isReadOnly:()=>this.deps.configController.isReadOnly,isReadonlyBypassed:()=>t.isReadonlyBypassed(),compositionState:this.inputManager.compositionTracker}),$o(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(pt,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,s=this.domElements,r=this.themeController,i=this.styleLease;if(!(e&&t&&n&&s&&r&&i))throw new Error("Cannot release an incomplete editor initialization session.");return{view:e,pluginManager:n,domElements:s,themeController:r,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}},jo={isComposing:!1,activeBlockId:null};function $o(e,t){e.classList.toggle("notectl-content--empty",Fs(t))}var _o=class extends Error{constructor(){super("Editor initialization was aborted because the editor was destroyed."),this.name="AbortError"}},Ko=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 _o),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}},Vo=class{runtimeStyleSheet=null;activeLease=null;setup(e,t,n){this.activeLease?this.release(this.activeLease):rn(e),this.runtimeStyleSheet=sn();const s={id:Symbol("notectl-style-lease"),shadow:e,themeController:n};return this.activeLease=s,n?.setRuntimeStyleSheets(this.runtimeStyleSheet?[this.runtimeStyleSheet]:[]),Zt(e,{nonce:t,sheet:this.runtimeStyleSheet}),s}teardown(e){e&&this.activeLease===e&&this.release(e)}release(e){rn(e.shadow),this.runtimeStyleSheet=null,e.themeController?.setRuntimeStyleSheets([]),this.activeLease===e&&(this.activeLease=null)}},Wo=class extends HTMLElement{view=null;pluginManager=null;domElements=null;configController=new Ks;events=new Gs;lifecycle=new Ko;styleCoordinator=new Vo;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(){lt(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(lt(this))throw yt();this.cancelAutoInit();const t=this.destroyVersion,n=this.pendingDestroyPromise;if(n&&(await n,t!==this.destroyVersion))throw new _o;const s=this.pendingInitPromise;if(s){if(await s,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 r;e&&this.configController.setConfig(e),this.events.setLogger(this.configController.getConfig().logger);try{r=this.ensureFreshShadowRoot()}catch(d){throw this.lifecycle.failReady(d),d}const i=++this.initVersion;let o=!1;this.cancelPendingInit=()=>{o=!0};const a=this.lifecycle.consumePreInitPlugins(),l=async function(e){return new Fo(e).run()}({shadow:r,config:this.configController.getConfig(),hostDir:this.getAttribute("dir")??void 0,configController:this.configController,styleCoordinator:this.styleCoordinator,events:this.events,preInitPlugins:a,isCancelled:()=>o||i!==this.initVersion}),c=this.completeInitialization(l,i,()=>o||i!==this.initVersion,a);this.pendingInitPromise=c;try{await c}finally{this.pendingInitPromise===c&&(this.pendingInitPromise=null,this.cancelPendingInit=null)}}async completeInitialization(e,t,n,s){let r=null;try{const s=await e;if(!s){if(n())throw new _o;throw new Error("Editor initialization completed without a result.")}if(t!==this.initVersion)throw await s.dispose(),new _o;if(this.activeInitResult=s,r=s,this.view=s.view,this.pluginManager=s.pluginManager,this.domElements=s.domElements,this.themeController=s.themeController,this.paperLayout=s.paperLayout,this.announce=s.announce,this.markdownImportedMessage=s.markdownImportedMessage,this.lifecycle.resolveReady(),this.events.emit("ready",void 0),t!==this.initVersion)throw new _o}catch(i){throw r&&this.activeInitResult===r&&(this.activeInitResult=null,this.clearPublishedRuntime(),await r.dispose()),t===this.initVersion&&(this.lifecycle.restorePreInitPlugins(s),this.lifecycle.failReady(i)),i}}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(),Os(e,this.pluginManager?.schemaRegistry,e=>this.replaceState(e))}async getContentHTML(t){if(!this.view)throw new Error("Editor not initialized");return function(t,n,s){const r=t.doc;if("classes"===s?.cssMode){const t=It(r,n,s);return s.pretty?{html:e(t.html),css:t.css,styleMap:t.styleMap}:t}const i=vt(r,n,s);return s?.pretty?e(i):i}(this.view.getState(),this.pluginManager?.schemaRegistry,t)}async setContentHTML(e,t){return this.assertInitialized(),function(e,t,n,s){Os(Nt(e,t,s),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:s}=await import("./MarkdownSerializer-CdUBWWGI.mjs").then(e=>e.t);return s(e.doc,t,n)}(this.view.getState(),this.pluginManager?.schemaRegistry,e)}async setContentMarkdown(e,t){this.assertInitialized();const n=this.view,s=this.pluginManager,r=this.announce,i=this.markdownImportedMessage;if(!n)return;const o=this.initVersion,a=s?.markdownSyntaxRegistry.getExtensions(),l={...t,syntaxExtensions:t?.syntaxExtensions??a};let c=!1;await async function(e,t,n,s,r){const{parseMarkdownToDocument:i}=await import("./MarkdownParser-CvYOvU3d.mjs").then(e=>e.t),o=i(e,n,r),a=t.doc.children.map(e=>e.id);Os({children:o.children.map((e,t)=>{const n=a[t];return n?L(e.type,e.children,n,e.attrs,e.htmlId):e})},n,s)}(e,n.getState(),s?.schemaRegistry,e=>{o===this.initVersion&&this.view===n&&this.pluginManager===s&&(n.replaceState(e),c=!0)},l),c&&o===this.initVersion&&this.view===n&&this.pluginManager===s&&this.announce===r&&r?.(i)}getText(){if(!this.view)throw new Error("Editor not initialized");return Hs(this.view.getState())}setText(e){this.assertInitialized(),this.view&&function(e,t,n,s){if(e===Hs(t))return;const r=e.split("\n"),i=t.doc.children.map(e=>e.id),o=r.map((e,t)=>L(he("paragraph"),[I(e)],i[t])),a=n?fe(n):void 0;s(As.create({doc:{children:o},schema:a}))}(e,this.view.getState(),this.pluginManager?.schemaRegistry,e=>this.replaceState(e))}isEmpty(){return!this.view||Fs(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=qe(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 lt(this)?Promise.reject(yt()):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 Lo(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 qo(e){const t=document.createElement("notectl-editor");return await t.init(e),t}function Uo(){"undefined"==typeof customElements||customElements.get("notectl-editor")||customElements.define("notectl-editor",Wo)}Uo();export{Ms as A,Vs as C,Ts as D,As as E,Pn as M,En as N,Rs as O,Qs as S,Ws as T,Gr as _,To as a,fr as b,Ci as c,bi as d,ni as f,Jr as g,Qr as h,_o as i,Es as j,Cs as k,Mi as l,Xr as m,Wo as n,Eo as o,ei as p,qo as r,Bi as s,Uo as t,Ii as u,vr as v,qs as w,Xs as x,Ir as y};
3
+ //# sourceMappingURL=register-Cb1YTAN4.mjs.map