@notectl/core 2.0.0 → 2.0.1

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 (292) hide show
  1. package/dist/chunks/{AttrRegistry-B2AGfTE0.mjs → AttrRegistry-Ckj9eCHj.mjs} +2 -2
  2. package/dist/chunks/{AttrRegistry-B2AGfTE0.mjs.map → AttrRegistry-Ckj9eCHj.mjs.map} +1 -1
  3. package/dist/chunks/AttributedMarkCommands-x7h4Xy7V.mjs +2 -0
  4. package/dist/chunks/AttributedMarkCommands-x7h4Xy7V.mjs.map +1 -0
  5. package/dist/chunks/BlockInsertion-zPxm6oa_.mjs +2 -0
  6. package/dist/chunks/BlockInsertion-zPxm6oa_.mjs.map +1 -0
  7. package/dist/chunks/{ColorPickerPopup-DRzFvt7o.mjs → ColorPickerPopup-CDUvkgcK.mjs} +2 -2
  8. package/dist/chunks/ColorPickerPopup-CDUvkgcK.mjs.map +1 -0
  9. package/dist/chunks/Commands-DwXBBVGR.mjs +2 -0
  10. package/dist/chunks/Commands-DwXBBVGR.mjs.map +1 -0
  11. package/dist/chunks/Document-HC8s50qJ.mjs +2 -0
  12. package/dist/chunks/Document-HC8s50qJ.mjs.map +1 -0
  13. package/dist/chunks/DocumentParser-w70-Axud.mjs +2 -0
  14. package/dist/chunks/DocumentParser-w70-Axud.mjs.map +1 -0
  15. package/dist/chunks/DomUtils-CznMAZZg.mjs +2 -0
  16. package/dist/chunks/DomUtils-CznMAZZg.mjs.map +1 -0
  17. package/dist/chunks/HTMLUtils-Cxy99Ak2.mjs +2 -0
  18. package/dist/chunks/HTMLUtils-Cxy99Ak2.mjs.map +1 -0
  19. package/dist/chunks/HeadingPlugin-B-LF-AMM.mjs +2 -0
  20. package/dist/chunks/HeadingPlugin-B-LF-AMM.mjs.map +1 -0
  21. package/dist/chunks/MarkCommands-CTuVDqnn.mjs +2 -0
  22. package/dist/chunks/MarkCommands-CTuVDqnn.mjs.map +1 -0
  23. package/dist/chunks/{NavigationQueries-ogQuObz7.mjs → NavigationQueries-DCOv4Ca5.mjs} +2 -2
  24. package/dist/chunks/{NavigationQueries-ogQuObz7.mjs.map → NavigationQueries-DCOv4Ca5.mjs.map} +1 -1
  25. package/dist/chunks/NotectlEditor-DBBJkPCW.mjs +3 -0
  26. package/dist/chunks/NotectlEditor-DBBJkPCW.mjs.map +1 -0
  27. package/dist/chunks/PluginHelpers-CdPR0MuT.mjs +2 -0
  28. package/dist/chunks/PluginHelpers-CdPR0MuT.mjs.map +1 -0
  29. package/dist/chunks/PopupManager-Du3dYnsJ.mjs +2 -0
  30. package/dist/chunks/{PopupManager-BM8IT6M7.mjs.map → PopupManager-Du3dYnsJ.mjs.map} +1 -1
  31. package/dist/chunks/PrintTypes-DukwDSWS.mjs +2 -0
  32. package/dist/chunks/{PrintTypes-ehbL7ipA.mjs.map → PrintTypes-DukwDSWS.mjs.map} +1 -1
  33. package/dist/chunks/{RangeIterator-CNI6smOg.mjs → RangeIterator-CprUbOWv.mjs} +2 -2
  34. package/dist/chunks/{RangeIterator-CNI6smOg.mjs.map → RangeIterator-CprUbOWv.mjs.map} +1 -1
  35. package/dist/chunks/{Selection-6-W6Flxc.mjs → Selection-DhbizDM4.mjs} +2 -2
  36. package/dist/chunks/{Selection-6-W6Flxc.mjs.map → Selection-DhbizDM4.mjs.map} +1 -1
  37. package/dist/chunks/{SelectionTransactions-q71GEzgE.mjs → SelectionTransactions-DB3YDIEa.mjs} +2 -2
  38. package/dist/chunks/{SelectionTransactions-q71GEzgE.mjs.map → SelectionTransactions-DB3YDIEa.mjs.map} +1 -1
  39. package/dist/chunks/{TextDirectionLocale-DB_aqrMg.mjs → TextDirectionLocale-BraFI9JF.mjs} +2 -2
  40. package/dist/chunks/{TextDirectionLocale-DB_aqrMg.mjs.map → TextDirectionLocale-BraFI9JF.mjs.map} +1 -1
  41. package/dist/chunks/XmlPatterns-DxQXGjP8.mjs +2 -0
  42. package/dist/chunks/XmlPatterns-DxQXGjP8.mjs.map +1 -0
  43. package/dist/chunks/ar-b6VdnxAs.mjs +2 -0
  44. package/dist/chunks/ar-b6VdnxAs.mjs.map +1 -0
  45. package/dist/chunks/de-fXvs5vQT.mjs +2 -0
  46. package/dist/chunks/de-fXvs5vQT.mjs.map +1 -0
  47. package/dist/chunks/es-BTqy_aQ4.mjs +2 -0
  48. package/dist/chunks/es-BTqy_aQ4.mjs.map +1 -0
  49. package/dist/chunks/fr-VdiCNF4J.mjs +2 -0
  50. package/dist/chunks/fr-VdiCNF4J.mjs.map +1 -0
  51. package/dist/chunks/hi-BdtVhAzs.mjs +2 -0
  52. package/dist/chunks/hi-BdtVhAzs.mjs.map +1 -0
  53. package/dist/chunks/index-CVwf0cdH.mjs +2 -0
  54. package/dist/chunks/index-CVwf0cdH.mjs.map +1 -0
  55. package/dist/chunks/index-D3BZFsAD.mjs +2 -0
  56. package/dist/chunks/index-D3BZFsAD.mjs.map +1 -0
  57. package/dist/chunks/pt-K0BUlM9X.mjs +2 -0
  58. package/dist/chunks/pt-K0BUlM9X.mjs.map +1 -0
  59. package/dist/chunks/ru-Tzd5N37W.mjs +2 -0
  60. package/dist/chunks/ru-Tzd5N37W.mjs.map +1 -0
  61. package/dist/chunks/zh-Di3WqY4_.mjs +2 -0
  62. package/dist/chunks/zh-Di3WqY4_.mjs.map +1 -0
  63. package/dist/{input → commands}/BlockInsertion.d.ts +14 -1
  64. package/dist/commands/BlockInsertion.d.ts.map +1 -0
  65. package/dist/commands/CommandHelpers.d.ts +4 -0
  66. package/dist/commands/CommandHelpers.d.ts.map +1 -1
  67. package/dist/commands/Commands.d.ts.map +1 -1
  68. package/dist/commands/GapCursorCommands.d.ts.map +1 -1
  69. package/dist/commands/NodeSelectionCommands.d.ts.map +1 -1
  70. package/dist/commands/PasteCommand.d.ts.map +1 -1
  71. package/dist/editor/EditorThemeController.d.ts.map +1 -1
  72. package/dist/editor/NotectlEditor.d.ts.map +1 -1
  73. package/dist/editor/styles/code-block.d.ts +1 -1
  74. package/dist/editor/styles/code-block.d.ts.map +1 -1
  75. package/dist/editor/theme/ThemeEngine.d.ts.map +1 -1
  76. package/dist/editor/theme/ThemeTokens.d.ts +17 -1
  77. package/dist/editor/theme/ThemeTokens.d.ts.map +1 -1
  78. package/dist/full.d.ts +1 -0
  79. package/dist/full.d.ts.map +1 -1
  80. package/dist/full.mjs +1 -1
  81. package/dist/html.mjs +1 -1
  82. package/dist/index.d.ts +1 -1
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/input/InputManager.d.ts +2 -0
  85. package/dist/input/InputManager.d.ts.map +1 -1
  86. package/dist/input/InternalClipboard.d.ts +2 -22
  87. package/dist/input/InternalClipboard.d.ts.map +1 -1
  88. package/dist/input/PasteHandler.d.ts +7 -0
  89. package/dist/input/PasteHandler.d.ts.map +1 -1
  90. package/dist/model/Document.d.ts.map +1 -1
  91. package/dist/model/HTMLUtils.d.ts +2 -0
  92. package/dist/model/HTMLUtils.d.ts.map +1 -1
  93. package/dist/model/PasteInterceptor.d.ts +21 -0
  94. package/dist/model/PasteInterceptor.d.ts.map +1 -0
  95. package/dist/model/RichBlockData.d.ts +24 -0
  96. package/dist/model/RichBlockData.d.ts.map +1 -0
  97. package/dist/model/SchemaRegistry.d.ts +2 -0
  98. package/dist/model/SchemaRegistry.d.ts.map +1 -1
  99. package/dist/notectl-core.mjs +1 -1
  100. package/dist/notectl-core.umd.js +1 -1
  101. package/dist/notectl-core.umd.js.map +1 -1
  102. package/dist/plugins/Plugin.d.ts +3 -0
  103. package/dist/plugins/Plugin.d.ts.map +1 -1
  104. package/dist/plugins/PluginManager.d.ts +7 -0
  105. package/dist/plugins/PluginManager.d.ts.map +1 -1
  106. package/dist/plugins/alignment/AlignmentPlugin.d.ts.map +1 -1
  107. package/dist/plugins/alignment.mjs +1 -1
  108. package/dist/plugins/alignment.mjs.map +1 -1
  109. package/dist/plugins/blockquote/BlockquoteKeyboardHandlers.d.ts.map +1 -1
  110. package/dist/plugins/blockquote/BlockquotePlugin.d.ts.map +1 -1
  111. package/dist/plugins/blockquote.mjs +1 -1
  112. package/dist/plugins/blockquote.mjs.map +1 -1
  113. package/dist/plugins/caret-navigation/CaretNavigationPlugin.d.ts.map +1 -1
  114. package/dist/plugins/caret-navigation.mjs +1 -1
  115. package/dist/plugins/code-block/CodeBlockKeyboardHandlers.d.ts.map +1 -1
  116. package/dist/plugins/code-block/CodeBlockPlugin.d.ts +5 -0
  117. package/dist/plugins/code-block/CodeBlockPlugin.d.ts.map +1 -1
  118. package/dist/plugins/code-block/CodeBlockTypes.d.ts +7 -0
  119. package/dist/plugins/code-block/CodeBlockTypes.d.ts.map +1 -1
  120. package/dist/plugins/code-block/highlighter/RegexTokenizer.d.ts +14 -0
  121. package/dist/plugins/code-block/highlighter/RegexTokenizer.d.ts.map +1 -0
  122. package/dist/plugins/code-block/highlighter/TokenizerTypes.d.ts +15 -0
  123. package/dist/plugins/code-block/highlighter/TokenizerTypes.d.ts.map +1 -0
  124. package/dist/plugins/code-block/highlighter/languages/index.d.ts +3 -0
  125. package/dist/plugins/code-block/highlighter/languages/index.d.ts.map +1 -0
  126. package/dist/plugins/code-block/highlighter/languages/json.d.ts +3 -0
  127. package/dist/plugins/code-block/highlighter/languages/json.d.ts.map +1 -0
  128. package/dist/plugins/code-block/highlighter/languages/xml.d.ts +3 -0
  129. package/dist/plugins/code-block/highlighter/languages/xml.d.ts.map +1 -0
  130. package/dist/plugins/code-block/index.d.ts +5 -1
  131. package/dist/plugins/code-block/index.d.ts.map +1 -1
  132. package/dist/plugins/code-block.mjs +1 -1
  133. package/dist/plugins/code-block.mjs.map +1 -1
  134. package/dist/plugins/font/FontPlugin.d.ts.map +1 -1
  135. package/dist/plugins/font-size/FontSizePlugin.d.ts.map +1 -1
  136. package/dist/plugins/font-size.mjs +1 -1
  137. package/dist/plugins/font-size.mjs.map +1 -1
  138. package/dist/plugins/font.mjs +1 -1
  139. package/dist/plugins/font.mjs.map +1 -1
  140. package/dist/plugins/gap-cursor/GapCursorPlugin.d.ts.map +1 -1
  141. package/dist/plugins/gap-cursor.mjs +1 -1
  142. package/dist/plugins/hard-break.mjs +1 -1
  143. package/dist/plugins/heading/HeadingInputRules.d.ts.map +1 -1
  144. package/dist/plugins/heading/HeadingKeyboardHandlers.d.ts.map +1 -1
  145. package/dist/plugins/heading/HeadingPlugin.d.ts.map +1 -1
  146. package/dist/plugins/heading.mjs +1 -1
  147. package/dist/plugins/highlight/HighlightPlugin.d.ts.map +1 -1
  148. package/dist/plugins/highlight.mjs +1 -1
  149. package/dist/plugins/highlight.mjs.map +1 -1
  150. package/dist/plugins/horizontal-rule/HorizontalRulePlugin.d.ts.map +1 -1
  151. package/dist/plugins/horizontal-rule.mjs +1 -1
  152. package/dist/plugins/horizontal-rule.mjs.map +1 -1
  153. package/dist/plugins/image/ImagePlugin.d.ts +0 -1
  154. package/dist/plugins/image/ImagePlugin.d.ts.map +1 -1
  155. package/dist/plugins/image/ImagePopup.d.ts +11 -0
  156. package/dist/plugins/image/ImagePopup.d.ts.map +1 -0
  157. package/dist/plugins/image.mjs +1 -1
  158. package/dist/plugins/image.mjs.map +1 -1
  159. package/dist/plugins/link/LinkPlugin.d.ts.map +1 -1
  160. package/dist/plugins/link.mjs +1 -1
  161. package/dist/plugins/link.mjs.map +1 -1
  162. package/dist/plugins/list/ListPlugin.d.ts.map +1 -1
  163. package/dist/plugins/list.mjs +1 -1
  164. package/dist/plugins/list.mjs.map +1 -1
  165. package/dist/plugins/print/PrintPlugin.d.ts.map +1 -1
  166. package/dist/plugins/print.mjs +1 -1
  167. package/dist/plugins/print.mjs.map +1 -1
  168. package/dist/plugins/shared/ColorMarkOperations.d.ts +1 -2
  169. package/dist/plugins/shared/ColorMarkOperations.d.ts.map +1 -1
  170. package/dist/plugins/shared/ColorPickerPopup.d.ts +1 -8
  171. package/dist/plugins/shared/ColorPickerPopup.d.ts.map +1 -1
  172. package/dist/plugins/shared/PluginHelpers.d.ts +8 -0
  173. package/dist/plugins/shared/PluginHelpers.d.ts.map +1 -1
  174. package/dist/plugins/shared/XmlPatterns.d.ts +10 -0
  175. package/dist/plugins/shared/XmlPatterns.d.ts.map +1 -0
  176. package/dist/plugins/shared/index.d.ts +1 -0
  177. package/dist/plugins/shared/index.d.ts.map +1 -1
  178. package/dist/plugins/shared.mjs +1 -1
  179. package/dist/plugins/shared.mjs.map +1 -1
  180. package/dist/plugins/smart-paste/SmartPasteLocale.d.ts +7 -0
  181. package/dist/plugins/smart-paste/SmartPasteLocale.d.ts.map +1 -0
  182. package/dist/plugins/smart-paste/SmartPastePlugin.d.ts +19 -0
  183. package/dist/plugins/smart-paste/SmartPastePlugin.d.ts.map +1 -0
  184. package/dist/plugins/smart-paste/SmartPasteTypes.d.ts +24 -0
  185. package/dist/plugins/smart-paste/SmartPasteTypes.d.ts.map +1 -0
  186. package/dist/plugins/smart-paste/detectors/JsonDetector.d.ts +6 -0
  187. package/dist/plugins/smart-paste/detectors/JsonDetector.d.ts.map +1 -0
  188. package/dist/plugins/smart-paste/detectors/XmlDetector.d.ts +26 -0
  189. package/dist/plugins/smart-paste/detectors/XmlDetector.d.ts.map +1 -0
  190. package/dist/plugins/smart-paste/index.d.ts +7 -0
  191. package/dist/plugins/smart-paste/index.d.ts.map +1 -0
  192. package/dist/plugins/smart-paste/locales/ar.d.ts +4 -0
  193. package/dist/plugins/smart-paste/locales/ar.d.ts.map +1 -0
  194. package/dist/plugins/smart-paste/locales/de.d.ts +4 -0
  195. package/dist/plugins/smart-paste/locales/de.d.ts.map +1 -0
  196. package/dist/plugins/smart-paste/locales/es.d.ts +4 -0
  197. package/dist/plugins/smart-paste/locales/es.d.ts.map +1 -0
  198. package/dist/plugins/smart-paste/locales/fr.d.ts +4 -0
  199. package/dist/plugins/smart-paste/locales/fr.d.ts.map +1 -0
  200. package/dist/plugins/smart-paste/locales/hi.d.ts +4 -0
  201. package/dist/plugins/smart-paste/locales/hi.d.ts.map +1 -0
  202. package/dist/plugins/smart-paste/locales/pt.d.ts +4 -0
  203. package/dist/plugins/smart-paste/locales/pt.d.ts.map +1 -0
  204. package/dist/plugins/smart-paste/locales/ru.d.ts +4 -0
  205. package/dist/plugins/smart-paste/locales/ru.d.ts.map +1 -0
  206. package/dist/plugins/smart-paste/locales/zh.d.ts +4 -0
  207. package/dist/plugins/smart-paste/locales/zh.d.ts.map +1 -0
  208. package/dist/plugins/smart-paste.mjs +2 -0
  209. package/dist/plugins/smart-paste.mjs.map +1 -0
  210. package/dist/plugins/strikethrough/StrikethroughPlugin.d.ts.map +1 -1
  211. package/dist/plugins/strikethrough.mjs +1 -1
  212. package/dist/plugins/strikethrough.mjs.map +1 -1
  213. package/dist/plugins/super-sub/SuperSubPlugin.d.ts.map +1 -1
  214. package/dist/plugins/super-sub.mjs +1 -1
  215. package/dist/plugins/super-sub.mjs.map +1 -1
  216. package/dist/plugins/table/TableCommands.d.ts.map +1 -1
  217. package/dist/plugins/table/TableNavigation.d.ts.map +1 -1
  218. package/dist/plugins/table/TablePlugin.d.ts.map +1 -1
  219. package/dist/plugins/table/index.d.ts +1 -0
  220. package/dist/plugins/table/index.d.ts.map +1 -1
  221. package/dist/plugins/table.mjs +1 -1
  222. package/dist/plugins/table.mjs.map +1 -1
  223. package/dist/plugins/text-color/TextColorPlugin.d.ts.map +1 -1
  224. package/dist/plugins/text-color.mjs +1 -1
  225. package/dist/plugins/text-color.mjs.map +1 -1
  226. package/dist/plugins/text-direction/TextDirectionCorePlugin.d.ts.map +1 -1
  227. package/dist/plugins/text-direction/TextDirectionPlugin.d.ts.map +1 -1
  228. package/dist/plugins/text-direction-advanced.mjs +1 -1
  229. package/dist/plugins/text-direction-advanced.mjs.map +1 -1
  230. package/dist/plugins/text-direction.mjs +1 -1
  231. package/dist/plugins/text-direction.mjs.map +1 -1
  232. package/dist/plugins/text-formatting/TextFormattingPlugin.d.ts.map +1 -1
  233. package/dist/plugins/text-formatting.mjs +1 -1
  234. package/dist/plugins/text-formatting.mjs.map +1 -1
  235. package/dist/plugins/toolbar/ToolbarPlugin.d.ts.map +1 -1
  236. package/dist/plugins/toolbar.mjs +1 -1
  237. package/dist/plugins/toolbar.mjs.map +1 -1
  238. package/dist/presets/FullPreset.d.ts.map +1 -1
  239. package/dist/presets/PresetTypes.d.ts +2 -0
  240. package/dist/presets/PresetTypes.d.ts.map +1 -1
  241. package/dist/presets/full.mjs +1 -1
  242. package/dist/presets/full.mjs.map +1 -1
  243. package/dist/serialization/DocumentSerializer.d.ts.map +1 -1
  244. package/dist/state/InlineContentOps.d.ts.map +1 -1
  245. package/dist/state/StepInversion.d.ts +7 -0
  246. package/dist/state/StepInversion.d.ts.map +1 -0
  247. package/dist/state/Steps.d.ts +108 -0
  248. package/dist/state/Steps.d.ts.map +1 -0
  249. package/dist/state/Transaction.d.ts +5 -174
  250. package/dist/state/Transaction.d.ts.map +1 -1
  251. package/dist/state/TransactionBuilder.d.ts +69 -0
  252. package/dist/state/TransactionBuilder.d.ts.map +1 -0
  253. package/dist/test/TestUtils.d.ts.map +1 -1
  254. package/dist/view/CaretNavigation.d.ts.map +1 -1
  255. package/dist/view/DomUtils.d.ts +10 -1
  256. package/dist/view/DomUtils.d.ts.map +1 -1
  257. package/dist/view/EditorView.d.ts +2 -2
  258. package/dist/view/EditorView.d.ts.map +1 -1
  259. package/dist/view/ViewMovementCommands.d.ts.map +1 -1
  260. package/package.json +11 -1
  261. package/dist/chunks/AttributedMarkCommands-BB7lzFct.mjs +0 -2
  262. package/dist/chunks/AttributedMarkCommands-BB7lzFct.mjs.map +0 -1
  263. package/dist/chunks/ColorPickerPopup-DRzFvt7o.mjs.map +0 -1
  264. package/dist/chunks/Commands-P9wS8qtN.mjs +0 -2
  265. package/dist/chunks/Commands-P9wS8qtN.mjs.map +0 -1
  266. package/dist/chunks/Document-BFYAonMF.mjs +0 -2
  267. package/dist/chunks/Document-BFYAonMF.mjs.map +0 -1
  268. package/dist/chunks/DocumentParser-DFcvVMGY.mjs +0 -2
  269. package/dist/chunks/DocumentParser-DFcvVMGY.mjs.map +0 -1
  270. package/dist/chunks/DomUtils-Cdz1eDKM.mjs +0 -2
  271. package/dist/chunks/DomUtils-Cdz1eDKM.mjs.map +0 -1
  272. package/dist/chunks/HTMLUtils-CCvQ5f83.mjs +0 -2
  273. package/dist/chunks/HTMLUtils-CCvQ5f83.mjs.map +0 -1
  274. package/dist/chunks/HeadingPlugin-DYy3IoT_.mjs +0 -2
  275. package/dist/chunks/HeadingPlugin-DYy3IoT_.mjs.map +0 -1
  276. package/dist/chunks/LocaleService-B6Z-wyAF.mjs +0 -2
  277. package/dist/chunks/LocaleService-B6Z-wyAF.mjs.map +0 -1
  278. package/dist/chunks/MarkCommands-B_erV7zz.mjs +0 -2
  279. package/dist/chunks/MarkCommands-B_erV7zz.mjs.map +0 -1
  280. package/dist/chunks/NotectlEditor-4NFnXLyD.mjs +0 -2
  281. package/dist/chunks/NotectlEditor-4NFnXLyD.mjs.map +0 -1
  282. package/dist/chunks/Plugin-OzM8Oxm_.mjs +0 -2
  283. package/dist/chunks/Plugin-OzM8Oxm_.mjs.map +0 -1
  284. package/dist/chunks/PluginHelpers-DjZt0pQi.mjs +0 -2
  285. package/dist/chunks/PluginHelpers-DjZt0pQi.mjs.map +0 -1
  286. package/dist/chunks/PopupManager-BM8IT6M7.mjs +0 -2
  287. package/dist/chunks/PrintTypes-ehbL7ipA.mjs +0 -2
  288. package/dist/chunks/index-C8xtb3SM.mjs +0 -2
  289. package/dist/chunks/index-C8xtb3SM.mjs.map +0 -1
  290. package/dist/chunks/index-DAoSt12h.mjs +0 -2
  291. package/dist/chunks/index-DAoSt12h.mjs.map +0 -1
  292. package/dist/input/BlockInsertion.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HTMLUtils-Cxy99Ak2.mjs","sources":["../../src/model/HTMLUtils.ts"],"sourcesContent":["/**\n * HTML string escaping and formatting utilities shared across serialization and parsing.\n */\n\n/**\n * URI scheme regex for DOMPurify that extends the default allowlist with `blob:` and `data:`.\n * `blob:` is needed to preserve same-origin blob URLs (e.g. uploaded images) through\n * clipboard round-trips and HTML serialization.\n */\nexport const SAFE_URI_REGEXP: RegExp =\n\t/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|blob|data):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i;\n\n/** Escapes special HTML characters in text content. */\nexport function escapeHTML(text: string): string {\n\treturn text\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n}\n\n/** Escapes a value for safe interpolation into an HTML attribute (double-quoted). */\nexport const escapeAttr: (value: string) => string = escapeHTML;\n\n/** Block-level HTML tags that should appear on their own line with indentation. */\nconst BLOCK_TAGS: ReadonlySet<string> = new Set([\n\t'p',\n\t'div',\n\t'h1',\n\t'h2',\n\t'h3',\n\t'h4',\n\t'h5',\n\t'h6',\n\t'ul',\n\t'ol',\n\t'li',\n\t'blockquote',\n\t'table',\n\t'thead',\n\t'tbody',\n\t'tfoot',\n\t'tr',\n\t'td',\n\t'th',\n\t'pre',\n\t'figure',\n\t'figcaption',\n\t'section',\n\t'article',\n\t'header',\n\t'footer',\n]);\n\n/** Void (self-closing) HTML tags that never have children. */\nconst VOID_TAGS: ReadonlySet<string> = new Set([\n\t'br',\n\t'hr',\n\t'img',\n\t'input',\n\t'col',\n\t'area',\n\t'meta',\n\t'link',\n]);\n\n/**\n * Pretty-prints an HTML string with indentation and line breaks for block-level elements.\n * Inline content (e.g. `<strong>bold</strong> text`) stays on a single line.\n */\nexport function formatHTML(html: string, indent = ' '): string {\n\tconst tokens: readonly string[] = tokenizeHTML(html);\n\tconst lines: string[] = [];\n\tlet depth = 0;\n\tlet inlineBuffer = '';\n\n\tconst flushInline = (): void => {\n\t\tconst trimmed: string = inlineBuffer.trim();\n\t\tif (trimmed.length > 0) {\n\t\t\tlines.push(`${indent.repeat(depth)}${trimmed}`);\n\t\t}\n\t\tinlineBuffer = '';\n\t};\n\n\tfor (const token of tokens) {\n\t\tconst tag: string = token.startsWith('<') ? extractTagName(token) : '';\n\t\tconst isBlock: boolean = BLOCK_TAGS.has(tag);\n\t\tconst isVoid: boolean = VOID_TAGS.has(tag);\n\n\t\tif (isBlock || isVoid) {\n\t\t\tflushInline();\n\n\t\t\tif (token.startsWith('</')) {\n\t\t\t\tdepth = Math.max(0, depth - 1);\n\t\t\t\tlines.push(`${indent.repeat(depth)}${token}`);\n\t\t\t} else {\n\t\t\t\tlines.push(`${indent.repeat(depth)}${token}`);\n\t\t\t\tif (isBlock && !isVoid && !token.endsWith('/>')) {\n\t\t\t\t\tdepth += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tinlineBuffer += token;\n\t\t}\n\t}\n\n\tflushInline();\n\treturn lines.join('\\n');\n}\n\n/** Splits HTML into a flat list of tokens: tags and text segments between block boundaries. */\nfunction tokenizeHTML(html: string): readonly string[] {\n\tconst tokens: string[] = [];\n\tlet textStart = 0;\n\tlet i = 0;\n\twhile (i < html.length) {\n\t\tif (html[i] !== '<') {\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet nameStart = i + 1;\n\t\tif (nameStart < html.length && html[nameStart] === '/') {\n\t\t\tnameStart += 1;\n\t\t}\n\t\tconst nameChar: string | undefined = html[nameStart];\n\t\tif (nameStart >= html.length || !nameChar || !isASCIILetter(nameChar)) {\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst tagEnd: number | undefined = findTagEnd(html, nameStart + 1);\n\t\tif (tagEnd === undefined) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (i > textStart) {\n\t\t\ttokens.push(html.slice(textStart, i));\n\t\t}\n\t\ttokens.push(html.slice(i, tagEnd + 1));\n\t\ti = tagEnd + 1;\n\t\ttextStart = i;\n\t}\n\n\tif (textStart < html.length) {\n\t\ttokens.push(html.slice(textStart));\n\t}\n\treturn tokens;\n}\n\nfunction findTagEnd(html: string, from: number): number | undefined {\n\tlet quote: '\"' | \"'\" | undefined;\n\tfor (let i = from; i < html.length; i += 1) {\n\t\tconst char: string = html[i] ?? '';\n\t\tif (quote) {\n\t\t\tif (char === quote) {\n\t\t\t\tquote = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' || char === \"'\") {\n\t\t\tquote = char;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '>') {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isASCIILetter(char: string): boolean {\n\treturn (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');\n}\n\n/** Extracts the tag name from an HTML tag string like `<p>` or `</div class=\"x\">`. */\nfunction extractTagName(tag: string): string {\n\tconst match: RegExpMatchArray | null = tag.match(/^<\\/?([a-zA-Z][a-zA-Z0-9]*)/);\n\treturn match?.[1]?.toLowerCase() ?? '';\n}\n"],"names":["SAFE_URI_REGEXP","escapeHTML","text","replace","escapeAttr","BLOCK_TAGS","Set","VOID_TAGS","formatHTML","html","indent","tokens","textStart","i","length","nameStart","nameChar","isASCIILetter","tagEnd","findTagEnd","push","slice","tokenizeHTML","lines","depth","inlineBuffer","flushInline","trimmed","trim","repeat","token","tag","startsWith","extractTagName","isBlock","has","isVoid","Math","max","endsWith","join","from","quote","char","match","toLowerCase"],"mappings":"AASO,MAAMA,EACZ,sGAGM,SAASC,EAAWC,GAC1B,OAAOA,EACLC,QAAQ,KAAM,SACdA,QAAQ,KAAM,QACdA,QAAQ,KAAM,QACdA,QAAQ,KAAM,SACjB,CAGO,MAAMC,EAAwCH,EAG/CI,qBAAsCC,IAAI,CAC/C,IACA,MACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,aACA,QACA,QACA,QACA,QACA,KACA,KACA,KACA,MACA,SACA,aACA,UACA,UACA,SACA,WAIKC,qBAAqCD,IAAI,CAC9C,KACA,KACA,MACA,QACA,MACA,OACA,OACA,SAOM,SAASE,EA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AAS,QACzCf,GAAS,KAIXC,GAAgBK,CAElB,CAGA,OADAJ,IACOH,EAAMiB,KAAK,KACnB,CA0CA,SAASrB,EAAWV,EAAcgC,GACjC,IAAIC,EACJ,IAAA,IAAS7B,EAAI4B,EAAM5B,EAAIJ,EAAKK,OAAQD,GAAK,EAAG,CAC3C,MAAM8B,EAAelC,EAAKI,IAAM,GAChC,GAAI6B,EACCC,IAASD,IACZA,OAAQ,QAIV,GAAa,MAATC,GAAyB,MAATA,GAIpB,GAAa,MAATA,EACH,OAAO9B,OAJP6B,EAAQC,CAMV,CAED,CAEA,SAAS1B,EAAc0B,GACtB,OAAQA,GAAQ,KAAOA,GAAQ,KAASA,GAAQ,KAAOA,GAAQ,GAChE,CAGA,SAASV,EAAeF,GACvB,MAAMa,EAAiCb,EAAIa,MAAM,+BACjD,OAAOA,IAAQ,IAAIC,eAAiB,EACrC"}
@@ -0,0 +1,2 @@
1
+ import{c as t}from"./DomUtils-CznMAZZg.mjs";import{r as e}from"./PluginHelpers-CdPR0MuT.mjs";import{j as n,i as o,c as i}from"./Selection-DhbizDM4.mjs";import{s as r}from"./StyleRuntime-BmsLoEa8.mjs";import{f as s,k as c,q as a,i as l,s as g}from"./Document-HC8s50qJ.mjs";import{n as p}from"./TypeBrands-Bp_Z_o5Y.mjs";function d(t,e,n,o){const i=document.createElement("button");i.type="button",i.className="notectl-heading-picker__item",i.setAttribute("role","option"),i.setAttribute("aria-selected",String(e)),e&&i.classList.add("notectl-heading-picker__item--active");const s=document.createElement("span");s.className="notectl-heading-picker__check",s.textContent=e?"✓":"",i.appendChild(s);const c=document.createElement("span");return c.className="notectl-heading-picker__label",c.textContent=t,o&&r(c,{fontSize:o.fontSize,fontWeight:o.fontWeight}),i.appendChild(c),i.addEventListener("mousedown",n),i}function h(t,e){return t[`heading${e}`]}function u(t,e){const o=t.getState();if(!n(o.selection))return!1;const i=o.getBlock(o.selection.anchor.blockId);return!!i&&(i.type===e?m(t,p("paragraph")):m(t,p(e)))}function f(t,e){const o=t.getState(),i=o.selection;if(!n(i))return!1;const r=o.getBlock(i.anchor.blockId);return!!r&&("heading"===r.type&&r.attrs?.level===e?m(t,p("paragraph")):m(t,p("heading"),{level:e}))}function m(t,e,o){const i=t.getState(),r=i.selection;if(!n(r))return!1;const l=i.getBlock(r.anchor.blockId);if(!l)return!1;const g=i.transaction("command"),p=t.getSchemaRegistry().getNodeSpec(e);p?.excludeMarks&&p.excludeMarks.length>0&&(function(t,e,n){if(0===s(e))return;const o=new Set(n),i=c(e);let r=0;for(const s of i)if(a(s)){if(s.text.length>0)for(const n of s.marks)o.has(n.type)&&t.removeMark(e.id,r,r+s.text.length,n);r+=s.text.length}else r+=1}(g,l,p.excludeMarks),function(t,e,n){if(!e.storedMarks)return;const o=new Set(n),i=e.storedMarks.filter(t=>!o.has(t.type));i.length!==e.storedMarks.length&&t.setStoredMarks(i.length>0?i:null,e.storedMarks)}(g,i,p.excludeMarks));const d=g.setBlockType(r.anchor.blockId,e,o).setSelection(r).build();return t.dispatch(d),!0}const k=/* @__PURE__ */new Set(["heading","title","subtitle"]);const b={paragraph:"Paragraph",title:"Title",subtitle:"Subtitle",heading1:"Heading 1",heading2:"Heading 2",heading3:"Heading 3",heading4:"Heading 4",heading5:"Heading 5",heading6:"Heading 6",blockTypeLabel:"Block Type",blockTypesAria:"Block types"},y=/* @__PURE__ */Object.assign({"./locales/ar.ts":()=>import("./ar-DtIHQ8nU.mjs"),"./locales/de.ts":()=>import("./de-OTfhhinm.mjs"),"./locales/es.ts":()=>import("./es-C2lnWyA0.mjs"),"./locales/fr.ts":()=>import("./fr-DDkBcjmO.mjs"),"./locales/hi.ts":()=>import("./hi-ClvEtEKe.mjs"),"./locales/pt.ts":()=>import("./pt-TuA3_GDM.mjs"),"./locales/ru.ts":()=>import("./ru-BO6BIS5W.mjs"),"./locales/zh.ts":()=>import("./zh-BqMtE-jN.mjs")});async function v(t){if("en"===t)return b;const e=y[`./locales/${t}.ts`];if(!e)return b;try{return(await e()).default}catch{return b}}const x={levels:[1,2,3,4,5,6]},S={1:"h1",2:"h2",3:"h3",4:"h4",5:"h5",6:"h6"};class T{id="heading";name="Heading";priority=30;config;locale;constructor(t){this.config={...x,...t}}async init(t){this.locale=await e(t,this.config.locale,b,v),t.registerStyleSheet("\n/* Heading Select — Width overrides for combobox button */\n.notectl-toolbar-btn--heading {\n\tmin-width: 100px;\n\tmax-width: 160px;\n}\n\n/* Heading Picker Popup */\n.notectl-heading-picker {\n\tmin-width: 200px;\n\tmax-height: 320px;\n\toverflow-y: auto;\n}\n\n.notectl-heading-picker__list {\n\tpadding: 4px 0;\n}\n\n.notectl-heading-picker__item {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n\twidth: 100%;\n\tpadding: 7px 12px;\n\tborder: none;\n\tbackground: none;\n\tcursor: pointer;\n\tfont-size: 14px;\n\tcolor: var(--notectl-fg);\n\ttext-align: start;\n\twhite-space: nowrap;\n\tfont-family: inherit;\n\ttransition: background 0.1s;\n}\n\n@media (hover: hover) {\n\t.notectl-heading-picker__item:hover {\n\t\tbackground: var(--notectl-hover-bg);\n\t}\n}\n\n.notectl-heading-picker__item--active {\n\tbackground: var(--notectl-active-bg);\n\tcolor: var(--notectl-primary-fg);\n}\n\n@media (hover: hover) {\n\t.notectl-heading-picker__item--active:hover {\n\t\tbackground: var(--notectl-active-bg);\n\t}\n}\n\n.notectl-heading-picker__check {\n\tdisplay: inline-flex;\n\talign-items: center;\n\tjustify-content: center;\n\twidth: 16px;\n\tflex-shrink: 0;\n\tfont-size: 13px;\n\tfont-weight: 600;\n\tcolor: var(--notectl-primary-fg);\n}\n\n.notectl-heading-picker__label {\n\tflex: 1;\n}\n"),this.registerNodeSpecs(t),function(t,e){t.registerCommand("setTitle",()=>u(t,"title")),t.registerCommand("setSubtitle",()=>u(t,"subtitle"));for(const n of e.levels)t.registerCommand(`setHeading${n}`,()=>f(t,n));t.registerCommand("toggleHeading",()=>f(t,1)),t.registerCommand("setParagraph",()=>m(t,p("paragraph")))}(t,this.config),function(t,e){const r={Enter:()=>function(t){return function(t,e){const i=t.getState();if(!n(i.selection))return!1;const r=i.selection;if(!o(r))return!1;const s=i.getBlock(r.anchor.blockId);return!(!s||!k.has(s.type))&&e({state:i,block:s,blockId:r.anchor.blockId,offset:r.anchor.offset})}(t,e=>{if(""===l(e.block)){const n=e.state.transaction("input").setBlockType(e.blockId,p("paragraph")).setSelection(e.state.selection).build();return t.dispatch(n),!0}const n=s(e.block);if(e.offset>=n){const n=g(),o=e.state.transaction("input").splitBlock(e.blockId,e.offset,n).setBlockType(n,p("paragraph")).setSelection(i(n,0)).build();return t.dispatch(o),!0}return!1})}(t)};for(const n of e.levels)n<=6&&(r[`Mod-Shift-${n}`]=()=>t.executeCommand(`setHeading${n}`));t.registerKeymap(r)}(t,this.config),function(t,e){for(const r of e.levels){const e="#".repeat(r),s=new RegExp(`^${e} $`);t.registerInputRule({pattern:s,handler(t,e,s,c){const a=t.selection;if(!n(a))return null;if(!o(a))return null;const l=t.getBlock(a.anchor.blockId);return l&&"paragraph"===l.type?t.transaction("input").deleteTextAt(a.anchor.blockId,s,s+r+1).setBlockType(a.anchor.blockId,p("heading"),{level:r}).setSelection(i(a.anchor.blockId,0)).build():null}})}}(t,this.config),function(t,e,o){t.registerBlockTypePickerEntry({id:"paragraph",label:o.paragraph,command:"setParagraph",priority:10,isActive:t=>{if(!n(t.selection))return!1;const e=t.getBlock(t.selection.anchor.blockId);return"paragraph"===e?.type}}),t.registerBlockTypePickerEntry({id:"title",label:o.title,command:"setTitle",priority:20,style:{fontSize:"1.6em",fontWeight:"700"},isActive:t=>{if(!n(t.selection))return!1;const e=t.getBlock(t.selection.anchor.blockId);return"title"===e?.type}}),t.registerBlockTypePickerEntry({id:"subtitle",label:o.subtitle,command:"setSubtitle",priority:30,style:{fontSize:"1.3em",fontWeight:"500"},isActive:t=>{if(!n(t.selection))return!1;const e=t.getBlock(t.selection.anchor.blockId);return"subtitle"===e?.type}});for(const i of e.levels)t.registerBlockTypePickerEntry({id:`heading-${i}`,label:h(o,i),command:`setHeading${i}`,priority:100+i,style:{fontSize:1.4-.1*i+"em",fontWeight:"600"},isActive:t=>{if(!n(t.selection))return!1;const e=t.getBlock(t.selection.anchor.blockId);return"heading"===e?.type&&e.attrs?.level===i}})}(t,this.config,this.locale),function(t,e){t.registerToolbarItem({id:"heading",group:"block",label:e.blockTypeLabel,tooltip:e.blockTypeLabel,command:"setParagraph",popupType:"combobox",getLabel:o=>function(t,e,o){if(!n(t.selection))return o.paragraph;const i=e.getBlockTypePickerRegistry().getBlockTypePickerEntries();for(const n of i)if(n.isActive(t))return n.label;return o.paragraph}(o,t,e),renderPopup:(t,o,i)=>{!function(t,e,o,i){t.classList.add("notectl-heading-picker");const r=e.getState();if(!n(r.selection))return;const s=e.getContainer(),c=document.createElement("div");c.className="notectl-heading-picker__list",c.setAttribute("role","listbox"),c.setAttribute("aria-label",o.blockTypesAria);const a=e.getBlockTypePickerRegistry().getBlockTypePickerEntries();for(const n of a){const t=n.isActive(r);c.appendChild(d(n.label,t,t=>{t.preventDefault(),t.stopPropagation(),e.executeCommand(n.command),i({restoreFocusTo:s})},n.style))}t.appendChild(c)}(t,o,e,i)},isActive:e=>t.getBlockTypePickerRegistry().getBlockTypePickerEntries().some(t=>"paragraph"!==t.id&&t.isActive(e))})}(t,this.locale)}registerNodeSpecs(e){e.registerNodeSpec({type:"title",group:"block",content:{allow:["text"]},excludeMarks:["fontSize"],toDOM(e){const n=t("h1",e.id);return n.classList.add("notectl-title"),n},toHTML:(t,e)=>`<h1 class="notectl-title">${e||"<br>"}</h1>`,parseHTML:[{tag:"h1",priority:60,getAttrs:t=>!!t.classList.contains("notectl-title")&&{}}],sanitize:{tags:["h1"],attrs:["class"]}}),e.registerNodeSpec({type:"subtitle",group:"block",content:{allow:["text"]},excludeMarks:["fontSize"],toDOM(e){const n=t("h2",e.id);return n.classList.add("notectl-subtitle"),n},toHTML:(t,e)=>`<h2 class="notectl-subtitle">${e||"<br>"}</h2>`,parseHTML:[{tag:"h2",priority:60,getAttrs:t=>!!t.classList.contains("notectl-subtitle")&&{}}],sanitize:{tags:["h2"],attrs:["class"]}}),e.registerNodeSpec({type:"heading",group:"block",content:{allow:["text"]},excludeMarks:["fontSize"],attrs:{level:{default:1}},toDOM(e){const n=e.attrs?.level??1;return t(S[n]??"h1",e.id)},toHTML(t,e){const n=t.attrs?.level??1,o=S[n]??"h1";return`<${o}>${e||"<br>"}</${o}>`},parseHTML:[{tag:"h1",getAttrs:()=>({level:1})},{tag:"h2",getAttrs:()=>({level:2})},{tag:"h3",getAttrs:()=>({level:3})},{tag:"h4",getAttrs:()=>({level:4})},{tag:"h5",getAttrs:()=>({level:5})},{tag:"h6",getAttrs:()=>({level:6})}],sanitize:{tags:["h1","h2","h3","h4","h5","h6"]}})}}export{b as H,T as a,v as l};
2
+ //# sourceMappingURL=HeadingPlugin-B-LF-AMM.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HeadingPlugin-B-LF-AMM.mjs","sources":["../../src/plugins/heading/HeadingBlockTypePicker.ts","../../src/plugins/heading/HeadingCommands.ts","../../src/plugins/heading/HeadingKeyboardHandlers.ts","../../src/plugins/heading/HeadingLocale.ts","../../src/plugins/heading/HeadingPlugin.ts","../../src/editor/styles/heading-select.ts","../../src/plugins/heading/HeadingInputRules.ts"],"sourcesContent":["/**\n * Block type picker entries and toolbar dropdown for heading block types.\n * Registers picker entries for paragraph, title, subtitle, and all heading levels,\n * plus a combobox-style toolbar item with a custom popup.\n */\n\nimport { isTextSelection } from '../../model/Selection.js';\nimport type { EditorState } from '../../state/EditorState.js';\nimport { setStyleProperties } from '../../style/StyleRuntime.js';\nimport type { PluginContext } from '../Plugin.js';\nimport type { PopupCloseOptions } from '../shared/PopupManager.js';\nimport type { PickerEntryStyle } from './BlockTypePickerEntry.js';\nimport type { HeadingLocale } from './HeadingLocale.js';\nimport type { HeadingConfig } from './HeadingPlugin.js';\nimport type { HeadingLevel } from './HeadingPlugin.js';\n\n// --- Picker Entry Registration ---\n\n/** Registers block type picker entries for paragraph, title, subtitle, and heading levels. */\nexport function registerHeadingPickerEntries(\n\tcontext: PluginContext,\n\tconfig: HeadingConfig,\n\tlocale: HeadingLocale,\n): void {\n\tcontext.registerBlockTypePickerEntry({\n\t\tid: 'paragraph',\n\t\tlabel: locale.paragraph,\n\t\tcommand: 'setParagraph',\n\t\tpriority: 10,\n\t\tisActive: (state) => {\n\t\t\tif (!isTextSelection(state.selection)) return false;\n\t\t\tconst block = state.getBlock(state.selection.anchor.blockId);\n\t\t\treturn block?.type === 'paragraph';\n\t\t},\n\t});\n\n\tcontext.registerBlockTypePickerEntry({\n\t\tid: 'title',\n\t\tlabel: locale.title,\n\t\tcommand: 'setTitle',\n\t\tpriority: 20,\n\t\tstyle: { fontSize: '1.6em', fontWeight: '700' },\n\t\tisActive: (state) => {\n\t\t\tif (!isTextSelection(state.selection)) return false;\n\t\t\tconst block = state.getBlock(state.selection.anchor.blockId);\n\t\t\treturn block?.type === 'title';\n\t\t},\n\t});\n\n\tcontext.registerBlockTypePickerEntry({\n\t\tid: 'subtitle',\n\t\tlabel: locale.subtitle,\n\t\tcommand: 'setSubtitle',\n\t\tpriority: 30,\n\t\tstyle: { fontSize: '1.3em', fontWeight: '500' },\n\t\tisActive: (state) => {\n\t\t\tif (!isTextSelection(state.selection)) return false;\n\t\t\tconst block = state.getBlock(state.selection.anchor.blockId);\n\t\t\treturn block?.type === 'subtitle';\n\t\t},\n\t});\n\n\tfor (const level of config.levels) {\n\t\tcontext.registerBlockTypePickerEntry({\n\t\t\tid: `heading-${level}`,\n\t\t\tlabel: getHeadingLabel(locale, level),\n\t\t\tcommand: `setHeading${level}`,\n\t\t\tpriority: 100 + level,\n\t\t\tstyle: { fontSize: `${1.4 - level * 0.1}em`, fontWeight: '600' },\n\t\t\tisActive: (state) => {\n\t\t\t\tif (!isTextSelection(state.selection)) return false;\n\t\t\t\tconst block = state.getBlock(state.selection.anchor.blockId);\n\t\t\t\treturn block?.type === 'heading' && block.attrs?.level === level;\n\t\t\t},\n\t\t});\n\t}\n}\n\n// --- Toolbar Item ---\n\n/** Registers the heading toolbar dropdown with a combobox picker popup. */\nexport function registerHeadingToolbarItem(context: PluginContext, locale: HeadingLocale): void {\n\tcontext.registerToolbarItem({\n\t\tid: 'heading',\n\t\tgroup: 'block',\n\t\tlabel: locale.blockTypeLabel,\n\t\ttooltip: locale.blockTypeLabel,\n\t\tcommand: 'setParagraph',\n\t\tpopupType: 'combobox',\n\t\tgetLabel: (state: EditorState): string => getActiveLabel(state, context, locale),\n\t\trenderPopup: (container, ctx, onClose) => {\n\t\t\trenderHeadingPopup(container, ctx, locale, onClose);\n\t\t},\n\t\tisActive: (state) => {\n\t\t\tconst entries = context.getBlockTypePickerRegistry().getBlockTypePickerEntries();\n\t\t\treturn entries.some((entry) => entry.id !== 'paragraph' && entry.isActive(state));\n\t\t},\n\t});\n}\n\n// --- Popup Rendering ---\n\nfunction renderHeadingPopup(\n\tcontainer: HTMLElement,\n\tcontext: PluginContext,\n\tlocale: HeadingLocale,\n\tonClose: (options?: PopupCloseOptions) => void,\n): void {\n\tcontainer.classList.add('notectl-heading-picker');\n\n\tconst state: EditorState = context.getState();\n\tif (!isTextSelection(state.selection)) return;\n\n\tconst contentElement: HTMLElement = context.getContainer();\n\n\tconst list: HTMLDivElement = document.createElement('div');\n\tlist.className = 'notectl-heading-picker__list';\n\tlist.setAttribute('role', 'listbox');\n\tlist.setAttribute('aria-label', locale.blockTypesAria);\n\n\tconst entries = context.getBlockTypePickerRegistry().getBlockTypePickerEntries();\n\tfor (const entry of entries) {\n\t\tconst active: boolean = entry.isActive(state);\n\t\tlist.appendChild(\n\t\t\tcreatePickerItem(\n\t\t\t\tentry.label,\n\t\t\t\tactive,\n\t\t\t\t(e: MouseEvent) => {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\tcontext.executeCommand(entry.command);\n\t\t\t\t\tonClose({ restoreFocusTo: contentElement });\n\t\t\t\t},\n\t\t\t\tentry.style,\n\t\t\t),\n\t\t);\n\t}\n\n\tcontainer.appendChild(list);\n}\n\nfunction createPickerItem(\n\tlabel: string,\n\tisActive: boolean,\n\thandler: (e: MouseEvent) => void,\n\tstyle?: PickerEntryStyle,\n): HTMLButtonElement {\n\tconst item: HTMLButtonElement = document.createElement('button');\n\titem.type = 'button';\n\titem.className = 'notectl-heading-picker__item';\n\titem.setAttribute('role', 'option');\n\titem.setAttribute('aria-selected', String(isActive));\n\n\tif (isActive) {\n\t\titem.classList.add('notectl-heading-picker__item--active');\n\t}\n\n\tconst check: HTMLSpanElement = document.createElement('span');\n\tcheck.className = 'notectl-heading-picker__check';\n\tcheck.textContent = isActive ? '\\u2713' : '';\n\titem.appendChild(check);\n\n\tconst labelSpan: HTMLSpanElement = document.createElement('span');\n\tlabelSpan.className = 'notectl-heading-picker__label';\n\tlabelSpan.textContent = label;\n\tif (style) {\n\t\tsetStyleProperties(labelSpan, {\n\t\t\tfontSize: style.fontSize,\n\t\t\tfontWeight: style.fontWeight,\n\t\t});\n\t}\n\titem.appendChild(labelSpan);\n\n\titem.addEventListener('mousedown', handler);\n\treturn item;\n}\n\n// --- Helpers ---\n\nfunction getHeadingLabel(locale: HeadingLocale, level: HeadingLevel): string {\n\tconst key = `heading${level}` as keyof HeadingLocale;\n\treturn locale[key] as string;\n}\n\nfunction getActiveLabel(state: EditorState, context: PluginContext, locale: HeadingLocale): string {\n\tif (!isTextSelection(state.selection)) return locale.paragraph;\n\tconst entries = context.getBlockTypePickerRegistry().getBlockTypePickerEntries();\n\tfor (const entry of entries) {\n\t\tif (entry.isActive(state)) return entry.label;\n\t}\n\treturn locale.paragraph;\n}\n","/**\n * Command registration and implementations for heading block types.\n * Handles toggle between heading/title/subtitle and paragraph,\n * plus excluded-mark stripping when switching block types.\n */\n\nimport type { BlockNode, Mark } from '../../model/Document.js';\nimport { getBlockLength, getInlineChildren, isTextNode } from '../../model/Document.js';\nimport { isTextSelection } from '../../model/Selection.js';\nimport { type NodeTypeName, nodeType } from '../../model/TypeBrands.js';\nimport type { EditorState } from '../../state/EditorState.js';\nimport type { TransactionBuilder } from '../../state/Transaction.js';\nimport type { PluginContext } from '../Plugin.js';\nimport type { HeadingConfig, HeadingLevel } from './HeadingPlugin.js';\n\n/** Registers all heading commands (setTitle, setSubtitle, setHeadingN, toggleHeading, setParagraph). */\nexport function registerHeadingCommands(context: PluginContext, config: HeadingConfig): void {\n\tcontext.registerCommand('setTitle', () => toggleSpecialBlock(context, 'title'));\n\n\tcontext.registerCommand('setSubtitle', () => toggleSpecialBlock(context, 'subtitle'));\n\n\tfor (const level of config.levels) {\n\t\tcontext.registerCommand(`setHeading${level}`, () => toggleHeading(context, level));\n\t}\n\n\tcontext.registerCommand('toggleHeading', () => toggleHeading(context, 1));\n\n\tcontext.registerCommand('setParagraph', () => setBlockType(context, nodeType('paragraph')));\n}\n\n// --- Command Implementations ---\n\n/**\n * Toggles between a special block type (title/subtitle) and paragraph.\n * If the block is already that type, resets to paragraph.\n */\nfunction toggleSpecialBlock(context: PluginContext, type: string): boolean {\n\tconst state: EditorState = context.getState();\n\tif (!isTextSelection(state.selection)) return false;\n\n\tconst block: BlockNode | undefined = state.getBlock(state.selection.anchor.blockId);\n\tif (!block) return false;\n\n\tif (block.type === type) {\n\t\treturn setBlockType(context, nodeType('paragraph'));\n\t}\n\n\treturn setBlockType(context, nodeType(type) as NodeTypeName);\n}\n\n/**\n * Toggles between heading (at given level) and paragraph.\n * If the block is already a heading at the same level, resets to paragraph.\n */\nfunction toggleHeading(context: PluginContext, level: HeadingLevel): boolean {\n\tconst state: EditorState = context.getState();\n\tconst sel = state.selection;\n\tif (!isTextSelection(sel)) return false;\n\n\tconst block: BlockNode | undefined = state.getBlock(sel.anchor.blockId);\n\tif (!block) return false;\n\n\tif (block.type === 'heading' && block.attrs?.level === level) {\n\t\treturn setBlockType(context, nodeType('paragraph'));\n\t}\n\n\treturn setBlockType(context, nodeType('heading'), { level });\n}\n\nfunction setBlockType(\n\tcontext: PluginContext,\n\ttype: NodeTypeName,\n\tattrs?: Record<string, string | number | boolean>,\n): boolean {\n\tconst state: EditorState = context.getState();\n\tconst sel = state.selection;\n\tif (!isTextSelection(sel)) return false;\n\n\tconst block: BlockNode | undefined = state.getBlock(sel.anchor.blockId);\n\tif (!block) return false;\n\n\tconst builder: TransactionBuilder = state.transaction('command');\n\n\tconst spec = context.getSchemaRegistry().getNodeSpec(type);\n\tif (spec?.excludeMarks && spec.excludeMarks.length > 0) {\n\t\tstripExcludedMarks(builder, block, spec.excludeMarks);\n\t\tclearExcludedStoredMarks(builder, state, spec.excludeMarks);\n\t}\n\n\tconst tr = builder.setBlockType(sel.anchor.blockId, type, attrs).setSelection(sel).build();\n\tcontext.dispatch(tr);\n\treturn true;\n}\n\n// --- Mark Stripping Helpers ---\n\n/**\n * Adds removeMark steps for each excluded mark type found\n * on the block's inline text content.\n */\nfunction stripExcludedMarks(\n\tbuilder: TransactionBuilder,\n\tblock: BlockNode,\n\texcludeMarks: readonly string[],\n): void {\n\tconst blockLength: number = getBlockLength(block);\n\tif (blockLength === 0) return;\n\n\tconst excludeSet: Set<string> = new Set(excludeMarks);\n\tconst inlineChildren = getInlineChildren(block);\n\tlet offset = 0;\n\n\tfor (const child of inlineChildren) {\n\t\tif (isTextNode(child)) {\n\t\t\tif (child.text.length > 0) {\n\t\t\t\tfor (const mark of child.marks) {\n\t\t\t\t\tif (excludeSet.has(mark.type)) {\n\t\t\t\t\t\tbuilder.removeMark(block.id, offset, offset + child.text.length, mark);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\toffset += child.text.length;\n\t\t} else {\n\t\t\toffset += 1;\n\t\t}\n\t}\n}\n\n/**\n * Clears excluded mark types from stored marks so that\n * subsequent typing does not reintroduce them.\n */\nfunction clearExcludedStoredMarks(\n\tbuilder: TransactionBuilder,\n\tstate: EditorState,\n\texcludeMarks: readonly string[],\n): void {\n\tif (!state.storedMarks) return;\n\n\tconst excludeSet: Set<string> = new Set(excludeMarks);\n\tconst filtered: readonly Mark[] = state.storedMarks.filter((m: Mark) => !excludeSet.has(m.type));\n\n\tif (filtered.length !== state.storedMarks.length) {\n\t\tbuilder.setStoredMarks(filtered.length > 0 ? filtered : null, state.storedMarks);\n\t}\n}\n","/**\n * Keyboard handlers for heading block types.\n * Handles Enter key behavior: empty heading → paragraph, cursor at end → split + paragraph.\n */\n\nimport type { BlockNode } from '../../model/Document.js';\nimport { generateBlockId, getBlockLength, getBlockText } from '../../model/Document.js';\nimport { createCollapsedSelection, isCollapsed, isTextSelection } from '../../model/Selection.js';\nimport type { BlockId } from '../../model/TypeBrands.js';\nimport { nodeType } from '../../model/TypeBrands.js';\nimport type { EditorState } from '../../state/EditorState.js';\nimport type { PluginContext } from '../Plugin.js';\nimport type { HeadingConfig } from './HeadingPlugin.js';\n\n// --- Context Guard ---\n\nconst HEADING_TYPES: ReadonlySet<string> = new Set(['heading', 'title', 'subtitle']);\n\ninterface HeadingContext {\n\treadonly state: EditorState;\n\treadonly block: BlockNode;\n\treadonly blockId: BlockId;\n\treadonly offset: number;\n}\n\n/**\n * Guards against NodeSelection, non-collapsed selections, and non-heading blocks.\n * Returns false (not handled) if the cursor is not inside a heading-type block.\n */\nfunction withHeadingContext(\n\tcontext: PluginContext,\n\thandler: (ctx: HeadingContext) => boolean,\n): boolean {\n\tconst state: EditorState = context.getState();\n\tif (!isTextSelection(state.selection)) return false;\n\n\tconst sel = state.selection;\n\tif (!isCollapsed(sel)) return false;\n\n\tconst block: BlockNode | undefined = state.getBlock(sel.anchor.blockId);\n\tif (!block || !HEADING_TYPES.has(block.type)) return false;\n\n\treturn handler({\n\t\tstate,\n\t\tblock,\n\t\tblockId: sel.anchor.blockId,\n\t\toffset: sel.anchor.offset,\n\t});\n}\n\n/** Registers all heading keyboard handlers (Enter, Mod-Shift-N shortcuts). */\nexport function registerHeadingKeymaps(context: PluginContext, config: HeadingConfig): void {\n\tconst keymap: Record<string, () => boolean> = {\n\t\tEnter: () => handleEnter(context),\n\t};\n\n\tfor (const level of config.levels) {\n\t\tif (level <= 6) {\n\t\t\tkeymap[`Mod-Shift-${level}`] = () => context.executeCommand(`setHeading${level}`);\n\t\t}\n\t}\n\n\tcontext.registerKeymap(keymap);\n}\n\n// --- Enter Handler ---\n\n/**\n * Handles Enter inside a heading block.\n * Empty heading → convert to paragraph.\n * Cursor at end → split and convert new block to paragraph.\n * Cursor in middle → normal split (both stay heading).\n */\nfunction handleEnter(context: PluginContext): boolean {\n\treturn withHeadingContext(context, (ctx) => {\n\t\tconst text: string = getBlockText(ctx.block);\n\n\t\tif (text === '') {\n\t\t\tconst tr = ctx.state\n\t\t\t\t.transaction('input')\n\t\t\t\t.setBlockType(ctx.blockId, nodeType('paragraph'))\n\t\t\t\t.setSelection(ctx.state.selection)\n\t\t\t\t.build();\n\t\t\tcontext.dispatch(tr);\n\t\t\treturn true;\n\t\t}\n\n\t\tconst blockLength: number = getBlockLength(ctx.block);\n\n\t\tif (ctx.offset >= blockLength) {\n\t\t\tconst newBlockId = generateBlockId();\n\t\t\tconst tr = ctx.state\n\t\t\t\t.transaction('input')\n\t\t\t\t.splitBlock(ctx.blockId, ctx.offset, newBlockId)\n\t\t\t\t.setBlockType(newBlockId, nodeType('paragraph'))\n\t\t\t\t.setSelection(createCollapsedSelection(newBlockId, 0))\n\t\t\t\t.build();\n\t\t\tcontext.dispatch(tr);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t});\n}\n","/**\n * Locale interface and default English locale for the HeadingPlugin.\n */\n\n// --- Locale Interface ---\n\nexport interface HeadingLocale {\n\treadonly paragraph: string;\n\treadonly title: string;\n\treadonly subtitle: string;\n\treadonly heading1: string;\n\treadonly heading2: string;\n\treadonly heading3: string;\n\treadonly heading4: string;\n\treadonly heading5: string;\n\treadonly heading6: string;\n\treadonly blockTypeLabel: string;\n\treadonly blockTypesAria: string;\n}\n\n// --- Default English Locale ---\n\nexport const HEADING_LOCALE_EN: HeadingLocale = {\n\tparagraph: 'Paragraph',\n\ttitle: 'Title',\n\tsubtitle: 'Subtitle',\n\theading1: 'Heading 1',\n\theading2: 'Heading 2',\n\theading3: 'Heading 3',\n\theading4: 'Heading 4',\n\theading5: 'Heading 5',\n\theading6: 'Heading 6',\n\tblockTypeLabel: 'Block Type',\n\tblockTypesAria: 'Block types',\n};\n\n// --- Lazy Locale Loader ---\n\nconst localeModules: Record<string, () => Promise<{ default: HeadingLocale }>> = import.meta.glob<{\n\tdefault: HeadingLocale;\n}>('./locales/*.ts', { eager: false });\n\nexport async function loadHeadingLocale(lang: string): Promise<HeadingLocale> {\n\tif (lang === 'en') return HEADING_LOCALE_EN;\n\tconst loader = localeModules[`./locales/${lang}.ts`];\n\tif (!loader) return HEADING_LOCALE_EN;\n\ttry {\n\t\tconst mod = await loader();\n\t\treturn mod.default;\n\t} catch {\n\t\treturn HEADING_LOCALE_EN;\n\t}\n}\n","/**\n * HeadingPlugin: registers Title, Subtitle, and H1–H6 heading block types\n * with NodeSpec, toggle commands, keyboard shortcuts, input rules, and a\n * combobox-style toolbar dropdown that reflects the current block type.\n *\n * This file is a thin orchestrator — command logic, input rules, keyboard\n * handlers, and picker/toolbar rendering are delegated to dedicated modules.\n */\n\nimport { HEADING_SELECT_CSS } from '../../editor/styles/heading-select.js';\nimport type { BlockAlignment } from '../../model/BlockAlignment.js';\nimport { createBlockElement } from '../../view/DomUtils.js';\nimport type { Plugin, PluginContext } from '../Plugin.js';\nimport { resolveLocale } from '../shared/PluginHelpers.js';\nimport {\n\tregisterHeadingPickerEntries,\n\tregisterHeadingToolbarItem,\n} from './HeadingBlockTypePicker.js';\nimport { registerHeadingCommands } from './HeadingCommands.js';\nimport { registerHeadingInputRules } from './HeadingInputRules.js';\nimport { registerHeadingKeymaps } from './HeadingKeyboardHandlers.js';\nimport { HEADING_LOCALE_EN, type HeadingLocale, loadHeadingLocale } from './HeadingLocale.js';\n\n// --- Attribute Registry Augmentation ---\n\ndeclare module '../../model/AttrRegistry.js' {\n\tinterface NodeAttrRegistry {\n\t\theading: { level: HeadingLevel; align?: BlockAlignment };\n\t\ttitle: { align?: BlockAlignment };\n\t\tsubtitle: { align?: BlockAlignment };\n\t}\n}\n\n// --- Configuration ---\n\nexport type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;\n\nexport interface HeadingConfig {\n\t/** Which heading levels to enable. Defaults to [1, 2, 3, 4, 5, 6]. */\n\treadonly levels: readonly HeadingLevel[];\n\treadonly locale?: HeadingLocale;\n}\n\nconst DEFAULT_CONFIG: HeadingConfig = {\n\tlevels: [1, 2, 3, 4, 5, 6],\n};\n\n// --- Heading Tag Mapping ---\n\nconst HEADING_TAGS: Record<HeadingLevel, string> = {\n\t1: 'h1',\n\t2: 'h2',\n\t3: 'h3',\n\t4: 'h4',\n\t5: 'h5',\n\t6: 'h6',\n};\n\n// --- Plugin ---\n\nexport class HeadingPlugin implements Plugin {\n\treadonly id = 'heading';\n\treadonly name = 'Heading';\n\treadonly priority = 30;\n\n\tprivate readonly config: HeadingConfig;\n\tprivate locale!: HeadingLocale;\n\n\tconstructor(config?: Partial<HeadingConfig>) {\n\t\tthis.config = { ...DEFAULT_CONFIG, ...config };\n\t}\n\n\tasync init(context: PluginContext): Promise<void> {\n\t\tthis.locale = await resolveLocale(\n\t\t\tcontext,\n\t\t\tthis.config.locale,\n\t\t\tHEADING_LOCALE_EN,\n\t\t\tloadHeadingLocale,\n\t\t);\n\t\tcontext.registerStyleSheet(HEADING_SELECT_CSS);\n\n\t\tthis.registerNodeSpecs(context);\n\t\tregisterHeadingCommands(context, this.config);\n\t\tregisterHeadingKeymaps(context, this.config);\n\t\tregisterHeadingInputRules(context, this.config);\n\t\tregisterHeadingPickerEntries(context, this.config, this.locale);\n\t\tregisterHeadingToolbarItem(context, this.locale);\n\t}\n\n\tprivate registerNodeSpecs(context: PluginContext): void {\n\t\tcontext.registerNodeSpec({\n\t\t\ttype: 'title',\n\t\t\tgroup: 'block',\n\t\t\tcontent: { allow: ['text'] },\n\t\t\texcludeMarks: ['fontSize'],\n\t\t\ttoDOM(node) {\n\t\t\t\tconst el = createBlockElement('h1', node.id);\n\t\t\t\tel.classList.add('notectl-title');\n\t\t\t\treturn el;\n\t\t\t},\n\t\t\ttoHTML(_node, content) {\n\t\t\t\treturn `<h1 class=\"notectl-title\">${content || '<br>'}</h1>`;\n\t\t\t},\n\t\t\tparseHTML: [\n\t\t\t\t{\n\t\t\t\t\ttag: 'h1',\n\t\t\t\t\tpriority: 60,\n\t\t\t\t\tgetAttrs: (el) => (el.classList.contains('notectl-title') ? {} : false),\n\t\t\t\t},\n\t\t\t],\n\t\t\tsanitize: { tags: ['h1'], attrs: ['class'] },\n\t\t});\n\n\t\tcontext.registerNodeSpec({\n\t\t\ttype: 'subtitle',\n\t\t\tgroup: 'block',\n\t\t\tcontent: { allow: ['text'] },\n\t\t\texcludeMarks: ['fontSize'],\n\t\t\ttoDOM(node) {\n\t\t\t\tconst el = createBlockElement('h2', node.id);\n\t\t\t\tel.classList.add('notectl-subtitle');\n\t\t\t\treturn el;\n\t\t\t},\n\t\t\ttoHTML(_node, content) {\n\t\t\t\treturn `<h2 class=\"notectl-subtitle\">${content || '<br>'}</h2>`;\n\t\t\t},\n\t\t\tparseHTML: [\n\t\t\t\t{\n\t\t\t\t\ttag: 'h2',\n\t\t\t\t\tpriority: 60,\n\t\t\t\t\tgetAttrs: (el) => (el.classList.contains('notectl-subtitle') ? {} : false),\n\t\t\t\t},\n\t\t\t],\n\t\t\tsanitize: { tags: ['h2'], attrs: ['class'] },\n\t\t});\n\n\t\tcontext.registerNodeSpec({\n\t\t\ttype: 'heading',\n\t\t\tgroup: 'block',\n\t\t\tcontent: { allow: ['text'] },\n\t\t\texcludeMarks: ['fontSize'],\n\t\t\tattrs: {\n\t\t\t\tlevel: { default: 1 },\n\t\t\t},\n\t\t\ttoDOM(node) {\n\t\t\t\tconst level = node.attrs?.level ?? 1;\n\t\t\t\tconst tag = HEADING_TAGS[level] ?? 'h1';\n\t\t\t\treturn createBlockElement(tag, node.id);\n\t\t\t},\n\t\t\ttoHTML(node, content) {\n\t\t\t\tconst level = (node.attrs?.level ?? 1) as HeadingLevel;\n\t\t\t\tconst tag: string = HEADING_TAGS[level] ?? 'h1';\n\t\t\t\treturn `<${tag}>${content || '<br>'}</${tag}>`;\n\t\t\t},\n\t\t\tparseHTML: [\n\t\t\t\t{ tag: 'h1', getAttrs: () => ({ level: 1 }) },\n\t\t\t\t{ tag: 'h2', getAttrs: () => ({ level: 2 }) },\n\t\t\t\t{ tag: 'h3', getAttrs: () => ({ level: 3 }) },\n\t\t\t\t{ tag: 'h4', getAttrs: () => ({ level: 4 }) },\n\t\t\t\t{ tag: 'h5', getAttrs: () => ({ level: 5 }) },\n\t\t\t\t{ tag: 'h6', getAttrs: () => ({ level: 6 }) },\n\t\t\t],\n\t\t\tsanitize: { tags: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] },\n\t\t});\n\t}\n}\n","/** Heading picker toolbar combobox + popup styles. */\nexport const HEADING_SELECT_CSS = `\n/* Heading Select — Width overrides for combobox button */\n.notectl-toolbar-btn--heading {\n\tmin-width: 100px;\n\tmax-width: 160px;\n}\n\n/* Heading Picker Popup */\n.notectl-heading-picker {\n\tmin-width: 200px;\n\tmax-height: 320px;\n\toverflow-y: auto;\n}\n\n.notectl-heading-picker__list {\n\tpadding: 4px 0;\n}\n\n.notectl-heading-picker__item {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n\twidth: 100%;\n\tpadding: 7px 12px;\n\tborder: none;\n\tbackground: none;\n\tcursor: pointer;\n\tfont-size: 14px;\n\tcolor: var(--notectl-fg);\n\ttext-align: start;\n\twhite-space: nowrap;\n\tfont-family: inherit;\n\ttransition: background 0.1s;\n}\n\n@media (hover: hover) {\n\t.notectl-heading-picker__item:hover {\n\t\tbackground: var(--notectl-hover-bg);\n\t}\n}\n\n.notectl-heading-picker__item--active {\n\tbackground: var(--notectl-active-bg);\n\tcolor: var(--notectl-primary-fg);\n}\n\n@media (hover: hover) {\n\t.notectl-heading-picker__item--active:hover {\n\t\tbackground: var(--notectl-active-bg);\n\t}\n}\n\n.notectl-heading-picker__check {\n\tdisplay: inline-flex;\n\talign-items: center;\n\tjustify-content: center;\n\twidth: 16px;\n\tflex-shrink: 0;\n\tfont-size: 13px;\n\tfont-weight: 600;\n\tcolor: var(--notectl-primary-fg);\n}\n\n.notectl-heading-picker__label {\n\tflex: 1;\n}\n`;\n","/**\n * Input rule registration for heading block types.\n * Converts `# `, `## `, etc. at the start of a paragraph into headings.\n */\n\nimport { createCollapsedSelection, isCollapsed, isTextSelection } from '../../model/Selection.js';\nimport { nodeType } from '../../model/TypeBrands.js';\nimport type { PluginContext } from '../Plugin.js';\nimport type { HeadingConfig } from './HeadingPlugin.js';\n\n/** Registers markdown-style input rules (e.g. `# ` → H1) for configured heading levels. */\nexport function registerHeadingInputRules(context: PluginContext, config: HeadingConfig): void {\n\tfor (const level of config.levels) {\n\t\tconst hashes: string = '#'.repeat(level);\n\t\tconst pattern: RegExp = new RegExp(`^${hashes} $`);\n\n\t\tcontext.registerInputRule({\n\t\t\tpattern,\n\t\t\thandler(state, _match, start, _end) {\n\t\t\t\tconst sel = state.selection;\n\t\t\t\tif (!isTextSelection(sel)) return null;\n\t\t\t\tif (!isCollapsed(sel)) return null;\n\n\t\t\t\tconst block = state.getBlock(sel.anchor.blockId);\n\t\t\t\tif (!block || block.type !== 'paragraph') return null;\n\n\t\t\t\treturn state\n\t\t\t\t\t.transaction('input')\n\t\t\t\t\t.deleteTextAt(sel.anchor.blockId, start, start + level + 1)\n\t\t\t\t\t.setBlockType(sel.anchor.blockId, nodeType('heading'), { level })\n\t\t\t\t\t.setSelection(createCollapsedSelection(sel.anchor.blockId, 0))\n\t\t\t\t\t.build();\n\t\t\t},\n\t\t});\n\t}\n}\n"],"names":["createPickerItem","label","isActive","handler","style","item","document","createElement","type","className","setAttribute","String","classList","add","check","textContent","appendChild","labelSpan","setStyleProperties","fontSize","fontWeight","addEventListener","getHeadingLabel","locale","level","toggleSpecialBlock","context","state","getState","isTextSelection","selection","block","getBlock","anchor","blockId","setBlockType","nodeType","toggleHeading","sel","attrs","builder","transaction","spec","getSchemaRegistry","getNodeSpec","excludeMarks","length","getBlockLength","excludeSet","Set","inlineChildren","getInlineChildren","offset","child","isTextNode","text","mark","marks","has","removeMark","id","stripExcludedMarks","storedMarks","filtered","filter","m","setStoredMarks","clearExcludedStoredMarks","tr","setSelection","build","dispatch","HEADING_TYPES","HEADING_LOCALE_EN","paragraph","title","subtitle","heading1","heading2","heading3","heading4","heading5","heading6","blockTypeLabel","blockTypesAria","localeModules","assign","import","async","loadHeadingLocale","lang","loader","default","DEFAULT_CONFIG","levels","HEADING_TAGS","HeadingPlugin","name","priority","config","constructor","this","init","resolveLocale","registerStyleSheet","registerNodeSpecs","registerCommand","registerHeadingCommands","keymap","Enter","isCollapsed","withHeadingContext","ctx","getBlockText","blockLength","newBlockId","generateBlockId","splitBlock","createCollapsedSelection","handleEnter","executeCommand","registerKeymap","registerHeadingKeymaps","hashes","repeat","pattern","RegExp","registerInputRule","_match","start","_end","deleteTextAt","registerHeadingInputRules","registerBlockTypePickerEntry","command","registerHeadingPickerEntries","registerToolbarItem","group","tooltip","popupType","getLabel","entries","getBlockTypePickerRegistry","getBlockTypePickerEntries","entry","getActiveLabel","renderPopup","container","onClose","contentElement","getContainer","list","active","e","preventDefault","stopPropagation","restoreFocusTo","renderHeadingPopup","some","registerHeadingToolbarItem","registerNodeSpec","content","allow","toDOM","node","el","createBlockElement","toHTML","_node","parseHTML","tag","getAttrs","contains","sanitize","tags"],"mappings":"8TA6IA,SAASA,EACRC,EACAC,EACAC,EACAC,GAEA,MAAMC,EAA0BC,SAASC,cAAc,UACvDF,EAAKG,KAAO,SACZH,EAAKI,UAAY,+BACjBJ,EAAKK,aAAa,OAAQ,UAC1BL,EAAKK,aAAa,gBAAiBC,OAAOT,IAE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"./TypeBrands-Bp_Z_o5Y.mjs";import{f as u}from"./RangeIterator-CprUbOWv.mjs";function f(){return{nodeTypes:["paragraph"],markTypes:["bold","italic","underline"],getNodeSpec:()=>{}}}function l(e){return{nodeTypes:e.getNodeTypes(),markTypes:e.getMarkTypes(),getNodeSpec:t=>e.getNodeSpec(t)}}function d(e,t){return e.markTypes.includes(t)}function m(e,t){return e.nodeTypes.includes(t)}const k={bold:!0,italic:!0,underline:!0};function p(n,r,o=k){if(function(e,t){const n=e;return"bold"===n?!t.bold:"italic"===n?!t.italic:"underline"===n&&!t.underline}(r,o))return null;if(!d(n.schema,r))return null;if(!s(n.selection))return null;const a={type:r},f=n.selection;if(i(f)){const o=n.getBlock(f.anchor.blockId);if(!o)return null;const s=n.storedMarks??t(o,f.anchor.offset),i=e(s,r)?s.filter(e=>e.type!==r):[...s,a];return n.transaction("command").setStoredMarks(i,n.storedMarks).setSelection(f).build()}const l=c(f,n.getBlockOrder()),m=n.transaction("command"),p=h(n,r);return u(n,l,(e,t,n)=>{p?m.removeMark(e,t,n,a):m.addMark(e,t,n,a)}),m.setSelection(f),m.build()}function g(e,t){return p(e,a("bold"),t)}function b(e,t){return p(e,a("italic"),t)}function y(e,t){return p(e,a("underline"),t)}function T(n,r){const o=n.selection;if(!s(o))return!1;if(i(o)){if(n.storedMarks)return e(n.storedMarks,r);const s=n.getBlock(o.anchor.blockId);if(!s)return!1;const i=t(s,o.anchor.offset);return e(i,r)}return h(n,r)}function h(e,t){const r=e.selection;if(!s(r))return!1;const o=e.getBlockOrder(),i=c(r,o),a=o.indexOf(i.from.blockId),u=o.indexOf(i.to.blockId);for(let s=a;s<=u;s++){const r=o[s];if(!r)continue;const c=e.getBlock(r);if(!c)continue;const f=n(c);if(!M(c,s===a?i.from.offset:0,s===u?i.to.offset:f,t))return!1}return!0}function M(t,n,s,i){if(n===s)return!1;let c=0;for(const a of r(t))if(o(a)){const t=c+a.text.length;if(t>n&&c<s&&!e(a.marks,i))return!1;c=t}else c+=1;return!0}export{d as a,b,p as c,f as d,y as e,m as f,T as i,l as s,g as t};
2
+ //# sourceMappingURL=MarkCommands-CTuVDqnn.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MarkCommands-CTuVDqnn.mjs","sources":["../../src/model/Schema.ts","../../src/commands/MarkCommands.ts"],"sourcesContent":["/**\n * Schema definition for the Notectl editor.\n * Defines which node types and marks are allowed.\n */\n\nimport type { NodeSpec } from './NodeSpec.js';\nimport type { SchemaRegistry } from './SchemaRegistry.js';\n\nexport interface Schema {\n\treadonly nodeTypes: readonly string[];\n\treadonly markTypes: readonly string[];\n\t/** Looks up the full NodeSpec for a given type. Available when created via schemaFromRegistry. */\n\treadonly getNodeSpec?: (type: string) => NodeSpec | undefined;\n}\n\n/** Creates the default schema with paragraph nodes and bold/italic/underline marks. */\nexport function defaultSchema(): Schema {\n\treturn {\n\t\tnodeTypes: ['paragraph'],\n\t\tmarkTypes: ['bold', 'italic', 'underline'],\n\t\tgetNodeSpec: () => undefined,\n\t};\n}\n\n/** Derives a Schema from a SchemaRegistry's registered specs. */\nexport function schemaFromRegistry(registry: SchemaRegistry): Schema {\n\treturn {\n\t\tnodeTypes: registry.getNodeTypes(),\n\t\tmarkTypes: registry.getMarkTypes(),\n\t\tgetNodeSpec: (type: string) => registry.getNodeSpec(type),\n\t};\n}\n\n/** Checks whether the given mark type is allowed by the schema. */\nexport function isMarkAllowed(schema: Schema, markType: string): boolean {\n\treturn schema.markTypes.includes(markType);\n}\n\n/** Checks whether the given node type is allowed by the schema. */\nexport function isNodeTypeAllowed(schema: Schema, nodeType: string): boolean {\n\treturn schema.nodeTypes.includes(nodeType);\n}\n","/**\n * Mark-related commands: toggling bold/italic/underline and checking\n * whether a mark is active.\n */\n\nimport {\n\ttype BlockNode,\n\ttype Mark,\n\tgetBlockLength,\n\tgetBlockMarksAtOffset,\n\tgetInlineChildren,\n\thasMark,\n\tisTextNode,\n} from '../model/Document.js';\nimport { isMarkAllowed } from '../model/Schema.js';\nimport { isCollapsed, isTextSelection, selectionRange } from '../model/Selection.js';\nimport type { MarkTypeName } from '../model/TypeBrands.js';\nimport { markType as mkType } from '../model/TypeBrands.js';\nimport type { EditorState } from '../state/EditorState.js';\nimport type { Transaction } from '../state/Transaction.js';\nimport { forEachBlockInRange } from './RangeIterator.js';\n\n// --- Feature Configuration ---\n\nexport interface FeatureConfig {\n\treadonly bold: boolean;\n\treadonly italic: boolean;\n\treadonly underline: boolean;\n}\n\nconst defaultFeatures: FeatureConfig = { bold: true, italic: true, underline: true };\n\n/**\n * Toggles a mark on the current selection.\n * If collapsed, toggles stored marks. If range, applies/removes from text.\n */\nexport function toggleMark(\n\tstate: EditorState,\n\tmarkType: MarkTypeName,\n\tfeatures: FeatureConfig = defaultFeatures,\n): Transaction | null {\n\tif (isFeatureGated(markType, features)) return null;\n\tif (!isMarkAllowed(state.schema, markType)) return null;\n\tif (!isTextSelection(state.selection)) return null;\n\n\tconst mark: Mark = { type: markType };\n\tconst sel = state.selection;\n\n\tif (isCollapsed(sel)) {\n\t\t// Toggle stored marks\n\t\tconst anchorBlock = state.getBlock(sel.anchor.blockId);\n\t\tif (!anchorBlock) return null;\n\t\tconst currentMarks = state.storedMarks ?? getBlockMarksAtOffset(anchorBlock, sel.anchor.offset);\n\t\tconst hasIt = hasMark(currentMarks, markType);\n\t\tconst newMarks = hasIt\n\t\t\t? currentMarks.filter((m) => m.type !== markType)\n\t\t\t: [...currentMarks, mark];\n\n\t\treturn state\n\t\t\t.transaction('command')\n\t\t\t.setStoredMarks(newMarks, state.storedMarks)\n\t\t\t.setSelection(sel)\n\t\t\t.build();\n\t}\n\n\t// Range selection — apply/remove mark to all blocks in range\n\tconst range = selectionRange(sel, state.getBlockOrder());\n\tconst builder = state.transaction('command');\n\n\t// Determine if we should add or remove\n\tconst shouldRemove = isMarkActiveInRange(state, markType);\n\n\tforEachBlockInRange(state, range, (blockId, from, to) => {\n\t\tif (shouldRemove) {\n\t\t\tbuilder.removeMark(blockId, from, to, mark);\n\t\t} else {\n\t\t\tbuilder.addMark(blockId, from, to, mark);\n\t\t}\n\t});\n\n\tbuilder.setSelection(sel);\n\treturn builder.build();\n}\n\nexport function toggleBold(state: EditorState, features?: FeatureConfig): Transaction | null {\n\treturn toggleMark(state, mkType('bold'), features);\n}\n\nexport function toggleItalic(state: EditorState, features?: FeatureConfig): Transaction | null {\n\treturn toggleMark(state, mkType('italic'), features);\n}\n\nexport function toggleUnderline(state: EditorState, features?: FeatureConfig): Transaction | null {\n\treturn toggleMark(state, mkType('underline'), features);\n}\n\n/** Checks if a mark is active at the current selection. */\nexport function isMarkActive(state: EditorState, markType: MarkTypeName): boolean {\n\tconst sel = state.selection;\n\tif (!isTextSelection(sel)) return false;\n\n\tif (isCollapsed(sel)) {\n\t\tif (state.storedMarks) {\n\t\t\treturn hasMark(state.storedMarks, markType);\n\t\t}\n\t\tconst block = state.getBlock(sel.anchor.blockId);\n\t\tif (!block) return false;\n\t\tconst marks = getBlockMarksAtOffset(block, sel.anchor.offset);\n\t\treturn hasMark(marks, markType);\n\t}\n\n\treturn isMarkActiveInRange(state, markType);\n}\n\n/** Checks if a mark is active across the entire selection range. */\nfunction isMarkActiveInRange(state: EditorState, markType: MarkTypeName): boolean {\n\tconst sel = state.selection;\n\tif (!isTextSelection(sel)) return false;\n\tconst blockOrder = state.getBlockOrder();\n\tconst range = selectionRange(sel, blockOrder);\n\n\tconst fromIdx = blockOrder.indexOf(range.from.blockId);\n\tconst toIdx = blockOrder.indexOf(range.to.blockId);\n\n\tfor (let i = fromIdx; i <= toIdx; i++) {\n\t\tconst blockId = blockOrder[i];\n\t\tif (!blockId) continue;\n\t\tconst block = state.getBlock(blockId);\n\t\tif (!block) continue;\n\t\tconst blockLen = getBlockLength(block);\n\t\tconst from = i === fromIdx ? range.from.offset : 0;\n\t\tconst to = i === toIdx ? range.to.offset : blockLen;\n\n\t\tif (!isMarkActiveInBlock(block, from, to, markType)) return false;\n\t}\n\n\treturn true;\n}\n\nfunction isMarkActiveInBlock(\n\tblock: BlockNode,\n\tfrom: number,\n\tto: number,\n\tmarkType: MarkTypeName,\n): boolean {\n\tif (from === to) return false;\n\tlet pos = 0;\n\tfor (const child of getInlineChildren(block)) {\n\t\tif (isTextNode(child)) {\n\t\t\tconst childEnd = pos + child.text.length;\n\t\t\tif (childEnd > from && pos < to) {\n\t\t\t\tif (!hasMark(child.marks, markType)) return false;\n\t\t\t}\n\t\t\tpos = childEnd;\n\t\t} else {\n\t\t\t// InlineNode: skip (width 1, no marks)\n\t\t\tpos += 1;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction isFeatureGated(type: MarkTypeName, features: FeatureConfig): boolean {\n\tconst key = type as string;\n\tif (key === 'bold') return !features.bold;\n\tif (key === 'italic') return !features.italic;\n\tif (key === 'underline') return !features.underline;\n\treturn false;\n}\n"],"names":["defaultSchema","nodeTypes","markTypes","getNodeSpec","schemaFromRegistry","registry","getNodeTypes","getMarkTypes","type","isMarkAllowed","schema","markType","includes","isNodeTypeAllowed","nodeType","defaultFeatures","bold","italic","underline","toggleMark","state","features","key","isFeatureGated","isTextSelection","selection","mark","sel","isCollapsed","anchorBlock","getBlock","anchor","blockId","currentMarks","storedMarks","getBlockMarksAtOffset","offset","newMarks","hasMark","filter","m","transaction","setStoredMarks","setSelection","build","range","selectionRange","getBlockOrder","builder","shouldRemove","isMarkActiveInRange","forEachBlockInRange","from","to","removeMark","addMark","toggleBold","mkType","toggleItalic","toggleUnderline","isMarkActive","block","marks","blockOrder","fromIdx","indexOf","toIdx","i","blockLen","getBlockLength","isMarkActiveInBlock","pos","child","getInlineChildren","isTextNode","childEnd","text","length"],"mappings":"6NAgBO,SAASA,IACf,MAAO,CACNC,UAAW,CAAC,aACZC,UAAW,CAAC,OAAQ,SAAU,aAC9BC,YAAa,OAEf,CAGO,SAASC,EAAmBC,GAClC,MAAO,CACNJ,UAAWI,EAASC,eACpBJ,UAAWG,EAASE,eACpBJ,YAAcK,GAAiBH,EAASF,YAAYK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AS2D,EACRT,EACAT,EACAC,EACA1C,GAEA,GAAIyC,IAASC,EAAI,OAAO,EACxB,IAAIkB,EAAM,EACV,IAAA,MAAWC,KAASC,EAAkBZ,GACrC,GAAIa,EAAWF,GAAQ,CACtB,MAAMG,EAAWJ,EAAMC,EAAMI,KAAKC,OAClC,GAAIF,EAAWvB,GAAQmB,EAAMlB,IACvBf,EAAQkC,EAAMV,MAAOnD,GAAW,OAAO,EAE7C4D,EAAMI,CACP,MAECJ,GAAO,EAGT,OAAO,CACR"}
@@ -1,2 +1,2 @@
1
- import{n}from"./Document-BFYAonMF.mjs";function t(t,e){if(0===e.length)return;let r=t.children.find(n=>n.id===e[0]);if(r){for(let t=1;t<e.length;t++){const i=e[t];if(!i)return;const o=r?.children.find(t=>n(t)&&t.id===i);if(!o)return;r=o}return r}}function e(e,r){if(0===r.length)return;if(1===r.length){const n=e.children.findIndex(n=>n.id===r[0]);if(-1===n)return;return{parent:e,index:n}}const i=t(e,r.slice(0,-1));if(!i)return;const o=r[r.length-1];if(!o)return;const c=i.children.findIndex(t=>n(t)&&t.id===o);return-1!==c?{parent:i,index:c}:void 0}function r(n,t){for(const e of n.children){if(e.id===t)return[t];const n=i(e,t);if(n)return[e.id,...n]}}function i(t,e){for(const r of t.children){if(!n(r))continue;if(r.id===e)return[e];const t=i(r,e);if(t)return[r.id,...t]}}function o(n,t){for(const e of n.children)c(e,[e.id],t)}function c(t,e,r){r(t,e);for(const i of t.children)n(i)&&c(i,[...e,i.id],r)}function f(n,t){for(const e of n.children){if(e.id===t)return e;const n=u(e,t);if(n)return n}}function u(t,e){for(const r of t.children){if(!n(r))continue;if(r.id===e)return r;const t=u(r,e);if(t)return t}}function s(n,e){const i=r(n,e);if(!i)return;const o=t(n,i);return o?{node:o,path:i}:void 0}function d(n,t){const e=n.getBlock(t);if(!e)return!1;const r=n.schema.getNodeSpec;return!!r&&!0===r(e.type)?.isVoid}function l(n,t,e){const r=n.getNodePath(t),i=n.getNodePath(e);if(!r||!i)return!1;if(r.length!==i.length)return!1;for(let o=0;o<r.length-1;o++)if(r[o]!==i[o])return!1;return!0}function h(n,t){const e=n.schema.getNodeSpec;if(!e)return!1;const r=n.getNodePath(t);if(!r||r.length<=1)return!1;for(let i=0;i<r.length-1;i++){const t=r[i];if(!t)continue;const o=n.getBlock(t);if(!o)continue;const c=e(o.type);if(c?.isolating)return!0}return!1}function a(n,t){const e=n.schema.getNodeSpec;if(!e)return!1;const r=n.getBlock(t);return!!r&&!0===e(r.type)?.isolating}function g(n,t,e){if(a(n,t)||a(n,e))return!1;const r=h(n,t),i=h(n,e);return r===i&&(!r||!i||l(n,t,e))}export{r as a,s as b,g as c,a as d,d as e,f,e as g,h as i,t as r,l as s,o as w};
2
- //# sourceMappingURL=NavigationQueries-ogQuObz7.mjs.map
1
+ import{n}from"./Document-HC8s50qJ.mjs";function t(t,e){if(0===e.length)return;let r=t.children.find(n=>n.id===e[0]);if(r){for(let t=1;t<e.length;t++){const i=e[t];if(!i)return;const o=r?.children.find(t=>n(t)&&t.id===i);if(!o)return;r=o}return r}}function e(e,r){if(0===r.length)return;if(1===r.length){const n=e.children.findIndex(n=>n.id===r[0]);if(-1===n)return;return{parent:e,index:n}}const i=t(e,r.slice(0,-1));if(!i)return;const o=r[r.length-1];if(!o)return;const c=i.children.findIndex(t=>n(t)&&t.id===o);return-1!==c?{parent:i,index:c}:void 0}function r(n,t){for(const e of n.children){if(e.id===t)return[t];const n=i(e,t);if(n)return[e.id,...n]}}function i(t,e){for(const r of t.children){if(!n(r))continue;if(r.id===e)return[e];const t=i(r,e);if(t)return[r.id,...t]}}function o(n,t){for(const e of n.children)c(e,[e.id],t)}function c(t,e,r){r(t,e);for(const i of t.children)n(i)&&c(i,[...e,i.id],r)}function f(n,t){for(const e of n.children){if(e.id===t)return e;const n=u(e,t);if(n)return n}}function u(t,e){for(const r of t.children){if(!n(r))continue;if(r.id===e)return r;const t=u(r,e);if(t)return t}}function s(n,e){const i=r(n,e);if(!i)return;const o=t(n,i);return o?{node:o,path:i}:void 0}function d(n,t){const e=n.getBlock(t);if(!e)return!1;const r=n.schema.getNodeSpec;return!!r&&!0===r(e.type)?.isVoid}function l(n,t,e){const r=n.getNodePath(t),i=n.getNodePath(e);if(!r||!i)return!1;if(r.length!==i.length)return!1;for(let o=0;o<r.length-1;o++)if(r[o]!==i[o])return!1;return!0}function h(n,t){const e=n.schema.getNodeSpec;if(!e)return!1;const r=n.getNodePath(t);if(!r||r.length<=1)return!1;for(let i=0;i<r.length-1;i++){const t=r[i];if(!t)continue;const o=n.getBlock(t);if(!o)continue;const c=e(o.type);if(c?.isolating)return!0}return!1}function a(n,t){const e=n.schema.getNodeSpec;if(!e)return!1;const r=n.getBlock(t);return!!r&&!0===e(r.type)?.isolating}function g(n,t,e){if(a(n,t)||a(n,e))return!1;const r=h(n,t),i=h(n,e);return r===i&&(!r||!i||l(n,t,e))}export{r as a,s as b,g as c,a as d,d as e,f,e as g,h as i,t as r,l as s,o as w};
2
+ //# sourceMappingURL=NavigationQueries-DCOv4Ca5.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"NavigationQueries-ogQuObz7.mjs","sources":["../../src/model/NodeResolver.ts","../../src/state/NavigationQueries.ts"],"sourcesContent":["/**\n * Utilities for resolving nodes by path within the document tree.\n * Supports both flat and recursive (nested) document structures.\n */\n\nimport type { BlockNode, Document } from './Document.js';\nimport { isBlockNode } from './Document.js';\n\n/**\n * Resolves a node in the document tree by its path (array of block IDs).\n * The path traces the lineage from the root block down to the target.\n */\nexport function resolveNodeByPath(doc: Document, path: readonly string[]): BlockNode | undefined {\n\tif (path.length === 0) return undefined;\n\n\tlet current: BlockNode | undefined = doc.children.find((b) => b.id === path[0]);\n\tif (!current) return undefined;\n\n\tfor (let i = 1; i < path.length; i++) {\n\t\tconst childId = path[i];\n\t\tif (!childId) return undefined;\n\t\tconst next: BlockNode | undefined = current?.children.find(\n\t\t\t(c): c is BlockNode => isBlockNode(c) && c.id === childId,\n\t\t);\n\t\tif (!next) return undefined;\n\t\tcurrent = next;\n\t}\n\n\treturn current;\n}\n\n/**\n * Resolves the parent of a node at the given path.\n * Returns the parent container (Document or BlockNode) and the child's index within it.\n */\nexport function resolveParentByPath(\n\tdoc: Document,\n\tpath: readonly string[],\n): { parent: Document | BlockNode; index: number } | undefined {\n\tif (path.length === 0) return undefined;\n\n\tif (path.length === 1) {\n\t\tconst index = doc.children.findIndex((b) => b.id === path[0]);\n\t\tif (index === -1) return undefined;\n\t\treturn { parent: doc, index };\n\t}\n\n\tconst parentPath = path.slice(0, -1);\n\tconst parent = resolveNodeByPath(doc, parentPath);\n\tif (!parent) return undefined;\n\n\tconst childId = path[path.length - 1];\n\tif (!childId) return undefined;\n\tconst index = parent.children.findIndex(\n\t\t(c): c is BlockNode => isBlockNode(c) && c.id === childId,\n\t);\n\tif (index === -1) return undefined;\n\n\treturn { parent, index };\n}\n\n/**\n * Finds the path (array of block IDs) to a node by its ID.\n * Performs recursive DFS through the document tree.\n */\nexport function findNodePath(doc: Document, nodeId: string): string[] | undefined {\n\tfor (const block of doc.children) {\n\t\tif (block.id === nodeId) return [nodeId];\n\n\t\tconst subPath = findNodePathInBlock(block, nodeId);\n\t\tif (subPath) return [block.id, ...subPath];\n\t}\n\treturn undefined;\n}\n\nfunction findNodePathInBlock(block: BlockNode, nodeId: string): string[] | undefined {\n\tfor (const child of block.children) {\n\t\tif (!isBlockNode(child)) continue;\n\t\tif (child.id === nodeId) return [nodeId];\n\n\t\tconst subPath = findNodePathInBlock(child, nodeId);\n\t\tif (subPath) return [child.id, ...subPath];\n\t}\n\treturn undefined;\n}\n\n/**\n * Walks all block nodes in the document tree in depth-first order.\n * Visits every BlockNode, including nested ones, with their full path.\n */\nexport function walkNodes(\n\tdoc: Document,\n\tcallback: (node: BlockNode, path: string[]) => void,\n): void {\n\tfor (const block of doc.children) {\n\t\twalkNodeRecursive(block, [block.id], callback);\n\t}\n}\n\nfunction walkNodeRecursive(\n\tnode: BlockNode,\n\tpath: string[],\n\tcallback: (node: BlockNode, path: string[]) => void,\n): void {\n\tcallback(node, path);\n\tfor (const child of node.children) {\n\t\tif (isBlockNode(child)) {\n\t\t\twalkNodeRecursive(child, [...path, child.id], callback);\n\t\t}\n\t}\n}\n\n/**\n * Finds a block node by ID anywhere in the document tree (recursive DFS).\n */\nexport function findNode(doc: Document, nodeId: string): BlockNode | undefined {\n\tfor (const block of doc.children) {\n\t\tif (block.id === nodeId) return block;\n\t\tconst found = findNodeInBlock(block, nodeId);\n\t\tif (found) return found;\n\t}\n\treturn undefined;\n}\n\nfunction findNodeInBlock(block: BlockNode, nodeId: string): BlockNode | undefined {\n\tfor (const child of block.children) {\n\t\tif (!isBlockNode(child)) continue;\n\t\tif (child.id === nodeId) return child;\n\t\tconst found = findNodeInBlock(child, nodeId);\n\t\tif (found) return found;\n\t}\n\treturn undefined;\n}\n\n/**\n * Finds a block node and returns it together with its path.\n */\nexport function findNodeWithPath(\n\tdoc: Document,\n\tnodeId: string,\n): { node: BlockNode; path: string[] } | undefined {\n\tconst path = findNodePath(doc, nodeId);\n\tif (!path) return undefined;\n\tconst node = resolveNodeByPath(doc, path);\n\tif (!node) return undefined;\n\treturn { node, path };\n}\n","/**\n * Pure navigation query functions for block boundary and isolating checks.\n *\n * These utilities inspect the document structure and schema to answer\n * questions about block traversal — whether a block is void, isolating,\n * or whether navigation between two blocks is allowed.\n */\n\nimport type { BlockId } from '../model/TypeBrands.js';\nimport type { EditorState } from './EditorState.js';\n\n/** Returns true if the block with the given ID is a void block (e.g. image, HR). */\nexport function isVoidBlock(state: EditorState, bid: BlockId): boolean {\n\tconst block = state.getBlock(bid);\n\tif (!block) return false;\n\tconst getNodeSpec = state.schema.getNodeSpec;\n\tif (!getNodeSpec) return false;\n\treturn getNodeSpec(block.type)?.isVoid === true;\n}\n\n/** Checks whether two blocks share the same parent in the document tree. */\nexport function sharesParent(state: EditorState, blockIdA: BlockId, blockIdB: BlockId): boolean {\n\tconst pathA = state.getNodePath(blockIdA);\n\tconst pathB = state.getNodePath(blockIdB);\n\tif (!pathA || !pathB) return false;\n\tif (pathA.length !== pathB.length) return false;\n\t// Compare parent paths (all but last element)\n\tfor (let i = 0; i < pathA.length - 1; i++) {\n\t\tif (pathA[i] !== pathB[i]) return false;\n\t}\n\treturn true;\n}\n\n/** Checks whether a block is inside an isolating node (e.g. table_cell). */\nexport function isInsideIsolating(state: EditorState, blockId: BlockId): boolean {\n\tconst getNodeSpec = state.schema.getNodeSpec;\n\tif (!getNodeSpec) return false;\n\tconst path = state.getNodePath(blockId);\n\tif (!path || path.length <= 1) return false;\n\n\t// Check ancestors (not the block itself)\n\tfor (let i = 0; i < path.length - 1; i++) {\n\t\tconst ancestorId = path[i];\n\t\tif (!ancestorId) continue;\n\t\tconst ancestor = state.getBlock(ancestorId);\n\t\tif (!ancestor) continue;\n\t\tconst spec = getNodeSpec(ancestor.type);\n\t\tif (spec?.isolating) return true;\n\t}\n\treturn false;\n}\n\n/** Returns true if the block itself has the isolating property. */\nexport function isIsolatingBlock(state: EditorState, blockId: BlockId): boolean {\n\tconst getNodeSpec = state.schema.getNodeSpec;\n\tif (!getNodeSpec) return false;\n\tconst block = state.getBlock(blockId);\n\tif (!block) return false;\n\treturn getNodeSpec(block.type)?.isolating === true;\n}\n\n/**\n * Checks whether navigation between two blocks is allowed.\n * Prevents crossing isolating boundaries (e.g. table cells).\n */\nexport function canCrossBlockBoundary(state: EditorState, fromId: BlockId, toId: BlockId): boolean {\n\t// A block that is itself isolating cannot be crossed into via arrow keys\n\tif (isIsolatingBlock(state, fromId) || isIsolatingBlock(state, toId)) return false;\n\n\tconst fromInside: boolean = isInsideIsolating(state, fromId);\n\tconst toInside: boolean = isInsideIsolating(state, toId);\n\n\t// One inside isolating, the other not → disallow\n\tif (fromInside !== toInside) return false;\n\n\t// Both inside isolating → must share the same parent\n\tif (fromInside && toInside) return sharesParent(state, fromId, toId);\n\n\treturn true;\n}\n"],"names":["resolveNodeByPath","doc","path","length","current","children","find","b","id","i","childId","next","c","isBlockNode","resolveParentByPath","index","findIndex","parent","slice","findNodePath","nodeId","block","subPath","findNodePathInBlock","child","walkNodes","callback","walkNodeRecursive","node","findNode","found","findNodeInBlock","findNodeWithPath","isVoidBlock","state","bid","getBlock","getNodeSpec","schema","type","isVoid","sharesParent","blockIdA","blockIdB","pathA","getNodePath","pathB","isInsideIsolating","blockId","ancestorId","ancestor","spec","isolating","isIsolatingBlock","canCrossBlockBoundary","fromId","toId","fromInside","toInside"],"mappings":"uCAYO,SAASA,EAAkBC,EAAeC,GAChD,GAAoB,IAAhBA,EAAKC,OAAc,OAEvB,IAAIC,EAAiCH,EAAII,SAASC,KAAMC,GAAMA,EAAEC,KAAON,EAAK,IAC5E,GAAKE,EAAL,CAEA,IAAA,IAASK,EAAI,EAAGA,EAAIP,EAAKC,OAAQM,IAAK,CACrC,MAAMC,EAAUR,EAAKO,GACrB,IAAKC,EAAS,OACd,MAAMC,EAA8BP,GAASC,SAASC,KACpDM,GAAsBC,EAAYD,IAAMA,EAAEJ,KAAOE,GAEnD,IAAKC,EAAM,OACXP,EAAUO,CACX,CAEA,OAAOP,CAZc,CAatB,CAMO,SAASU,EACfb,EACAC,GAEA,GAAoB,IAAhBA,EAAKC,OAAc,OAEvB,GAAoB,IAAhBD,EAAKC,OAAc,CACtB,MAAMY,EAAQd,EAAII,SAASW,UAAWT,GAAMA,EAAEC,KAAON,EAAK,IAC1D,QAAIa,EAAc,OAClB,MAAO,CAAEE,OAAQhB,EAAKc,MAAAA,EACvB,CAEA,MACME,EAASjB,EAAkBC,EADdC,EAAKgB,MAAM,GAAG,IAEjC,IAAKD,EAAQ,OAEb,MAAMP,EAAUR,EAAKA,EAAKC,OAAS,GACnC,IAAKO,EAAS,OACd,MAAMK,EAAQE,EAAOZ,SAASW,UAC5BJ,GAAsBC,EAAYD,IAAMA,EAAEJ,KAAOE,GAEnD,WAAIK,EAEG,CAAEE,SAAQF,cAFjB,CAGD,CAMO,SAASI,EAAalB,EAAemB,GAC3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AAiBnB,EAAOsB,GAAO,OAAO,EAE7E,MAAMC,EAAsBV,EAAkBb,EAAOqB,GAC/CG,EAAoBX,EAAkBb,EAAOsB,GAGnD,OAAIC,IAAeC,KAGfD,IAAcC,GAAiBjB,EAAaP,EAAOqB,EAAQC,GAGhE"}
1
+ {"version":3,"file":"NavigationQueries-DCOv4Ca5.mjs","sources":["../../src/model/NodeResolver.ts","../../src/state/NavigationQueries.ts"],"sourcesContent":["/**\n * Utilities for resolving nodes by path within the document tree.\n * Supports both flat and recursive (nested) document structures.\n */\n\nimport type { BlockNode, Document } from './Document.js';\nimport { isBlockNode } from './Document.js';\n\n/**\n * Resolves a node in the document tree by its path (array of block IDs).\n * The path traces the lineage from the root block down to the target.\n */\nexport function resolveNodeByPath(doc: Document, path: readonly string[]): BlockNode | undefined {\n\tif (path.length === 0) return undefined;\n\n\tlet current: BlockNode | undefined = doc.children.find((b) => b.id === path[0]);\n\tif (!current) return undefined;\n\n\tfor (let i = 1; i < path.length; i++) {\n\t\tconst childId = path[i];\n\t\tif (!childId) return undefined;\n\t\tconst next: BlockNode | undefined = current?.children.find(\n\t\t\t(c): c is BlockNode => isBlockNode(c) && c.id === childId,\n\t\t);\n\t\tif (!next) return undefined;\n\t\tcurrent = next;\n\t}\n\n\treturn current;\n}\n\n/**\n * Resolves the parent of a node at the given path.\n * Returns the parent container (Document or BlockNode) and the child's index within it.\n */\nexport function resolveParentByPath(\n\tdoc: Document,\n\tpath: readonly string[],\n): { parent: Document | BlockNode; index: number } | undefined {\n\tif (path.length === 0) return undefined;\n\n\tif (path.length === 1) {\n\t\tconst index = doc.children.findIndex((b) => b.id === path[0]);\n\t\tif (index === -1) return undefined;\n\t\treturn { parent: doc, index };\n\t}\n\n\tconst parentPath = path.slice(0, -1);\n\tconst parent = resolveNodeByPath(doc, parentPath);\n\tif (!parent) return undefined;\n\n\tconst childId = path[path.length - 1];\n\tif (!childId) return undefined;\n\tconst index = parent.children.findIndex(\n\t\t(c): c is BlockNode => isBlockNode(c) && c.id === childId,\n\t);\n\tif (index === -1) return undefined;\n\n\treturn { parent, index };\n}\n\n/**\n * Finds the path (array of block IDs) to a node by its ID.\n * Performs recursive DFS through the document tree.\n */\nexport function findNodePath(doc: Document, nodeId: string): string[] | undefined {\n\tfor (const block of doc.children) {\n\t\tif (block.id === nodeId) return [nodeId];\n\n\t\tconst subPath = findNodePathInBlock(block, nodeId);\n\t\tif (subPath) return [block.id, ...subPath];\n\t}\n\treturn undefined;\n}\n\nfunction findNodePathInBlock(block: BlockNode, nodeId: string): string[] | undefined {\n\tfor (const child of block.children) {\n\t\tif (!isBlockNode(child)) continue;\n\t\tif (child.id === nodeId) return [nodeId];\n\n\t\tconst subPath = findNodePathInBlock(child, nodeId);\n\t\tif (subPath) return [child.id, ...subPath];\n\t}\n\treturn undefined;\n}\n\n/**\n * Walks all block nodes in the document tree in depth-first order.\n * Visits every BlockNode, including nested ones, with their full path.\n */\nexport function walkNodes(\n\tdoc: Document,\n\tcallback: (node: BlockNode, path: string[]) => void,\n): void {\n\tfor (const block of doc.children) {\n\t\twalkNodeRecursive(block, [block.id], callback);\n\t}\n}\n\nfunction walkNodeRecursive(\n\tnode: BlockNode,\n\tpath: string[],\n\tcallback: (node: BlockNode, path: string[]) => void,\n): void {\n\tcallback(node, path);\n\tfor (const child of node.children) {\n\t\tif (isBlockNode(child)) {\n\t\t\twalkNodeRecursive(child, [...path, child.id], callback);\n\t\t}\n\t}\n}\n\n/**\n * Finds a block node by ID anywhere in the document tree (recursive DFS).\n */\nexport function findNode(doc: Document, nodeId: string): BlockNode | undefined {\n\tfor (const block of doc.children) {\n\t\tif (block.id === nodeId) return block;\n\t\tconst found = findNodeInBlock(block, nodeId);\n\t\tif (found) return found;\n\t}\n\treturn undefined;\n}\n\nfunction findNodeInBlock(block: BlockNode, nodeId: string): BlockNode | undefined {\n\tfor (const child of block.children) {\n\t\tif (!isBlockNode(child)) continue;\n\t\tif (child.id === nodeId) return child;\n\t\tconst found = findNodeInBlock(child, nodeId);\n\t\tif (found) return found;\n\t}\n\treturn undefined;\n}\n\n/**\n * Finds a block node and returns it together with its path.\n */\nexport function findNodeWithPath(\n\tdoc: Document,\n\tnodeId: string,\n): { node: BlockNode; path: string[] } | undefined {\n\tconst path = findNodePath(doc, nodeId);\n\tif (!path) return undefined;\n\tconst node = resolveNodeByPath(doc, path);\n\tif (!node) return undefined;\n\treturn { node, path };\n}\n","/**\n * Pure navigation query functions for block boundary and isolating checks.\n *\n * These utilities inspect the document structure and schema to answer\n * questions about block traversal — whether a block is void, isolating,\n * or whether navigation between two blocks is allowed.\n */\n\nimport type { BlockId } from '../model/TypeBrands.js';\nimport type { EditorState } from './EditorState.js';\n\n/** Returns true if the block with the given ID is a void block (e.g. image, HR). */\nexport function isVoidBlock(state: EditorState, bid: BlockId): boolean {\n\tconst block = state.getBlock(bid);\n\tif (!block) return false;\n\tconst getNodeSpec = state.schema.getNodeSpec;\n\tif (!getNodeSpec) return false;\n\treturn getNodeSpec(block.type)?.isVoid === true;\n}\n\n/** Checks whether two blocks share the same parent in the document tree. */\nexport function sharesParent(state: EditorState, blockIdA: BlockId, blockIdB: BlockId): boolean {\n\tconst pathA = state.getNodePath(blockIdA);\n\tconst pathB = state.getNodePath(blockIdB);\n\tif (!pathA || !pathB) return false;\n\tif (pathA.length !== pathB.length) return false;\n\t// Compare parent paths (all but last element)\n\tfor (let i = 0; i < pathA.length - 1; i++) {\n\t\tif (pathA[i] !== pathB[i]) return false;\n\t}\n\treturn true;\n}\n\n/** Checks whether a block is inside an isolating node (e.g. table_cell). */\nexport function isInsideIsolating(state: EditorState, blockId: BlockId): boolean {\n\tconst getNodeSpec = state.schema.getNodeSpec;\n\tif (!getNodeSpec) return false;\n\tconst path = state.getNodePath(blockId);\n\tif (!path || path.length <= 1) return false;\n\n\t// Check ancestors (not the block itself)\n\tfor (let i = 0; i < path.length - 1; i++) {\n\t\tconst ancestorId = path[i];\n\t\tif (!ancestorId) continue;\n\t\tconst ancestor = state.getBlock(ancestorId);\n\t\tif (!ancestor) continue;\n\t\tconst spec = getNodeSpec(ancestor.type);\n\t\tif (spec?.isolating) return true;\n\t}\n\treturn false;\n}\n\n/** Returns true if the block itself has the isolating property. */\nexport function isIsolatingBlock(state: EditorState, blockId: BlockId): boolean {\n\tconst getNodeSpec = state.schema.getNodeSpec;\n\tif (!getNodeSpec) return false;\n\tconst block = state.getBlock(blockId);\n\tif (!block) return false;\n\treturn getNodeSpec(block.type)?.isolating === true;\n}\n\n/**\n * Checks whether navigation between two blocks is allowed.\n * Prevents crossing isolating boundaries (e.g. table cells).\n */\nexport function canCrossBlockBoundary(state: EditorState, fromId: BlockId, toId: BlockId): boolean {\n\t// A block that is itself isolating cannot be crossed into via arrow keys\n\tif (isIsolatingBlock(state, fromId) || isIsolatingBlock(state, toId)) return false;\n\n\tconst fromInside: boolean = isInsideIsolating(state, fromId);\n\tconst toInside: boolean = isInsideIsolating(state, toId);\n\n\t// One inside isolating, the other not → disallow\n\tif (fromInside !== toInside) return false;\n\n\t// Both inside isolating → must share the same parent\n\tif (fromInside && toInside) return sharesParent(state, fromId, toId);\n\n\treturn true;\n}\n"],"names":["resolveNodeByPath","doc","path","length","current","children","find","b","id","i","childId","next","c","isBlockNode","resolveParentByPath","index","findIndex","parent","slice","findNodePath","nodeId","block","subPath","findNodePathInBlock","child","walkNodes","callback","walkNodeRecursive","node","findNode","found","findNodeInBlock","findNodeWithPath","isVoidBlock","state","bid","getBlock","getNodeSpec","schema","type","isVoid","sharesParent","blockIdA","blockIdB","pathA","getNodePath","pathB","isInsideIsolating","blockId","ancestorId","ancestor","spec","isolating","isIsolatingBlock","canCrossBlockBoundary","fromId","toId","fromInside","toInside"],"mappings":"uCAYO,SAASA,EAAkBC,EAAeC,GAChD,GAAoB,IAAhBA,EAAKC,OAAc,OAEvB,IAAIC,EAAiCH,EAAII,SAASC,KAAMC,GAAMA,EAAEC,KAAON,EAAK,IAC5E,GAAKE,EAAL,CAEA,IAAA,IAASK,EAAI,E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C,KAAOqC,EAAMrC,GAAI,OAAO,EAEnC,OAAO,CACR,CAGO,SAASsC,EAAkBb,EAAoBc,GACrD,MAAMX,EAAcH,EAAMI,OAAOD,YACjC,IAAKA,EAAa,OAAO,EACzB,MAAMnC,EAAOgC,EAAMW,YAAYG,GAC/B,IAAK9C,GAAQA,EAAKC,QAAU,EAAG,OAAO,EAGtC,IAAA,IAASM,EAAI,EAAGA,EAAIP,EAAKC,OAAS,EAAGM,IAAK,CACzC,MAAMwC,EAAa/C,EAAKO,GACxB,IAAKwC,EAAY,SACjB,MAAMC,EAAWhB,EAAME,SAASa,GAChC,IAAKC,EAAU,SACf,MAAMC,EAAOd,EAAYa,EAASX,MAClC,GAAIY,GAAMC,UAAW,OAAO,CAC7B,CACA,OAAO,CACR,CAGO,SAASC,EAAiBnB,EAAoBc,GACpD,MAAMX,EAAcH,EAAMI,OAAOD,YACjC,IAAKA,EAAa,OAAO,EACzB,MAAMhB,EAAQa,EAAME,SAASY,GAC7B,QAAK3B,IACyC,IAAvCgB,EAAYhB,EAAMkB,OAAOa,SACjC,CAMO,SAASE,EAAsBpB,EAAoBqB,EAAiBC,GAE1E,GAAIH,EAAiBnB,EAAOqB,IAAWF,EAAiBnB,EAAOsB,GAAO,OAAO,EAE7E,MAAMC,EAAsBV,EAAkBb,EAAOqB,GAC/CG,EAAoBX,EAAkBb,EAAOsB,GAGnD,OAAIC,IAAeC,KAGfD,IAAcC,GAAiBjB,EAAaP,EAAOqB,EAAQC,GAGhE"}
@@ -0,0 +1,3 @@
1
+ import{b as e,c as t,k as n,m as s,s as r,n as i,f as o,d as a,a as c,e as l,i as h,l as d,r as p,g as u,h as f,j as g,o as m}from"./Commands-DwXBBVGR.mjs";import{D as y,d as k}from"./Decoration-D49mFXrH.mjs";import{L as b,a as S}from"./PluginHelpers-CdPR0MuT.mjs";import{n as v,o as w,e as R,q as x,t as C,u as I,k as T,v as E,f as B,c as M,w as P,i as A,h as N,j as D,a as O,p as L,s as H,r as _,g as z}from"./Document-HC8s50qJ.mjs";import{f as F,r as K,a as $}from"./NavigationQueries-DCOv4Ca5.mjs";import{b as j,c as V,h as U,g as W,e as q,d as G,i as Q,k as J,j as X,s as Y}from"./Selection-DhbizDM4.mjs";import{c as Z,b as ee,d as te,p as ne}from"./DocumentParser-w70-Axud.mjs";import{o as se,n as re,M as ie,N as oe,O as ae,P as ce,Q as le,R as he,G as de,e as pe,C as ue,p as fe,D as ge,K as me}from"./index-CVwf0cdH.mjs";import ye from"dompurify";import{s as ke,f as be,r as Se,a as ve,v as we,c as Re,b as xe,d as Ce}from"./BlockInsertion-zPxm6oa_.mjs";import{b as Ie,n as Te,m as Ee}from"./TypeBrands-Bp_Z_o5Y.mjs";import{S as Be,f as Me}from"./HTMLUtils-Cxy99Ak2.mjs";import{d as Pe,a as Ae,f as Ne,s as De,i as Oe}from"./MarkCommands-CTuVDqnn.mjs";import{b as Le,c as He,u as _e,d as ze,r as Fe,a as Ke}from"./StyleRuntime-BmsLoEa8.mjs";import{g as $e}from"./Platform-CU6itXZo.mjs";import{B as je}from"./BlockTypePickerRegistry-DcSE6IXB.mjs";import{ToolbarRegistry as Ve,ToolbarPlugin as Ue}from"../plugins/toolbar.mjs";import{i as We,b as qe,a as Ge,P as Qe,d as Je,B as Xe}from"./PrintTypes-DukwDSWS.mjs";import{c as Ye,b as Ze}from"./DomUtils-CznMAZZg.mjs";import{G as et,n as tt}from"./index-D3BZFsAD.mjs";import{TextFormattingPlugin as nt}from"../plugins/text-formatting.mjs";class st{_nodeSpecs=/* @__PURE__ */new Map;_markSpecs=/* @__PURE__ */new Map;_inlineNodeSpecs=/* @__PURE__ */new Map;registerNodeSpec(e){if(this._nodeSpecs.has(e.type))throw new Error(`NodeSpec for type "${e.type}" is already registered.`);this._nodeSpecs.set(e.type,e)}getNodeSpec(e){return this._nodeSpecs.get(e)}removeNodeSpec(e){this._nodeSpecs.delete(e)}getNodeTypes(){return[...this._nodeSpecs.keys()]}registerMarkSpec(e){if(this._markSpecs.has(e.type))throw new Error(`MarkSpec for type "${e.type}" is already registered.`);this._markSpecs.set(e.type,e)}getMarkSpec(e){return this._markSpecs.get(e)}removeMarkSpec(e){this._markSpecs.delete(e)}getMarkTypes(){return[...this._markSpecs.keys()]}registerInlineNodeSpec(e){if(this._inlineNodeSpecs.has(e.type))throw new Error(`InlineNodeSpec for type "${e.type}" is already registered.`);this._inlineNodeSpecs.set(e.type,e)}getInlineNodeSpec(e){return this._inlineNodeSpecs.get(e)}removeInlineNodeSpec(e){this._inlineNodeSpecs.delete(e)}getInlineNodeTypes(){return[...this._inlineNodeSpecs.keys()]}getBlockParseRules(){return this.collectParseRules(this._nodeSpecs)}getInlineParseRules(){return this.collectParseRules(this._inlineNodeSpecs)}getMarkParseRules(){return this.collectParseRules(this._markSpecs)}getAllowedTags(){return[...this.collectSanitizeValues(
2
+ /* @__PURE__ */new Set(["p","br","div","span"]),e=>e.sanitize?.tags)]}getAllowedAttrs(){return[...this.collectSanitizeValues(/* @__PURE__ */new Set(["style","dir"]),e=>e.sanitize?.attrs)]}collectParseRules(e){const t=[];for(const[n,s]of e)if(s.parseHTML)for(const e of s.parseHTML)t.push({rule:e,type:n});return t.sort((e,t)=>(t.rule.priority??50)-(e.rule.priority??50))}collectSanitizeValues(e,t){const n=[this._nodeSpecs,this._inlineNodeSpecs,this._markSpecs];for(const s of n)for(const n of s.values()){const s=t(n);if(s)for(const t of s)e.add(t)}return e}clear(){this._nodeSpecs.clear(),this._markSpecs.clear(),this._inlineNodeSpecs.clear()}}function rt(e,t,n){const s=e.getNodeSpec(t);if(!s?.content)return!0;const r=e.getNodeSpec(n),i=r?.group;for(const o of s.content.allow){if(o===n)return!0;if("text"!==o&&i&&o===i)return!0}return!1}function it(e,t,n){const s=e.getNodeSpec(t);if(!s?.content)return!0;const{min:r=0,max:i=Number.POSITIVE_INFINITY}=s.content,o=n.filter(e=>"text"!==e);if(o.length<r||o.length>i)return!1;for(const a of o)if(!rt(e,t,a))return!1;return!0}function ot(e){e.registerNodeSpec({type:"paragraph",group:"block",content:{allow:["text"]},toDOM:e=>Ye("p",e.id),toHTML:(e,t)=>`<p>${t||"<br>"}</p>`,parseHTML:[{tag:"p"},{tag:"div",priority:10}],sanitize:{tags:["p"]}})}function at(e,t,n){return{children:ct(e.children,t,n)}}function ct(e,t,n){return e.map(e=>{if(!v(e))return e;if(e.id===t)return n(e);const s=ct(e.children,t,n);return s===e.children?e:{...e,children:s}})}function lt(e,t,n){if(0===t.length)return e;const s=t[0];return s?{children:e.children.map(e=>v(e)&&e.id===s?1===t.length?n(e):ht(e,t,1,n):e)}:e}function ht(e,t,n,s){const r=t[n];if(!r)return e;const i=e.children.map(e=>v(e)&&e.id===r?n===t.length-1?s(e):ht(e,t,n+1,s):e);return{...e,children:i}}function dt(e,t,n){if(t(e))return n(e);let s=!1;const r=e.map(e=>{if(!v(e))return e;const r=dt(e.children,t,n);return r?(s=!0,{...e,children:r}):e});return s?r:null}function pt(e,t,n){const s=[];let r=0,i=!1;for(const o of e){if(w(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),c=o.text.slice(e);a&&s.push(R(a,o.marks)),s.push(...n()),c&&s.push(R(c,o.marks)),i=!0}else s.push(o);r=e}return i||s.push(...n()),s}function ut(e,t,n){const s=[];let r=0;for(const i of e){if(w(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(R(a,i.marks))}r=e}return 0===s.length&&s.push(R("")),s}function ft(e,t,n,s,r){const i=[];let o=0;for(const a of e){if(w(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?C(a.marks,s):I(a.marks,s.type);i.push(R(a.text,e))}else{const e=Math.max(0,t-o),c=Math.min(a.text.length,n-o),l=a.text.slice(0,e),h=a.text.slice(e,c),d=a.text.slice(c);if(l&&i.push(R(l,a.marks)),h){const e=r?C(a.marks,s):I(a.marks,s.type);i.push(R(h,e))}d&&i.push(R(d,a.marks))}o=e}return i}function gt(e,t){if(e.every(e=>x(e)||w(e)))return t;const n=e.filter(e=>!x(e)&&!w(e));return[...t,...n]}function mt(e,t){switch(t.type){case"insertText":return function(e,t){return yt(e,t.blockId,e=>{return t.segments?(n=e,s=t.offset,r=t.segments,pt(n,s,()=>r.map(e=>R(e.text,e.marks)))):function(e,t,n,s){return pt(e,t,()=>[R(n,s)])}(e,t.offset,t.text,t.marks);var n,s,r})}(e,t);case"deleteText":return function(e,t){return yt(e,t.blockId,e=>function(e,t,n){const s=[];let r=0;for(const i of e){if(w(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(R(a,i.marks))}r=e}return s}(e,t.from,t.to))}(e,t);case"splitBlock":return function(e,t){const n=dt(e.children,e=>e.some(e=>v(e)&&e.id===t.blockId),e=>{const n=e.findIndex(e=>v(e)&&e.id===t.blockId);if(-1===n)return e;const s=e[n],r=T(s),i=B(s),o=ut(r,0,t.offset),a=ut(r,t.offset,i),c={...s,children:E(o)},l=M(s.type,E(a),t.newBlockId,s.attrs),h=[...e];return h.splice(n,1,c,l),h});return n?{children:n}:e}(e,t);case"mergeBlocks":return function(e,t){const n=dt(e.children,e=>e.some(e=>v(e)&&e.id===t.targetBlockId)&&e.some(e=>v(e)&&e.id===t.sourceBlockId),e=>{const n=e.findIndex(e=>v(e)&&e.id===t.targetBlockId),s=e.findIndex(e=>v(e)&&e.id===t.sourceBlockId);if(-1===n||-1===s)return e;const r=e[n],i=e[s],o=T(r),a=T(i),c=E([...o,...a]),l={...r,children:c};return e.filter(e=>!v(e)||e.id!==t.sourceBlockId).map(e=>v(e)&&e.id===t.targetBlockId?l:e)});return n?{children:n}:e}(e,t);case"addMark":return function(e,t){return yt(e,t.blockId,e=>ft(e,t.from,t.to,t.mark,!0))}(e,t);case"removeMark":return function(e,t){return yt(e,t.blockId,e=>ft(e,t.from,t.to,t.mark,!1))}(e,t);case"setStoredMarks":return e;case"setBlockType":return function(e,t){return at(e,t.blockId,e=>({...e,type:t.nodeType,...t.attrs?{attrs:t.attrs}:{attrs:void 0}}))}(e,t);case"insertNode":return function(e,t){if(0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,0,t.node),{children:n}}return lt(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,0,t.node),{...e,children:n}})}(e,t);case"removeNode":return function(e,t){if(0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,1),{children:n}}return lt(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,1),{...e,children:n}})}(e,t);case"setNodeAttr":return function(e,t){const n=t.path[t.path.length-1];return n?at(e,n,e=>({...e,attrs:t.attrs})):e}(e,t);case"insertInlineNode":return function(e,t){return yt(e,t.blockId,e=>function(e,t,n){const s=[];let r=0,i=!1;for(const o of e){if(w(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),c=o.text.slice(e);a&&s.push(R(a,o.marks)),s.push(n),c&&s.push(R(c,o.marks)),i=!0}else s.push(o);r=e}return i||s.push(n),s}(e,t.offset,t.node))}(e,t);case"removeInlineNode":return function(e,t){return yt(e,t.blockId,e=>function(e,t){const n=[];let s=0;for(const r of e)w(r)?(s!==t&&n.push(r),s+=1):(n.push(r),s+=r.text.length);return n}(e,t.offset))}(e,t);case"setInlineNodeAttr":return function(e,t){return yt(e,t.blockId,e=>function(e,t,n){const s=[];let r=0;for(const i of e)w(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)}(e,t)}}function yt(e,t,n,s=!0){return at(e,t,e=>{const t=T(e),r=n(t);return{...e,children:gt(e.children,s?E(r):r)}})}function kt(e){return e.path?{path:e.path}:{}}function bt(e){switch(e.type){case"insertText":return{type:"deleteText",blockId:e.blockId,from:e.offset,to:e.offset+e.text.length,deletedText:e.text,deletedMarks:e.marks,deletedSegments:e.segments??[{text:e.text,marks:[...e.marks]}],...kt(e)};case"deleteText":return{type:"insertText",blockId:e.blockId,offset:e.from,text:e.deletedText,marks:e.deletedMarks,segments:e.deletedSegments,...kt(e)};case"splitBlock":return{type:"mergeBlocks",targetBlockId:e.blockId,sourceBlockId:e.newBlockId,targetLengthBefore:e.offset,...kt(e)};case"mergeBlocks":return{type:"splitBlock",blockId:e.targetBlockId,offset:e.targetLengthBefore,newBlockId:e.sourceBlockId,...kt(e)};case"addMark":return{type:"removeMark",blockId:e.blockId,from:e.from,to:e.to,mark:e.mark,...kt(e)};case"removeMark":return{type:"addMark",blockId:e.blockId,from:e.from,to:e.to,mark:e.mark,...kt(e)};case"setStoredMarks":return{type:"setStoredMarks",marks:e.previousMarks,previousMarks:e.marks};case"setBlockType":return{type:"setBlockType",blockId:e.blockId,nodeType:e.previousNodeType,attrs:e.previousAttrs,previousNodeType:e.nodeType,previousAttrs:e.attrs,...kt(e)};case"insertNode":return{type:"removeNode",parentPath:e.parentPath,index:e.index,removedNode:e.node};case"removeNode":return{type:"insertNode",parentPath:e.parentPath,index:e.index,node:e.removedNode};case"setNodeAttr":return{type:"setNodeAttr",path:e.path,attrs:e.previousAttrs,previousAttrs:e.attrs};case"insertInlineNode":return{type:"removeInlineNode",blockId:e.blockId,offset:e.offset,removedNode:e.node,...kt(e)};case"removeInlineNode":return{type:"insertInlineNode",blockId:e.blockId,offset:e.offset,node:e.removedNode,...kt(e)};case"setInlineNodeAttr":return{type:"setInlineNodeAttr",blockId:e.blockId,offset:e.offset,attrs:e.previousAttrs,previousAttrs:e.attrs,...kt(e)}}}function St(e){return{steps:e.steps.map(bt).reverse(),selectionBefore:e.selectionAfter,selectionAfter:e.selectionBefore,storedMarksAfter:null,metadata:{origin:"history",timestamp:Date.now()}}}class vt{steps=[];selection;storedMarks;selectionBefore;origin;workingDoc;_readonlyAllowed=!1;constructor(e,t,n="api",s){this.selection=e,this.selectionBefore=e,this.storedMarks=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.steps.push(i),this.advanceDoc(i),this}deleteText(e,t,n,s,r,i){let o;if(i)o=i;else if(this.workingDoc){const i=F(this.workingDoc,e);o=i?P(i,t,n):[{text:s,marks:[...r]}]}else o=[{text:s,marks:[...r]}];const a={type:"deleteText",blockId:e,from:t,to:n,deletedText:s,deletedMarks:r,deletedSegments:o};return this.steps.push(a),this.advanceDoc(a),this}deleteTextAt(e,t,n){const s=this.requireDoc("deleteTextAt"),r=this.requireBlock(s,e),i=A(r).slice(t,n),o=N(r,t),a=P(r,t,n);return this.deleteText(e,t,n,i,o,a)}splitBlock(e,t,n){const s={type:"splitBlock",blockId:e,offset:t,newBlockId:n};return this.steps.push(s),this.advanceDoc(s),this}mergeBlocks(e,t,n){const s={type:"mergeBlocks",targetBlockId:e,sourceBlockId:t,targetLengthBefore:n};return this.steps.push(s),this.advanceDoc(s),this}mergeBlocksAt(e,t){const n=this.requireDoc("mergeBlocksAt"),s=this.requireBlock(n,e),r=B(s);return this.mergeBlocks(e,t,r)}addMark(e,t,n,s){const r={type:"addMark",blockId:e,from:t,to:n,mark:s};return this.steps.push(r),this.advanceDoc(r),this}removeMark(e,t,n,s){const r={type:"removeMark",blockId:e,from:t,to:n,mark:s};return this.steps.push(r),this.advanceDoc(r),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.steps.push(i),this.advanceDoc(i),this}insertNode(e,t,n){const s={type:"insertNode",parentPath:e,index:t,node:n};return this.steps.push(s),this.advanceDoc(s),this}removeNode(e,t){const n=function(e,t,n){if(0===t.length){const t=e.children[n];return t&&v(t)?t:void 0}const s=K(e,t);if(!s)return;const r=s.children[n];return r&&v(r)?r:void 0}(this.requireDoc("removeNode"),e,t);if(!n)throw new Error(`Node at index ${t} not found under parent path [${e.join(", ")}].`);const s={type:"removeNode",parentPath:e,index:t,removedNode:n};return this.steps.push(s),this.advanceDoc(s),this}setNodeAttr(e,t){const n=this.requireDoc("setNodeAttr"),s=K(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.steps.push(r),this.advanceDoc(r),this}insertInlineNode(e,t,n){const s={type:"insertInlineNode",blockId:e,offset:t,node:n};return this.steps.push(s),this.advanceDoc(s),this}removeInlineNode(e,t){const n=this.requireDoc("removeInlineNode"),s=this.requireBlock(n,e),r=D(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.steps.push(i),this.advanceDoc(i),this}setInlineNodeAttr(e,t,n){const s=this.requireDoc("setInlineNodeAttr"),r=this.requireBlock(s,e),i=T(r);let o=0;for(const a of i){if(w(a)&&o===t){const s={type:"setInlineNodeAttr",blockId:e,offset:t,attrs:n,previousAttrs:a.attrs};return this.steps.push(s),this.advanceDoc(s),this}o+=w(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=e,this}setNodeSelection(e,t){return this.selection=j(e,t),this}setStoredMarks(e,t){return this.steps.push({type:"setStoredMarks",marks:e,previousMarks:t}),this.storedMarks=e,this}build(){return{steps:[...this.steps],selectionBefore:this.selectionBefore,selectionAfter:this.selection,storedMarksAfter:this.storedMarks,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=F(e,t);if(!n)throw new Error(`Block "${t}" not found in working document.`);return n}advanceDoc(e){this.workingDoc&&(this.workingDoc=mt(this.workingDoc,e))}}class wt{doc;selection;storedMarks;schema;_blockMap=null;_blockOrder=null;constructor(e,t,n,s){this.doc=e,this.selection=t,this.storedMarks=n,this.schema=s}static create(e){const t=e?.schema??Pe(),n=e?.doc??O(),s=n.children[0],r=e?.selection??V(s?s.id:Ie(""),0);return new wt(n,r,null,t)}transaction(e="api"){return new vt(this.selection,this.storedMarks,e,this.doc)}apply(e){let t=this.doc;for(const s of e.steps)t=mt(t,s);const n=function(e,t){if(U(t))return F(e,t.nodeId)?t:xt(e,t);if(W(t))return F(e,t.blockId)?t:xt(e,t);const n=Rt(e,t.anchor),s=Rt(e,t.head);return n===t.anchor&&s===t.head?t:q(n,s)}(t,e.selectionAfter);return new wt(t,n,e.storedMarksAfter,this.schema)}getBlock(e){return this._blockMap??=function(e){const t=/* @__PURE__ */new Map;return function e(n){for(const s of n)v(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)v(s)&&(L(s)?t.push(s.id):e(s.children))}(e.children),t}(this.doc),this._blockOrder}getNodePath(e){return $(this.doc,e)}getParent(e){const t=$(this.doc,e);if(!t||t.length<=1)return;const n=t[t.length-2];return n?F(this.doc,n):void 0}toJSON(){return{doc:this.doc,selection:this.selection}}static fromJSON(e,t){return new wt(e.doc,e.selection,null,t??Pe())}}function Rt(e,t){const n=F(e,t.blockId);if(n){const e=B(n);return t.offset>e?G(t.blockId,e,t.path):t}const s=e.children[0];return s?G(s.id,0):t}function xt(e,t){const n=Ct(e.children);return n?V(n.id,0):t}function Ct(e){for(const t of e){if(!v(t))continue;if(L(t))return t;const e=Ct(t.children);if(e)return e}return null}function It(e){for(const t of e.steps)if("setStoredMarks"!==t.type)return!1;return!0}function Tt(e){return!!e.metadata.readonlyAllowed||It(e)}class Et{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]={transactions:[...n.transactions,e],timestamp:t}:this.undoStack.push({transactions:[e],timestamp:t}),this.lastOrigin=e.metadata.origin,this.redoStack=[];this.undoStack.length>this.maxDepth;)this.undoStack.shift()}undo(e){const t=this.undoStack.pop();if(!t)return null;let n=e;const s=[];for(let r=t.transactions.length-1;r>=0;r--){const e=t.transactions[r];if(!e)continue;const i=St(e);n=n.apply(i),s.push(...i.steps)}return this.redoStack.push({transactions:t.transactions,timestamp:Date.now()}),this.lastOrigin=null,{state:n,transaction:{steps:s,selectionBefore:e.selection,selectionAfter:n.selection,storedMarksAfter:n.storedMarks,metadata:{origin:"history",timestamp:Date.now(),historyDirection:"undo"}}}}redo(e){const t=this.redoStack.pop();if(!t)return null;let n=e;const s=[];for(const r of t.transactions)n=n.apply(r),s.push(...r.steps);return this.undoStack.push({transactions:t.transactions,timestamp:Date.now()}),this.lastOrigin=null,{state:n,transaction:{steps:s,selectionBefore:e.selection,selectionAfter:n.selection,storedMarksAfter:n.storedMarks,metadata:{origin:"history",timestamp:Date.now(),historyDirection:"redo"}}}}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];if(!n)return!1;const s=n.steps[0]?.type,r=t.steps[0]?.type;return s===r}}function Bt(n,s){const r=n.selection;if(U(r))return e(n,r);if(W(r))return null;if(!Q(r))return t(n);const i=n.getBlock(r.anchor.blockId);if(!i)return null;const o=s.range(i,r.anchor.offset);if(!o)return s.merge(n);const[a,c]=o;return n.transaction("input").deleteTextAt(i.id,a,c).setSelection(V(i.id,a)).build()}function Mt(e){return Bt(e,{merge:s,range:(e,t)=>t>0?[t-1,t]:null})}function Pt(e){return Bt(e,{merge:n,range:(e,t)=>t<B(e)?[t,t+1]:null})}class At{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.handleKeydown=this.onKeydown.bind(this),e.addEventListener("keydown",this.handleKeydown)}getState;dispatch;undo;redo;keymapRegistry;isReadOnly;compositionTracker;getTextDirectionFn;navigateFromGapCursorFn;handleKeydown;onKeydown(e){if(this.compositionTracker?.isComposing)return;if(this.handleNodeSelectionKeys(e))return;if(this.handleGapCursorKeys(e))return;if(this.isReadOnly()){if(this.keymapRegistry){const t=Nt(e),n=this.keymapRegistry.getKeymapsByPriority().navigation;for(let s=n.length-1;s>=0;s--){const r=n[s]?.[t];if(r?.())return void e.preventDefault()}}return void this.handleEscape(e)}if(this.keymapRegistry){const t=Nt(e),n=this.keymapRegistry.getKeymapsByPriority();for(const s of[n.context,n.navigation,n.default])for(let n=s.length-1;n>=0;n--){const r=s[n]?.[t];if(r?.())return void e.preventDefault()}}if(this.handleGapCursorArrowFallback(e))return;if(this.handleTab(e))return;if(this.handleEscape(e))return;if(!e.metaKey&&!e.ctrlKey)return;const t=e.key.toLowerCase(),n=this.getState();let s=null;return"z"!==t||e.shiftKey?"z"===t&&e.shiftKey||"y"===t&&!e.shiftKey?(e.preventDefault(),void this.redo()):("a"!==t||e.shiftKey||(e.preventDefault(),s=r(n)),void(s&&this.dispatch(s))):(e.preventDefault(),void this.undo())}handleNodeSelectionKeys(t){const n=this.getState(),s=n.selection;if(!U(s))return!1;const r=t.key;if(!("ArrowLeft"!==r&&"ArrowUp"!==r&&"ArrowRight"!==r&&"ArrowDown"!==r||t.shiftKey||t.metaKey||t.ctrlKey||t.altKey)){const e="ArrowLeft"===r?"left":"ArrowRight"===r?"right":"ArrowUp"===r?"up":"down",o=this.isSelectedBlockRtl(s.nodeId),a=i(n,e,o);return!!a&&(t.preventDefault(),this.dispatch(a),!0)}if("Backspace"===r||"Delete"===r){if(this.isReadOnly())return t.preventDefault(),!0;t.preventDefault();const r=e(n,s);return r&&this.dispatch(r),!0}if("Enter"===r){if(this.isReadOnly())return t.preventDefault(),!0;t.preventDefault();const e=o(n);return e&&this.dispatch(e),!0}if("Escape"===r){t.preventDefault();const e=i(n,"right");return e&&this.dispatch(e),!0}return!1}handleGapCursorKeys(e){const t=this.getState(),n=t.selection;if(!W(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=o(t);return n&&this.dispatch(n),!0}if("Backspace"===s){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const s=a(t,n);return s&&this.dispatch(s),!0}if("Delete"===s){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const s=c(t,n);return s&&this.dispatch(s),!0}if(1===s.length){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=l(t,s);return this.dispatch(n),!0}return!1}handleGapCursorArrowFallback(e){const t=this.getState(),n=t.selection;if(!W(n))return!1;const s=e.key;if("ArrowLeft"!==s&&"ArrowRight"!==s&&"ArrowUp"!==s&&"ArrowDown"!==s)return!1;const r="ArrowLeft"===s?"left":"ArrowRight"===s?"right":"ArrowUp"===s?"up":"down";if(!this.navigateFromGapCursorFn)return!1;const i=this.navigateFromGapCursorFn(t,r,this.element);return!(!i||J(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=l(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 Nt(e){const t=[];(e.metaKey||e.ctrlKey)&&t.push("Mod"),e.shiftKey&&t.push("Shift"),e.altKey&&t.push("Alt");let n=e.key;return" "===n?n="Space":1===n.length&&(n=n.toUpperCase()),t.push(n),t.join("-")}let Dt;function Ot(e){return e.replace(/\r\n?/g,"\n")}class Lt{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)}getState;dispatch;schemaRegistry;syncSelection;isReadOnly;handleCopy;handleCut;onCopy(e){this.syncSelection?.();const t=this.getState(),n=t.selection;if(W(n))return;if(X(n)&&Q(n))return;e.preventDefault();const s=e.clipboardData;s&&(U(n)?this.writeNodeSelectionToClipboard(s,t):this.writeTextSelectionToClipboard(s,t))}onCut(n){if(this.isReadOnly())return;this.syncSelection?.();const s=this.getState(),r=s.selection;if(W(r))return;if(X(r)&&Q(r))return;n.preventDefault();const i=n.clipboardData;if(i)if(U(r)){this.writeNodeSelectionToClipboard(i,s);const t=e(s,r);t&&this.dispatch(t)}else{this.writeTextSelectionToClipboard(i,s);const e=t(s);e&&this.dispatch(e)}}writeNodeSelectionToClipboard(e,t){const n=t.selection;if(!U(n))return;const s=t.getBlock(n.nodeId);if(!s)return;const r={type:s.type,...s.attrs?{attrs:{...s.attrs}}:{}};e.setData("application/x-notectl-block",JSON.stringify(r));const i=this.schemaRegistry?.getNodeSpec(s.type);i?.toHTML&&e.setData("text/html",i.toHTML(s,""));const o=s.attrs,a="string"==typeof o?.alt?o.alt:"";e.setData("text/plain",a)}writeTextSelectionToClipboard(e,t){const n=t.selection;if(U(n))return;if(W(n))return;if(Q(n))return;if(this.selectionRequiresDocumentSerializer(t))return void this.writeCompositeSelectionToClipboard(e,t);const s=t.getBlockOrder(),r=Y(n,s),i=s.indexOf(r.from.blockId),o=s.indexOf(r.to.blockId),a=[],c=[],l=[];for(let d=i;d<=o;d++){const e=s[d];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const h=A(n),p=B(n),u=d===i?r.from.offset:0,f=d===o?r.to.offset:p,g=h.slice(u,f);a.push(g),l.push({block:n,start:u,end:f});const m=this.extractSegmentsForRange(n,u,f);c.push({type:n.type,text:g,...n.attrs?{attrs:{...n.attrs}}:{},...m.length>0?{segments:m}:{}})}const h=a.join("\n");if(e.setData("text/plain",h),this.schemaRegistry){const n=Z(this.schemaRegistry);if(i!==o){const t=this.serializeBlocksToClipboardHTML(l,n,c);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)}}}!function(e,t){Dt={plainText:Ot(e),blocks:t}}(h,c)}selectionRequiresDocumentSerializer(e){const t=this.getTextSelection(e);if(!t||Q(t))return!1;const n=e.getBlockOrder(),s=Y(t,n),r=$(e.doc,s.from.blockId),i=$(e.doc,s.to.blockId);if(!r||!i)return!1;if(r[0]===i[0]){const t=e.doc.children.find(e=>e.id===r[0]);return!(!t||L(t))}const o=e.doc.children.findIndex(e=>e.id===r[0]),a=e.doc.children.findIndex(e=>e.id===i[0]);for(let c=o;c<=a;c++){const t=e.doc.children[c];if(!t)continue;if(!L(t))return!0;const n=this.schemaRegistry?.getNodeSpec(t.type);if(n?.isVoid)return!0}return!1}getTextSelection(e){const t=e.selection;if(X(t))return t}writeCompositeSelectionToClipboard(e,t){const n=this.getTextSelection(t);if(!n)return;const s=t.getBlockOrder(),r=Y(n,s),i=s.indexOf(r.from.blockId),o=s.indexOf(r.to.blockId),a=[];for(let c=i;c<=o;c++){const e=s[c];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const l=A(n),h=c===i?r.from.offset:0,d=c===o?r.to.offset:B(n);a.push(l.slice(h,d))}if(e.setData("text/plain",a.join("\n")),this.schemaRegistry){const n=$(t.doc,r.from.blockId),s=$(t.doc,r.to.blockId);if(n&&s){const r=t.doc.children.findIndex(e=>e.id===n[0]),i=t.doc.children.findIndex(e=>e.id===s[0]),o=t.doc.children.slice(r,i+1),a=O(o),c=ee(a,this.schemaRegistry);e.setData("text/html",c)}}}serializeBlockRangeToHTML(e,t,n,s){const r=T(e),i=[];let o=0;for(const a of r){const e=o+(w(a)?1:a.text.length);if(e<=t||o>=n)o=e;else{if(x(a)){const e=Math.max(0,t-o),r=Math.min(a.text.length,n-o),c=a.text.slice(e,r);c.length>0&&this.schemaRegistry&&i.push(te(c,a.marks,this.schemaRegistry,s))}else if(w(a)){const e=this.schemaRegistry?.getInlineNodeSpec(a.inlineType);e?.toHTMLString&&i.push(e.toHTMLString(a))}o=e}}return i.join("")}extractSegmentsForRange(e,t,n){const s=T(e),r=[];let i=0;for(const o of s){const e=i+(w(o)?1:o.text.length);if(e<=t||i>=n)i=e;else{if(x(o)){const e=Math.max(0,t-i),s=Math.min(o.text.length,n-i),a=o.text.slice(e,s);if(a.length>0){const e=o.marks.map(e=>({type:e.type,...e.attrs?{attrs:{...e.attrs}}:{}}));r.push({text:a,marks:e})}}i=e}}return r}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 c of e){const{block:e,start:n,end:a}=c,l=this.serializeBlockRangeToHTML(e,n,a,t),h=this.schemaRegistry?.getNodeSpec(e.type);if(h?.wrapper){const t=h.wrapper(e).tag;r!==t&&(o(),r=t),h.toHTML?i.push(h.toHTML(e,l)):i.push(`<li>${l}</li>`)}else o(),h?.toHTML?s.push(h.toHTML(e,l)):s.push(`<p>${l}</p>`)}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)}}class Ht{_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}}class _t{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.compositionTracker=t.compositionTracker??new Ht,this.handleBeforeInput=this.onBeforeInput.bind(this),this.handleCompositionStart=this.onCompositionStart.bind(this),this.handleCompositionEnd=this.onCompositionEnd.bind(this),e.addEventListener("beforeinput",this.handleBeforeInput),e.addEventListener("compositionstart",this.handleCompositionStart),e.addEventListener("compositionend",this.handleCompositionEnd)}getState;dispatch;syncSelection;inputRuleRegistry;isReadOnly;compositionTracker;handleBeforeInput;handleCompositionStart;handleCompositionEnd;onBeforeInput(e){if(this.isReadOnly())return;if(this.compositionTracker.isComposing&&"insertCompositionText"===e.inputType)return;e.preventDefault(),"insertText"!==e.inputType&&"insertCompositionText"!==e.inputType&&this.syncSelection();const t=this.getState();let r=null;switch(e.inputType){case"insertText":e.data&&(r=l(t,e.data,"input"));break;case"insertParagraph":r=o(t);break;case"insertLineBreak":r=h(t);break;case"deleteContentBackward":case"deleteByCut":r=Mt(t);break;case"deleteContentForward":r=Pt(t);break;case"deleteWordBackward":r=function(e){return Bt(e,{merge:s,range:(e,t)=>t>0?[re(e,t),t]:null})}(t);break;case"deleteWordForward":r=function(e){return Bt(e,{merge:n,range:(e,t)=>t<B(e)?[t,se(e,t)]:null})}(t);break;case"deleteSoftLineBackward":r=function(e){return Bt(e,{merge:s,range:(e,t)=>t>0?[0,t]:null})}(t);break;case"deleteSoftLineForward":r=function(e){return Bt(e,{merge:n,range:(e,t)=>{const n=B(e);return t<n?[t,n]:null}})}(t)}r&&(this.dispatch(r),"insertText"===e.inputType&&this.checkInputRules())}onCompositionStart(e){const t=this.getState();X(t.selection)&&this.compositionTracker.start(t.selection.anchor.blockId)}onCompositionEnd(e){if(this.compositionTracker.end(),this.isReadOnly())return;const t=e.data;if(!t)return;const n=this.getState(),s=l(n,t,"input");this.dispatch(s)}checkInputRules(){if(!this.inputRuleRegistry)return;const e=this.inputRuleRegistry.getInputRules();if(0===e.length)return;const t=this.getState();if(!X(t.selection))return;const{anchor:n}=t.selection,s=t.getBlock(n.blockId);if(!s)return;const r=A(s).slice(0,n.offset);for(const i of e){const e=i.pattern.exec(r);if(e){const n=e.index,s=n+e[0].length,r=i.handler(t,e,n,s);if(r)return void this.dispatch(r)}}}destroy(){this.element.removeEventListener("beforeinput",this.handleBeforeInput),this.element.removeEventListener("compositionstart",this.handleCompositionStart),this.element.removeEventListener("compositionend",this.handleCompositionEnd)}}function zt(e){return e.reduce((e,t)=>e+t.text,"")}function Ft(e){return e.reduce((e,t)=>e+t.text.length,0)}function Kt(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===Te("paragraph")?function(e,t){const n=e.selection;if(U(n))return e.transaction("paste").setSelection(n).build();if(W(n))return function(e,t,n){const s=$t(e,t);if(!s)return e.transaction("paste").setSelection(t).build();const r=H(),i=zt(n),o=Ft(n),a=e.transaction("paste");return a.insertNode(s.parentPath,s.insertIndex,M(Te("paragraph"),[R("")],r)),i.length>0&&a.insertText(r,0,i,[],n),a.setSelection(V(r,o)),a.build()}(e,n,t);const s=e.transaction("paste");Q(n)||d(e,s);const{blockId:r,offset:i}=p(n,e.getBlockOrder()),o=Ft(t),a=zt(t);return s.insertText(r,i,a,[],t),s.setSelection(V(r,i+o)),s.build()}(e,n.segments):1===t.blocks.length?function(e,t){const n=e.selection;if(U(n))return e.transaction("paste").setSelection(n).build();if(W(n))return jt(e,n,[t]);const s=e.transaction("paste");Q(n)||d(e,s);const{blockId:r,offset:i}=p(n,e.getBlockOrder()),o=Ft(t.segments),a=zt(t.segments);return s.setBlockType(r,t.type,t.attrs),s.insertText(r,i,a,[],t.segments),s.setSelection(V(r,i+o)),s.build()}(e,n):function(e,t){const n=e.selection;if(U(n))return e.transaction("paste").setSelection(n).build();if(W(n))return jt(e,n,t.blocks);const s=e.transaction("paste");Q(n)||d(e,s);const r=e.getBlockOrder(),{blockId:i,offset:o}=p(n,r),a=r.indexOf(i),c=t.blocks[0],l=t.blocks[t.blocks.length-1];if(!c||!l)return s.build();const h=t.blocks.slice(1,-1),u=Ft(c.segments);c.segments.length>0&&u>0&&s.insertText(i,o,zt(c.segments),[],c.segments),c.type!==Te("paragraph")&&s.setBlockType(i,c.type,c.attrs);const f=o+u,g=H();s.splitBlock(i,f,g);let m=a+1;for(const d of h){const e=d.segments.map(e=>R(e.text,[...e.marks])),t=M(d.type,e.length>0?e:void 0,H(),d.attrs);s.insertNode([],m,t),m++}const y=Ft(l.segments);return l.segments.length>0&&y>0&&s.insertText(g,0,zt(l.segments),[],l.segments),l.type!==Te("paragraph")&&s.setBlockType(g,l.type,l.attrs),s.setSelection(V(g,y)),s.build()}(e,t):e.transaction("paste").setSelection(e.selection).build()}function $t(e,t){const n=$(e.doc,t.blockId);if(!n)return null;const s=u(n),r=f(e,s),i=g(r,t.blockId);return i<0?null:{parentPath:s,insertIndex:"before"===t.side?i:i+1}}function jt(e,t,n){const s=$t(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=H(),t=zt(c.segments),n=c.segments.map(e=>R(e.text,[...e.marks])),l=M(c.type,n.length>0?n:[R("")],e,c.attrs);r.insertNode(s.parentPath,o,l),o++,i=e,a=t.length}return i&&r.setSelection(V(i,a)),r.build()}const Vt=/* @__PURE__ */new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","UL","OL","LI","HR","PRE","TABLE","THEAD","TBODY","TR"]),Ut=/* @__PURE__ */new Set(["STRONG","B","EM","I","U","S","STRIKE","DEL","A","SPAN","BR","SUB","SUP","CODE"]);class Wt{schema;blockParseRules;markParseRules;constructor(e){this.schema=e.schema,this.blockParseRules=e.schemaRegistry?.getBlockParseRules()??[],this.markParseRules=e.schemaRegistry?.getMarkParseRules()??[]}parse(e){const t=this.parseContainer(e);return 0===t.length?{blocks:[{type:this.resolveBlockType(Te("paragraph")),segments:[{text:"",marks:[]}]}]}:{blocks:t}}parseContainer(e){const t=[];let n=[];for(const s of Array.from(e.childNodes))if(s.nodeType===Node.ELEMENT_NODE){const e=s;this.isBlockElement(e)?(this.flushPendingSegments(t,n),n=[],t.push(...this.parseBlockElement(e))):e.children.length>0&&this.containsBlockDescendants(e)?(this.flushPendingSegments(t,n),n=[],t.push(...this.parseContainerWithMarks(e,this.marksFromElement(e)))):n.push(...this.parseInlineNode(s,[]))}else if(s.nodeType===Node.TEXT_NODE){const e=s.textContent??"";e&&n.push({text:e,marks:[]})}return this.flushPendingSegments(t,n),t}parseBlockElement(e){const t=e.tagName,n=/^H([1-6])$/.exec(t);if(n){const t=Number(n[1]),s=this.resolveBlockType(Te("heading"));return[{type:s,...s===Te("heading")?{attrs:{level:t}}:{},segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}switch(t){case"P":case"DIV":return this.parseBlockWithLineBreaks(e,this.resolveBlockType(Te("paragraph")));case"BLOCKQUOTE":return this.parseBlockquote(e);case"UL":return this.parseList(e,"bullet",0);case"OL":return this.parseList(e,"ordered",0);case"LI":return this.parseListItem(e,"bullet",0);case"HR":return[{type:this.resolveBlockType(Te("horizontal_rule")),segments:[]}];case"PRE":return[{type:this.resolveBlockType(Te("paragraph")),segments:this.ensureSegments(this.parsePreContent(e))}];case"TABLE":case"THEAD":case"TBODY":case"TR":return this.parseTableAsParagraphs(e);default:{const t=this.matchBlockRule(e);return t?[{type:t.type,...t.attrs?{attrs:t.attrs}:{},segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]:[{type:this.resolveBlockType(Te("paragraph")),segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}}}parseBlockquote(e){const t=this.resolveBlockType(Te("blockquote"));return Array.from(e.childNodes).some(e=>e.nodeType===Node.ELEMENT_NODE&&this.isBlockElement(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(Te("list_item")),i=this.hasCheckbox(e),o=i?"checklist":t,a=!!i&&this.isCheckboxChecked(e),c=[],l=[];for(const h of Array.from(e.childNodes))if(h.nodeType===Node.ELEMENT_NODE){const e=h;"UL"===e.tagName||"OL"===e.tagName?l.push(e):"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")||(this.isBlockElement(e)?c.push(...this.parseInlineChildren(e,[])):c.push(...this.parseInlineNode(h,[])))}else if(h.nodeType===Node.TEXT_NODE){const e=h.textContent??"";e&&c.push({text:e,marks:[]})}s.push({type:r,attrs:{listType:o,indent:n,..."checklist"===o?{checked:a}:{}},segments:this.ensureSegments(this.normalizeSegments(c))});for(const h of l){const e="OL"===h.tagName?"ordered":"bullet";s.push(...this.parseList(h,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?[{text:n,marks:this.resolveMarks(t)}]:[]}if(e.nodeType!==Node.ELEMENT_NODE)return[];const n=e,s=n.tagName;if("BR"===s)return[{text:"\n",marks:this.resolveMarks(t)}];if(this.isBlockElement(n)&&!Ut.has(s))return this.parseInlineChildren(n,t);const r=this.mergeMarks(t,this.marksFromElement(n));return this.parseInlineChildren(n,r)}parsePreContent(e){const t=e.textContent??"";return t?[{text:t,marks:[]}]:[]}parseTableAsParagraphs(e){const t=[],n=e.querySelectorAll("td, th");for(const s of Array.from(n)){const e=this.parseInlineChildren(s,[]);e.length>0&&e.some(e=>e.text.length>0)&&t.push({type:this.resolveBlockType(Te("paragraph")),segments:this.ensureSegments(e)})}return t}marksFromElement(e){const t=[],n=e.tagName.toLowerCase();if(this.markParseRules.length>0){const s=/* @__PURE__ */new Set;for(const r of this.markParseRules)if(r.rule.tag===n&&!s.has(r.type))if(r.rule.getAttrs){const n=r.rule.getAttrs(e);if(!1===n)continue;t.push({type:Ee(r.type),...Object.keys(n).length>0?{attrs:n}:{}}),s.add(r.type)}else t.push({type:Ee(r.type)}),s.add(r.type);if(s.size>0)return t}const s=e.tagName;if("STRONG"===s||"B"===s){const n=e.style.fontWeight,s=Number.parseInt(n,10);"normal"===n||!Number.isNaN(s)&&s<700||t.push({type:Ee("bold")})}if("EM"!==s&&"I"!==s||t.push({type:Ee("italic")}),"U"===s&&t.push({type:Ee("underline")}),"S"!==s&&"STRIKE"!==s&&"DEL"!==s||t.push({type:Ee("strikethrough")}),"A"===s){const n=e.getAttribute("href")??"";t.push({type:Ee("link"),attrs:{href:n}})}return t}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=>Ae(this.schema,e.type))}resolveBlockType(e){return Ne(this.schema,e)?e:Te("paragraph")}normalizeSegments(e){if(0===e.length)return[];const t=[];for(const n of e){const e=t[t.length-1];e&&_(e.marks,n.marks)?t[t.length-1]={text:e.text+n.text,marks:e.marks}:n.text.length>0&&t.push(n)}return t}ensureSegments(e){return 0===e.length?[{text:"",marks:[]}]:e}matchBlockRule(e){const t=e.tagName.toLowerCase();for(const n of this.blockParseRules)if(n.rule.tag===t){if(n.rule.getAttrs){const t=n.rule.getAttrs(e);if(!1===t)continue;return{type:Te(n.type),attrs:t}}return{type:Te(n.type)}}return null}isBlockElement(e){if(Vt.has(e.tagName))return!0;const t=e.tagName.toLowerCase();return this.blockParseRules.some(e=>e.rule.tag===t)}hasCheckbox(e){return null!==e.querySelector('input[type="checkbox"]')}isCheckboxChecked(e){const t=e.querySelector('input[type="checkbox"]');return t?.hasAttribute("checked")??!1}containsBlockDescendants(e){for(const t of Array.from(e.children)){if(this.isBlockElement(t))return!0;if(this.containsBlockDescendants(t))return!0}return!1}parseContainerWithMarks(e,t){const n=this.parseContainer(e);return 0===t.length?n:n.map(e=>({...e,segments:this.prependMarks(e.segments,t)}))}prependMarks(e,t){return e.map(e=>({text:e.text,marks:this.mergeMarks(t,e.marks)}))}parseBlockWithLineBreaks(e,t){const n=this.parseInlineChildren(e,[]);if(!n.some(e=>e.text.includes("\n")))return[{type:t,segments:this.ensureSegments(n)}];const s=[];let r=[];for(const i of n){const e=i.text.split("\n");for(let n=0;n<e.length;n++){n>0&&(s.push({type:t,segments:this.ensureSegments(this.normalizeSegments(r))}),r=[]);const o=e[n]??"";o&&r.push({text:o,marks:i.marks})}}return s.push({type:t,segments:this.ensureSegments(this.normalizeSegments(r))}),s}flushPendingSegments(e,t){const n=this.normalizeSegments(t);0!==n.length&&(n.every(e=>""===e.text.trim())||e.push({type:this.resolveBlockType(Te("paragraph")),segments:n}))}}const qt={1:"x-small",2:"small",3:"medium",4:"large",5:"x-large",6:"xx-large",7:"xxx-large"};function Gt(e){return e.toLowerCase().includes("font-size")}function Qt(e,t){for(;e.firstChild;)t.appendChild(e.firstChild)}function Jt(e){const t=e.parentNode;if(t){for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}}const Xt=["script","style","iframe","object","embed","form","noscript"];class Yt{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.handlePaste=this.onPaste.bind(this),e.addEventListener("paste",this.handlePaste)}getState;dispatch;schemaRegistry;fileHandlerRegistry;isReadOnly;getPasteInterceptors;handlePaste;onPaste(e){if(e.preventDefault(),this.isReadOnly())return;const t=e.clipboardData;if(!t)return;const n=t.getData("application/x-notectl-block");if(n)return void this.handleBlockPaste(n);if(this.handleFilePaste(t))return;const s=t.getData("text/plain");if(s){const e=function(e){if(Dt&&Dt.plainText===Ot(e))return Dt.blocks}(s);if(e&&this.handleRichPaste(e))return}const r=t.getData("text/html");s&&this.tryPasteInterceptors(s,r)||this.handleHTMLOrTextPaste(t,s)}tryPasteInterceptors(e,t){const n=this.getPasteInterceptors(),s=this.getState();for(const r of n){const n=r.interceptor(e,t,s);if(n)return this.dispatch(n),!0}return!1}handleHTMLOrTextPaste(e,t){const n=this.getState(),s=e.getData("text/html");if(s){const e=ye.sanitize(s,{FORBID_TAGS:Xt,ALLOWED_URI_REGEXP:Be}),t=this.extractRichData(e);if(t&&this.handleRichPasteFromJson(t))return;const r=document.createElement("template");r.innerHTML=e,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)){Jt(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&&!Gt(r)){const e=qt[s];e&&o.push(`font-size: ${e};`)}Le(i,o.join(" ")),Qt(n,i),n.parentNode?.replaceChild(i,n)}}(r.content);const i=r.innerHTML,o=this.schemaRegistry?this.schemaRegistry.getAllowedTags():["strong","em","u","b","i","p","br","div","span"],a=this.schemaRegistry?this.schemaRegistry.getAllowedAttrs():[],c=ye.sanitize(i,{ALLOWED_TAGS:o,ALLOWED_ATTR:a,ALLOWED_URI_REGEXP:Be});if(this.schemaRegistry){const e=document.createElement("template");if(e.innerHTML=c,this.requiresDocumentParser(c,e.content))return void this.handleDocumentPaste(c,n);const t=De(this.schemaRegistry),s=new Wt({schema:t,schemaRegistry:this.schemaRegistry}).parse(e.content);this.dispatch(Kt(n,s))}else{const e=this.extractTextFromHTML(c);e&&this.dispatch(l(n,e,"paste"))}return}if(t){const e=function(e){const t=e.split(/\r?\n/).map(e=>({type:Te("paragraph"),segments:[{text:e,marks:[]}]}));return{blocks:t.length>0?t:[{type:Te("paragraph"),segments:[{text:"",marks:[]}]}]}}(t);this.dispatch(Kt(this.getState(),e))}}handleBlockPaste(e){let t;try{t=JSON.parse(e)}catch{return}const n=t.type;if(!n)return;const s=this.schemaRegistry?.getNodeSpec(n);if(this.schemaRegistry&&!s)return;const r=this.getState(),i=r.selection,o=U(i)?i.nodeId:W(i)?i.blockId:i.anchor.blockId,a=H(),c=ke(t.attrs,s?.attrs),l=M(Te(n),void 0,a,c),h=be(r,o);if(h){const e=Se(r,o,h,this.schemaRegistry);if(!e)return;const t=r.getBlock(h);if(!t)return;const n=r.transaction("paste");return n.insertNode(e.parentPath,t.children.length,l),n.setSelection(j(a,[...e.parentPath,a])),void this.dispatch(n.build())}const d=ve(r,o,this.schemaRegistry);if(!d)return;const p=W(i)&&"before"===i.side?0:1,u=r.transaction("paste");u.insertNode(d.parentPath,d.anchorIndex+p,l),u.setSelection(j(a,[...d.parentPath,a])),this.dispatch(u.build())}handleRichPasteFromJson(e){let t;try{t=JSON.parse(e)}catch{return!1}return!(!Array.isArray(t)||0===t.length)&&this.handleRichPaste(t)}handleRichPaste(e){if(0===e.length)return!1;if(!e.some(e=>void 0!==e.type&&"paragraph"!==e.type)&&e.length<=1)return!1;let t=this.getState();const n=t.selection;if(X(n)&&!Q(n)){const n=t.transaction("paste"),s=d(t,n),r=n.build();if(this.dispatch(r),t=t.apply(r),s)return this.resolveAndInsertRichBlocks(e,t,s)}const s=U(n)?n.nodeId:W(n)?n.blockId:n.anchor.blockId;return this.resolveAndInsertRichBlocks(e,t,s)}resolveAndInsertRichBlocks(e,t,n){const s=t.selection,r=be(t,n);if(r){const s=Se(t,n,r,this.schemaRegistry);if(!s)return!1;const i=t.getBlock(r),o=s.anchorIndex>=0?s.anchorIndex+1:i?.children.length??0;return this.insertRichBlocks(e,t,s,o,!0)}const i=ve(t,n,this.schemaRegistry);if(!i)return!1;const o=W(s)&&"before"===s.side?0:1;return this.insertRichBlocks(e,t,i,i.anchorIndex+o,!W(s))}insertRichBlocks(e,t,n,s,r){const i=t.transaction("paste");let o,a=s,c=0;for(const l of e){const e=we(l,this.schemaRegistry);if(!e)continue;const t=Re(e);i.insertNode(n.parentPath,a,t),a++,o=t.id,c=(e.text??"").length}return r&&n.isAnchorEmpty&&n.anchorIndex>=0&&i.removeNode(n.parentPath,n.anchorIndex),o&&i.setSelection(V(o,c)),this.dispatch(i.build()),!0}handleFilePaste(e){if(!this.fileHandlerRegistry)return!1;const t=Array.from(e.files);if(0===t.length)for(let s=0;s<e.items.length;s++){const n=e.items[s];if(n&&"file"===n.kind){const e=n.getAsFile();e&&t.push(e)}}if(0===t.length)return!1;let n=!1;for(const s of t){const e=this.fileHandlerRegistry.matchFileHandlers(s.type);for(const t of e){const e=t(s,null);if(!0===e||e instanceof Promise){n=!0;break}}}return n}extractRichData(e){const t=document.createElement("template");t.innerHTML=e;const n=t.content.querySelector("[data-notectl-rich]"),s=n?.getAttribute("data-notectl-rich");if(s)return this.decodeHTMLEntities(s)}decodeHTMLEntities(e){return e.replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}requiresDocumentParser(e,t){return!!/<table[\s>]/i.test(e)||this.containsVoidBlockElements(t)}containsVoidBlockElements(e){if(!this.schemaRegistry)return!1;const t=this.schemaRegistry.getBlockParseRules();for(const n of t){const t=this.schemaRegistry.getNodeSpec(n.type);if(!t?.isVoid)continue;const s=e.querySelectorAll(n.rule.tag);for(const e of Array.from(s)){if(!n.rule.getAttrs)return!0;if(!1!==n.rule.getAttrs(e))return!0}}return!1}handleDocumentPaste(e,t){if(!this.schemaRegistry)return;const n=ne(e,this.schemaRegistry);if(0===n.children.length)return;const s=t.selection,r=t.transaction("paste");let i;X(s)&&!Q(s)&&(i=d(t,r));const o=i??(U(s)?s.nodeId:W(s)?s.blockId:s.anchor.blockId),a=ve(t,o,this.schemaRegistry);if(!a)return;const c=W(s)&&"before"===s.side?0:1;let l,h,p=a.anchorIndex+c;for(const d of n.children){const e=H(),t=xe(d,e);r.insertNode(a.parentPath,p,t),p++,l=m(t),h=t}if(a.isAnchorEmpty&&!W(s)&&r.removeNode(a.parentPath,a.anchorIndex),l&&h){const e=Ce(h,l),t=e?A(e).length:0;r.setSelection(V(l,t))}this.dispatch(r.build())}extractTextFromHTML(e){const t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}destroy(){this.element.removeEventListener("paste",this.handlePaste)}}class Zt{compositionTracker;inputHandler;keyboardHandler;pasteHandler;clipboardHandler;constructor(e,t){this.compositionTracker=new Ht,this.inputHandler=new _t(e,{getState:t.getState,dispatch:t.dispatch,syncSelection:t.syncSelection,inputRuleRegistry:t.inputRuleRegistry,isReadOnly:t.isReadOnly,compositionTracker:this.compositionTracker}),this.keyboardHandler=new At(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}),this.pasteHandler=new Yt(e,{getState:t.getState,dispatch:t.dispatch,schemaRegistry:t.schemaRegistry,fileHandlerRegistry:t.fileHandlerRegistry,isReadOnly:t.isReadOnly,getPasteInterceptors:t.getPasteInterceptors}),this.clipboardHandler=new Lt(e,{getState:t.getState,dispatch:t.dispatch,schemaRegistry:t.schemaRegistry,syncSelection:t.syncSelection,isReadOnly:t.isReadOnly})}destroy(){this.inputHandler.destroy(),this.keyboardHandler.destroy(),this.pasteHandler.destroy(),this.clipboardHandler.destroy()}}class en{_contextKeymaps=[];_navigationKeymaps=[];_defaultKeymaps=[];registerKeymap(e,t){const n=[...this._contextKeymaps,...this._navigationKeymaps,...this._defaultKeymaps];for(const s of Object.keys(e))for(const e of n)if(s in e){console.debug(`[notectl] Keymap shortcut "${s}" is already registered and will be overridden.`);break}this.keymapArrayForPriority(t?.priority??"default").push(e)}getKeymaps(){return[...this._contextKeymaps,...this._navigationKeymaps,...this._defaultKeymaps]}getKeymapsByPriority(){return{context:[...this._contextKeymaps],navigation:[...this._navigationKeymaps],default:[...this._defaultKeymaps]}}removeKeymap(e){for(const t of[this._contextKeymaps,this._navigationKeymaps,this._defaultKeymaps]){const n=t.indexOf(e);if(-1!==n)return void t.splice(n,1)}}clear(){this._contextKeymaps.length=0,this._navigationKeymaps.length=0,this._defaultKeymaps.length=0}keymapArrayForPriority(e){switch(e){case"context":return this._contextKeymaps;case"navigation":return this._navigationKeymaps;case"default":return this._defaultKeymaps}}}class tn{_inputRules=[];registerInputRule(e){this._inputRules.push(e)}getInputRules(){return this._inputRules}removeInputRule(e){const t=this._inputRules.indexOf(e);-1!==t&&this._inputRules.splice(t,1)}clear(){this._inputRules.length=0}}class nn{_fileHandlers=[];registerFileHandler(e,t){this._fileHandlers.push({pattern:e,handler:t})}getFileHandlers(){return this._fileHandlers}matchFileHandlers(e){const t=[];for(const n of this._fileHandlers)sn(n.pattern,e)&&t.push(n.handler);return t}removeFileHandler(e){const t=this._fileHandlers.findIndex(t=>t.handler===e);-1!==t&&this._fileHandlers.splice(t,1)}clear(){this._fileHandlers.length=0}}function sn(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}class rn{_nodeViews=/* @__PURE__ */new Map;registerNodeView(e,t){if(this._nodeViews.has(e))throw new Error(`NodeView for type "${e}" is already registered.`);this._nodeViews.set(e,t)}getNodeViewFactory(e){return this._nodeViews.get(e)}removeNodeView(e){this._nodeViews.delete(e)}clear(){this._nodeViews.clear()}}function on(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 an(e,t,n){if(0===t.length)return e;const s=[...t].sort((e,t)=>on(e,n)-on(t,n));let r=e;for(let i=s.length-1;i>=0;i--){const e=s[i];if(!e)continue;const t=cn(e,n);t.appendChild(r),r=t}return r}function cn(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")}}class ln{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(!X(n))return;if(!Q(n))return;const s=document.createElement("span");s.setAttribute("data-cursor-wrapper","");const r=document.createTextNode("​"),i=an(r,t,this.registry);s.appendChild(i);const o=ie();if(!o||0===o.rangeCount)return;let a;const c=oe(this.container,o);if(c){const e=document.createRange();try{e.setStart(c.anchorNode,c.anchorOffset),e.setEnd(c.focusNode,c.focusOffset)}catch{return}a=e}else a=o.getRangeAt(0);a.insertNode(s);try{o.collapse(r,r.length)}catch{}this.wrapperElement=s}cleanup(){this.wrapperElement&&(this.wrapperElement.remove(),this.wrapperElement=null)}}class hn{listeners=/* @__PURE__ */new Map;emit(e,t){const n=this.listeners.get(e.id);if(n)for(const r of n)try{r(t)}catch(s){console.error(`[EventBus] 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()}}const dn=100;class pn{plugins=/* @__PURE__ */new Map;commands=/* @__PURE__ */new Map;services=/* @__PURE__ */new Map;middlewares=[];pasteInterceptors=[];registrations=/* @__PURE__ */new Map;eventBus=new hn;pluginStyleSheets=[];schemaRegistry=new st;keymapRegistry=new en;inputRuleRegistry=new tn;fileHandlerRegistry=new nn;nodeViewRegistry=new rn;toolbarRegistry=new Ve;blockTypePickerRegistry=new je;middlewareSorted=null;pasteInterceptorsSorted=null;initOrder=[];initialized=!1;initializing=!1;readOnly=!1;readonlyBypassActive=!1;registerService(e,t){if(this.services.has(e.id))throw new Error(`Service "${e.id}" is already registered.`);this.services.set(e.id,t)}register(e){if(this.initialized||this.initializing)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)}async init(e){if(!this.initialized&&!this.initializing){this.initializing=!0,this.initOrder=this.resolveOrder();for(const n of this.initOrder){const s=this.plugins.get(n);if(!s)continue;const r=this.createContext(n,e);try{await s.init(r)}catch(t){console.error(`[PluginManager] Plugin "${n}" failed to initialize:`,t)}}e.onBeforeReady&&await e.onBeforeReady();for(const e of this.initOrder){const n=this.plugins.get(e);if(n?.onReady)try{await n.onReady()}catch(t){console.error(`[PluginManager] Plugin "${e}" error in onReady:`,t)}}this.initialized=!0,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){console.error(`[PluginManager] Plugin "${r}" error in onStateChange:`,s)}}}collectDecorations(e,t){let n=y.empty;for(const r of this.initOrder){const i=this.plugins.get(r);if(i?.decorations)try{const s=i.decorations(e,t);s.isEmpty||(n=n.merge(s))}catch(s){console.error(`[PluginManager] Plugin "${r}" error in decorations():`,s)}}return n}dispatchWithMiddleware(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 c=e=>{i||(i=!0,o(e))};try{n.middleware(e,t,c)}catch(a){console.error(`[PluginManager] Middleware "${n.name}" error:`,a),c(e)}}else i||(i=!0,n(e))};o(e)}canExecuteCommand(e){const t=this.commands.get(e);return!(!t||this.readOnly&&!t.readonlyAllowed)}executeCommand(e){const t=this.commands.get(e);if(!t)return!1;if(this.readOnly&&!t.readonlyAllowed)return!1;const n=this.readOnly&&t.readonlyAllowed;n&&(this.readonlyBypassActive=!0);try{return t.handler()}catch(s){return console.error(`[PluginManager] Command "${e}" error:`,s),!1}finally{n&&(this.readonlyBypassActive=!1)}}isReadonlyBypassed(){return this.readonlyBypassActive}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){console.error(`[PluginManager] 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){console.error(`[PluginManager] Plugin "${n}" error in onReadOnlyChange:`,t)}}}}getPluginIds(){return[...this.plugins.keys()]}getMiddlewareChain(){return this.getSortedMiddleware().map(e=>({name:e.name,priority:e.priority,pluginId:e.pluginId}))}getPasteInterceptors(){return this.getSortedPasteInterceptors()}get(e){return this.plugins.get(e)}getService(e){return this.services.get(e.id)}onEvent(e,t){return this.eventBus.on(e,t)}getPluginStyleSheets(){return this.pluginStyleSheets}async destroy(){const e=[...this.initOrder].reverse();for(const t of e)await this.destroyPlugin(t);this.plugins.clear(),this.commands.clear(),this.services.clear(),this.middlewares.length=0,this.middlewareSorted=null,this.pasteInterceptors.length=0,this.pasteInterceptorsSorted=null,this.pluginStyleSheets.length=0,this.eventBus.clear(),this.registrations.clear(),this.schemaRegistry.clear(),this.keymapRegistry.clear(),this.inputRuleRegistry.clear(),this.fileHandlerRegistry.clear(),this.nodeViewRegistry.clear(),this.toolbarRegistry.clear(),this.blockTypePickerRegistry.clear(),this.initOrder=[],this.initialized=!1}async destroyPlugin(e){const t=this.plugins.get(e);if(t?.destroy)try{await t.destroy()}catch(n){console.error(`[PluginManager] Plugin "${e}" error in destroy:`,n)}this.cleanupRegistrations(e)}cleanupRegistrations(e){const t=this.registrations.get(e);if(t){for(const e of t.commands)this.commands.delete(e);for(const e of t.services)this.services.delete(e);for(const e of t.middlewares){const t=this.middlewares.indexOf(e);-1!==t&&this.middlewares.splice(t,1)}for(const e of t.pasteInterceptors){const t=this.pasteInterceptors.indexOf(e);-1!==t&&this.pasteInterceptors.splice(t,1)}for(const e of t.unsubscribers)e();for(const e of t.nodeSpecs)this.schemaRegistry.removeNodeSpec(e);for(const e of t.markSpecs)this.schemaRegistry.removeMarkSpec(e);for(const e of t.inlineNodeSpecs)this.schemaRegistry.removeInlineNodeSpec(e);for(const e of t.nodeViews)this.nodeViewRegistry.removeNodeView(e);for(const e of t.keymaps)this.keymapRegistry.removeKeymap(e);for(const e of t.inputRules)this.inputRuleRegistry.removeInputRule(e);for(const e of t.toolbarItems)this.toolbarRegistry.removeToolbarItem(e);for(const e of t.fileHandlers)this.fileHandlerRegistry.removeFileHandler(e);for(const e of t.blockTypePickerEntries)this.blockTypePickerRegistry.removeBlockTypePickerEntry(e);for(const e of t.stylesheets){const t=this.pluginStyleSheets.indexOf(e);-1!==t&&this.pluginStyleSheets.splice(t,1)}this.middlewareSorted=null,this.pasteInterceptorsSorted=null,this.registrations.delete(e)}}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}createContext(e,t){const n={commands:[],services:[],middlewares:[],pasteInterceptors:[],unsubscribers:[],nodeSpecs:[],markSpecs:[],inlineNodeSpecs:[],nodeViews:[],keymaps:[],inputRules:[],toolbarItems:[],fileHandlers:[],blockTypePickerEntries:[],stylesheets:[]};this.registrations.set(e,n);const s={emit:(e,t)=>this.eventBus.emit(e,t),on:(e,t)=>{const s=this.eventBus.on(e,t);return n.unsubscribers.push(s),s},off:(e,t)=>this.eventBus.off(e,t)};return{getState:t.getState,dispatch:t.dispatch,getContainer:t.getContainer,getPluginContainer:t.getPluginContainer,isReadOnly:()=>this.readOnly,registerCommand:(t,s,r)=>{if(this.commands.has(t)){const e=this.commands.get(t);throw new Error(`Command "${t}" is already registered by plugin "${e?.pluginId}".`)}const i=r?.readonlyAllowed??!1;this.commands.set(t,{name:t,handler:s,pluginId:e,readonlyAllowed:i}),n.commands.push(t)},executeCommand:e=>this.executeCommand(e),getEventBus:()=>s,registerMiddleware:(t,s)=>{const r={name:s?.name??(t.name||"anonymous"),pluginId:e,middleware:t,priority:s?.priority??dn};this.middlewares.push(r),n.middlewares.push(r),this.middlewareSorted=null},registerService:(e,t)=>{if(this.services.has(e.id))throw new Error(`Service "${e.id}" is already registered by another plugin.`);this.services.set(e.id,t),n.services.push(e.id)},getService:e=>this.services.get(e.id),updateConfig:t=>{const n=this.plugins.get(e);if(n?.onConfigure)try{n.onConfigure(t)}catch(s){console.error(`[PluginManager] Plugin "${e}" error in onConfigure:`,s)}},registerNodeSpec:e=>{this.schemaRegistry.registerNodeSpec(e),n.nodeSpecs.push(e.type)},registerMarkSpec:e=>{this.schemaRegistry.registerMarkSpec(e),n.markSpecs.push(e.type)},registerNodeView:(e,t)=>{this.nodeViewRegistry.registerNodeView(e,t),n.nodeViews.push(e)},registerKeymap:(e,t)=>{this.keymapRegistry.registerKeymap(e,t),n.keymaps.push(e)},registerInputRule:e=>{this.inputRuleRegistry.registerInputRule(e),n.inputRules.push(e)},registerToolbarItem:t=>{this.toolbarRegistry.registerToolbarItem(t,e),n.toolbarItems.push(t.id)},registerInlineNodeSpec:e=>{this.schemaRegistry.registerInlineNodeSpec(e),n.inlineNodeSpecs.push(e.type)},registerFileHandler:(e,t)=>{this.fileHandlerRegistry.registerFileHandler(e,t),n.fileHandlers.push(t)},registerBlockTypePickerEntry:e=>{this.blockTypePickerRegistry.registerBlockTypePickerEntry(e),n.blockTypePickerEntries.push(e.id)},registerPasteInterceptor:(t,s)=>{const r={name:s?.name??"anonymous",pluginId:e,interceptor:t,priority:s?.priority??dn};this.pasteInterceptors.push(r),n.pasteInterceptors.push(r),this.pasteInterceptorsSorted=null},getSchemaRegistry:()=>this.schemaRegistry,getKeymapRegistry:()=>this.keymapRegistry,getInputRuleRegistry:()=>this.inputRuleRegistry,getFileHandlerRegistry:()=>this.fileHandlerRegistry,getNodeViewRegistry:()=>this.nodeViewRegistry,getToolbarRegistry:()=>this.toolbarRegistry,getBlockTypePickerRegistry:()=>this.blockTypePickerRegistry,registerStyleSheet:e=>{const t=new CSSStyleSheet;t.replaceSync(e),this.pluginStyleSheets.push(t),n.stylesheets.push(t)},announce:e=>{t.announce?.(e)},hasAnnouncement:()=>t.hasAnnouncement?.()??!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),s=e?.dependencies??[];t.set(i,s.length);for(const t of s){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??dn)-(this.plugins.get(t)?.priority??dn));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}}const un={Light:"light",Dark:"dark",System:"system"},fn={name:"light",primitives:{background:"#ffffff",foreground:"#1a1a1a",mutedForeground:"#666666",border:"#d0d0d0",borderFocus:"#4a90d9",primary:"#4a90d9",primaryForeground:"#1a5fa0",primaryMuted:"#d0e0f0",surfaceRaised:"#f8f8f8",surfaceOverlay:"#ffffff",hoverBackground:"#e8e8e8",activeBackground:"#d0e0f0",danger:"#dc2626",dangerMuted:"#fee2e2",success:"#1a8c1a",shadow:"rgba(0, 0, 0, 0.15)",focusRing:"rgba(74, 144, 217, 0.2)"},codeBlock:{background:"#f8fafc",foreground:"#334155",headerBackground:"#f1f5f9",headerForeground:"#64748b",headerBorder:"#e2e8f0",syntax:{keyword:"#d73a49",string:"#032f62",comment:"#6a737d",number:"#005cc5",function:"#6f42c1",operator:"#d73a49",punctuation:"#24292e",boolean:"#005cc5",null:"#005cc5",property:"#005cc5"}},tooltip:{background:"#1a1a1a",foreground:"#ffffff"}},gn={name:"dark",primitives:{background:"#1e1e2e",foreground:"#cdd6f4",mutedForeground:"#7f849c",border:"#45475a",borderFocus:"#89b4fa",primary:"#89b4fa",primaryForeground:"#89b4fa",primaryMuted:"rgba(137, 180, 250, 0.15)",surfaceRaised:"#313244",surfaceOverlay:"#313244",hoverBackground:"#45475a",activeBackground:"rgba(137, 180, 250, 0.15)",danger:"#f38ba8",dangerMuted:"rgba(243, 139, 168, 0.15)",success:"#a6e3a1",shadow:"rgba(0, 0, 0, 0.4)",focusRing:"rgba(137, 180, 250, 0.25)"},codeBlock:{background:"#11111b",foreground:"#cdd6f4",headerBackground:"#181825",headerForeground:"#7f849c",headerBorder:"rgba(205, 214, 244, 0.08)",syntax:{keyword:"#cba6f7",string:"#a6e3a1",comment:"#6c7086",number:"#fab387",function:"#89b4fa",operator:"#89dceb",punctuation:"#bac2de",boolean:"#fab387",null:"#f38ba8",property:"#89b4fa"}},tooltip:{background:"#585b70",foreground:"#cdd6f4"}};function mn(e,t){return{name:t.name,primitives:{...e.primitives,...t.primitives},toolbar:t.toolbar?{...e.toolbar,...t.toolbar}:e.toolbar,codeBlock:t.codeBlock?{...e.codeBlock,...t.codeBlock,syntax:t.codeBlock.syntax?{...e.codeBlock?.syntax,...t.codeBlock.syntax}:e.codeBlock?.syntax}:e.codeBlock,tooltip:t.tooltip?{...e.tooltip,...t.tooltip}:e.tooltip}}function yn(e){if("object"==typeof e)return e;switch(e){case un.Light:return fn;case un.Dark:return gn;default:return fn}}const kn=[["primitives.background","--notectl-bg"],["primitives.foreground","--notectl-fg"],["primitives.mutedForeground","--notectl-fg-muted"],["primitives.border","--notectl-border"],["primitives.borderFocus","--notectl-border-focus"],["primitives.primary","--notectl-primary"],["primitives.primaryForeground","--notectl-primary-fg"],["primitives.primaryMuted","--notectl-primary-muted"],["primitives.surfaceRaised","--notectl-surface-raised"],["primitives.surfaceOverlay","--notectl-surface-overlay"],["primitives.hoverBackground","--notectl-hover-bg"],["primitives.activeBackground","--notectl-active-bg"],["primitives.danger","--notectl-danger"],["primitives.dangerMuted","--notectl-danger-muted"],["primitives.success","--notectl-success"],["primitives.shadow","--notectl-shadow"],["primitives.focusRing","--notectl-focus-ring"],["toolbar.background","--notectl-toolbar-bg"],["toolbar.borderColor","--notectl-toolbar-border"],["codeBlock.background","--notectl-code-block-bg"],["codeBlock.foreground","--notectl-code-block-color"],["codeBlock.headerBackground","--notectl-code-block-header-bg"],["codeBlock.headerForeground","--notectl-code-block-header-color"],["codeBlock.headerBorder","--notectl-code-block-header-border"],["codeBlock.syntax.keyword","--notectl-code-token-keyword"],["codeBlock.syntax.string","--notectl-code-token-string"],["codeBlock.syntax.comment","--notectl-code-token-comment"],["codeBlock.syntax.number","--notectl-code-token-number"],["codeBlock.syntax.function","--notectl-code-token-function"],["codeBlock.syntax.operator","--notectl-code-token-operator"],["codeBlock.syntax.punctuation","--notectl-code-token-punctuation"],["codeBlock.syntax.boolean","--notectl-code-token-boolean"],["codeBlock.syntax.null","--notectl-code-token-null"],["codeBlock.syntax.property","--notectl-code-token-property"],["tooltip.background","--notectl-tooltip-bg"],["tooltip.foreground","--notectl-tooltip-fg"]],bn=/* @__PURE__ */new Map([["--notectl-toolbar-bg","var(--notectl-surface-raised)"],["--notectl-toolbar-border","var(--notectl-border)"],["--notectl-code-block-bg","var(--notectl-surface-raised)"],["--notectl-code-block-color","var(--notectl-fg)"],["--notectl-code-block-header-bg","var(--notectl-surface-raised)"],["--notectl-code-block-header-color","var(--notectl-fg-muted)"],["--notectl-code-block-header-border","var(--notectl-border)"],["--notectl-code-token-keyword","var(--notectl-code-block-color)"],["--notectl-code-token-string","var(--notectl-code-block-color)"],["--notectl-code-token-comment","var(--notectl-code-block-color)"],["--notectl-code-token-number","var(--notectl-code-block-color)"],["--notectl-code-token-function","var(--notectl-code-block-color)"],["--notectl-code-token-operator","var(--notectl-code-block-color)"],["--notectl-code-token-punctuation","var(--notectl-code-block-color)"],["--notectl-code-token-boolean","var(--notectl-code-block-color)"],["--notectl-code-token-null","var(--notectl-code-block-color)"],["--notectl-code-token-property","var(--notectl-code-block-color)"],["--notectl-tooltip-bg","var(--notectl-fg)"],["--notectl-tooltip-fg","var(--notectl-bg)"]]);function Sn(e,t){const n=t.split(".");let s=e;for(const r of n){if(null==s)return;if("object"!=typeof s)return;s=s[r]}return"string"==typeof s?s:void 0}function vn(e){const t=[":host {"];for(const[n,s]of kn){const r=Sn(e,n);if(void 0!==r)t.push(`\t${s}: ${r};`);else{const e=bn.get(s);e&&t.push(`\t${s}: ${e};`)}}return t.push("}"),t.join("\n")}function wn(e){const t=new CSSStyleSheet;return t.replaceSync(vn(e)),t}const Rn={EN:"en",DE:"de",ES:"es",FR:"fr",ZH:"zh",RU:"ru",AR:"ar",HI:"hi",PT:"pt",BROWSER:"browser"},xn={paragraph:"Paragraph",heading:"Heading",code_block:"Code Block",blockquote:"Block Quote",list_item:"List Item",horizontal_rule:"Horizontal Rule",image:"Image",table:"Table"};function Cn(e,t){return"heading"===e&&t?.level?`Heading ${t.level}`:xn[e]??e}function In(e,t){const n=t?.document??globalThis.document,s=t?.container??n.head;if(t?.id){const s=n.getElementById(t.id);if(s instanceof HTMLStyleElement)return s.textContent=e,t.nonce&&s.setAttribute("nonce",t.nonce),s}const r=n.createElement("style");return r.textContent=e,t?.id&&(r.id=t.id),t?.nonce&&r.setAttribute("nonce",t.nonce),s.appendChild(r),r}function Tn(e,t){const n=(t??globalThis.document).getElementById(e);n&&n.remove()}const En=/* @__PURE__ */new WeakSet;function Bn(e,t){const n=t?.target??globalThis.document,s=new CSSStyleSheet;return s.replaceSync(e),En.add(s),t?.replace&&(n.adoptedStyleSheets=n.adoptedStyleSheets.filter(e=>!En.has(e))),n.adoptedStyleSheets=[...n.adoptedStyleSheets,s],s}function Mn(e,t){const n=t??globalThis.document;n.adoptedStyleSheets=n.adoptedStyleSheets.filter(t=>t!==e)}function Pn(e,t,n){if(!n)return;const s=[];let r=null,i=[];for(const o of t){const e=n.getNodeSpec(o.type),t=e?.wrapper?.(o);t&&r&&t.key===r.key?i.push(o.id):t?(r&&i.length>0&&s.push({spec:r,blockIds:i}),r=t,i=[o.id]):(r&&i.length>0&&s.push({spec:r,blockIds:i}),r=null,i=[])}r&&i.length>0&&s.push({spec:r,blockIds:i});for(const o of s){const t=e.querySelector(`[data-block-id="${o.blockIds[0]}"]`);if(!t)continue;const n=document.createElement(o.spec.tag);if(n.setAttribute("data-block-wrapper",o.spec.key),o.spec.className&&(n.className=o.spec.className),o.spec.attrs)for(const[e,s]of Object.entries(o.spec.attrs))n.setAttribute(e,s);t.before(n);for(const s of o.blockIds){const t=e.querySelector(`[data-block-id="${s}"]`);t&&n.appendChild(t)}}}function An(e){e.parentElement?.removeChild(e)}function Nn(e,t,n){const s=e.parentElement;s?s.replaceChild(t,e):n.replaceChild(t,e)}function Dn(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 On(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 Ln(e){let t=e.replace(/ {2}/g,"  ");return t.endsWith(" ")&&(t=`${t.slice(0,-1)} `),t.startsWith(" ")&&(t=` ${t.slice(1)}`),t}function Hn(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&&Le(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 _n(e,t,n){const s=n?.decorations?.findNode(t);if(s&&0!==s.length)for(const r of s){if(r.attrs.class)for(const t of r.attrs.class.split(" "))t&&e.classList.add(t);r.attrs.style&&He(e,r.attrs.style)}}function zn(e,t,n,s){const r=s?.decorations?.findInline(e.id),i=s?.nodeViewRegistry;if(i&&t&&n&&s?.getState&&s?.dispatch){const o=i.getNodeViewFactory(e.type);if(o){const i=o(e,s.getState,s.dispatch);n.set(e.id,i);const a=t.getNodeSpec(e.type);if(a?.isVoid&&i.dom.setAttribute("data-void","true"),a?.selectable&&i.dom.setAttribute("data-selectable","true"),i.contentDOM&&i.contentDOM!==i.dom&&i.contentDOM.setAttribute("data-content-dom","true"),L(e)&&i.contentDOM)Fn(i.contentDOM,e,t,r);else{const r=z(e),o=/* @__PURE__ */new Map;for(const e of r){const r=i.getContentDOM?.(e.id)??i.contentDOM;if(r){const i=zn(e,t,n,s);r.appendChild(i);let a=o.get(r);a||(a=[],o.set(r,a)),a.push(e)}}for(const[e,n]of o)Pn(e,n,t)}return i.dom.setAttribute("data-block-type",e.type),_n(i.dom,e.id,s),i.dom}}if(t){const i=t.getNodeSpec(e.type);if(i){const o=i.toDOM(e);if(i.isVoid&&o.setAttribute("data-void","true"),i.selectable&&o.setAttribute("data-selectable","true"),!i.isVoid)if(L(e))Fn(o,e,t,r);else{const r=z(e);for(const e of r){const r=zn(e,t,n,s);o.appendChild(r)}Pn(o,r,t)}return o.setAttribute("data-block-type",e.type),_n(o,e.id,s),o}}return function(e,t,n){const s=Ye("p",e.id);return s.setAttribute("data-block-type",e.type),Fn(s,e,t,n),s}(e,t,r)}function Fn(e,t,n,s){for(const o of e.querySelectorAll("[data-cursor-wrapper]"))o.remove();const r=T(t);if(1===r.length&&x(r[0])&&""===r[0].text)return void e.appendChild(document.createElement("br"));if(s&&0!==s.length)!function(e,t,n,s){let r=0;for(const i of t){if(w(i)){e.appendChild(On(i,s)),r+=1;continue}const t=r,o=r+i.text.length;if(0===i.text.length){r=o;continue}const a=/* @__PURE__ */new Set;a.add(t),a.add(o);for(const e of n){const n=Math.max(t,e.from),s=Math.min(o,e.to);n>t&&n<o&&a.add(n),s>t&&s<o&&a.add(s)}const c=[...a].sort((e,t)=>e-t);for(let r=0;r<c.length-1;r++){const o=c[r],a=c[r+1];if(void 0===o||void 0===a||o>=a)continue;const l=o-t,h=a-t,d=i.text.slice(l,h),p=[];for(const e of n)e.from<=o&&e.to>=a&&p.push(e);let u=an(document.createTextNode(Ln(d)),i.marks,s);for(const e of p){const t=Hn(e.attrs);t.appendChild(u),u=t}e.appendChild(u)}r=o}}(e,r,s,n);else for(const o of r)x(o)?e.appendChild(Kn(o,n)):e.appendChild(On(o,n));const i=r[r.length-1];i&&w(i)&&"hard_break"===i.inlineType&&e.appendChild(document.createElement("br"))}function Kn(e,t){return""===e.text?document.createTextNode(""):an(document.createTextNode(Ln(e.text)),e.marks,t)}function $n(e,t,n,s){const r=t?.doc.children??[],i=n.doc.children,o=s?.registry,a=s?.nodeViews,c=null!=s?.compositionBlockId;c||function(e){const t=Array.from(e.querySelectorAll(":scope > [data-block-wrapper]"));for(const n of t){for(;n.firstChild;)e.insertBefore(n.firstChild,n);n.remove()}}(e);const l=/* @__PURE__ */new Map;for(const g 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=g.getAttribute("data-block-id");e&&l.set(Ie(e),g)}const h=new Set(i.map(e=>e.id));for(const[g,m]of l)if(!h.has(g)){An(m),l.delete(g);const e=a?.get(g);e&&(e.destroy?.(),a?.delete(g))}const d=/* @__PURE__ */new Map;for(const g of r)d.set(g.id,g);let p=null;const u=s?.selectedNodeId,f=s?.previousSelectedNodeId;for(const g of i){const t=l.get(g.id),n=d.get(g.id);if(s?.compositionBlockId===g.id&&t){p=t;continue}const r=s?.oldDecorations?.find(g.id),i=s?.decorations?.find(g.id);if(t&&n&&!jn(n,g,r,i))p=t;else if(t){const n=a?.get(g.id);if(n){if(n.update?.(g)){if(L(g)&&n.contentDOM){n.contentDOM.textContent="";const e=s?.decorations?.findInline(g.id);Fn(n.contentDOM,g,o,e)}p=n.dom;continue}n.destroy?.(),a?.delete(g.id)}const r=zn(g,o,a,s);Nn(t,r,e),p=r}else{const t=zn(g,o,a,s);Dn(e,p,t),p=t}if(u===g.id){const e=a?.get(g.id);if(e)e.selectNode?.();else{const e=l.get(g.id)??p;e instanceof HTMLElement&&e.classList.add("notectl-node-selected")}}else if(f===g.id){const e=a?.get(g.id);if(e)e.deselectNode?.();else{const e=l.get(g.id)??p;e instanceof HTMLElement&&e.classList.remove("notectl-node-selected")}}}if(f&&f!==u){const e=a?.get(f);e&&!h.has(f)&&e.deselectNode?.()}if(u&&!h.has(u)){const e=a?.get(u);e&&e.selectNode?.()}c||Pn(e,i,o)}function jn(e,t,n,s){if(e.type!==t.type)return!0;if(e.children.length!==t.children.length)return!0;const r=e.attrs,i=t.attrs;if(r!==i){if(!r||!i)return!0;const e=Object.keys(r),t=Object.keys(i);if(e.length!==t.length)return!0;for(const n of e)if(r[n]!==i[n])return!0}for(let c=0;c<e.children.length;c++){const n=e.children[c],s=t.children[c];if(!n||!s)return!0;if(x(n)&&x(s)){if(n.text!==s.text)return!0;if(!_(n.marks,s.marks))return!0}else if(w(n)&&w(s)){if(n.inlineType!==s.inlineType)return!0;if(!Vn(n.attrs,s.attrs))return!0}else{if(x(n)||x(s)||w(n)||w(s))return!0;if(jn(n,s))return!0}}const o=n??[],a=s??[];return o!==a&&!k(o,a)}function Vn(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}class Un{state;contentElement;history;stateChangeCallbacks=[];handleSelectionChange;handleMousedown;handleDragover;handleDrop;handleCompositionStartForWrapper;handleCompositionEndForWrapper;isUpdating=!1;pendingNodeSelectionClear=!1;pendingGapCursorClear=!1;schemaRegistry;keymapRegistry;fileHandlerRegistry;nodeViewRegistry;nodeViews=/* @__PURE__ */new Map;decorations=y.empty;getDecorations;isReadOnly;navigationKeymap=null;compositionState;cursorWrapper;goalColumn=null;preserveGoalColumn=!1;constructor(e,t){this.state=t.state,this.contentElement=e,this.schemaRegistry=t.schemaRegistry,this.keymapRegistry=t.keymapRegistry,this.fileHandlerRegistry=t.fileHandlerRegistry,this.nodeViewRegistry=t.nodeViewRegistry,this.getDecorations=t.getDecorations,this.isReadOnly=t.isReadOnly??(()=>!1),this.compositionState=t.compositionState??{isComposing:!1,activeBlockId:null},this.history=new Et({maxDepth:t.maxHistoryDepth??100}),t.onStateChange&&this.stateChangeCallbacks.push(t.onStateChange),this.cursorWrapper=new ln(e,this.schemaRegistry),this.handleCompositionStartForWrapper=()=>{this.cursorWrapper.onCompositionStart(this.state)},this.handleCompositionEndForWrapper=()=>{this.cursorWrapper.cleanup()},e.addEventListener("compositionstart",this.handleCompositionStartForWrapper),e.addEventListener("compositionend",this.handleCompositionEndForWrapper),this.handleSelectionChange=this.onSelectionChange.bind(this),document.addEventListener("selectionchange",this.handleSelectionChange),this.handleMousedown=this.onMousedown.bind(this),e.addEventListener("mousedown",this.handleMousedown),this.handleDragover=this.onDragover.bind(this),e.addEventListener("dragover",this.handleDragover),this.handleDrop=this.onDrop.bind(this),e.addEventListener("drop",this.handleDrop),this.decorations=this.getDecorations?.(this.state)??y.empty,$n(e,null,this.state,{...this.reconcileOptions(),decorations:this.decorations}),ae(e,this.state.selection),this.registerNavigationKeymaps()}getState(){return this.state}applyUpdate(e,t,n){if(!this.isUpdating){this.isUpdating=!0;try{const s=this.state;this.state=e,this.cursorWrapper.isActive&&!e.storedMarks?.length&&this.cursorWrapper.cleanup(),n?.pushHistory&&"history"!==t.metadata.origin&&this.history.push(t);const r=this.getDecorations?.(e,t)??y.empty;this.reconcileAndSync(s,e,r);for(const n of this.stateChangeCallbacks)n(s,e,t);this.preserveGoalColumn||(this.goalColumn=null)}finally{this.isUpdating=!1}}}dispatch(e){const t=this.state.apply(e);this.applyUpdate(t,e,{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;this.state=e,this.history.clear();const n=this.getDecorations?.(e)??y.empty;this.reconcileAndSync(t,e,n)}finally{this.isUpdating=!1}}}syncSelectionFromDOM(){if(this.compositionState.isComposing)return;if(this.cursorWrapper.isActive&&this.cursorWrapper.cleanup(),U(this.state.selection)&&!this.pendingNodeSelectionClear)return;if(W(this.state.selection)&&!this.pendingGapCursorClear)return;this.pendingNodeSelectionClear=!1,this.pendingGapCursorClear=!1;const e=ce(this.contentElement);if(!e)return;if(J(e,this.state.selection))return;const t=this.state.transaction("input").setSelection(e).setStoredMarks(null,this.state.storedMarks).build(),n=this.state.apply(t);this.applyUpdate(n,t)}onMousedown(e){if(this.isUpdating)return;this.goalColumn=null;const t=e.target;if(!(t instanceof HTMLElement))return;const n=t.closest("[data-block-id]");if(!(n instanceof HTMLElement&&this.contentElement.contains(n)))return void((this.contentElement.contains(t)||t===this.contentElement)&&this.handleClickBelowContent(e));if(!n.hasAttribute("data-void")&&!n.hasAttribute("data-selectable"))return U(this.state.selection)&&(this.pendingNodeSelectionClear=!0),void(W(this.state.selection)&&(this.pendingGapCursorClear=!0));const s=n.querySelector("[data-content-dom]");if(s?.contains(t))return U(this.state.selection)&&(this.pendingNodeSelectionClear=!0),void(W(this.state.selection)&&(this.pendingGapCursorClear=!0));e.preventDefault(),this.contentElement.focus();const r=Ie(n.getAttribute("data-block-id")??""),i=Ze(this.contentElement,n),o=j(r,i),a=this.state.transaction("input").setSelection(o).setStoredMarks(null,this.state.storedMarks).build(),c=this.state.apply(a);this.applyUpdate(c,a)}handleClickBelowContent(e){if(this.isReadOnly())return;const t=this.state.getBlockOrder(),n=t[t.length-1];if(!n)return;const s=this.contentElement.querySelector(`[data-block-id="${n}"]`);if(!s)return;const r=s.getBoundingClientRect();if(e.clientY<=r.bottom)return;const i=this.state.getBlock(n);if("paragraph"===i?.type&&0===B(i)){const t=this.state.transaction("input").setSelection(V(n,0)).build();return this.dispatch(t),void e.preventDefault()}e.preventDefault(),this.contentElement.focus();const o=H(),a=i?B(i):0,c=this.state.transaction("input").splitBlock(n,a,o).setBlockType(o,Te("paragraph")).setSelection(V(o,0)).build();this.dispatch(c)}onDragover(e){this.fileHandlerRegistry&&e.dataTransfer&&e.dataTransfer.types.includes("Files")&&e.preventDefault()}onDrop(e){if(this.isReadOnly())return;if(!this.fileHandlerRegistry)return;if(!e.dataTransfer)return;const t=Array.from(e.dataTransfer.files);if(0===t.length)return;const n=this.getPositionFromPoint(e.clientX,e.clientY);let s=!1;for(const r of t){const e=this.fileHandlerRegistry.matchFileHandlers(r.type);for(const t of e){const e=t(r,n);if(!0===e||e instanceof Promise){s=!0;break}}}s&&e.preventDefault()}getPositionFromPoint(e,t){const n=this.contentElement.getRootNode(),s=le(n,e,t);return s&&this.contentElement.contains(s.node)?he(this.contentElement,s.node,s.offset):null}onSelectionChange(){if(this.isUpdating)return;const e=this.contentElement.getRootNode(),t="activeElement"in e?e.activeElement:document.activeElement;(this.contentElement.contains(t)||t===this.contentElement)&&this.syncSelectionFromDOM()}reconcileAndSync(e,t,n){const s=this.decorations;this.decorations=n,$n(this.contentElement,e,t,{...this.reconcileOptions(e.selection),decorations:n,oldDecorations:s,compositionBlockId:this.compositionState.isComposing?this.compositionState.activeBlockId??void 0:void 0}),this.compositionState.isComposing||ae(this.contentElement,t.selection)}reconcileOptions(e){const t=U(this.state.selection)?this.state.selection.nodeId:void 0,n=e&&U(e)?e.nodeId:void 0;return{registry:this.schemaRegistry,nodeViewRegistry:this.nodeViewRegistry,nodeViews:this.nodeViews,getState:()=>this.state,dispatch:e=>this.dispatch(e),selectedNodeId:t,previousSelectedNodeId:n}}registerNavigationKeymaps(){if(!this.keymapRegistry)return;const e={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},t={};for(const[n,s]of Object.entries(e))t[n]=()=>this.handleNavigationArrow(s);this.navigationKeymap=t,this.keymapRegistry.registerKeymap(t,{priority:"navigation"})}handleNavigationArrow(e){return!U(this.state.selection)&&!W(this.state.selection)&&!!Q(this.state.selection)&&("left"===e||"right"===e?this.handleHorizontalArrow(e):this.handleVerticalArrow(e))}handleHorizontalArrow(e){this.goalColumn=null;const t=this.resolveLogicalHorizontalDirection(e),n=de(this.state,t);if(n)return this.dispatch(n),this.validateSelectionAfterInlineSkip(),!0;if(!pe(this.contentElement,this.state,e))return!1;const s=ue(this.state,t);return!!s&&(this.dispatch(s),!0)}resolveLogicalHorizontalDirection(e){const t=this.state.selection;if(!X(t))return e;const n=this.contentElement.querySelector(`[data-block-id="${t.anchor.blockId}"]`);return n instanceof HTMLElement&&"rtl"===$e(n)?"left"===e?"right":"left":e}handleVerticalArrow(e){const t=this.contentElement.ownerDocument.getSelection?.()??null,n=t?fe(t):null;if(!pe(this.contentElement,this.state,e,n))return!1;null===this.goalColumn&&n&&(this.goalColumn=n.left),this.preserveGoalColumn=!0;const s=ge(this.contentElement,this.state,e,this.goalColumn);return s?(this.dispatch(s),this.preserveGoalColumn=!1,!0):(this.preserveGoalColumn=!1,!1)}validateSelectionAfterInlineSkip(){const e=ce(this.contentElement);e&&J(e,this.state.selection)||ae(this.contentElement,this.state.selection)}syncSelection(){this.syncSelectionFromDOM()}destroy(){this.cursorWrapper.cleanup(),this.contentElement.removeEventListener("compositionstart",this.handleCompositionStartForWrapper),this.contentElement.removeEventListener("compositionend",this.handleCompositionEndForWrapper),document.removeEventListener("selectionchange",this.handleSelectionChange),this.contentElement.removeEventListener("mousedown",this.handleMousedown),this.contentElement.removeEventListener("dragover",this.handleDragover),this.contentElement.removeEventListener("drop",this.handleDrop),this.navigationKeymap&&this.keymapRegistry&&(this.keymapRegistry.removeKeymap(this.navigationKeymap),this.navigationKeymap=null);for(const e of this.nodeViews.values())e.destroy?.();this.nodeViews.clear()}}function Wn(e,t,n){const s=t?function(e,t){return{children:e.children.map(e=>qn(e,t))}}(e,t):e,r=t?De(t):void 0;n(wt.create({doc:s,schema:r,selection:V(s.children[0]?.id??Ie(""),0)}))}function qn(e,t){const n=t.getNodeSpec(e.type);if(!n?.content||!((s=n.content).allow.length>0)||s.allow.includes("text"))return e;var s;if(L(e)){const t=e.children.length>0?e.children:void 0,n=M(Te("paragraph"),t);return M(e.type,[n],e.id,e.attrs)}const r=e.children.map(e=>x(e)||w(e)?e:qn(e,t));return M(e.type,r,e.id,e.attrs)}class Gn{config={};getConfig(){return this.config}setConfig(e){this.config=e}mergeConfig(e){this.config={...this.config,...e}}applyAttribute(e,t,n){if("placeholder"===e&&this.applyPlaceholder(t??"",n.contentElement),"readonly"===e){const e=null!==t;this.applyReadonly(e,n.contentElement,n.pluginManager),this.config={...this.config,readonly:e}}"theme"===e&&n.themeController?.apply(t??un.Light),"paper-size"===e&&(null===t?(n.applyPaperSize(void 0),this.config={...this.config,paperSize:void 0}):We(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??un.Light}get isReadOnly(){return this.config.readonly??!1}getPaperSize(){return this.config.paperSize}applyPlaceholder(e,t){t?.setAttribute("data-placeholder",e)}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")))}}const Qn={ariaLabel:"Rich text editor",ariaDescription:"Press Escape to exit the editor",defaultPlaceholder:"Start typing..."},Jn=/* @__PURE__ */Object.assign({"./locales/ar.ts":()=>import("./ar-mSCYQYnL.mjs"),"./locales/de.ts":()=>import("./de-DOLwx_M7.mjs"),"./locales/es.ts":()=>import("./es-Bk0bRDFE.mjs"),"./locales/fr.ts":()=>import("./fr-C1W7jyd6.mjs"),"./locales/hi.ts":()=>import("./hi-ntUsOspQ.mjs"),"./locales/pt.ts":()=>import("./pt-cN6r-f7f.mjs"),"./locales/ru.ts":()=>import("./ru-CZvkdGnf.mjs"),"./locales/zh.ts":()=>import("./zh-lhynyH6Q.mjs")});class Xn{listeners=/* @__PURE__ */new Map;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)for(const s of n)s(t)}clear(){this.listeners.clear()}}class Yn{initialized=!1;readyPromiseResolve=null;readyPromise;preInitPlugins=[];constructor(){this.readyPromise=this.createReadyPromise()}isInitialized(){return this.initialized}markInitialized(){return!this.initialized&&(this.initialized=!0,!0)}whenReady(){return this.readyPromise}resolveReady(){this.readyPromiseResolve?.()}registerPreInitPlugin(e){if(this.initialized)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}reset(){this.initialized=!1,this.preInitPlugins=[],this.readyPromise=this.createReadyPromise()}createReadyPromise(){return new Promise(e=>{this.readyPromiseResolve=e})}}class Zn{runtimeStyleSheet=null;setup(e,t,n){_e(e),this.runtimeStyleSheet=ze(),n?.setRuntimeStyleSheets(this.runtimeStyleSheet?[this.runtimeStyleSheet]:[]),Fe(e,{nonce:t,sheet:this.runtimeStyleSheet})}teardown(e,t){e&&_e(e),this.runtimeStyleSheet=null,t?.setRuntimeStyleSheets([])}}const es=["\n:host {\n\tdisplay: block;\n\tfont-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n\tfont-size: 16px;\n\tline-height: 1.6;\n\tcolor: var(--notectl-fg);\n}\n\n.notectl-editor {\n\tdisplay: flex;\n\tflex-direction: column;\n\tborder: 1px solid var(--notectl-border);\n\tborder-radius: 6px;\n\toverflow: hidden;\n\tbackground: var(--notectl-bg);\n}\n\n.notectl-editor:focus-within {\n\tborder-color: var(--notectl-border-focus);\n\tbox-shadow: 0 0 0 2px var(--notectl-focus-ring);\n}\n\n/* Content Area */\n.notectl-content {\n\tflex: 1;\n\tpadding: 12px 16px;\n\toutline: none;\n\tmin-height: var(--notectl-content-min-height, 400px);\n\tcursor: text;\n\tposition: relative;\n\twhite-space: pre-wrap;\n\tword-wrap: break-word;\n\t-webkit-user-select: text;\n\tuser-select: text;\n\t-moz-tab-size: 4;\n\ttab-size: 4;\n}\n\n.notectl-content p {\n\tmargin: 0;\n\tpadding: 2px 0;\n\tmin-height: 1.6em;\n}\n\n.notectl-content p + p {\n\tmargin-top: 0;\n}\n\n/* Horizontal Rule */\n.notectl-content hr {\n\tborder: none;\n\tborder-top: 1px solid var(--notectl-border);\n\tmargin: 8px 0;\n\tpadding: 0;\n\tcursor: default;\n\tuser-select: none;\n}\n\n/* Placeholder */\n.notectl-content.notectl-content--empty::before {\n\tcontent: attr(data-placeholder);\n\tcolor: var(--notectl-fg-muted);\n\tpointer-events: none;\n\tposition: absolute;\n\ttop: 12px;\n\tinset-inline-start: 16px;\n}\n\n/* Plugin container bottom */\n.notectl-plugin-container--bottom {\n\tborder-top: 1px solid var(--notectl-border);\n}\n\n/* Screen reader announcements */\n.notectl-sr-only {\n\tposition: absolute;\n\twidth: 1px;\n\theight: 1px;\n\tmargin: -1px;\n\tpadding: 0;\n\toverflow: hidden;\n\tclip: rect(0, 0, 0, 0);\n\twhite-space: nowrap;\n\tborder: 0;\n}\n\n/* Node selection */\n.notectl-node-selected {\n\toutline: 2px solid var(--notectl-primary);\n\toutline-offset: 2px;\n}\n","\n@media (prefers-reduced-motion: reduce) {\n\t.notectl-toolbar-btn,\n\t.notectl-image__resize-handle,\n\t.notectl-image__size-indicator,\n\t.notectl-color-picker__swatch,\n\t.notectl-font-picker__item,\n\t.notectl-heading-picker__item,\n\t.notectl-font-size-picker__item,\n\t.ntbl-handle,\n\t.ntbl-handle-delete,\n\t.ntbl-insert-line,\n\t.ntbl-insert-btn,\n\t.ntbl-add-zone,\n\t.ntbl-add-icon,\n\t.ntbl-col-bar,\n\t.ntbl-row-bar,\n\t.ntbl-delete-table-btn,\n\t.notectl-code-block__copy {\n\t\ttransition: none !important;\n\t}\n}\n",`\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: ${qe}px 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: ${Ge}px ${Qe}px;\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: ${Ge}px;\n\tinset-inline-start: ${Qe}px;\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");let ts=null;class ns{themeStyleSheet=new CSSStyleSheet;systemThemeQuery=null;systemThemeHandler=null;pluginSheets=[];runtimeSheets=[];shadow;constructor(e){this.shadow=e}apply(e){if(this.cleanupSystemThemeListener(),e===un.System){this.setupSystemThemeListener();const e=yn(this.getSystemTheme());this.setThemeStyleSheet(e)}else this.setThemeStyleSheet(yn(e))}setPluginStyleSheets(e){this.pluginSheets=e,this.refreshAdoptedStyleSheets()}setRuntimeStyleSheets(e){this.runtimeSheets=e,this.refreshAdoptedStyleSheets()}destroy(){this.cleanupSystemThemeListener()}setThemeStyleSheet(e){this.themeStyleSheet.replaceSync(vn(e)),this.refreshAdoptedStyleSheets()}refreshAdoptedStyleSheets(){this.shadow.adoptedStyleSheets=[this.themeStyleSheet,(ts||(ts=new CSSStyleSheet,ts.replaceSync(es)),ts),...this.pluginSheets,...this.runtimeSheets]}setupSystemThemeListener(){this.systemThemeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.systemThemeHandler=e=>{const t=yn(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?un.Dark:un.Light}}class ss{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=Je(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&&(Ke(this.surface,"width",`${this.currentPaperWidthPx}px`),Ke(this.surface,"minHeight",`${this.currentPaperHeightPx}px`))}onViewportResize(e){if(!this.surface||0===this.currentPaperWidthPx)return;const t=e-2*qe,n=Math.min(1,t/this.currentPaperWidthPx);this.currentScale=n,Ke(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 Ke(this.surface,"marginBottom","");const t=this.surface.scrollHeight,n=t*e-t;Ke(this.surface,"marginBottom",`${n}px`)}}function rs(e){return!Array.isArray(e)}class is extends HTMLElement{view=null;inputManager=null;pluginManager=null;domElements=null;configController=new Gn;events=new Xn;lifecycle=new Yn;styleCoordinator=new Zn;themeController=null;paperLayout=null;constructor(){super(),this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","readonly","theme","paper-size","dir"]}connectedCallback(){this.lifecycle.isInitialized()||this.init()}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(!this.lifecycle.markInitialized())return;e&&this.configController.setConfig(e);const t=this.configController.getConfig(),n=this.shadowRoot;if(!n)return;this.themeController=new ns(n),this.styleCoordinator.setup(n,t.styleNonce,this.themeController),this.themeController.apply(t.theme??un.Light);const s=new b(t.locale??"browser"),r=s.getLocale(),i="en"===r?Qn:await async function(e){if("en"===e)return Qn;const t=Jn[`./locales/${e}.ts`];if(!t)return Qn;try{return(await t()).default}catch{return Qn}}(r);if(this.domElements=function(e){const t=e.locale??Qn,n=document.createElement("div");n.className="notectl-editor";const s=document.createElement("div");s.className="notectl-plugin-container--top",s.setAttribute("data-notectl-no-print","");const r=document.createElement("div");r.className="notectl-content",r.contentEditable=e.readonly?"false":"true",r.setAttribute("role","textbox"),r.setAttribute("aria-multiline","true"),r.setAttribute("aria-label",t.ariaLabel),e.readonly&&r.setAttribute("aria-readonly","true"),r.setAttribute("aria-description",t.ariaDescription),r.setAttribute("data-placeholder",e.placeholder??t.defaultPlaceholder),e.dir&&(n.setAttribute("dir",e.dir),r.setAttribute("dir",e.dir));const i=document.createElement("div");i.className="notectl-plugin-container--bottom",i.setAttribute("data-notectl-no-print","");const o=document.createElement("div");return o.className="notectl-sr-only",o.setAttribute("data-notectl-no-print",""),o.setAttribute("aria-live","polite"),o.setAttribute("aria-atomic","true"),n.appendChild(s),n.appendChild(r),n.appendChild(i),n.appendChild(o),{wrapper:n,content:r,topPluginContainer:s,bottomPluginContainer:i,announcer:o}}({readonly:t.readonly,placeholder:t.placeholder,dir:t.dir??this.getAttribute("dir")??void 0,locale:i}),n.appendChild(this.domElements.wrapper),t.paperSize&&(this.paperLayout=new ss(this.domElements.wrapper,this.domElements.content),this.paperLayout.apply(t.paperSize)),this.pluginManager=new pn,this.pluginManager.registerService(S,s),ot(this.pluginManager.schemaRegistry),function(e,t){if(!t)return;const n=rs(t)?t.groups:t,s=rs(t)?t.overflow:void 0,r=[];for(const o of n){const t=[];for(const n of o)t.push(n.id),e.register(n);r.push(t)}const i={groups:r,overflow:s};e.register(new Ue(i))}(this.pluginManager,t.toolbar),!this.pluginManager)return;for(const f of t.plugins??[])this.pluginManager.register(f);for(const f of this.lifecycle.consumePreInitPlugins())this.pluginManager.register(f);if(o=this.pluginManager,a=t.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 nt(n))}(o,a),function(e){void 0===e.get("caret-navigation")&&e.register(new me)}(o),function(e){void 0===e.get("gap-cursor")&&e.register(new et)}(o),!this.pluginManager)return;var o,a;this.domElements.content.addEventListener("focus",()=>this.events.emit("focus",void 0)),this.domElements.content.addEventListener("blur",()=>this.events.emit("blur",void 0));const c=this.domElements,l=c.content,h=this.pluginManager,d=c.topPluginContainer,p=c.bottomPluginContainer,u=c.announcer;await h.init({getState:()=>{if(!this.view)throw new Error("View not initialized");return this.view.getState()},dispatch:e=>this.dispatch(e),getContainer:()=>l,getPluginContainer:e=>"top"===e?d:p,announce:e=>{u&&(u.textContent=e)},hasAnnouncement:()=>!!u?.textContent,onBeforeReady:()=>{const e=De(h.schemaRegistry),n=wt.create({schema:e});this.inputManager=new Zt(l,{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:h.schemaRegistry,keymapRegistry:h.keymapRegistry,inputRuleRegistry:h.inputRuleRegistry,fileHandlerRegistry:h.fileHandlerRegistry,isReadOnly:()=>this.configController.isReadOnly,getPasteInterceptors:()=>h.getPasteInterceptors(),getTextDirection:$e,navigateFromGapCursor:tt}),this.view=new Un(l,{state:n,schemaRegistry:h.schemaRegistry,keymapRegistry:h.keymapRegistry,fileHandlerRegistry:h.fileHandlerRegistry,nodeViewRegistry:h.nodeViewRegistry,maxHistoryDepth:t.maxHistoryDepth,getDecorations:(e,t)=>this.pluginManager?.collectDecorations(e,t)??y.empty,onStateChange:(e,t,n)=>{this.onStateChange(e,t,n)},isReadOnly:()=>this.configController.isReadOnly,compositionState:this.inputManager.compositionTracker}),this.updateEmptyState();const s=h.getPluginStyleSheets();s.length>0&&this.themeController?.setPluginStyleSheets(s)}}),this.pluginManager&&(t.readonly&&this.pluginManager.setReadOnly(!0),this.pluginManager.onEvent(Xe,e=>{!e.options.paperSize&&this.configController.getPaperSize()&&(e.options={...e.options,paperSize:this.configController.getPaperSize()})}),t.autofocus&&requestAnimationFrame(()=>this.domElements?.content.focus()),this.lifecycle.resolveReady(),this.events.emit("ready",void 0))}get isReadOnly(){return this.configController.isReadOnly}getJSON(){if(!this.view)throw new Error("Editor not initialized");return this.view.getState().doc}setJSON(e){Wn(e,this.pluginManager?.schemaRegistry,e=>this.replaceState(e))}async getContentHTML(e){if(!this.view)throw new Error("Editor not initialized");return async function(e,t,n){const s=e.doc,{serializeDocumentToHTML:r,serializeDocumentToCSS:i}=await import("./DocumentParser-w70-Axud.mjs").then(e=>e.D);if("classes"===n?.cssMode){const e=i(s,t);return n.pretty?{html:Me(e.html),css:e.css,styleMap:e.styleMap}:e}const o=r(s,t);return n?.pretty?Me(o):o}(this.view.getState(),this.pluginManager?.schemaRegistry,e)}async setContentHTML(e,t){return async function(e,t,n,s){const{parseHTMLToDocument:r}=await import("./DocumentParser-w70-Axud.mjs").then(e=>e.e);Wn(r(e,t,s),t,n)}(e,this.pluginManager?.schemaRegistry,e=>this.replaceState(e),t)}getText(){if(!this.view)throw new Error("Editor not initialized");return this.view.getState().doc.children.map(e=>A(e)).join("\n")}isEmpty(){return!this.view||function(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&&""===A(t)}(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=r(this.view.getState());this.dispatch(e)}};can(){const e=this.view?.getState().schema,t=this.configController.isReadOnly;return{toggleBold:()=>!t&&!!e&&Ae(e,"bold"),toggleItalic:()=>!t&&!!e&&Ae(e,"italic"),toggleUnderline:()=>!t&&!!e&&Ae(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.configController.isReadOnly||Tt(e)||this.pluginManager.isReadonlyBypassed())&&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 this.lifecycle.whenReady()}configure(e){this.configController.applyRuntimeConfig(e,this.getConfigDeps())}setTheme(e){this.configController.applyTheme(e,this.themeController)}getTheme(){return this.configController.getTheme()}getPaperSize(){return this.configController.getPaperSize()}destroy(){this.paperLayout?.destroy(),this.paperLayout=null,this.styleCoordinator.teardown(this.shadowRoot,this.themeController),this.themeController?.destroy(),this.themeController=null,this.inputManager?.destroy(),this.inputManager=null,this.view?.destroy();const e=this.pluginManager?.destroy()??Promise.resolve();return this.view=null,this.pluginManager=null,this.lifecycle.reset(),this.events.clear(),this.domElements?.wrapper.remove(),this.domElements=null,e}getConfigDeps(){return{contentElement:this.domElements?.content??null,editorWrapper:this.domElements?.wrapper??null,pluginManager:this.pluginManager,themeController:this.themeController,applyPaperSize:e=>this.applyPaperSize(e)}}applyPaperSize(e){this.domElements&&(e?(this.paperLayout||(this.paperLayout=new ss(this.domElements.wrapper,this.domElements.content)),this.paperLayout.apply(e)):this.paperLayout?.apply(null))}onStateChange(e,t,n){const s=this.domElements?.announcer;if(s&&(s.textContent=""),this.pluginManager?.notifyStateChange(e,t,n),this.updateEmptyState(),this.events.emit("stateChange",{oldState:e,newState:t,transaction:n}),J(e.selection,t.selection)||this.events.emit("selectionChange",{selection:t.selection}),!s?.textContent){const r=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 Cn(s.nodeType,s.attrs);for(const s of t.schema.markTypes){const n=Ee(s),r=Oe(e,n),i=Oe(t,n);if(r!==i)return`${s} ${i?"on":"off"}`}return null}(e,t,n);r&&s&&(s.textContent=r)}}updateEmptyState(){this.domElements?.content.classList.toggle("notectl-content--empty",this.isEmpty())}replaceState(e){this.view&&(this.view.replaceState(e),this.updateEmptyState())}}async function os(e){const t=document.createElement("notectl-editor");return await t.init(e),t}"undefined"==typeof customElements||customElements.get("notectl-editor")||customElements.define("notectl-editor",is);export{yn as A,it as B,Lt as C,gn as D,wt as E,nn as F,Et as H,Zt as I,en as K,fn as L,rn as N,pn as P,st as S,un as T,Ht as a,ln as b,hn as c,tn as d,Rn as e,is as f,vt as g,Bn as h,mt as i,rt as j,os as k,mn as l,wn as m,Mt as n,Pt as o,vn as p,Cn as q,In as r,bt as s,St as t,Tt as u,It as v,Nt as w,ot as x,Mn as y,Tn as z};
3
+ //# sourceMappingURL=NotectlEditor-DBBJkPCW.mjs.map