@blocknote/core 0.54.2 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (491) hide show
  1. package/dist/BlockNoteExtension-DjEkXkR5.cjs +2 -0
  2. package/dist/BlockNoteExtension-DjEkXkR5.cjs.map +1 -0
  3. package/dist/{BlockNoteExtension-CbvDA0F7.js → BlockNoteExtension-TsTGtIeX.js} +34 -27
  4. package/dist/BlockNoteExtension-TsTGtIeX.js.map +1 -0
  5. package/dist/{UserStore-mj3fXW4D.cjs → UserStore-CTVzVGh-.cjs} +2 -2
  6. package/dist/{UserStore-mj3fXW4D.cjs.map → UserStore-CTVzVGh-.cjs.map} +1 -1
  7. package/dist/{UserStore-C4TzkGEn.js → UserStore-OZJP3K8T.js} +2 -2
  8. package/dist/{UserStore-C4TzkGEn.js.map → UserStore-OZJP3K8T.js.map} +1 -1
  9. package/dist/blocknote.cjs +1 -1
  10. package/dist/blocknote.js +6 -6
  11. package/dist/blocks-COVwe5Cf.cjs +12 -0
  12. package/dist/blocks-COVwe5Cf.cjs.map +1 -0
  13. package/dist/{blocks-Dol85hpH.js → blocks-COYcDVg7.js} +1577 -1155
  14. package/dist/blocks-COYcDVg7.js.map +1 -0
  15. package/dist/blocks.cjs +1 -1
  16. package/dist/blocks.js +2 -2
  17. package/dist/comments.cjs +1 -1
  18. package/dist/comments.cjs.map +1 -1
  19. package/dist/comments.js +69 -43
  20. package/dist/comments.js.map +1 -1
  21. package/dist/{en-uzHzj6eH.js → en-Ch-vvt5e.js} +40 -3
  22. package/dist/en-Ch-vvt5e.js.map +1 -0
  23. package/dist/en-N5lu0-j8.cjs +2 -0
  24. package/dist/en-N5lu0-j8.cjs.map +1 -0
  25. package/dist/extensions-BbM81hHa.js +3069 -0
  26. package/dist/extensions-BbM81hHa.js.map +1 -0
  27. package/dist/extensions-D_WkAfSt.cjs +58 -0
  28. package/dist/extensions-D_WkAfSt.cjs.map +1 -0
  29. package/dist/extensions.cjs +1 -1
  30. package/dist/extensions.js +4 -4
  31. package/dist/locales.cjs +1 -1
  32. package/dist/locales.cjs.map +1 -1
  33. package/dist/locales.js +859 -45
  34. package/dist/locales.js.map +1 -1
  35. package/dist/src-4OQT3z5S.cjs +23 -0
  36. package/dist/src-4OQT3z5S.cjs.map +1 -0
  37. package/dist/src-BmLsLZfE.js +3491 -0
  38. package/dist/src-BmLsLZfE.js.map +1 -0
  39. package/dist/style.css +1 -1
  40. package/dist/webpack-stats.json +1 -1
  41. package/dist/y.cjs +1 -1
  42. package/dist/y.cjs.map +1 -1
  43. package/dist/y.js +1284 -554
  44. package/dist/y.js.map +1 -1
  45. package/dist/yjs.cjs +1 -1
  46. package/dist/yjs.cjs.map +1 -1
  47. package/dist/yjs.js +189 -148
  48. package/dist/yjs.js.map +1 -1
  49. package/package.json +18 -18
  50. package/src/api/blockManipulation/commands/insertBlocks/insertBlocks.ts +45 -6
  51. package/src/api/blockManipulation/commands/insertBlocks/insertPlacement.test.ts +217 -0
  52. package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.test.ts +113 -9
  53. package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.ts +151 -163
  54. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.test.ts +47 -31
  55. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.ts +122 -181
  56. package/src/api/blockManipulation/commands/nestBlock/nestBlock.test.ts +256 -0
  57. package/src/api/blockManipulation/commands/nestBlock/nestBlock.ts +80 -40
  58. package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.test.ts +71 -0
  59. package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.ts +39 -31
  60. package/src/api/blockManipulation/commands/splitBlock/splitBlock.test.ts +221 -8
  61. package/src/api/blockManipulation/commands/splitBlock/splitBlock.ts +40 -8
  62. package/src/api/blockManipulation/commands/updateBlock/updateBlock.test.ts +272 -40
  63. package/src/api/blockManipulation/commands/updateBlock/updateBlock.ts +138 -117
  64. package/src/api/blockManipulation/getBlock/getBlock.ts +4 -11
  65. package/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.ts +173 -0
  66. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.ts +293 -0
  67. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.ts +145 -0
  68. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.ts +783 -0
  69. package/src/api/blockManipulation/layoutBlocks/plainBlocks.test.ts +180 -0
  70. package/src/api/blockManipulation/layoutBlocks/titledBlocks.test.ts +365 -0
  71. package/src/api/blockManipulation/selections/selection.ts +20 -53
  72. package/src/api/blockManipulation/selections/textCursorPosition.ts +17 -72
  73. package/src/api/blockManipulation/setupTestEnv.ts +38 -6
  74. package/src/api/clipboard/fromClipboard/handleFileInsertion.ts +4 -4
  75. package/src/api/clipboard/toClipboard/copyExtension.ts +3 -3
  76. package/src/api/combineTransactionSteps.ts +22 -0
  77. package/src/api/exporters/html/externalHTMLExporter.ts +1 -1
  78. package/src/api/exporters/html/internalHTMLSerializer.ts +4 -4
  79. package/src/api/exporters/html/util/serializeBlocksExternalHTML.ts +111 -36
  80. package/src/api/exporters/html/util/serializeBlocksInternalHTML.ts +51 -21
  81. package/src/api/exporters/markdown/htmlToMarkdown.ts +12 -1
  82. package/src/api/exporters/markdown/markdownExporter.ts +1 -1
  83. package/src/api/getBlockInfoFromPos.test.ts +428 -3
  84. package/src/api/getBlockInfoFromPos.ts +531 -129
  85. package/src/api/getBlocksChangedByTransaction.test.ts +7 -7
  86. package/src/api/getBlocksChangedByTransaction.ts +3 -3
  87. package/src/api/{getChangedRange.ts → getChangedRangeWithAttrs.ts} +2 -2
  88. package/src/api/getChangedRanges.test.ts +391 -0
  89. package/src/api/getChangedRanges.ts +368 -0
  90. package/src/api/nodeConversions/blockToNode.ts +44 -16
  91. package/src/api/nodeConversions/fragmentToBlocks.ts +29 -44
  92. package/src/api/nodeConversions/nodeToBlock.ts +120 -68
  93. package/src/api/nodeUtil.ts +1 -1
  94. package/src/api/parsers/markdown/autolink.ts +23 -0
  95. package/src/api/parsers/markdown/markdownToHtml.ts +115 -11
  96. package/src/blocks/Code/block.test.ts +4 -4
  97. package/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.ts +6 -1
  98. package/src/blocks/Heading/block.ts +54 -15
  99. package/src/blocks/ListItem/BulletListItem/block.ts +6 -4
  100. package/src/blocks/ListItem/CheckListItem/block.test.ts +2 -2
  101. package/src/blocks/ListItem/CheckListItem/block.ts +6 -4
  102. package/src/blocks/ListItem/NumberedListItem/IndexingPlugin.ts +14 -17
  103. package/src/blocks/ListItem/NumberedListItem/block.ts +6 -4
  104. package/src/blocks/ListItem/ToggleListItem/block.ts +23 -12
  105. package/src/blocks/Table/block.ts +2 -10
  106. package/src/blocks/ToggleWrapper/createToggleFrame.ts +126 -0
  107. package/src/blocks/ToggleWrapper/toggleBlocks.browser.test.ts +1056 -0
  108. package/src/blocks/defaultBlockTypeItems.test.ts +70 -0
  109. package/src/blocks/defaultBlockTypeItems.ts +99 -0
  110. package/src/blocks/defaultBlocks.test.ts +67 -0
  111. package/src/blocks/defaultBlocks.ts +7 -1
  112. package/src/blocks/index.ts +2 -1
  113. package/src/comments/CommentEditorSubmitExtension.test.ts +141 -0
  114. package/src/comments/CommentEditorSubmitExtension.ts +56 -0
  115. package/src/comments/extension.ts +8 -0
  116. package/src/comments/index.ts +1 -0
  117. package/src/editor/Block.css +286 -154
  118. package/src/editor/BlockNoteEditor.node.test.ts +35 -0
  119. package/src/editor/BlockNoteEditor.test.ts +2 -2
  120. package/src/editor/BlockNoteEditor.ts +165 -50
  121. package/src/editor/BlockNoteExtension.ts +11 -6
  122. package/src/editor/blockColors.browser.test.ts +127 -0
  123. package/src/editor/editor.css +60 -0
  124. package/src/editor/managers/BlockManager.ts +4 -3
  125. package/src/editor/managers/EventManager.browser.test.ts +334 -0
  126. package/src/editor/managers/EventManager.ts +128 -31
  127. package/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.ts +45 -0
  128. package/src/editor/managers/ExtensionManager/ExtensionManager.node.test.ts +209 -0
  129. package/src/editor/managers/ExtensionManager/ExtensionManager.test.ts +88 -1
  130. package/src/editor/managers/ExtensionManager/extensions.ts +10 -1
  131. package/src/editor/managers/ExtensionManager/index.ts +165 -75
  132. package/src/editor/managers/StateManager.ts +14 -4
  133. package/src/editor/managers/StyleManager.browser.test.ts +122 -0
  134. package/src/editor/managers/StyleManager.test.ts +98 -0
  135. package/src/editor/managers/StyleManager.ts +31 -15
  136. package/src/editor/managers/index.ts +1 -0
  137. package/src/editor/transformPasted.ts +14 -13
  138. package/src/exporter/Exporter.test.ts +70 -1
  139. package/src/exporter/Exporter.ts +34 -4
  140. package/src/exporter/mapping.ts +41 -10
  141. package/src/extensions/DropCursor/DropCursor.ts +119 -6
  142. package/src/extensions/DropCursor/dropIntoChildren.ts +80 -0
  143. package/src/extensions/FormattingToolbar/FormattingToolbar.ts +29 -0
  144. package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.ts +190 -0
  145. package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.ts +41 -4
  146. package/src/extensions/Placeholder/Placeholder.test.ts +23 -0
  147. package/src/extensions/Placeholder/Placeholder.ts +8 -7
  148. package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +36 -0
  149. package/src/extensions/PreviousBlockType/PreviousBlockType.ts +8 -4
  150. package/src/extensions/ReadOnly/ReadOnly.test.ts +181 -0
  151. package/src/extensions/ReadOnly/ReadOnly.ts +73 -0
  152. package/src/extensions/SideMenu/SideMenu.ts +401 -749
  153. package/src/extensions/SideMenu/blockDropHandling.ts +372 -0
  154. package/src/extensions/SideMenu/blockGeometry.browser.test.ts +148 -0
  155. package/src/extensions/SideMenu/blockGeometry.test.ts +46 -0
  156. package/src/extensions/SideMenu/blockGeometry.ts +53 -0
  157. package/src/extensions/SideMenu/dragging.ts +19 -32
  158. package/src/extensions/SideMenu/sideMenuHover.test.ts +36 -0
  159. package/src/extensions/SideMenu/sideMenuHover.ts +270 -0
  160. package/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts +5 -4
  161. package/src/extensions/SuggestionMenu/SuggestionMenu.ts +10 -1
  162. package/src/extensions/SuggestionMenu/getDefaultSlashMenuItems.ts +36 -136
  163. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.ts +14 -4
  164. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts +1 -1
  165. package/src/extensions/SyntaxHighlighting/shiki.ts +1 -1
  166. package/src/extensions/TableHandles/TableHandles.browser.test.ts +3 -1
  167. package/src/extensions/TableHandles/TableHandles.ts +4 -6
  168. package/src/extensions/Versioning/Versioning.browser.test.ts +151 -0
  169. package/src/extensions/Versioning/Versioning.node.test.ts +177 -0
  170. package/src/extensions/Versioning/Versioning.ts +145 -612
  171. package/src/extensions/Versioning/__test__/result.ts +12 -0
  172. package/src/extensions/Versioning/comparison.test.ts +40 -0
  173. package/src/extensions/Versioning/createVersioning.test.ts +867 -0
  174. package/src/extensions/Versioning/createVersioning.ts +499 -0
  175. package/src/extensions/Versioning/formatVersionDate.ts +24 -0
  176. package/src/extensions/Versioning/inMemoryVersioning.test.ts +533 -430
  177. package/src/extensions/Versioning/inMemoryVersioning.ts +246 -251
  178. package/src/extensions/Versioning/index.ts +4 -0
  179. package/src/extensions/Versioning/scrollScheduling.test.ts +51 -0
  180. package/src/extensions/Versioning/scrollToFirstChange.test.ts +320 -0
  181. package/src/extensions/Versioning/scrollToFirstChange.ts +139 -0
  182. package/src/extensions/Versioning/types.ts +219 -0
  183. package/src/extensions/Versioning/versioningState.ts +154 -0
  184. package/src/extensions/blockDOM.browser.test.ts +102 -0
  185. package/src/extensions/blockDOM.test.ts +178 -0
  186. package/src/extensions/blockDOM.ts +135 -0
  187. package/src/extensions/index.ts +2 -0
  188. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.ts +1719 -53
  189. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +645 -531
  190. package/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.ts +152 -0
  191. package/src/extensions/tiptap-extensions/Link/helpers/autolink.ts +4 -9
  192. package/src/extensions/tiptap-extensions/UniqueID/UniqueID.test.ts +10 -24
  193. package/src/extensions/tiptap-extensions/UniqueID/UniqueID.ts +22 -19
  194. package/src/fonts/inter.browser.test.ts +57 -0
  195. package/src/fonts/inter.css +111 -0
  196. package/src/i18n/locales/ar.ts +33 -0
  197. package/src/i18n/locales/de.ts +33 -0
  198. package/src/i18n/locales/en.ts +33 -0
  199. package/src/i18n/locales/es.ts +33 -0
  200. package/src/i18n/locales/fa.ts +33 -0
  201. package/src/i18n/locales/fr.ts +33 -0
  202. package/src/i18n/locales/he.ts +33 -0
  203. package/src/i18n/locales/hr.ts +33 -0
  204. package/src/i18n/locales/is.ts +33 -0
  205. package/src/i18n/locales/it.ts +33 -0
  206. package/src/i18n/locales/ja.ts +33 -0
  207. package/src/i18n/locales/ko.ts +33 -0
  208. package/src/i18n/locales/nl.ts +33 -0
  209. package/src/i18n/locales/no.ts +33 -0
  210. package/src/i18n/locales/pl.ts +33 -0
  211. package/src/i18n/locales/pt.ts +33 -0
  212. package/src/i18n/locales/ru.ts +33 -0
  213. package/src/i18n/locales/sk.ts +33 -0
  214. package/src/i18n/locales/uk.ts +33 -0
  215. package/src/i18n/locales/uz.ts +33 -0
  216. package/src/i18n/locales/vi.ts +33 -0
  217. package/src/i18n/locales/zh-tw.ts +33 -0
  218. package/src/i18n/locales/zh.ts +33 -0
  219. package/src/index.ts +14 -3
  220. package/src/pm-nodes/BlockContainer.test.ts +101 -0
  221. package/src/pm-nodes/BlockContainer.ts +110 -1
  222. package/src/pm-nodes/BlockGroup.ts +2 -1
  223. package/src/pm-nodes/README.md +2 -0
  224. package/src/schema/blocks/children.test.ts +288 -0
  225. package/src/schema/blocks/children.ts +136 -0
  226. package/src/schema/blocks/createSpec.browser.test.ts +176 -0
  227. package/src/schema/blocks/createSpec.test.ts +231 -0
  228. package/src/schema/blocks/createSpec.ts +493 -267
  229. package/src/schema/blocks/frame.test.ts +112 -0
  230. package/src/schema/blocks/frame.ts +337 -0
  231. package/src/schema/blocks/internal.ts +50 -17
  232. package/src/schema/blocks/keyboard.ts +154 -0
  233. package/src/schema/blocks/layoutBlockAttributes.ts +29 -0
  234. package/src/schema/blocks/meta.test.ts +53 -0
  235. package/src/schema/blocks/meta.ts +35 -0
  236. package/src/schema/blocks/renderFrame.test.ts +691 -0
  237. package/src/schema/blocks/types.ts +285 -21
  238. package/src/schema/blocks/validateChildren.ts +156 -0
  239. package/src/schema/dataAttributes.test.ts +72 -0
  240. package/src/schema/dataAttributes.ts +69 -0
  241. package/src/schema/index.ts +3 -0
  242. package/src/schema/inlineContent/internal.ts +7 -12
  243. package/src/schema/markGroups.ts +34 -2
  244. package/src/schema/schema.ts +8 -1
  245. package/src/user/userColors.test.ts +108 -0
  246. package/src/user/userColors.ts +42 -13
  247. package/src/util/browser.ts +24 -0
  248. package/src/y/comments/RESTYjsThreadStore.ts +1 -1
  249. package/src/y/comments/YjsThreadStore.test.ts +1 -1
  250. package/src/y/comments/YjsThreadStore.ts +27 -27
  251. package/src/y/comments/YjsThreadStoreBase.ts +2 -2
  252. package/src/y/comments/yjsHelpers.ts +11 -11
  253. package/src/y/extensions/AttributionExtension.test.ts +271 -2
  254. package/src/y/extensions/AttributionExtension.ts +146 -123
  255. package/src/y/extensions/DiffVersioningExtension.test.ts +67 -18
  256. package/src/y/extensions/DiffVersioningExtension.ts +95 -123
  257. package/src/y/extensions/EmptyDocBinding.test.ts +282 -0
  258. package/src/y/extensions/ForkYDoc.node.test.ts +77 -0
  259. package/src/y/extensions/ForkYDoc.test.ts +93 -2
  260. package/src/y/extensions/ForkYDoc.ts +22 -13
  261. package/src/y/extensions/History.test.ts +125 -0
  262. package/src/y/extensions/RelativePositionMapping.test.ts +35 -0
  263. package/src/y/extensions/RelativePositionMapping.ts +7 -11
  264. package/src/y/extensions/Versioning.node.test.ts +126 -0
  265. package/src/y/extensions/Versioning.test.ts +110 -401
  266. package/src/y/extensions/Versioning.ts +66 -107
  267. package/src/y/extensions/YAttributionMarks.ts +111 -9
  268. package/src/y/extensions/YCursorPlugin.ts +3 -0
  269. package/src/y/extensions/YSync.node.test.ts +75 -0
  270. package/src/y/extensions/YSync.ts +76 -4
  271. package/src/y/extensions/YSyncRemount.test.ts +99 -0
  272. package/src/y/extensions/blockMatchNodes.ts +20 -29
  273. package/src/y/extensions/index.ts +10 -26
  274. package/src/y/extensions/legacyYjsDocBinding.test.ts +652 -0
  275. package/src/y/extensions/nestingChanges.test.ts +326 -0
  276. package/src/y/extensions/persistentBlockGroups.test.ts +1709 -0
  277. package/src/y/extensions/persistentBlockGroups.ts +953 -0
  278. package/src/y/extensions/snapshotCodec.test.ts +105 -0
  279. package/src/y/extensions/snapshotCodec.ts +39 -0
  280. package/src/y/extensions/snapshotPreview.test.ts +201 -0
  281. package/src/y/extensions/snapshotPreview.ts +292 -0
  282. package/src/y/extensions/tableReshape.test.ts +121 -0
  283. package/src/y/extensions/v1BindingSnapshotDiff.test.ts +121 -0
  284. package/src/y/extensions/versionDiffAttribution.test.ts +944 -0
  285. package/src/y/extensions/versionDiffPerformance.test.ts +101 -0
  286. package/src/y/index.ts +1 -0
  287. package/src/y/utils.test.ts +289 -22
  288. package/src/y/utils.ts +167 -43
  289. package/src/y/versioning/__test__/fixtures/activity-all-after.json +5 -5
  290. package/src/y/versioning/__test__/fixtures/activity-all.json +3 -3
  291. package/src/y/versioning/__test__/fixtures/activity-filtered-after.json +2 -2
  292. package/src/y/versioning/__test__/yhub.test.ts +902 -721
  293. package/src/y/versioning/index.ts +6 -1
  294. package/src/y/versioning/yhub.ts +316 -603
  295. package/src/y/versioning/yhubClient.ts +345 -0
  296. package/src/yjs/comments/RESTYjsThreadStore.test.ts +10 -0
  297. package/src/yjs/extensions/FixUpSchema.ts +11 -0
  298. package/src/yjs/extensions/ForkYDoc.browser.test.ts +84 -0
  299. package/src/yjs/extensions/ForkYDoc.node.test.ts +231 -0
  300. package/src/yjs/extensions/ForkYDoc.test.ts +68 -1
  301. package/src/yjs/extensions/ForkYDoc.ts +57 -39
  302. package/src/yjs/extensions/Versioning.test.ts +345 -530
  303. package/src/yjs/extensions/Versioning.ts +111 -68
  304. package/src/yjs/extensions/index.ts +1 -1
  305. package/src/yjs/index.ts +4 -0
  306. package/types/src/api/blockManipulation/commands/insertBlocks/insertBlocks.d.ts +2 -1
  307. package/types/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.d.ts +24 -24
  308. package/types/src/api/blockManipulation/commands/nestBlock/nestBlock.d.ts +3 -2
  309. package/types/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.d.ts +1 -1
  310. package/types/src/api/blockManipulation/commands/splitBlock/splitBlock.d.ts +2 -2
  311. package/types/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.d.ts +34 -0
  312. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.d.ts +1 -0
  313. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.d.ts +460 -0
  314. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.d.ts +1 -0
  315. package/types/src/api/blockManipulation/layoutBlocks/plainBlocks.test.d.ts +1 -0
  316. package/types/src/api/blockManipulation/layoutBlocks/titledBlocks.test.d.ts +1 -0
  317. package/types/src/api/blockManipulation/setupTestEnv.d.ts +15 -69
  318. package/types/src/api/combineTransactionSteps.d.ts +12 -0
  319. package/types/src/api/getBlockInfoFromPos.d.ts +218 -44
  320. package/types/src/api/{getChangedRange.d.ts → getChangedRangeWithAttrs.d.ts} +1 -1
  321. package/types/src/api/getChangedRanges.d.ts +23 -0
  322. package/types/src/api/getChangedRanges.test.d.ts +1 -0
  323. package/types/src/api/nodeConversions/fragmentToBlocks.d.ts +0 -3
  324. package/types/src/api/parsers/markdown/autolink.d.ts +5 -0
  325. package/types/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.d.ts +4 -0
  326. package/types/src/blocks/ToggleWrapper/createToggleFrame.d.ts +29 -0
  327. package/types/src/blocks/ToggleWrapper/toggleBlocks.browser.test.d.ts +1 -0
  328. package/types/src/blocks/defaultBlockTypeItems.d.ts +37 -0
  329. package/types/src/blocks/defaultBlockTypeItems.test.d.ts +1 -0
  330. package/types/src/blocks/defaultBlocks.test.d.ts +1 -0
  331. package/types/src/blocks/index.d.ts +2 -1
  332. package/types/src/comments/CommentEditorSubmitExtension.d.ts +19 -0
  333. package/types/src/comments/CommentEditorSubmitExtension.test.d.ts +1 -0
  334. package/types/src/comments/extension.d.ts +7 -0
  335. package/types/src/comments/index.d.ts +1 -0
  336. package/types/src/editor/BlockNoteEditor.d.ts +88 -27
  337. package/types/src/editor/BlockNoteEditor.node.test.d.ts +1 -0
  338. package/types/src/editor/BlockNoteExtension.d.ts +3 -0
  339. package/types/src/editor/blockColors.browser.test.d.ts +1 -0
  340. package/types/src/editor/managers/BlockManager.d.ts +4 -3
  341. package/types/src/editor/managers/EventManager.browser.test.d.ts +1 -0
  342. package/types/src/editor/managers/EventManager.d.ts +55 -0
  343. package/types/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.d.ts +1 -0
  344. package/types/src/editor/managers/ExtensionManager/ExtensionManager.node.test.d.ts +1 -0
  345. package/types/src/editor/managers/ExtensionManager/index.d.ts +15 -3
  346. package/types/src/editor/managers/StateManager.d.ts +1 -1
  347. package/types/src/editor/managers/StyleManager.browser.test.d.ts +1 -0
  348. package/types/src/editor/managers/StyleManager.d.ts +4 -2
  349. package/types/src/editor/managers/StyleManager.test.d.ts +1 -0
  350. package/types/src/editor/managers/index.d.ts +1 -0
  351. package/types/src/editor/transformPasted.d.ts +1 -1
  352. package/types/src/exporter/Exporter.d.ts +11 -4
  353. package/types/src/exporter/mapping.d.ts +13 -1
  354. package/types/src/extensions/DropCursor/DropCursor.d.ts +1 -1
  355. package/types/src/extensions/DropCursor/dropIntoChildren.d.ts +38 -0
  356. package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.d.ts +1 -1
  357. package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.d.ts +1 -0
  358. package/types/src/extensions/Placeholder/Placeholder.test.d.ts +1 -0
  359. package/types/src/extensions/ReadOnly/ReadOnly.d.ts +21 -0
  360. package/types/src/extensions/ReadOnly/ReadOnly.test.d.ts +1 -0
  361. package/types/src/extensions/SideMenu/SideMenu.d.ts +49 -88
  362. package/types/src/extensions/SideMenu/blockDropHandling.d.ts +11 -0
  363. package/types/src/extensions/SideMenu/blockGeometry.browser.test.d.ts +1 -0
  364. package/types/src/extensions/SideMenu/blockGeometry.d.ts +22 -0
  365. package/types/src/extensions/SideMenu/blockGeometry.test.d.ts +1 -0
  366. package/types/src/extensions/SideMenu/dragging.d.ts +0 -4
  367. package/types/src/extensions/SideMenu/sideMenuHover.d.ts +58 -0
  368. package/types/src/extensions/SideMenu/sideMenuHover.test.d.ts +1 -0
  369. package/types/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.d.ts +3 -0
  370. package/types/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.d.ts +1 -0
  371. package/types/src/extensions/Versioning/Versioning.browser.test.d.ts +1 -0
  372. package/types/src/extensions/Versioning/Versioning.d.ts +34 -311
  373. package/types/src/extensions/Versioning/Versioning.node.test.d.ts +1 -0
  374. package/types/src/extensions/Versioning/__test__/result.d.ts +3 -0
  375. package/types/src/extensions/Versioning/comparison.test.d.ts +1 -0
  376. package/types/src/extensions/Versioning/createVersioning.d.ts +32 -0
  377. package/types/src/extensions/Versioning/createVersioning.test.d.ts +1 -0
  378. package/types/src/extensions/Versioning/formatVersionDate.d.ts +7 -0
  379. package/types/src/extensions/Versioning/inMemoryVersioning.d.ts +64 -36
  380. package/types/src/extensions/Versioning/index.d.ts +4 -0
  381. package/types/src/extensions/Versioning/scrollScheduling.test.d.ts +1 -0
  382. package/types/src/extensions/Versioning/scrollToFirstChange.d.ts +18 -0
  383. package/types/src/extensions/Versioning/scrollToFirstChange.test.d.ts +1 -0
  384. package/types/src/extensions/Versioning/types.d.ts +239 -0
  385. package/types/src/extensions/Versioning/versioningState.d.ts +43 -0
  386. package/types/src/extensions/blockDOM.browser.test.d.ts +1 -0
  387. package/types/src/extensions/blockDOM.d.ts +37 -0
  388. package/types/src/extensions/blockDOM.test.d.ts +1 -0
  389. package/types/src/extensions/index.d.ts +2 -0
  390. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.d.ts +1 -0
  391. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.d.ts +3 -0
  392. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.d.ts +1 -0
  393. package/types/src/fonts/inter.browser.test.d.ts +2 -0
  394. package/types/src/i18n/locales/en.d.ts +33 -0
  395. package/types/src/i18n/locales/fa.d.ts +33 -0
  396. package/types/src/i18n/locales/sk.d.ts +33 -0
  397. package/types/src/index.d.ts +7 -3
  398. package/types/src/pm-nodes/BlockContainer.d.ts +6 -0
  399. package/types/src/pm-nodes/BlockContainer.test.d.ts +1 -0
  400. package/types/src/schema/blocks/children.d.ts +39 -0
  401. package/types/src/schema/blocks/children.test.d.ts +1 -0
  402. package/types/src/schema/blocks/createSpec.browser.test.d.ts +1 -0
  403. package/types/src/schema/blocks/createSpec.d.ts +13 -0
  404. package/types/src/schema/blocks/frame.d.ts +109 -0
  405. package/types/src/schema/blocks/frame.test.d.ts +1 -0
  406. package/types/src/schema/blocks/internal.d.ts +6 -0
  407. package/types/src/schema/blocks/keyboard.d.ts +111 -0
  408. package/types/src/schema/blocks/layoutBlockAttributes.d.ts +9 -0
  409. package/types/src/schema/blocks/meta.d.ts +14 -0
  410. package/types/src/schema/blocks/meta.test.d.ts +1 -0
  411. package/types/src/schema/blocks/renderFrame.test.d.ts +1 -0
  412. package/types/src/schema/blocks/types.d.ts +228 -15
  413. package/types/src/schema/blocks/validateChildren.d.ts +5 -0
  414. package/types/src/schema/dataAttributes.d.ts +19 -0
  415. package/types/src/schema/dataAttributes.test.d.ts +1 -0
  416. package/types/src/schema/index.d.ts +3 -0
  417. package/types/src/schema/markGroups.d.ts +8 -0
  418. package/types/src/user/userColors.d.ts +24 -3
  419. package/types/src/user/userColors.test.d.ts +1 -0
  420. package/types/src/util/browser.d.ts +2 -0
  421. package/types/src/y/comments/RESTYjsThreadStore.d.ts +1 -1
  422. package/types/src/y/comments/YjsThreadStore.d.ts +1 -1
  423. package/types/src/y/comments/YjsThreadStoreBase.d.ts +2 -2
  424. package/types/src/y/comments/yjsHelpers.d.ts +5 -5
  425. package/types/src/y/extensions/AttributionExtension.d.ts +19 -21
  426. package/types/src/y/extensions/DiffVersioningExtension.d.ts +9 -4
  427. package/types/src/y/extensions/EmptyDocBinding.test.d.ts +1 -0
  428. package/types/src/y/extensions/ForkYDoc.d.ts +3 -1
  429. package/types/src/y/extensions/ForkYDoc.node.test.d.ts +1 -0
  430. package/types/src/y/extensions/History.test.d.ts +1 -0
  431. package/types/src/y/extensions/Versioning.d.ts +4 -15
  432. package/types/src/y/extensions/Versioning.node.test.d.ts +1 -0
  433. package/types/src/y/extensions/YAttributionMarks.d.ts +13 -2
  434. package/types/src/y/extensions/YCursorPlugin.d.ts +1 -0
  435. package/types/src/y/extensions/YSync.d.ts +4 -18
  436. package/types/src/y/extensions/YSync.node.test.d.ts +1 -0
  437. package/types/src/y/extensions/YSyncRemount.test.d.ts +1 -0
  438. package/types/src/y/extensions/blockMatchNodes.d.ts +0 -22
  439. package/types/src/y/extensions/index.d.ts +27 -44
  440. package/types/src/y/extensions/legacyYjsDocBinding.test.d.ts +1 -0
  441. package/types/src/y/extensions/nestingChanges.test.d.ts +1 -0
  442. package/types/src/y/extensions/persistentBlockGroups.d.ts +189 -0
  443. package/types/src/y/extensions/persistentBlockGroups.test.d.ts +1 -0
  444. package/types/src/y/extensions/snapshotCodec.d.ts +13 -0
  445. package/types/src/y/extensions/snapshotCodec.test.d.ts +1 -0
  446. package/types/src/y/extensions/snapshotPreview.d.ts +21 -0
  447. package/types/src/y/extensions/snapshotPreview.test.d.ts +1 -0
  448. package/types/src/y/extensions/tableReshape.test.d.ts +1 -0
  449. package/types/src/y/extensions/v1BindingSnapshotDiff.test.d.ts +1 -0
  450. package/types/src/y/extensions/versionDiffAttribution.test.d.ts +1 -0
  451. package/types/src/y/extensions/versionDiffPerformance.test.d.ts +1 -0
  452. package/types/src/y/index.d.ts +1 -0
  453. package/types/src/y/utils.d.ts +39 -19
  454. package/types/src/y/versioning/index.d.ts +1 -1
  455. package/types/src/y/versioning/yhub.d.ts +69 -86
  456. package/types/src/y/versioning/yhubClient.d.ts +67 -0
  457. package/types/src/yjs/extensions/ForkYDoc.browser.test.d.ts +1 -0
  458. package/types/src/yjs/extensions/ForkYDoc.d.ts +2 -0
  459. package/types/src/yjs/extensions/ForkYDoc.node.test.d.ts +1 -0
  460. package/types/src/yjs/extensions/Versioning.d.ts +36 -22
  461. package/types/src/yjs/extensions/index.d.ts +2 -1
  462. package/types/src/yjs/index.d.ts +1 -0
  463. package/dist/BlockNoteExtension-BJCLnwrE.cjs +0 -2
  464. package/dist/BlockNoteExtension-BJCLnwrE.cjs.map +0 -1
  465. package/dist/BlockNoteExtension-CbvDA0F7.js.map +0 -1
  466. package/dist/blocks-CTB_5Vyj.cjs +0 -12
  467. package/dist/blocks-CTB_5Vyj.cjs.map +0 -1
  468. package/dist/blocks-Dol85hpH.js.map +0 -1
  469. package/dist/en-BuzSuuTq.cjs +0 -2
  470. package/dist/en-BuzSuuTq.cjs.map +0 -1
  471. package/dist/en-uzHzj6eH.js.map +0 -1
  472. package/dist/extensions-B7Rsp_Ft.cjs +0 -58
  473. package/dist/extensions-B7Rsp_Ft.cjs.map +0 -1
  474. package/dist/extensions-D6JcJCwd.js +0 -2138
  475. package/dist/extensions-D6JcJCwd.js.map +0 -1
  476. package/dist/src-Buuo5l7X.js +0 -3317
  477. package/dist/src-Buuo5l7X.js.map +0 -1
  478. package/dist/src-C54Ok9E0.cjs +0 -23
  479. package/dist/src-C54Ok9E0.cjs.map +0 -1
  480. package/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.ts +0 -173
  481. package/src/blocks/ListItem/ListItemKeyboardShortcuts.ts +0 -63
  482. package/src/blocks/ToggleWrapper/createToggleWrapper.ts +0 -197
  483. package/src/blocks/utils/listItemEnterHandler.ts +0 -43
  484. package/src/extensions/Versioning/Versioning.test.ts +0 -435
  485. package/src/extensions/getDraggableBlockFromElement.ts +0 -19
  486. package/types/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.d.ts +0 -32
  487. package/types/src/blocks/ListItem/ListItemKeyboardShortcuts.d.ts +0 -2
  488. package/types/src/blocks/ToggleWrapper/createToggleWrapper.d.ts +0 -15
  489. package/types/src/blocks/utils/listItemEnterHandler.d.ts +0 -2
  490. package/types/src/extensions/getDraggableBlockFromElement.d.ts +0 -5
  491. /package/types/src/{extensions/Versioning/Versioning.test.d.ts → api/blockManipulation/commands/insertBlocks/insertPlacement.test.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-BmLsLZfE.js","names":[],"sources":["../src/schema/blocks/types.ts","../src/schema/inlineContent/createSpec.ts","../src/api/blockManipulation/commands/insertBlocks/insertBlocks.ts","../src/api/blockManipulation/layoutBlocks/fixLayoutBlock.ts","../src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.ts","../src/api/blockManipulation/commands/updateBlock/updateBlock.ts","../src/pm-nodes/BlockContainer.ts","../src/api/exporters/html/util/serializeBlocksInternalHTML.ts","../src/api/exporters/html/internalHTMLSerializer.ts","../src/user/userColors.ts","../src/util/EventEmitter.ts","../src/api/blockManipulation/commands/moveBlocks/moveBlocks.ts","../src/api/blockManipulation/commands/nestBlock/nestBlock.ts","../src/api/blockManipulation/getBlock/getBlock.ts","../src/editor/managers/BlockManager.ts","../src/editor/managers/EventManager.ts","../src/api/parsers/html/util/nestedLists.ts","../src/api/parsers/html/util/normalizeWhitespace.ts","../src/api/parsers/html/parseHTML.ts","../src/api/parsers/markdown/markdownToHtml.ts","../src/api/parsers/markdown/parseMarkdown.ts","../src/editor/managers/ExportManager.ts","../src/api/blockManipulation/selections/textCursorPosition.ts","../src/api/clipboard/fromClipboard/acceptedMIMETypes.ts","../src/api/clipboard/fromClipboard/handleFileInsertion.ts","../src/api/clipboard/fromClipboard/fileDropExtension.ts","../src/api/parsers/markdown/detectMarkdown.ts","../src/api/clipboard/fromClipboard/handleVSCodePaste.ts","../src/api/clipboard/fromClipboard/pasteExtension.ts","../src/api/clipboard/toClipboard/copyExtension.ts","../src/extensions/tiptap-extensions/BackgroundColor/BackgroundColorExtension.ts","../src/extensions/tiptap-extensions/HardBreak/HardBreak.ts","../src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.ts","../src/api/blockManipulation/commands/splitBlock/splitBlock.ts","../src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts","../src/extensions/tiptap-extensions/TextAlignment/TextAlignmentExtension.ts","../src/extensions/tiptap-extensions/TextColor/TextColorExtension.ts","../src/extensions/tiptap-extensions/Link/helpers/whitespace.ts","../src/extensions/tiptap-extensions/Link/helpers/autolink.ts","../src/extensions/tiptap-extensions/Link/helpers/clickHandler.ts","../src/extensions/tiptap-extensions/Link/helpers/pasteHandler.ts","../src/extensions/tiptap-extensions/Link/link.ts","../src/pm-nodes/BlockGroup.ts","../src/pm-nodes/Doc.ts","../src/editor/managers/ExtensionManager/extensions.ts","../src/editor/managers/ExtensionManager/index.ts","../src/util/expandToWords.ts","../src/api/blockManipulation/selections/selection.ts","../src/editor/managers/SelectionManager.ts","../src/editor/managers/StateManager.ts","../src/api/blockManipulation/insertContentAt.ts","../src/editor/managers/StyleManager.ts","../src/editor/transformPasted.ts","../src/editor/BlockNoteEditor.ts","../src/exporter/Exporter.ts","../src/exporter/ExportImage.ts","../src/exporter/mapping.ts","../src/util/combineByGroup.ts"],"sourcesContent":["import type { FrameView } from \"./frame.js\";\n/** Define the main block types **/\n// import { Extension, Node } from \"@tiptap/core\";\nimport type { Node, NodeViewRendererProps } from \"@tiptap/core\";\nimport type { Fragment, Node as PMNode, Schema } from \"prosemirror-model\";\nimport type { ViewMutationRecord } from \"prosemirror-view\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport type {\n Extension,\n ExtensionFactoryInstance,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type {\n InlineContent,\n InlineContentSchema,\n PartialInlineContent,\n StyledText,\n} from \"../inlineContent/types.js\";\nimport type { PropSchema, Props } from \"../propTypes.js\";\nimport type { BlockKeyboard, BlockKeyboardOption } from \"./keyboard.js\";\nimport type { StyleSchema } from \"../styles/types.js\";\n\nexport type BlockNoteDOMElement =\n | \"editor\"\n | \"block\"\n | \"blockGroup\"\n | \"blockContent\"\n | \"inlineContent\";\n\nexport type BlockNoteDOMAttributes = Partial<{\n [DOMElement in BlockNoteDOMElement]: Record<string, string>;\n}>;\n\nexport interface BlockConfigMeta<\n TName extends string = string,\n TProps extends PropSchema = PropSchema,\n> {\n /**\n * Defines which keyboard shortcut should be used to insert a hard break into the block's inline content.\n * @default \"shift+enter\"\n * @deprecated Use `experimental_keyboard.enter` and\n * `experimental_keyboard.shiftEnter` instead: `\"enter\"` is\n * `experimental_keyboard: { enter: \"line-break\" }`, and `\"none\"` is\n * `experimental_keyboard: { shiftEnter: \"same-as-enter\" }`.\n */\n hardBreakShortcut?: \"shift+enter\" | \"enter\" | \"none\";\n\n /**\n * Whether the block is selectable\n */\n selectable?: boolean;\n\n /**\n * The accept mime types for the file block\n */\n fileBlockAccept?: string[];\n\n /**\n * Whether the block is a {@link https://prosemirror.net/docs/ref/#model.NodeSpec.code} block\n */\n code?: boolean;\n\n /**\n * Whether the block is a {@link https://prosemirror.net/docs/ref/#model.NodeSpec.defining} block\n */\n defining?: boolean;\n\n /**\n * Whether the block is a {@link https://prosemirror.net/docs/ref/#model.NodeSpec.isolating} block\n */\n isolating?: boolean;\n\n /**\n * Whether this block type gets a side menu drag handle (and can be dragged\n * by it). Applies to any block type, layout block or not: e.g. a\n * \"locked\" block can opt out of dragging entirely. A block that opts out is\n * skipped when looking for a drag handle, so the handle falls through to the\n * nearest draggable ancestor.\n * @default `true`, or `false` for a layout block placeable `\"namedOnly\"`, which\n * can only live in its parent\n */\n draggable?: boolean;\n\n /**\n * Whether a block dragged onto this block's content or frame chrome becomes\n * its first child (as in Notion's toggles), instead of going before or after\n * it. A block dragged onto its children still goes between them.\n * @default false\n */\n dropsIntoChildren?(block: { type: TName; props: Props<TProps> }): boolean;\n\n /**\n * Enables syntax highlighting of the contents of the block with the result of this callback\n */\n highlight?(block: { type: TName; props: Props<TProps> }): string | undefined;\n\n /**\n * Marks the block as rendering a preview with an editable source popup, driven\n * by the editor-wide `SourceBlockWithPreviewExtension`. When `true`, the\n * block's source is hidden behind its preview and edited via the popup.\n */\n hasPreview?: boolean;\n}\n\n/**\n * A block's `meta` with every default applied: what a block spec in a schema\n * holds, so readers never see a missing setting (see `resolveBlockMeta`).\n */\nexport type ResolvedBlockConfigMeta<\n TName extends string = string,\n TProps extends PropSchema = PropSchema,\n> = BlockConfigMeta<TName, TProps> &\n Required<\n Pick<\n BlockConfigMeta<TName, TProps>,\n \"selectable\" | \"code\" | \"defining\" | \"isolating\" | \"draggable\"\n >\n >;\n\n/**\n * The type name of a layout block, as used in {@link ChildrenConfig.allow}.\n */\nexport type AllowedChildType = string;\n\n/**\n * What may appear as a child of a layout block.\n *\n * - `\"blocks\"`: any regular block, or any layout block placeable anywhere.\n * This cannot be narrowed to specific regular block types: every regular\n * block is the *same* ProseMirror node (`blockContainer`), so paragraphs,\n * headings and code blocks are indistinguishable at the node level.\n * - `readonly AllowedChildType[]`: only these layout block types, enforced exactly\n * by the schema. Naming a regular block type is a startup error; per-type\n * regular-block filtering can be added to this same form later, with no API\n * change.\n *\n * Neither form includes `placeable: \"namedOnly\"` types. Those appear only\n * where a parent names them explicitly in an array.\n */\nexport type ChildrenAllow = \"blocks\" | readonly AllowedChildType[];\n\n/**\n * Which child blocks a layout block holds (`layoutOnly: true`), exposed as\n * `block.children` at runtime.\n *\n * The config describes one uniform set of children, semantically a single\n * implicit slot. Ordered multi-slot children (a `sequence` of slots) can be\n * added later as a sibling form.\n */\nexport type ChildrenConfig =\n | {\n /**\n * Any blocks, the default. When its last child is removed, the\n * layout block is removed too.\n */\n allow?: \"blocks\";\n /**\n * Layout block types the block does not hold, out of those placeable\n * anywhere: a column holds any block except a column list. Regular\n * block types can't be excluded, as every regular block is the same\n * ProseMirror node.\n */\n exclude?: readonly AllowedChildType[];\n }\n | {\n /** Which layout block types may appear as a child. */\n allow: readonly AllowedChildType[];\n /**\n * How few children the layout block may hold; `0` lets it be empty.\n * @default 1\n */\n min?: number;\n /**\n * Whether a layout block with too few children dissolves into what they\n * hold, like a column list with one column left. `false` keeps the\n * layout block and its empty children, like a tab set.\n * @default true\n */\n dissolve?: boolean;\n };\n\nexport interface BlockConfig<\n T extends string = string,\n PS extends PropSchema = PropSchema,\n C extends \"inline\" | \"none\" | \"table\" | \"plain\" =\n | \"inline\"\n | \"none\"\n | \"table\"\n | \"plain\",\n> {\n /**\n * The type of the block (unique identifier within a schema)\n */\n type: T;\n /**\n * The properties that the block supports\n * @todo will be zod schema in the future\n */\n readonly propSchema: PS;\n /**\n * The content that the block supports\n */\n content: C;\n /**\n * `true` makes the block a layout block: a block without content of its own\n * (`content: \"none\"`) whose own node holds its child blocks. Its\n * `renderFrame` puts them in its slot (React: `slotRef`). With `false` (the\n * default), the block's child blocks are indented below it. Only a block\n * with `content: \"none\"` can set `true`.\n */\n layoutOnly?: C extends \"none\" ? boolean : false;\n /**\n * Which child blocks the block may have. Every block can have any child\n * blocks (`{ allow: \"blocks\" }`, the default). Only a layout block\n * (`layoutOnly: true`) can restrict them to certain types or a minimum\n * count, since the child blocks of other blocks all share one untyped\n * group. How the keyboard treats a block's children (e.g. whether Enter in\n * the block's text starts them) is set with its `experimental_keyboard`\n * settings.\n */\n children?: C extends \"none\"\n ? ChildrenConfig\n : {\n allow?: \"blocks\";\n exclude?: undefined;\n min?: undefined;\n dissolve?: undefined;\n };\n /**\n * Where this block may be placed.\n *\n * - `\"anywhere\"` (default): anywhere a regular block goes, the document\n * root or nested under any other block.\n * - `\"namedOnly\"`: only inside a layout block that names this type in its\n * `children.allow` array (e.g. a `column` inside a `columnList`).\n *\n * Only meaningful for layout blocks; regular blocks are always placeable\n * anywhere.\n */\n placeable?: \"anywhere\" | \"namedOnly\";\n}\n\ndeclare module \"prosemirror-model\" {\n interface NodeSpec {\n /**\n * The config of the BlockNote block this node was built from, so code\n * holding a bare `Node` can read block-level facts (like the content\n * kind) without an editor or schema reference. Set on every node built\n * from a block spec.\n */\n blockConfig?: BlockConfig;\n }\n}\n\n/**\n * BlockConfigOrCreator is a union type of BlockConfig and a function that returns a BlockConfig.\n * This is used to create block configs that can be passed to the createBlockSpec function.\n */\nexport type BlockConfigOrCreator<\n TName extends string = string,\n TProps extends PropSchema = PropSchema,\n TContent extends \"inline\" | \"none\" | \"plain\" = \"inline\" | \"none\" | \"plain\",\n TOptions extends Record<string, any> | undefined =\n | Record<string, any>\n | undefined,\n> =\n | BlockConfig<TName, TProps, TContent>\n | (TOptions extends undefined\n ? () => BlockConfig<TName, TProps, TContent>\n : (options: Partial<TOptions>) => BlockConfig<TName, TProps, TContent>);\n\n/**\n * ExtractBlockConfigFromConfigOrCreator is a helper type that extracts the BlockConfig type from a BlockConfigOrCreator.\n */\nexport type ExtractBlockConfigFromConfigOrCreator<\n ConfigOrCreator extends\n | BlockConfig<string, PropSchema, \"inline\" | \"none\" | \"plain\">\n | ((\n ...args: any[]\n ) => BlockConfig<string, PropSchema, \"inline\" | \"none\" | \"plain\">),\n> = ConfigOrCreator extends (...args: any[]) => infer Config\n ? Config\n : ConfigOrCreator;\n\n// restrict content to \"inline\" and \"none\" only\nexport type CustomBlockConfig<\n T extends string = string,\n PS extends PropSchema = PropSchema,\n C extends \"inline\" | \"none\" | \"plain\" = \"inline\" | \"none\" | \"plain\",\n> = BlockConfig<T, PS, C>;\n\n// A Spec contains both the Config and Implementation\nexport type BlockSpec<\n T extends string = string,\n PS extends PropSchema = PropSchema,\n C extends \"inline\" | \"none\" | \"table\" | \"plain\" =\n | \"inline\"\n | \"none\"\n | \"table\"\n | \"plain\",\n> = {\n config: BlockConfig<T, PS, C>;\n implementation: BlockImplementation<T, PS, C>;\n extensions?: (Extension | ExtensionFactoryInstance)[];\n};\n\n/**\n * BlockSpecOrCreator is a union type of BlockSpec and a function that returns a BlockSpec.\n * This is used to create block specs that can be passed to the createBlockSpec function.\n */\nexport type BlockSpecOrCreator<\n T extends string = string,\n PS extends PropSchema = PropSchema,\n C extends \"inline\" | \"none\" | \"table\" | \"plain\" =\n | \"inline\"\n | \"none\"\n | \"table\"\n | \"plain\",\n TOptions extends Record<string, any> | undefined =\n | Record<string, any>\n | undefined,\n> =\n | BlockSpec<T, PS, C>\n | (TOptions extends undefined\n ? () => BlockSpec<T, PS, C>\n : (options: Partial<TOptions>) => BlockSpec<T, PS, C>);\n\n/**\n * ExtractBlockSpecFromSpecOrCreator is a helper type that extracts the BlockSpec type from a BlockSpecOrCreator.\n */\nexport type ExtractBlockSpecFromSpecOrCreator<\n SpecOrCreator extends\n | BlockSpec<string, PropSchema, \"inline\" | \"none\" | \"plain\">\n | ((\n ...args: any[]\n ) => BlockSpec<string, PropSchema, \"inline\" | \"none\" | \"plain\">),\n> = SpecOrCreator extends (...args: any[]) => infer Spec ? Spec : SpecOrCreator;\n\n/**\n * This allows de-coupling the types that we display to users versus the types we expose internally.\n *\n * This prevents issues with type-inference across parameters that Typescript cannot handle.\n * Specifically, the blocks shape cannot be properly inferred to a specific type like we expose to the user.\n */\nexport type LooseBlockSpec<\n T extends string = string,\n PS extends PropSchema = PropSchema,\n C extends \"inline\" | \"none\" | \"table\" | \"plain\" =\n | \"inline\"\n | \"none\"\n | \"table\"\n | \"plain\",\n> = {\n config: BlockConfig<T, PS, C>;\n implementation: Omit<\n BlockImplementation<T, PS, C>,\n | \"render\"\n | \"renderFrame\"\n | \"toExternalHTML\"\n | \"experimental_keyboard\"\n | \"meta\"\n > & {\n /** Every keyboard setting of the block, with defaults filled in. */\n keyboard: (block: any) => BlockKeyboard;\n /** The block's `meta`, with defaults filled in. */\n meta: ResolvedBlockConfigMeta<T, PS>;\n // purposefully stub the types for render and toExternalHTML since they reference the block\n // A layout block declares `renderFrame` instead of `render`.\n render?: (\n /**\n * The custom block to render\n */\n block: any,\n /**\n * The BlockNote editor instance\n */\n editor: BlockNoteEditor<any>,\n ) => {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n ignoreMutation?: (mutation: ViewMutationRecord) => boolean;\n destroy?: () => void;\n update?: (node: PMNode) => boolean | void;\n };\n renderFrame?: <I extends InlineContentSchema, S extends StyleSchema>(\n block: any,\n editor: BlockNoteEditor<any, I, S>,\n ) =>\n | {\n dom: HTMLElement;\n slot: HTMLElement;\n /** Releases resources when the live frame is replaced or destroyed. */\n destroy?: () => void;\n update?: (block: any) => boolean | void;\n }\n | undefined;\n toExternalHTML?: (\n block: any,\n editor: BlockNoteEditor<any>,\n context: {\n nestingLevel: number;\n },\n ) =>\n | {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n childrenDOM?: HTMLElement;\n }\n | undefined;\n\n node: Node;\n };\n extensions?: (Extension | ExtensionFactoryInstance)[];\n};\n\n// Utility type. For a given object block schema, ensures that the key of each\n// block spec matches the name of the TipTap node in it.\ntype NamesMatch<Blocks extends Record<string, BlockConfig>> = Blocks extends {\n [Type in keyof Blocks]: Type extends string\n ? Blocks[Type] extends { type: Type }\n ? Blocks[Type]\n : never\n : never;\n}\n ? Blocks\n : never;\n\n// A Schema contains all the types (Configs) supported in an editor\n// The keys are the \"type\" of a block\nexport type BlockSchema = NamesMatch<Record<string, BlockConfig>>;\n\nexport type BlockSpecs = {\n [k in string]: {\n config: BlockSpec<k>[\"config\"];\n implementation: Omit<\n BlockSpec<k>[\"implementation\"],\n \"render\" | \"renderFrame\" | \"toExternalHTML\" | \"experimental_keyboard\"\n > & {\n experimental_keyboard?: BlockKeyboardOption<any>;\n // purposefully stub the types for render and toExternalHTML since they reference the block\n // A layout block declares `renderFrame` instead of `render`.\n render?: (\n /**\n * The custom block to render\n */\n block: any,\n /**\n * The BlockNote editor instance\n */\n editor: BlockNoteEditor<any>,\n ) => {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n ignoreMutation?: (mutation: ViewMutationRecord) => boolean;\n destroy?: () => void;\n update?: (node: PMNode) => boolean | void;\n };\n renderFrame?: <I extends InlineContentSchema, S extends StyleSchema>(\n block: any,\n editor: BlockNoteEditor<any, I, S>,\n ) =>\n | {\n dom: HTMLElement;\n slot: HTMLElement;\n /** Releases resources when the live frame is replaced or destroyed. */\n destroy?: () => void;\n update?: (block: any) => boolean | void;\n }\n | undefined;\n toExternalHTML?: (\n block: any,\n editor: BlockNoteEditor<any>,\n context: {\n nestingLevel: number;\n },\n ) =>\n | {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n childrenDOM?: HTMLElement;\n }\n | undefined;\n };\n extensions?: BlockSpec<k>[\"extensions\"];\n };\n};\n\nexport type BlockImplementations = Record<\n string,\n BlockImplementation<any, any>\n>;\n\nexport type BlockSchemaFromSpecs<BS extends BlockSpecs> = {\n [K in keyof BS]: BS[K][\"config\"];\n};\n\nexport type BlockSpecsFromSchema<BS extends BlockSchema> = {\n [K in keyof BS]: {\n config: BlockConfig<BS[K][\"type\"], BS[K][\"propSchema\"], BS[K][\"content\"]>;\n implementation: BlockImplementation<\n BS[K][\"type\"],\n BS[K][\"propSchema\"],\n BS[K][\"content\"]\n >;\n extensions?: (Extension | ExtensionFactoryInstance)[];\n };\n};\n\nexport type BlockSchemaWithBlock<T extends string, C extends BlockConfig> = {\n [k in T]: C;\n};\n\nexport type TableCellProps = {\n backgroundColor: string;\n textColor: string;\n textAlignment: \"left\" | \"center\" | \"right\" | \"justify\";\n colspan?: number;\n rowspan?: number;\n};\n\nexport type TableCell<\n I extends InlineContentSchema,\n S extends StyleSchema = StyleSchema,\n> = {\n type: \"tableCell\";\n props: TableCellProps;\n content: InlineContent<I, S>[];\n};\n\nexport type TableContent<\n I extends InlineContentSchema,\n S extends StyleSchema = StyleSchema,\n> = {\n type: \"tableContent\";\n columnWidths: (number | undefined)[];\n headerRows?: number;\n headerCols?: number;\n rows: {\n cells: InlineContent<I, S>[][] | TableCell<I, S>[];\n }[];\n};\n\n// The content of a block with \"plain\" content (e.g. a code block): unstyled\n// text, represented as StyledText items whose `styles` is always empty.\nexport type PlainContent = (StyledText<{}> & {\n styles: Record<string, never>;\n})[];\n\n// Partial form of PlainContent: also accepts bare strings (both as the whole\n// content and as array items), which are normalized on write.\nexport type PartialPlainContent =\n | string\n | (string | (StyledText<{}> & { styles: Record<string, never> }))[];\n\n/**\n * The text of a block's `\"plain\"` content (e.g. a code block's source code).\n * Accepts the partial form too: block render/export paths can receive\n * `PartialBlock`s (e.g. the HTML serializers take them directly), where\n * plain content may still be the bare-string sugar.\n */\nexport function plainContentToString(\n content: PlainContent | PartialPlainContent,\n): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((item) => (typeof item === \"string\" ? item : item.text))\n .join(\"\");\n}\n\n// A BlockConfig has all the information to get the type of a Block (which is a specific instance of the BlockConfig.\n// i.e.: paragraphConfig: BlockConfig defines what a \"paragraph\" is / supports, and BlockFromConfigNoChildren<paragraphConfig> is the shape of a specific paragraph block.\n// (for internal use)\nexport type BlockFromConfigNoChildren<\n B extends BlockConfig,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = {\n id: string;\n type: B[\"type\"];\n props: Props<B[\"propSchema\"]>;\n content: B[\"content\"] extends \"inline\"\n ? InlineContent<I, S>[]\n : B[\"content\"] extends \"table\"\n ? TableContent<I, S>\n : B[\"content\"] extends \"plain\"\n ? PlainContent\n : B[\"content\"] extends \"none\"\n ? undefined\n : never;\n};\n\nexport type BlockFromConfig<\n B extends BlockConfig,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = BlockFromConfigNoChildren<B, I, S> & {\n children: BlockNoDefaults<BlockSchema, I, S>[];\n};\n\n// Converts each block spec into a Block object without children. We later merge\n// them into a union type and add a children property to create the Block and\n// PartialBlock objects we use in the external API.\ntype BlocksWithoutChildren<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = {\n [BType in keyof BSchema]: BlockFromConfigNoChildren<BSchema[BType], I, S>;\n};\n\n// Converts each block spec into a Block object without children, merges them\n// into a union type, and adds a children property\nexport type BlockNoDefaults<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = BlocksWithoutChildren<BSchema, I, S>[keyof BSchema] & {\n children: BlockNoDefaults<BSchema, I, S>[];\n};\n\nexport type SpecificBlock<\n BSchema extends BlockSchema,\n BType extends keyof BSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = BlocksWithoutChildren<BSchema, I, S>[BType] & {\n children: BlockNoDefaults<BSchema, I, S>[];\n};\n\n/** CODE FOR PARTIAL BLOCKS, analogous to above\n *\n * Partial blocks are convenience-wrappers to make it easier to\n *create/update blocks in the editor.\n *\n */\n\nexport type PartialTableCell<\n I extends InlineContentSchema,\n S extends StyleSchema = StyleSchema,\n> = {\n type: \"tableCell\";\n props?: Partial<TableCellProps>;\n content?: PartialInlineContent<I, S>;\n};\n\nexport type PartialTableContent<\n I extends InlineContentSchema,\n S extends StyleSchema = StyleSchema,\n> = {\n type: \"tableContent\";\n columnWidths?: (number | undefined)[];\n headerRows?: number;\n headerCols?: number;\n rows: {\n cells: PartialInlineContent<I, S>[] | PartialTableCell<I, S>[];\n }[];\n};\n\ntype PartialBlockFromConfigNoChildren<\n B extends BlockConfig,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = {\n id?: string;\n type?: B[\"type\"];\n props?: Partial<Props<B[\"propSchema\"]>>;\n content?: B[\"content\"] extends \"inline\"\n ? PartialInlineContent<I, S>\n : B[\"content\"] extends \"table\"\n ? PartialTableContent<I, S>\n : B[\"content\"] extends \"plain\"\n ? PartialPlainContent\n : B[\"content\"] extends \"none\"\n ? undefined\n : never;\n};\n\ntype PartialBlocksWithoutChildren<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = {\n [BType in keyof BSchema]: PartialBlockFromConfigNoChildren<\n BSchema[BType],\n I,\n S\n >;\n};\n\nexport type PartialBlockNoDefaults<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = PartialBlocksWithoutChildren<\n BSchema,\n I,\n S\n>[keyof PartialBlocksWithoutChildren<BSchema, I, S>] &\n Partial<{\n children: PartialBlockNoDefaults<BSchema, I, S>[];\n }>;\n\nexport type SpecificPartialBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n BType extends keyof BSchema,\n S extends StyleSchema,\n> = PartialBlocksWithoutChildren<BSchema, I, S>[BType] & {\n children?: BlockNoDefaults<BSchema, I, S>[];\n};\n\nexport type PartialBlockFromConfig<\n B extends BlockConfig,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = PartialBlockFromConfigNoChildren<B, I, S> & {\n children?: BlockNoDefaults<BlockSchema, I, S>[];\n};\n\nexport type BlockIdentifier = { id: string } | string;\n\nexport type BlockImplementation<\n TName extends string = string,\n TProps extends PropSchema = PropSchema,\n TContent extends \"inline\" | \"none\" | \"table\" | \"plain\" =\n | \"inline\"\n | \"none\"\n | \"table\"\n | \"plain\",\n> = {\n /**\n * @internal Framework adapter (React): draws the block's frame in the\n * editor, for the node view of a framed block's `blockContainer` or of a\n * layout block. Core uses it instead of the vanilla `renderFrame` when present.\n *\n * TODO: the content node view has no such hook yet: React builds it inside\n * `render` (see the `TODO` there). Add one, so `render` / `renderFrame`\n * only draw.\n */\n frameView?: (props: NodeViewRendererProps) => FrameView;\n /**\n * Metadata\n */\n meta?: BlockConfigMeta<TName, TProps>;\n /**\n * Experimental: how the keyboard treats the block and its children (Enter,\n * Shift-Enter, Backspace, and outdenting): the settings that differ from the\n * defaults, or a function of the block that returns them. See\n * {@link BlockKeyboard}. This API may change.\n */\n experimental_keyboard?: BlockKeyboardOption<\n BlockFromConfig<BlockConfig<TName, TProps, TContent>, any, any>\n >;\n /**\n * A function that converts the block into a DOM element. Every block\n * declares it, except a layout block (`layoutOnly: true`), which has no content\n * to draw and declares only `renderFrame`.\n *\n * FIXME: optional for every block here, checked at runtime\n * (`validateRenderHooks`). The types could require exactly one of `render`\n * and `renderFrame`, but core's first `createBlockSpec` overload can't see\n * `layoutOnly`.\n */\n render?: (\n this:\n | Record<string, never>\n | ({\n blockContentDOMAttributes: Record<string, string>;\n propSchema?: TProps;\n } & (\n | {\n renderType: \"nodeView\";\n props: NodeViewRendererProps;\n }\n | {\n renderType: \"dom\";\n props: undefined;\n }\n )),\n /**\n * The custom block to render\n */\n block: BlockFromConfig<BlockConfig<TName, TProps, TContent>, any, any>,\n /**\n * The BlockNote editor instance\n */\n editor: BlockNoteEditor<\n Record<TName, BlockConfig<TName, TProps, TContent>>\n >,\n ) => {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n ignoreMutation?: (mutation: ViewMutationRecord) => boolean;\n destroy?: () => void;\n /**\n * Called by ProseMirror when this block's node is updated (e.g. its content\n * or props change). Return `true` to handle the update in place - keeping\n * the existing DOM - or `false` to have the node view recreated via\n * `render`. When omitted, ProseMirror keeps the node view and reconciles its\n * `contentDOM` in place as long as the node type stays the same.\n *\n * Useful for blocks whose `render` builds custom DOM that needs to stay in\n * sync with the node (e.g. a code block rendering a preview of its content).\n */\n update?: (node: PMNode) => boolean | void;\n };\n\n /**\n * Draws the chrome *around* a block's content and children: the author's\n * markup wraps both, and the `slot` is where BlockNote mounts them.\n *\n * The slot holds the content first and the children after it. A layout block\n * (`layoutOnly: true`) has no content, so it draws only its frame, with its\n * child blocks in the slot. The frame's root is then the block's element,\n * and a layout block must always draw it.\n *\n * `render` stays the knob for the block's own content. A block may use\n * both: `render` draws the title, `renderFrame` draws the box around title\n * and body. Returning `undefined` declines — the block renders plain — so\n * a block can decide from its props, content, or children whether it is framed.\n *\n * Chrome outside the slot is the author's: ProseMirror leaves its events\n * alone. An `update` hook receives the current block on updates and patches\n * the frame in place. Return `false` to rebuild (or decline) the frame.\n * Without an update hook, a change to the block's props rebuilds the frame;\n * its content and children are in the slot, so typing doesn't. A frame\n * whose chrome shows the block's content or children needs an `update`\n * hook. Whether a block declines may depend only on its props: a declined\n * frame is asked again when the block's props change.\n */\n renderFrame?: <I extends InlineContentSchema, S extends StyleSchema>(\n this:\n | Record<string, never>\n | ({\n propSchema?: TProps;\n } & (\n | {\n renderType: \"nodeView\";\n props: NodeViewRendererProps;\n }\n | {\n renderType: \"dom\";\n props: undefined;\n }\n )),\n block: BlockFromConfig<BlockConfig<TName, TProps, TContent>, any, any>,\n editor: BlockNoteEditor<\n Record<TName, BlockConfig<TName, TProps, TContent>>,\n I,\n S\n >,\n ) =>\n | {\n dom: HTMLElement;\n /** Where BlockNote mounts the block's content and/or children. */\n slot: HTMLElement;\n /** Releases resources when the live frame is replaced or destroyed. */\n destroy?: () => void;\n update?: (\n block: BlockFromConfig<\n BlockConfig<TName, TProps, TContent>,\n any,\n any\n >,\n ) => boolean | void;\n }\n | undefined;\n\n /**\n * Exports block to external HTML. If not defined, the output will be the same\n * as `render(...).dom`, inside the block's frame (`renderFrame`) if it has\n * one. When defined, it replaces both.\n */\n toExternalHTML?: (\n this: Partial<{\n blockContentDOMAttributes: Record<string, string>;\n propSchema: TProps;\n }>,\n block: BlockFromConfig<BlockConfig<TName, TProps, TContent>, any, any>,\n editor: BlockNoteEditor<\n Record<TName, BlockConfig<TName, TProps, TContent>>\n >,\n context: {\n nestingLevel: number;\n },\n ) =>\n | {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n childrenDOM?: HTMLElement;\n }\n | undefined;\n\n /**\n * Parses an external HTML element into a block of this type when it returns the block props object, otherwise undefined\n */\n parse?: (el: HTMLElement) => Partial<Props<TProps>> | undefined;\n\n /**\n * The blocks that this block should run before.\n * This is used to determine the order in which blocks are parsed\n */\n runsBefore?: string[];\n\n /**\n * Advanced parsing function that controls how content within the block is parsed.\n * This is not recommended to use, and is only useful for advanced use cases.\n */\n parseContent?: (options: {\n el: HTMLElement;\n schema: Schema;\n }) => Fragment | undefined;\n};\n\n/**\n * BlockImplementationOrCreator is a union type of BlockImplementation and a function that returns a BlockImplementation.\n * This is used to create block implementations that can be passed to the createBlockSpec function.\n */\nexport type BlockImplementationOrCreator<\n ConfigOrCreator extends BlockConfigOrCreator = BlockConfigOrCreator,\n TOptions extends Record<string, any> | undefined =\n | Record<string, any>\n | undefined,\n Config extends ExtractBlockConfigFromConfigOrCreator<ConfigOrCreator> =\n ExtractBlockConfigFromConfigOrCreator<ConfigOrCreator>,\n> =\n | BlockImplementation<Config[\"type\"], Config[\"propSchema\"], Config[\"content\"]>\n | (TOptions extends undefined\n ? () => BlockImplementation<\n Config[\"type\"],\n Config[\"propSchema\"],\n Config[\"content\"]\n >\n : (\n options: Partial<TOptions>,\n ) => BlockImplementation<\n Config[\"type\"],\n Config[\"propSchema\"],\n Config[\"content\"]\n >);\n\n/**\n * ExtractBlockImplementationFromImplementationOrCreator is a helper type that extracts the BlockImplementation type from a BlockImplementationOrCreator.\n */\nexport type ExtractBlockImplementationFromImplementationOrCreator<\n ImplementationOrCreator extends\n | BlockImplementation<string, PropSchema, \"inline\" | \"none\" | \"plain\">\n | ((\n ...args: any[]\n ) => BlockImplementation<\n string,\n PropSchema,\n \"inline\" | \"none\" | \"plain\"\n >),\n> = ImplementationOrCreator extends (...args: any[]) => infer Implementation\n ? Implementation\n : ImplementationOrCreator;\n\n// restrict content to \"inline\" and \"none\" only\nexport type CustomBlockImplementation<\n T extends string = string,\n PS extends PropSchema = PropSchema,\n C extends \"inline\" | \"none\" | \"plain\" = \"inline\" | \"none\" | \"plain\",\n> = Omit<BlockImplementation<T, PS, C>, \"frameView\">;\n","import { Node } from \"@tiptap/core\";\n\nimport {\n DOMParser,\n Fragment,\n Node as ProsemirrorNode,\n Schema,\n TagParseRule,\n} from \"@tiptap/pm/model\";\nimport { inlineContentToNodes } from \"../../api/nodeConversions/blockToNode.js\";\nimport { nodeToCustomInlineContent } from \"../../api/nodeConversions/nodeToBlock.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { ignoreDarkReaderMutations } from \"../nodeViewMutations.js\";\nimport { propsToAttributes } from \"../blocks/internal.js\";\nimport { nonFormattingMarks } from \"../markGroups.js\";\nimport { Props } from \"../propTypes.js\";\nimport { StyleSchema } from \"../styles/types.js\";\nimport {\n addInlineContentAttributes,\n addInlineContentKeyboardShortcuts,\n createInlineContentSpecFromTipTapNode,\n} from \"./internal.js\";\nimport {\n CustomInlineContentConfig,\n InlineContentFromConfig,\n InlineContentSpec,\n PartialCustomInlineContentFromConfig,\n} from \"./types.js\";\n\nexport type CustomInlineContentImplementation<\n T extends CustomInlineContentConfig,\n S extends StyleSchema,\n> = {\n meta?: {\n draggable?: boolean;\n code?: boolean;\n /**\n * When {@link code} is `true`, this can syntax highlight the contents of the\n * inline content with the result of this callback.\n */\n // Method syntax (rather than an arrow-function property) so its parameter is\n // checked bivariantly, keeping a specific implementation assignable to the\n // generic spec record type.\n highlight?(\n inlineContent: Pick<InlineContentFromConfig<T, S>, \"type\" | \"props\">,\n ): string | undefined;\n /**\n * Marks the inline content as rendering a preview with an editable source\n * popup, driven by the editor-wide\n * `SourceInlineContentWithPreviewExtension`.\n */\n hasPreview?: boolean;\n };\n\n /**\n * Parses an external HTML element into a inline content of this type when it returns the block props object, otherwise undefined\n */\n parse?: (el: HTMLElement) => Partial<Props<T[\"propSchema\"]>> | undefined;\n\n /**\n * Advanced parsing function that controls how the content within the inline\n * content is parsed. This is not recommended to use, and is only useful for\n * advanced use cases. Only applies to inline content with `content: \"styled\"`.\n * Return `undefined` to fall through to the default inline content parsing.\n */\n parseContent?: (options: {\n el: HTMLElement;\n schema: Schema;\n }) => Fragment | undefined;\n\n /**\n * Renders an inline content to DOM elements\n */\n render: (\n /**\n * The custom inline content to render\n */\n inlineContent: InlineContentFromConfig<T, S>,\n /**\n * A callback that allows overriding the inline content element\n */\n updateInlineContent: (\n update: PartialCustomInlineContentFromConfig<T, S>,\n ) => void,\n /**\n * The BlockNote editor instance\n * This is typed generically. If you want an editor with your custom schema, you need to\n * cast it manually, e.g.: `const e = editor as BlockNoteEditor<typeof mySchema>;`\n */\n editor: BlockNoteEditor<any, any, S>,\n // (note) if we want to fix the manual cast, we need to prevent circular references and separate block definition and render implementations\n // or allow manually passing <BSchema>, but that's not possible without passing the other generics because Typescript doesn't support partial inferred generics\n /**\n * The ProseMirror node backing this inline content.\n */\n node: ProsemirrorNode,\n /**\n * Returns this inline content's position in the document. When rendered\n * outside the editor (i.e. serialized to HTML), this is a no-op that returns\n * `undefined`.\n */\n getPos: () => number | undefined,\n ) => {\n dom: HTMLElement;\n contentDOM?: HTMLElement;\n destroy?: () => void;\n };\n\n /**\n * Renders an inline content to external HTML elements for use outside the editor\n * If not provided, falls back to the render method\n */\n toExternalHTML?: (\n /**\n * The custom inline content to render\n */\n inlineContent: InlineContentFromConfig<T, S>,\n /**\n * The BlockNote editor instance\n * This is typed generically. If you want an editor with your custom schema, you need to\n * cast it manually, e.g.: `const e = editor as BlockNoteEditor<typeof mySchema>;`\n */\n editor: BlockNoteEditor<any, any, S>,\n ) =>\n | {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n }\n | undefined;\n\n runsBefore?: string[];\n};\n\n// Resolves the element whose children hold the inline content's editable\n// content, i.e. the `[data-editable]` element (or the element itself if it is /\n// contains none).\nfunction getEditableElement(element: HTMLElement) {\n if (element.matches(\"[data-editable]\")) {\n return element;\n }\n\n return element.querySelector<HTMLElement>(\"[data-editable]\") || element;\n}\n\n// Parses an element's children as inline content.\nfunction parseInlineContent(el: HTMLElement, schema: Schema) {\n return DOMParser.fromSchema(schema).parse(el, {\n topNode: schema.nodes.paragraph.create(),\n preserveWhitespace: true,\n }).content;\n}\n\n// Flattens parsed inline content into text nodes only. \"plain\" inline content\n// holds text only, so non-text inline nodes are flattened: line breaks become\n// newline characters and other nodes (e.g. mentions) are kept as their text.\nfunction flattenToText(content: Fragment, schema: Schema) {\n const textNodes: ProsemirrorNode[] = [];\n content.forEach((child) => {\n if (child.isText) {\n textNodes.push(child);\n } else {\n const text =\n child.type === schema.linebreakReplacement ? \"\\n\" : child.textContent;\n if (text) {\n textNodes.push(schema.text(text, child.marks));\n }\n }\n });\n\n return Fragment.fromArray(textNodes);\n}\n\nexport function getInlineContentParseRules<C extends CustomInlineContentConfig>(\n config: C,\n customParseFunction?: CustomInlineContentImplementation<C, any>[\"parse\"],\n customParseContentFunction?: CustomInlineContentImplementation<\n C,\n any\n >[\"parseContent\"],\n) {\n // When a custom `parseContent` function is provided (and this inline content\n // actually holds content), it controls how content within the inline content\n // is parsed. This applies to _both_ parse rules below, as content copied from\n // within the editor is tagged with `data-inline-content-type` (matched by the\n // first rule), while content pasted from outside is matched by the custom\n // `parse` function (the second rule). `resolveContentElement` locates the\n // element whose children to parse as a fallback when `parseContent` returns\n // `undefined`.\n // \"plain\" inline content always needs `getContent` so its parsed content is\n // flattened to text (`<br>`/line breaks become newline characters), regardless\n // of whether a custom `parseContent` is provided — mirroring \"plain\" blocks.\n // \"styled\" inline content only needs it to run a custom `parseContent`.\n const getContent =\n config.content === \"plain\" ||\n (customParseContentFunction && config.content === \"styled\")\n ? (resolveContentElement: (el: HTMLElement) => HTMLElement) =>\n (node: HTMLElement, schema: Schema) => {\n const result = customParseContentFunction?.({ el: node, schema });\n\n // `parseContent` may return `undefined` to fall through to the\n // default inline content parsing.\n if (result !== undefined) {\n return config.content === \"plain\"\n ? flattenToText(result, schema)\n : result;\n }\n\n const parsed = parseInlineContent(\n resolveContentElement(node),\n schema,\n );\n return config.content === \"plain\"\n ? flattenToText(parsed, schema)\n : parsed;\n }\n : undefined;\n\n const rules: TagParseRule[] = [\n {\n tag: `[data-inline-content-type=\"${config.type}\"]`,\n contentElement: (element) => getEditableElement(element as HTMLElement),\n getContent: getContent\n ? (node, schema) =>\n getContent(getEditableElement)(node as HTMLElement, schema)\n : undefined,\n },\n ];\n\n if (customParseFunction) {\n rules.push({\n tag: \"*\",\n getAttrs(node: string | HTMLElement) {\n if (typeof node === \"string\") {\n return false;\n }\n\n const props = customParseFunction?.(node);\n\n if (props === undefined) {\n return false;\n }\n\n return props;\n },\n // Because we do the parsing ourselves, we want to preserve whitespace for\n // content we've parsed.\n preserveWhitespace: getContent ? true : undefined,\n getContent: getContent\n ? (node, schema) => getContent((el) => el)(node as HTMLElement, schema)\n : undefined,\n });\n }\n return rules;\n}\n\nexport function createInlineContentSpec<\n T extends CustomInlineContentConfig,\n S extends StyleSchema,\n>(\n inlineContentConfig: T,\n inlineContentImplementation: CustomInlineContentImplementation<T, S>,\n): InlineContentSpec<T> {\n const node = Node.create({\n name: inlineContentConfig.type,\n inline: true,\n group: \"inline\",\n draggable: inlineContentImplementation.meta?.draggable,\n selectable: inlineContentConfig.content !== \"none\",\n atom: inlineContentConfig.content === \"none\",\n code: inlineContentImplementation.meta?.code,\n content:\n inlineContentConfig.content === \"styled\"\n ? \"inline*\"\n : inlineContentConfig.content === \"plain\"\n ? \"text*\"\n : \"\",\n // \"plain\" inline content holds unstyled text, so it disallows formatting\n // marks (mirroring \"plain\" blocks). It still allows the non-formatting marks\n // (comments and suggestions/diffs), which annotate content without changing\n // it and are ignored by the content model. `nonFormattingMarks` resolves the\n // group only when at least one such mark is registered, so a plain inline\n // content in an editor without any of them doesn't reference an empty\n // (unknown) mark group.\n marks() {\n return inlineContentConfig.content === \"plain\"\n ? nonFormattingMarks(this.editor)\n : undefined;\n },\n\n addAttributes() {\n return propsToAttributes(inlineContentConfig.propSchema);\n },\n\n addKeyboardShortcuts() {\n return addInlineContentKeyboardShortcuts(inlineContentConfig);\n },\n\n parseHTML() {\n return getInlineContentParseRules(\n inlineContentConfig,\n inlineContentImplementation.parse,\n inlineContentImplementation.parseContent,\n );\n },\n\n renderHTML({ node }) {\n const editor = this.options.editor;\n\n const output = inlineContentImplementation.render.call(\n { renderType: \"dom\", props: undefined },\n nodeToCustomInlineContent(\n node,\n editor.schema.inlineContentSchema,\n editor.schema.styleSchema,\n ) as any as InlineContentFromConfig<T, S>, // TODO: fix cast\n () => {\n // No-op\n },\n editor,\n node,\n () => undefined,\n );\n\n return addInlineContentAttributes(\n output,\n inlineContentConfig.type,\n node.attrs as Props<T[\"propSchema\"]>,\n inlineContentConfig.propSchema,\n );\n },\n\n addNodeView() {\n return (props) => {\n const { node, getPos } = props;\n const editor = this.options.editor as BlockNoteEditor<any, any, S>;\n\n const output = inlineContentImplementation.render.call(\n { renderType: \"nodeView\", props },\n nodeToCustomInlineContent(\n node,\n editor.schema.inlineContentSchema,\n editor.schema.styleSchema,\n ) as any as InlineContentFromConfig<T, S>, // TODO: fix cast\n (update) => {\n const content = inlineContentToNodes([update], editor.pmSchema);\n\n const pos = getPos();\n\n if (!pos) {\n return;\n }\n\n editor.transact((tr) =>\n tr.replaceWith(pos, pos + node.nodeSize, content),\n );\n },\n editor,\n node,\n getPos,\n );\n\n const nodeView = addInlineContentAttributes(\n output,\n inlineContentConfig.type,\n node.attrs as Props<T[\"propSchema\"]>,\n inlineContentConfig.propSchema,\n );\n\n // Ignores Dark Reader's rewrites of the inline content's DOM, which\n // would otherwise trigger an infinite re-render loop that freezes the tab.\n ignoreDarkReaderMutations(nodeView);\n\n return nodeView;\n };\n },\n });\n\n return createInlineContentSpecFromTipTapNode(\n node,\n inlineContentConfig.propSchema,\n {\n ...inlineContentImplementation,\n toExternalHTML: inlineContentImplementation.toExternalHTML,\n render(inlineContent, updateInlineContent, editor) {\n // Rendered outside the editor (serialization), so there's no live node\n // view - derive the node from the content and stub out `getPos`.\n const node = inlineContentToNodes(\n [inlineContent] as any,\n editor.pmSchema,\n )[0];\n\n const output = inlineContentImplementation.render(\n inlineContent,\n updateInlineContent,\n editor,\n node,\n () => undefined,\n );\n\n return addInlineContentAttributes(\n output,\n inlineContentConfig.type,\n inlineContent.props,\n inlineContentConfig.propSchema,\n );\n },\n },\n ) as InlineContentSpec<T>;\n}\n","import { Fragment, Slice } from \"prosemirror-model\";\nimport type { Transaction } from \"prosemirror-state\";\nimport { ReplaceStep } from \"prosemirror-transform\";\nimport { Block, PartialBlock } from \"../../../../blocks/defaultBlocks.js\";\nimport {\n BlockIdentifier,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../../schema/index.js\";\nimport {\n type BlockPlacement,\n getInsertionPos,\n getBlockInfoAt,\n} from \"../../../getBlockInfoFromPos.js\";\nimport { blockToNode } from \"../../../nodeConversions/blockToNode.js\";\nimport { nodeToBlock } from \"../../../nodeConversions/nodeToBlock.js\";\nimport { getNodeById } from \"../../../nodeUtil.js\";\nimport { getPmSchema } from \"../../../pmUtil.js\";\n\nexport function insertBlocks<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n tr: Transaction,\n blocksToInsert: PartialBlock<BSchema, I, S>[],\n referenceBlock: BlockIdentifier,\n placement: BlockPlacement = \"before\",\n): Block<BSchema, I, S>[] {\n const id =\n typeof referenceBlock === \"string\" ? referenceBlock : referenceBlock.id;\n const pmSchema = getPmSchema(tr);\n const nodesToInsert = blocksToInsert.map((block) => {\n const node = blockToNode(block, pmSchema);\n node.check(); // `blockToNode` is lenient; validate before mutating the doc\n return node;\n });\n\n const posInfo = getNodeById(id, tr.doc);\n if (!posInfo) {\n throw new Error(`Block with ID ${id} not found`);\n }\n\n if (nodesToInsert.length === 0) {\n return [];\n }\n\n const target = getInsertionPos(\n tr.doc,\n getBlockInfoAt(tr.doc, posInfo.posBeforeNode),\n placement,\n nodesToInsert[0].type,\n );\n if (!target) {\n throw new Error(\n `Cannot insert blocks at \"${placement}\" of block \"${id}\": no valid position for them`,\n );\n }\n\n // `getInsertionPos` can only answer for the first node's type: the fragment\n // doesn't exist yet when it runs. The whole fragment still has to fit — a\n // `blockGroup` takes a paragraph but not a `namedOnly` block — so it is\n // checked here, where the nodes are known, rather than left to `tr.step` to\n // reject with a ProseMirror-level message.\n if (\n target.wrapIn &&\n !target.wrapIn.validContent(Fragment.from(nodesToInsert))\n ) {\n throw new Error(\n `Cannot insert blocks at \"${placement}\" of block \"${id}\": a \"${target.wrapIn.name}\" doesn't accept them`,\n );\n }\n\n const fragment = target.wrapIn\n ? Fragment.from(target.wrapIn.create(null, nodesToInsert))\n : Fragment.from(nodesToInsert);\n\n const $target = tr.doc.resolve(target.pos);\n if (!$target.parent.canReplace($target.index(), $target.index(), fragment)) {\n throw new Error(\n `Cannot insert blocks at \"${placement}\" of block \"${id}\": a \"${$target.parent.type.name}\" doesn't accept them`,\n );\n }\n\n tr.step(new ReplaceStep(target.pos, target.pos, new Slice(fragment, 0, 0)));\n\n // Now that the `PartialBlock`s have been converted to nodes, we can\n // re-convert them into full `Block`s.\n const insertedBlocks = nodesToInsert.map((node) =>\n nodeToBlock(node, tr.doc),\n ) as Block<BSchema, I, S>[];\n\n return insertedBlocks;\n}\n","import { Fragment, type Node, Slice } from \"prosemirror-model\";\nimport { type Transaction } from \"prosemirror-state\";\nimport { ReplaceAroundStep } from \"prosemirror-transform\";\n\nimport {\n isLayoutNode,\n isNamedOnly,\n minChildren,\n} from \"../../../schema/blocks/children.js\";\nimport { getNodeById } from \"../../nodeUtil.js\";\n\n/**\n * Whether `node` is a layout block child the user has emptied out: a layout block\n * (a column, a cell) holding nothing but one empty paragraph, or one holding\n * nothing at all that its content expression requires children.\n * @internal\n */\nexport function isEmptyLayoutChild(node: Node): boolean {\n if (node.type.name === \"blockContainer\") {\n const content = node.firstChild;\n return (\n node.childCount === 1 &&\n !!content &&\n content.type.name === \"paragraph\" &&\n content.childCount === 0\n );\n }\n if (isLayoutNode(node.type)) {\n if (node.childCount === 1) {\n return isEmptyLayoutChild(node.firstChild!);\n }\n // A layout block left with no children at all: its last child was removed\n // and no fill happened on the way. A `min: 0` layout block in this state is\n // valid and stays; any other is broken structure.\n if (node.childCount === 0) {\n return minChildren(node.type.spec.blockConfig?.children) >= 1;\n }\n return false;\n }\n return false;\n}\n\n/**\n * Repairs the layout block at `layoutBlockPos` after children were (re)moved from\n * it: drops the ones the user emptied, and dissolves the layout block when too\n * few are left for it to mean anything (a column list with one column is just\n * that column's blocks).\n *\n * A layout block that only exists inside another layout block (a column) is left to\n * its parent, which is the thing that decides whether it still belongs.\n *\n * @param layoutBlockPos The position just before the layout block node.\n * @internal\n */\nexport function fixLayoutBlock(tr: Transaction, layoutBlockPos: number) {\n const layoutBlock = tr.doc.resolve(layoutBlockPos).nodeAfter;\n if (!layoutBlock || !isLayoutNode(layoutBlock.type)) {\n throw new Error(\n \"Invalid layoutBlockPos: does not point to a layout block node.\",\n );\n }\n\n // A `namedOnly` layout block (a column) keeps existing: it is its parent's\n // decision whether the layout block still belongs, and ProseMirror pads it\n // back up to its minimum when children are removed.\n if (isNamedOnly(layoutBlock.type)) {\n return;\n }\n\n // A layout block that does not dissolve keeps its empty children, and stays\n // when too few are left: ProseMirror fills it back up to its minimum with\n // empty children (`children.dissolve`).\n const children = layoutBlock.type.spec.blockConfig?.children;\n if (children && \"dissolve\" in children && children.dissolve === false) {\n return;\n }\n\n const min = minChildren(layoutBlock.type.spec.blockConfig?.children);\n const survivors: { node: Node; offset: number }[] = [];\n const emptied: { from: number; to: number }[] = [];\n layoutBlock.forEach((child, offset) => {\n if (!isEmptyLayoutChild(child)) {\n survivors.push({ node: child, offset });\n } else if (isLayoutNode(child.type)) {\n const from = layoutBlockPos + 1 + offset;\n emptied.push({ from, to: from + child.nodeSize });\n }\n });\n\n if (survivors.length >= min) {\n // Keep intentional empty paragraphs. Only remove empty structural children,\n // back to front so positions (and selections in surviving children) stay valid.\n for (const { from, to } of emptied.reverse()) {\n tr.delete(from, to);\n }\n return;\n }\n\n // Too few children left for the layout block to mean anything, so it is\n // replaced by its surviving children.\n\n // A single survivor supplying the whole replacement is an unwrap, and doing\n // it as a `ReplaceAroundStep` leaves that content in place in the document:\n // positions inside it - a caret, a collaborator's concurrent edit - map\n // through it, where deleting and reinserting the same content would collapse\n // them onto the edge of the replaced range.\n if (survivors.length === 1) {\n const [{ node: survivor, offset }] = survivors;\n const survivorPos = layoutBlockPos + 1 + offset;\n // A `namedOnly` survivor is lifted out of two wrappers at once - the column\n // and the layout block - and any other survivor out of just the layout block.\n const gap = isNamedOnly(survivor.type)\n ? { from: survivorPos + 1, to: survivorPos + survivor.nodeSize - 1 }\n : { from: survivorPos, to: survivorPos + survivor.nodeSize };\n\n tr.step(\n new ReplaceAroundStep(\n layoutBlockPos,\n layoutBlockPos + layoutBlock.nodeSize,\n gap.from,\n gap.to,\n Slice.empty,\n 0,\n // Not a pure unwrap: emptied siblings sit outside the gap and go with\n // the layout block, which the `structure` check would refuse.\n false,\n ),\n );\n return;\n }\n\n // Several survivors are not one contiguous range once an emptied child sits\n // between them, so this path rebuilds them and positions inside them\n // collapse. It takes a layout block with a `min` of 3 or more to reach.\n const replacement: Node[] = [];\n for (const { node: survivor } of survivors) {\n if (isNamedOnly(survivor.type)) {\n // The survivor can't stand on its own either (a column only exists\n // inside a column list), so what it holds is what's left.\n survivor.forEach((grandChild) => replacement.push(grandChild));\n } else {\n replacement.push(survivor);\n }\n }\n\n tr.replaceWith(\n layoutBlockPos,\n layoutBlockPos + layoutBlock.nodeSize,\n Fragment.from(replacement),\n );\n}\n\n/**\n * Runs {@link fixLayoutBlock} on each of the given layout blocks, looked up by ID\n * in `tr`'s current doc. Layout blocks are repaired deepest-first so that an\n * inner repair (e.g. a column emptying out) is observed by the outer\n * layout block's repair (e.g. its columnList unwrapping) in the same pass.\n * Layout blocks that no longer exist by the time their turn comes are skipped —\n * an earlier repair may have removed them.\n */\nexport function fixLayoutBlocksById(\n tr: Transaction,\n layoutBlocks: { id: string; depth: number }[],\n) {\n [...layoutBlocks]\n .sort((a, b) => b.depth - a.depth)\n .forEach(({ id }) => {\n const target = getNodeById(id, tr.doc);\n if (target && isLayoutNode(target.node.type)) {\n fixLayoutBlock(tr, target.posBeforeNode);\n }\n });\n}\n","import { type Node } from \"prosemirror-model\";\nimport { type Transaction } from \"prosemirror-state\";\nimport type { Block, PartialBlock } from \"../../../../blocks/defaultBlocks.js\";\nimport {\n getNodeId,\n getAncestorLayoutBlocks,\n} from \"../../../getBlockInfoFromPos.js\";\nimport type {\n BlockIdentifier,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../../schema/index.js\";\nimport { blockToNode } from \"../../../nodeConversions/blockToNode.js\";\nimport { nodeToBlock } from \"../../../nodeConversions/nodeToBlock.js\";\nimport { getPmSchema } from \"../../../pmUtil.js\";\nimport { fixLayoutBlocksById } from \"../../layoutBlocks/fixLayoutBlock.js\";\n\nexport function removeAndInsertBlocks<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n tr: Transaction,\n blocksToRemove: BlockIdentifier[],\n blocksToInsert: PartialBlock<BSchema, I, S>[],\n options: {\n fixLayoutBlocks?: boolean;\n } = {},\n): {\n insertedBlocks: Block<BSchema, I, S>[];\n removedBlocks: Block<BSchema, I, S>[];\n} {\n const pmSchema = getPmSchema(tr);\n // Converts the `PartialBlock`s to ProseMirror nodes to insert them into the\n // document.\n const nodesToInsert: Node[] = blocksToInsert.map((block) => {\n const node = blockToNode(block, pmSchema);\n node.check(); // `blockToNode` is lenient; validate before mutating the doc\n return node;\n });\n\n const idsOfBlocksToRemove = new Set<string>(\n blocksToRemove.map((block) =>\n typeof block === \"string\" ? block : block.id,\n ),\n );\n const removedBlocks: Block<BSchema, I, S>[] = [];\n // Ancestor layout blocks of removed blocks, to repair afterwards. Tracked by\n // node id (not position) since the removals and earlier repairs shift\n // positions; recorded with their depth so repairs run deepest-first.\n const layoutBlocksToFix: { id: string; depth: number }[] = [];\n\n const idOfFirstBlock =\n typeof blocksToRemove[0] === \"string\"\n ? blocksToRemove[0]\n : blocksToRemove[0].id;\n\n // The walk below reads the document as it is now, but mutates it as it\n // goes, so its positions go stale. `tr.mapping` already tracks exactly\n // that; sliced from here so it ignores steps the caller added earlier.\n const stepsBefore = tr.steps.length;\n const mapPos = (pos: number) => tr.mapping.slice(stepsBefore).map(pos);\n\n tr.doc.descendants((node, pos) => {\n // Skips traversing nodes after all target blocks have been removed.\n if (idsOfBlocksToRemove.size === 0) {\n return false;\n }\n\n // Keeps traversing nodes if block with target ID has not been found.\n if (!node.type.isInGroup(\"bnBlock\")) {\n return true;\n }\n\n const nodeId = getNodeId(node, tr.doc);\n\n if (!idsOfBlocksToRemove.has(nodeId)) {\n return true;\n }\n\n // Saves the block that is being deleted.\n removedBlocks.push(nodeToBlock(node, tr.doc));\n idsOfBlocksToRemove.delete(nodeId);\n\n if (blocksToInsert.length > 0 && nodeId === idOfFirstBlock) {\n tr.insert(mapPos(pos), nodesToInsert);\n }\n\n const $pos = tr.doc.resolve(mapPos(pos));\n\n for (const layoutBlock of getAncestorLayoutBlocks($pos.doc, $pos.pos)) {\n if (!layoutBlocksToFix.some((c) => c.id === layoutBlock.id)) {\n layoutBlocksToFix.push(layoutBlock);\n }\n }\n\n // When the block is the only child of a nested `blockGroup`, delete the\n // group with it (`blockGroup` acting as a `min: 1` layout block that unwraps\n // when emptied). This can't route through `fixLayoutBlock`: repair runs after\n // the delete, and by then ProseMirror's replace-fitting has padded the\n // `blockGroupChild+` group with a fresh empty `blockContainer`\n // indistinguishable from an intentional one. Only here, before the\n // delete, is \"this was the group's last child\" still knowable.\n const parent = $pos.node();\n if (\n parent.type.name === \"blockGroup\" &&\n $pos.node($pos.depth - 1).type.name !== \"doc\" &&\n parent.childCount === 1\n ) {\n tr.delete($pos.before(), $pos.after());\n } else {\n tr.delete($pos.pos, $pos.pos + node.nodeSize);\n }\n\n return false;\n });\n\n // Throws an error if not all blocks could be found.\n if (idsOfBlocksToRemove.size > 0) {\n const notFoundIds = [...idsOfBlocksToRemove].join(\"\\n\");\n\n throw Error(\n \"Blocks with the following IDs could not be found in the editor: \" +\n notFoundIds,\n );\n }\n\n // Repairs the layout blocks the removed blocks lived in (e.g. collapses\n // emptied columns/columnLists), deepest-first. Callers where the removal\n // isn't a deletion can opt out, e.g. `moveBlocks` re-inserts the blocks\n // elsewhere and deliberately leaves emptied layout blocks as-is.\n if (options.fixLayoutBlocks !== false) {\n fixLayoutBlocksById(tr, layoutBlocksToFix);\n }\n\n // Converts the nodes created from `blocksToInsert` into full `Block`s.\n const insertedBlocks = nodesToInsert.map((node) =>\n nodeToBlock(node, tr.doc),\n ) as Block<BSchema, I, S>[];\n\n return { insertedBlocks, removedBlocks };\n}\n","import {\n Fragment,\n type NodeType,\n type Node as PMNode,\n Slice,\n} from \"prosemirror-model\";\nimport { TextSelection, Transaction } from \"prosemirror-state\";\nimport { TableMap } from \"prosemirror-tables\";\nimport { ReplaceStep, Transform } from \"prosemirror-transform\";\n\nimport type { Block, PartialBlock } from \"../../../../blocks/defaultBlocks.js\";\nimport type {\n BlockIdentifier,\n BlockSchema,\n} from \"../../../../schema/blocks/types.js\";\nimport type { InlineContentSchema } from \"../../../../schema/inlineContent/types.js\";\nimport type { StyleSchema } from \"../../../../schema/styles/types.js\";\nimport { UnreachableCaseError } from \"../../../../util/typescript.js\";\nimport {\n type BlockInfo,\n getBlockInfoAt,\n} from \"../../../getBlockInfoFromPos.js\";\nimport {\n blockToNode,\n inlineContentToNodes,\n tableContentToNodes,\n} from \"../../../nodeConversions/blockToNode.js\";\nimport { nodeToBlock } from \"../../../nodeConversions/nodeToBlock.js\";\nimport { getNodeById } from \"../../../nodeUtil.js\";\nimport { getBlockSchema, getPmSchema } from \"../../../pmUtil.js\";\nimport {\n createBlockGroup,\n isLayoutNode,\n} from \"../../../../schema/blocks/children.js\";\n\n// for compatibility with tiptap. TODO: remove as we want to remove dependency on tiptap command interface\nexport const updateBlockCommand = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n posBeforeBlock: number,\n block: PartialBlock<BSchema, I, S>,\n) => {\n return ({\n tr,\n dispatch,\n }: {\n tr: Transaction;\n dispatch?: () => void;\n }): boolean => {\n if (dispatch) {\n updateBlockTr(tr, posBeforeBlock, block);\n }\n return true;\n };\n};\n\nexport function updateBlockTr<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n tr: Transform | Transaction,\n posBeforeBlock: number,\n block: PartialBlock<BSchema, I, S>,\n replaceFromPos?: number,\n replaceToPos?: number,\n) {\n // Positions in `blockInfo` are valid in the doc as it stands now, i.e.\n // after any steps the caller already added to `tr`. Remapping them through\n // the whole `tr.mapping` would apply those caller steps twice, so\n // `restoreCellAnchor` maps through only the steps added below.\n const stepsBefore = tr.mapping.maps.length;\n const blockInfo = getBlockInfoAt(tr.doc, posBeforeBlock);\n\n const cellAnchor =\n blockInfo.hasContent && blockInfo.blockNoteType === \"table\"\n ? captureCellAnchor(tr)\n : null;\n\n const pmSchema = getPmSchema(tr);\n\n if (\n replaceFromPos !== undefined &&\n replaceToPos !== undefined &&\n replaceFromPos > replaceToPos\n ) {\n throw new Error(\"Invalid replaceFromPos or replaceToPos\");\n }\n\n const newBlockType = block.type || blockInfo.blockNoteType;\n const newNodeType = pmSchema.nodes[newBlockType];\n const newBnBlockNodeType = newNodeType.isInGroup(\"bnBlock\")\n ? newNodeType\n : pmSchema.nodes[\"blockContainer\"];\n\n const replaceFromOffset =\n blockInfo.hasContent &&\n replaceFromPos !== undefined &&\n replaceFromPos >= blockInfo.contentStart &&\n replaceFromPos <= blockInfo.contentEnd\n ? replaceFromPos - blockInfo.contentStart\n : undefined;\n\n const replaceToOffset =\n blockInfo.hasContent &&\n replaceToPos !== undefined &&\n replaceToPos >= blockInfo.contentStart &&\n replaceToPos <= blockInfo.contentEnd\n ? replaceToPos - blockInfo.contentStart\n : undefined;\n\n // Rebuild when the block's shape changes or a layout block's existing children\n // cannot satisfy the new type (e.g. changing to a pair requiring two children).\n if (\n blockInfo.hasContent !== newNodeType.isInGroup(\"blockContent\") ||\n (!blockInfo.hasContent &&\n !newNodeType.validContent(blockInfo.block.node.content))\n ) {\n const existingBlock: Block<any, any, any> = nodeToBlock(\n blockInfo.block.node,\n tr.doc,\n );\n const targetConfig = getBlockSchema(pmSchema)[newBlockType];\n let content: PartialBlock<any, any, any>[\"content\"];\n const children: PartialBlock<any, any, any>[] = [...existingBlock.children];\n if (Array.isArray(existingBlock.content) && existingBlock.content.length) {\n if (\n targetConfig.content === \"inline\" ||\n targetConfig.content === \"plain\"\n ) {\n content = existingBlock.content;\n } else if (isLayoutNode(newNodeType)) {\n children.unshift({ type: \"paragraph\", content: existingBlock.content });\n }\n }\n\n const replacementNode = blockToNode(\n {\n // The rebuilt block keeps its id, so references to it stay valid.\n id: existingBlock.id,\n ...(content ? { content } : {}),\n // Omit empty children so a new layout block can seed its required children.\n ...(children.length > 0 ? { children } : {}),\n ...block,\n },\n pmSchema,\n );\n replacementNode.check(); // `blockToNode` is lenient; validate before mutating the doc\n\n // Validate the parent too: a valid column still cannot replace a root block.\n const $oldPos = tr.doc.resolve(blockInfo.block.beforePos);\n if (\n !$oldPos.parent.canReplace(\n $oldPos.index(),\n $oldPos.index(),\n Fragment.from(replacementNode),\n )\n ) {\n throw new Error(\n `Cannot update block to \"${newBlockType}\": a \"${$oldPos.parent.type.name}\" doesn't accept it`,\n );\n }\n\n tr.replaceWith(\n blockInfo.block.beforePos,\n blockInfo.block.afterPos,\n replacementNode,\n );\n\n return;\n }\n\n updateChildren(block, tr, blockInfo);\n\n if (blockInfo.hasContent) {\n // The code below determines the new content of the block.\n // or \"keep\" to keep as-is\n updateBlockContentNode(\n block,\n tr,\n pmSchema.nodes[blockInfo.blockNoteType],\n newNodeType,\n blockInfo,\n replaceFromOffset,\n replaceToOffset,\n );\n }\n\n // Adds all provided props as attributes to the parent blockContainer node too, and also preserves existing\n\n // attributes. Uses minimal steps so that an unchanged container (e.g. when\n // only children or content changed) doesn't emit a step at all.\n setNodeMarkupMinimal(tr, blockInfo.block.beforePos, newBnBlockNodeType, {\n ...block.props,\n });\n\n if (cellAnchor && blockInfo.hasContent) {\n restoreCellAnchor(\n tr,\n tr.mapping.slice(stepsBefore).map(blockInfo.content.beforePos),\n cellAnchor,\n );\n }\n}\n\nfunction updateBlockContentNode<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n block: PartialBlock<BSchema, I, S>,\n tr: Transform,\n oldNodeType: NodeType,\n newNodeType: NodeType,\n blockInfo: Extract<BlockInfo, { hasContent: true }>,\n replaceFromOffset?: number,\n replaceToOffset?: number,\n) {\n const pmSchema = getPmSchema(tr);\n let content: PMNode[] | \"keep\" = \"keep\";\n\n // Has there been any custom content provided?\n if (block.content) {\n if (typeof block.content === \"string\") {\n // Adds a single text node with no marks to the content.\n content = inlineContentToNodes(\n [block.content],\n pmSchema,\n newNodeType.name,\n );\n } else if (Array.isArray(block.content)) {\n // Adds a text node with the provided styles converted into marks to the content,\n // for each InlineContent object.\n content = inlineContentToNodes(block.content, pmSchema, newNodeType.name);\n } else if (block.content.type === \"tableContent\") {\n content = tableContentToNodes(block.content, pmSchema);\n } else {\n throw new UnreachableCaseError(block.content.type);\n }\n } else {\n // no custom content has been provided, use existing content IF possible\n // Since some block types contain inline content and others don't,\n // we either need to call setNodeMarkup to just update type &\n // attributes, or replaceWith to replace the whole content.\n const oldContent = blockInfo.content.node.content;\n if (oldNodeType.spec.content === \"\") {\n // keep old content, because it's empty anyway and should be compatible with\n // any newContentType\n } else if (newNodeType.spec.content === oldNodeType.spec.content) {\n // keep old content, because the content type is the same and should be compatible\n } else if (newNodeType.validContent(oldContent)) {\n // The content-type strings differ (e.g. \"inline*\" vs a plain block's\n // \"text*\"), but the existing content is still valid for the new type\n // (e.g. plain, unstyled text), so keep it rather than clearing it.\n } else if (newNodeType.inlineContent && oldNodeType.inlineContent) {\n // Both blocks hold text, but the existing content isn't directly valid\n // for the new type (e.g. converting styled/complex inline content into a\n // plain block that disallows formatting marks and inline nodes). Preserve\n // the text, dropping the styling the new type can't represent.\n const text = blockInfo.content.node.textContent;\n content = text.length > 0 ? [pmSchema.text(text)] : [];\n } else {\n // the content type changed and is incompatible, replace the previous content\n content = [];\n }\n }\n\n // Now, changes the content node type and adds the provided props\n // as attributes. Also preserves all existing attributes that are\n // compatible with the new type.\n //\n // Use either setNodeMarkup or replaceWith depending on whether the\n // content is being replaced or not.\n if (content === \"keep\") {\n // only update the type and attributes, keeping the content as-is\n setNodeMarkupMinimal(tr, blockInfo.content.beforePos, newNodeType, {\n ...block.props,\n });\n } else if (replaceFromOffset !== undefined || replaceToOffset !== undefined) {\n // Update the markup of the containing node, then get its (possibly shifted)\n // position back.\n const contentBeforePos = setNodeMarkupMinimalAndRemap(\n tr,\n blockInfo.content.beforePos,\n newNodeType,\n { ...block.props },\n );\n\n const start = contentBeforePos + 1 + (replaceFromOffset ?? 0);\n const end =\n contentBeforePos +\n 1 +\n (replaceToOffset ?? blockInfo.content.node.content.size);\n\n // for content like table cells (where the blockcontent has nested PM nodes),\n // we need to figure out the correct openStart and openEnd for the slice when replacing\n\n const contentDepth = tr.doc.resolve(contentBeforePos).depth;\n const startDepth = tr.doc.resolve(start).depth;\n const endDepth = tr.doc.resolve(end).depth;\n\n tr.replace(\n start,\n end,\n new Slice(\n Fragment.from(content),\n startDepth - contentDepth - 1,\n endDepth - contentDepth - 1,\n ),\n );\n } else if (\n newNodeType === oldNodeType ||\n newNodeType.validContent(blockInfo.content.node.content)\n ) {\n // The new type can hold the existing content, so we can update the markup\n // first and then diff the content. This keeps both steps minimal.\n //\n // First update the markup (type & attributes) of the content node using\n // minimal steps (avoids replacing the whole node just to change attrs), then\n // get its (possibly shifted) position back.\n const contentBeforePos = setNodeMarkupMinimalAndRemap(\n tr,\n blockInfo.content.beforePos,\n newNodeType,\n { ...block.props },\n );\n\n // Then replace only the part of the content that actually changed, keeping\n // any shared prefix/suffix untouched.\n replaceContentMinimal(tr, contentBeforePos, Fragment.from(content));\n } else {\n // The content type is incompatible with the new node type (e.g. switching\n // between inline content, table content, and no content). We can't update\n // the markup in-place, so replace the whole content node atomically.\n tr.replaceWith(\n blockInfo.content.beforePos,\n blockInfo.content.afterPos,\n newNodeType.createChecked(\n {\n ...blockInfo.content.node.attrs,\n ...block.props,\n },\n content,\n ),\n );\n }\n}\n\n/**\n * Replaces the content of the node at `nodePos` with `newContent`, only\n * touching the range that actually differs between the old and new content.\n *\n * - For textblocks (inline content), this diffs at the character level using\n * `Fragment.findDiffStart`/`findDiffEnd`, so e.g. changing a single word only\n * replaces that word rather than the entire paragraph.\n * - For nested content (like tables or blockGroups), the diff is snapped to\n * whole top-level children (rows / blocks), so only the changed children are\n * replaced while unchanged leading/trailing children are left untouched.\n */\nfunction replaceContentMinimal(\n tr: Transform,\n nodePos: number,\n newContent: Fragment,\n) {\n const node = tr.doc.nodeAt(nodePos);\n if (!node) {\n throw new RangeError(\"No node at given position\");\n }\n\n const oldContent = node.content;\n // Position of the first child inside the node.\n const contentStart = nodePos + 1;\n\n if (node.isTextblock) {\n // Inline content: diff at the character/token level. A flat slice (no open\n // depth) is valid because the children are inline leaves.\n const diffStart = oldContent.findDiffStart(newContent);\n if (diffStart === null) {\n return;\n }\n\n // `findDiffEnd` returns ends in TWO separate coordinate systems: `a` is an\n // offset into the OLD content, `b` is an offset into the NEW content. They\n // are NOT interchangeable when the two fragments differ in size.\n const diffEnd = oldContent.findDiffEnd(newContent)!;\n let { a: oldEnd, b: newEnd } = diffEnd;\n\n // The shared prefix (`diffStart`) and shared suffix can overlap, e.g. when\n // inserting/deleting a run of text at a boundary. When that happens an end\n // can fall before `diffStart`. Push the ends forward so neither precedes the\n // shared prefix, keeping the OLD and NEW ranges aligned by the same amount\n // (each coordinate system is checked independently, then the larger shift is\n // applied to both so the suffix stays in sync).\n const shift = Math.max(0, diffStart - oldEnd, diffStart - newEnd);\n if (shift > 0) {\n oldEnd += shift;\n newEnd += shift;\n }\n\n tr.replace(\n // OLD-doc range to remove: uses old-content offsets.\n contentStart + diffStart,\n contentStart + oldEnd,\n // Replacement: cut the NEW content using new-content offsets. `diffStart`\n // is valid here because it lies within the shared prefix (identical in\n // both fragments), and `newEnd` is a new-content offset.\n new Slice(newContent.cut(diffStart, newEnd), 0, 0),\n );\n return;\n }\n\n // Nested/block content (table rows, child blocks, ...): snap the diff to whole\n // top-level children so the replacement slice is always a valid sequence of\n // complete children (open depth 0).\n const oldChildCount = oldContent.childCount;\n const newChildCount = newContent.childCount;\n\n // Number of identical leading children.\n let startIndex = 0;\n while (\n startIndex < oldChildCount &&\n startIndex < newChildCount &&\n oldContent.child(startIndex).eq(newContent.child(startIndex))\n ) {\n startIndex++;\n }\n\n // Number of identical trailing children (not overlapping the shared prefix).\n let oldEndIndex = oldChildCount;\n let newEndIndex = newChildCount;\n while (\n oldEndIndex > startIndex &&\n newEndIndex > startIndex &&\n oldContent.child(oldEndIndex - 1).eq(newContent.child(newEndIndex - 1))\n ) {\n oldEndIndex--;\n newEndIndex--;\n }\n\n // Nothing changed.\n if (startIndex === oldEndIndex && startIndex === newEndIndex) {\n return;\n }\n\n // Convert child indices to document positions.\n let from = contentStart;\n for (let i = 0; i < startIndex; i++) {\n from += oldContent.child(i).nodeSize;\n }\n let to = from;\n for (let i = startIndex; i < oldEndIndex; i++) {\n to += oldContent.child(i).nodeSize;\n }\n\n // Collect the changed replacement children.\n const replacement: PMNode[] = [];\n for (let i = startIndex; i < newEndIndex; i++) {\n replacement.push(newContent.child(i));\n }\n\n // Use a strict ReplaceStep (rather than the lenient `tr.replace`) so that\n // invalid content for the parent node type (e.g. a columnList that would end\n // up with non-column children) throws instead of being silently coerced.\n tr.step(\n new ReplaceStep(from, to, new Slice(Fragment.from(replacement), 0, 0)),\n );\n}\n\n/**\n * Updates the type and/or attributes of the node at `pos` using the smallest\n * possible set of steps.\n *\n * - If neither the type nor any attribute changes, no step is emitted.\n * - If only attributes change (type stays the same), an `AttrStep` is emitted\n * for each changed attribute. These are minimal steps that don't touch the\n * node's content.\n * - If the type changes, `setNodeMarkup` is used, which keeps the node's content\n * via a `ReplaceAroundStep`.\n */\nfunction setNodeMarkupMinimal(\n tr: Transform,\n pos: number,\n newType: NodeType,\n newAttrs: Record<string, unknown>,\n) {\n const node = tr.doc.nodeAt(pos);\n if (!node) {\n throw new RangeError(\"No node at given position\");\n }\n\n // Only consider attributes that are actually valid for the target node type.\n // `block.props` may contain props that belong to the content node but not the\n // container (or vice versa), and these should be ignored here.\n const validAttrs = newType.spec.attrs ?? {};\n const filteredNewAttrs: Record<string, unknown> = {};\n for (const attr of Object.keys(newAttrs)) {\n if (attr in validAttrs) {\n filteredNewAttrs[attr] = newAttrs[attr];\n }\n }\n\n const mergedAttrs = { ...node.attrs, ...filteredNewAttrs };\n\n if (node.type === newType) {\n // Only emit AttrSteps for attributes that actually changed.\n for (const attr of Object.keys(mergedAttrs)) {\n if (mergedAttrs[attr] !== node.attrs[attr]) {\n tr.setNodeAttribute(pos, attr, mergedAttrs[attr]);\n }\n }\n return;\n }\n\n // Type changed - setNodeMarkup keeps the content via a ReplaceAroundStep.\n tr.setNodeMarkup(pos, newType, mergedAttrs);\n}\n\n/**\n * Applies a minimal markup update to the node at `pos`, then returns `pos`\n * re-mapped through only the steps that update added.\n *\n * `setNodeMarkupMinimal` may add a step (e.g. a ReplaceAroundStep when the node\n * type changes), which leaves the original `pos` stale. Because `tr` may already\n * contain steps from earlier ops (other `updateBlock` calls sharing the same\n * transaction), we map through only the steps added here — not the whole\n * `tr.mapping` — using a -1 (before) bias so the position stays anchored before\n * the node rather than being pushed past it.\n */\nfunction setNodeMarkupMinimalAndRemap(\n tr: Transform,\n pos: number,\n newType: NodeType,\n newAttrs: Record<string, unknown>,\n): number {\n const baseMapLen = tr.mapping.maps.length;\n setNodeMarkupMinimal(tr, pos, newType, newAttrs);\n return tr.mapping.slice(baseMapLen).map(pos, -1);\n}\n\nfunction updateChildren<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(block: PartialBlock<BSchema, I, S>, tr: Transform, blockInfo: BlockInfo) {\n const pmSchema = getPmSchema(tr);\n if (block.children !== undefined && block.children.length > 0) {\n const childNodes = block.children.map((child) => {\n const node = blockToNode(child, pmSchema);\n node.check(); // `blockToNode` is lenient; validate before mutating the doc\n return node;\n });\n\n if (blockInfo.children) {\n // Replaces the child nodes in the existing children holder, only\n // touching the range that actually changed (keeping unchanged\n // leading/trailing children untouched).\n replaceContentMinimal(\n tr,\n blockInfo.children.beforePos,\n Fragment.from(childNodes),\n );\n } else if (blockInfo.hasContent) {\n // A `blockContainer` with no children yet: its `blockGroup` is lazy\n // (`blockContent blockGroup?`), so create it around the child nodes and\n // insert it after the content node. (Layout blocks always have a children\n // holder, so no holder implies a `blockContainer`.)\n tr.insert(\n blockInfo.content.afterPos,\n createBlockGroup(pmSchema, childNodes),\n );\n }\n }\n}\n\nexport function updateBlock<\n BSchema extends BlockSchema = any,\n I extends InlineContentSchema = any,\n S extends StyleSchema = any,\n>(\n tr: Transform,\n blockToUpdate: BlockIdentifier,\n update: PartialBlock<BSchema, I, S>,\n replaceFromPos?: number,\n replaceToPos?: number,\n): Block<BSchema, I, S> {\n const id =\n typeof blockToUpdate === \"string\" ? blockToUpdate : blockToUpdate.id;\n const posInfo = getNodeById(id, tr.doc);\n if (!posInfo) {\n throw new Error(`Block with ID ${id} not found`);\n }\n\n updateBlockTr(\n tr,\n posInfo.posBeforeNode,\n update,\n replaceFromPos,\n replaceToPos,\n );\n\n // `updateBlockTr` may have replaced the node, so re-resolve it at the same\n // position (an update never moves the block).\n const updatedNode = tr.doc.resolve(posInfo.posBeforeNode).nodeAfter;\n if (!updatedNode) {\n throw new Error(`Block with ID ${id} not found after update`);\n }\n\n return nodeToBlock(updatedNode, tr.doc);\n}\n\ntype CellAnchor = { row: number; col: number; offset: number };\n\n/**\n * Captures the cell anchor from the current selection.\n * @param tr - The transaction to capture the cell anchor from.\n *\n * @returns The cell anchor, or null if no cell is selected.\n */\nexport function captureCellAnchor(tr: Transform): CellAnchor | null {\n const sel = \"selection\" in tr ? tr.selection : null;\n if (!(sel instanceof TextSelection)) {\n return null;\n }\n\n const $head = tr.doc.resolve(sel.head);\n // Find enclosing cell and table\n let cellDepth = -1;\n let tableDepth = -1;\n for (let d = $head.depth; d >= 0; d--) {\n const name = $head.node(d).type.name;\n if (cellDepth < 0 && (name === \"tableCell\" || name === \"tableHeader\")) {\n cellDepth = d;\n }\n if (name === \"table\") {\n tableDepth = d;\n break;\n }\n }\n if (cellDepth < 0 || tableDepth < 0) {\n return null;\n }\n\n // Absolute positions (before the cell)\n const cellPos = $head.before(cellDepth);\n const tablePos = $head.before(tableDepth);\n const table = tr.doc.nodeAt(tablePos);\n if (!table || table.type.name !== \"table\") {\n return null;\n }\n\n // Visual grid position via TableMap (handles spans)\n const map = TableMap.get(table);\n const rel = cellPos - (tablePos + 1); // relative to inside table\n const idx = map.map.indexOf(rel);\n if (idx < 0) {\n return null;\n }\n\n const row = Math.floor(idx / map.width);\n const col = idx % map.width;\n\n // Caret offset relative to the start of paragraph text\n const paraPos = cellPos + 1; // pos BEFORE tableParagraph\n const textStart = paraPos + 1; // start of paragraph text\n const offset = Math.max(0, sel.head - textStart);\n\n return { row, col, offset };\n}\n\nfunction restoreCellAnchor(\n tr: Transform | Transaction,\n tablePos: number,\n a: CellAnchor,\n): boolean {\n const table = tr.doc.nodeAt(tablePos);\n if (!table || table.type.name !== \"table\") {\n return false;\n }\n\n // 2) Clamp row/col to the table’s current grid\n const map = TableMap.get(table);\n const row = Math.max(0, Math.min(a.row, map.height - 1));\n const col = Math.max(0, Math.min(a.col, map.width - 1));\n\n // 3) Compute the absolute position of the target cell (pos BEFORE the cell)\n const cellIndex = row * map.width + col;\n const relCellPos = map.map[cellIndex]; // relative to (tablePos + 1)\n if (relCellPos == null) {\n return false;\n }\n const cellPos = tablePos + 1 + relCellPos;\n\n // 4) Place the caret inside the cell, clamping the text offset\n const textPos = cellPos + 1;\n const textNode = tr.doc.nodeAt(textPos);\n const textStart = textPos + 1;\n const max = textNode ? textNode.content.size : 0;\n const head = textStart + Math.max(0, Math.min(a.offset, max));\n\n if (\"selection\" in tr) {\n tr.setSelection(TextSelection.create(tr.doc, head));\n }\n return true;\n}\n","import {\n Node,\n type NodeViewRenderer,\n type NodeViewRendererProps,\n} from \"@tiptap/core\";\nimport type { NodeView } from \"@tiptap/pm/view\";\n\nimport type { BlockNoteEditor } from \"../editor/BlockNoteEditor.js\";\nimport {\n blockFrameView,\n findFrameSlot,\n frameNodeViewHooks,\n} from \"../schema/blocks/frame.js\";\nimport { BlockNoteDOMAttributes } from \"../schema/index.js\";\nimport { mergeCSSClasses } from \"../util/browser.js\";\nimport { suggestionMarks } from \"./suggestionMarks.js\";\n\n/** The block props whose colors `Block.css` applies to a block's children. */\nconst BLOCK_COLORS = [\n [\"textColor\", \"data-text-color\"],\n [\"backgroundColor\", \"data-background-color\"],\n] as const;\n\nfunction isColorSet(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"default\";\n}\n\n/** Whether a block has a text or background color other than the default. */\nfunction hasBlockColors(props: Record<string, unknown>) {\n return BLOCK_COLORS.some(([prop]) => isColorSet(props[prop]));\n}\n\n/**\n * Puts a block's text and background color on its own element (`.bn-block`),\n * so they also apply to its children however deep a frame puts its content.\n * Only these two props, which `Block.css` applies to a block's children.\n */\nexport function setBlockColorAttributes(\n element: HTMLElement,\n props: Record<string, unknown> | undefined,\n) {\n for (const [prop, attribute] of BLOCK_COLORS) {\n const value = props?.[prop];\n if (isColorSet(value)) {\n element.setAttribute(attribute, value);\n } else {\n element.removeAttribute(attribute);\n }\n }\n}\n\n// Object containing all possible block attributes.\nconst BlockAttributes: Record<string, string> = {\n blockColor: \"data-block-color\",\n blockStyle: \"data-block-style\",\n id: \"data-id\",\n depth: \"data-depth\",\n depthChange: \"data-depth-change\",\n};\n\n/**\n * The main \"Block node\" documents consist of\n */\nexport const BlockContainer = Node.create<{\n domAttributes?: BlockNoteDOMAttributes;\n editor: BlockNoteEditor<any, any, any>;\n}>({\n name: \"blockContainer\",\n group: \"blockGroupChild bnBlock\",\n // A block always contains content, and optionally a blockGroup which contains nested blocks\n content: \"blockContent blockGroup?\",\n // Ensures content-specific keyboard handlers trigger first.\n priority: 50,\n defining: true,\n marks() {\n return suggestionMarks(this.editor);\n },\n parseHTML() {\n return [\n {\n tag: \"div[data-node-type=\" + this.name + \"]\",\n getAttrs: (element) => {\n if (typeof element === \"string\") {\n return false;\n }\n\n const attrs: Record<string, string> = {};\n for (const [nodeAttr, HTMLAttr] of Object.entries(BlockAttributes)) {\n if (element.getAttribute(HTMLAttr)) {\n attrs[nodeAttr] = element.getAttribute(HTMLAttr)!;\n }\n }\n\n return attrs;\n },\n // The frame's slot: the rest of a frame is chrome, not document\n // content.\n contentElement: (element) =>\n findFrameSlot(element as HTMLElement) ?? (element as HTMLElement),\n },\n // Ignore `blockOuter` divs, but parse the `blockContainer` divs inside them.\n {\n tag: `div[data-node-type=\"blockOuter\"]`,\n skip: true,\n },\n ];\n },\n\n renderHTML({ HTMLAttributes }) {\n const blockOuter = document.createElement(\"div\");\n blockOuter.className = \"bn-block-outer\";\n blockOuter.setAttribute(\"data-node-type\", \"blockOuter\");\n for (const [attribute, value] of Object.entries(HTMLAttributes)) {\n if (attribute !== \"class\") {\n blockOuter.setAttribute(attribute, value);\n }\n }\n\n const blockHTMLAttributes = {\n ...(this.options.domAttributes?.block || {}),\n ...HTMLAttributes,\n };\n const block = document.createElement(\"div\");\n block.className = mergeCSSClasses(\"bn-block\", blockHTMLAttributes.class);\n block.setAttribute(\"data-node-type\", this.name);\n for (const [attribute, value] of Object.entries(blockHTMLAttributes)) {\n if (attribute !== \"class\") {\n block.setAttribute(attribute, value);\n }\n }\n\n blockOuter.appendChild(block);\n\n return {\n dom: blockOuter,\n contentDOM: block,\n };\n },\n\n addNodeView() {\n // Every block gets this node view: it draws the block's frame (or none),\n // keeps it current, and keeps the block's colors on `.bn-block`. Without\n // a frame, it is as fast as ProseMirror's default (`performance.test.ts`).\n // Cast: this returns a plain ProseMirror node view, which tiptap's\n // `NodeViewRenderer` type doesn't model.\n return ((props: NodeViewRendererProps) => {\n const { dom, contentDOM: block } = this.type.spec.toDOM!(props.node) as {\n dom: HTMLElement;\n contentDOM: HTMLElement;\n };\n const editor = this.options.editor;\n // The block's frame: React draws its own, otherwise the block's\n // vanilla `renderFrame`. A drawn frame goes inside `.bn-block`; a block\n // without one keeps its content and children in `.bn-block` itself.\n const frame = blockFrameView({\n props,\n editor,\n blockNode: (node) => node.firstChild!,\n unframed: block,\n });\n if (frame.dom !== block) {\n block.appendChild(frame.dom);\n }\n // A new `.bn-block` has no color attributes, so a block with the default\n // colors needs no DOM calls. Skipping them keeps typing in large\n // documents fast (`performance.test.ts`).\n const attrs = props.node.firstChild!.attrs;\n if (hasBlockColors(attrs)) {\n setBlockColorAttributes(block, attrs);\n }\n\n const nodeView: NodeView = {\n dom,\n contentDOM: frame.slot,\n update(node, decorations, innerDecorations) {\n const before = frame.node;\n // Like ProseMirror's default, the view is rebuilt when the block's\n // own attributes change (another block), and otherwise kept while\n // ProseMirror updates the content and children. It is also rebuilt\n // when the frame no longer fits, for example after a change of the\n // block's type or props.\n if (\n !node.sameMarkup(before) ||\n !frame.update(node, decorations, innerDecorations)\n ) {\n return false;\n }\n // `Block.css` applies a block's colors to its children too, from\n // its element. They are props, so only a prop change moves them.\n if (!node.firstChild!.sameMarkup(before.firstChild!)) {\n setBlockColorAttributes(block, node.firstChild!.attrs);\n }\n return true;\n },\n ...frameNodeViewHooks(frame),\n };\n return nodeView;\n }) as unknown as NodeViewRenderer;\n },\n});\n","import { DOMSerializer, Fragment, Node } from \"prosemirror-model\";\n\nimport { PartialBlock } from \"../../../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../../schema/index.js\";\nimport { isLayoutNode } from \"../../../../schema/blocks/children.js\";\nimport { UnreachableCaseError } from \"../../../../util/typescript.js\";\nimport {\n inlineContentToNodes,\n tableContentToNodes,\n} from \"../../../nodeConversions/blockToNode.js\";\n\nimport { nodeToCustomInlineContent } from \"../../../nodeConversions/nodeToBlock.js\";\nimport { setBlockColorAttributes } from \"../../../../pm-nodes/BlockContainer.js\";\nimport {\n markFrameSlot,\n renderFrameDOM,\n} from \"../../../../schema/blocks/frame.js\";\nexport function serializeInlineContentInternalHTML<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<any, I, S>,\n blockContent: PartialBlock<BSchema, I, S>[\"content\"],\n serializer: DOMSerializer,\n blockType?: string,\n options?: { document?: Document },\n) {\n let nodes: Node[];\n\n // TODO: reuse function from nodeconversions?\n if (!blockContent) {\n throw new Error(\"blockContent is required\");\n } else if (typeof blockContent === \"string\") {\n nodes = inlineContentToNodes([blockContent], editor.pmSchema, blockType);\n } else if (Array.isArray(blockContent)) {\n nodes = inlineContentToNodes(blockContent, editor.pmSchema, blockType);\n } else if (blockContent.type === \"tableContent\") {\n nodes = tableContentToNodes(blockContent, editor.pmSchema);\n } else {\n throw new UnreachableCaseError(blockContent.type);\n }\n\n // Check if any of the nodes are custom inline content with toExternalHTML\n const doc = options?.document ?? document;\n const fragment = doc.createDocumentFragment();\n\n for (const node of nodes) {\n // Check if this is a custom inline content node with toExternalHTML\n if (\n node.type.name !== \"text\" &&\n editor.schema.inlineContentSchema[node.type.name]\n ) {\n const inlineContentImplementation =\n editor.schema.inlineContentSpecs[node.type.name].implementation;\n\n if (inlineContentImplementation) {\n // Convert the node to inline content format\n const inlineContent = nodeToCustomInlineContent(\n node,\n editor.schema.inlineContentSchema,\n editor.schema.styleSchema,\n );\n\n // Use the custom toExternalHTML method\n const output = inlineContentImplementation.render.call(\n {\n renderType: \"dom\",\n props: undefined,\n },\n inlineContent as any,\n () => {\n // No-op\n },\n editor as any,\n );\n\n if (output) {\n fragment.appendChild(output.dom);\n\n // If contentDOM exists, render the inline content into it\n if (output.contentDOM) {\n const contentFragment = serializer.serializeFragment(\n node.content,\n options,\n );\n output.contentDOM.dataset.editable = \"\";\n output.contentDOM.appendChild(contentFragment);\n }\n continue;\n }\n }\n } else if (node.type.name === \"text\") {\n // We serialize text nodes manually as we need to serialize the styles/\n // marks using `styleSpec.implementation.render`. When left up to\n // ProseMirror, it'll use `toDOM` which is incorrect.\n let dom: globalThis.Node | Text = document.createTextNode(\n node.textContent,\n );\n // Reverse the order of marks to maintain the correct priority.\n for (const mark of node.marks.toReversed()) {\n if (mark.type.name in editor.schema.styleSpecs) {\n const newDom = editor.schema.styleSpecs[\n mark.type.name\n ].implementation.render(mark.attrs[\"stringValue\"], editor);\n newDom.contentDOM!.appendChild(dom);\n dom = newDom.dom;\n } else {\n const domOutputSpec = mark.type.spec.toDOM!(mark, true);\n const newDom = DOMSerializer.renderSpec(document, domOutputSpec);\n newDom.contentDOM!.appendChild(dom);\n dom = newDom.dom;\n }\n }\n\n fragment.appendChild(dom);\n } else {\n // Fall back to default serialization for this node\n const nodeFragment = serializer.serializeFragment(\n Fragment.from([node]),\n options,\n );\n fragment.appendChild(nodeFragment);\n }\n }\n\n return fragment;\n}\n\nfunction serializeBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n block: PartialBlock<BSchema, I, S>,\n serializer: DOMSerializer,\n options?: { document?: Document },\n) {\n const BC_NODE = editor.pmSchema.nodes[\"blockContainer\"];\n\n // set default props in case we were passed a partial block\n const props = block.props || {};\n for (const [name, spec] of Object.entries(\n editor.schema.blockSchema[block.type as any].propSchema,\n )) {\n if (!(name in props) && spec.default !== undefined) {\n (props as any)[name] = spec.default;\n }\n }\n const children = block.children || [];\n\n const impl = editor.blockImplementations[block.type as any].implementation;\n const fullBlock = { ...block, props, children } as any;\n\n if (isLayoutNode(editor.pmSchema.nodes[block.type as any])) {\n // A layout block is its frame. `renderFrameDOM` stamps the frame's root with\n // the block's attributes and marks the slot, which holds the children, so\n // the round-trip parse rule reads only the slot and not the chrome around\n // it.\n const frame = renderFrameDOM(editor, fullBlock);\n if (!frame) {\n throw new Error(\n `Layout block \"${block.type}\" drew no frame. This is a bug in BlockNote.`,\n );\n }\n if (children.length > 0) {\n frame.slot.append(serializeBlocks(editor, children, serializer, options));\n }\n return frame.dom;\n }\n\n // Every block but a layout block declares `render` (`validateRenderHooks`).\n if (!impl.render) {\n throw new Error(\n `Block \"${block.type}\" has no \\`render\\`. This is a bug in BlockNote.`,\n );\n }\n const ret = impl.render.call(\n {\n renderType: \"dom\",\n props: undefined,\n },\n fullBlock,\n editor as any,\n );\n\n if (ret.contentDOM && block.content) {\n const ic = serializeInlineContentInternalHTML(\n editor,\n block.content as any, // TODO\n serializer,\n block.type,\n options,\n );\n ret.contentDOM.appendChild(ic);\n }\n\n // wrap the block in a blockContainer\n const bc = BC_NODE.spec?.toDOM?.(\n BC_NODE.create({\n id: block.id,\n ...props,\n }),\n ) as {\n dom: HTMLElement;\n contentDOM?: HTMLElement;\n };\n if (bc.contentDOM) {\n setBlockColorAttributes(bc.contentDOM, props);\n }\n\n // The block's content and children go into the blockContainer, or into the\n // slot of the frame around them. The DOM render context lets interactive\n // frames export without browser view state.\n let contentDOM = bc.contentDOM;\n const frame = renderFrameDOM(editor, fullBlock);\n if (frame) {\n // Marks where the block's content and children are, for the parser: the\n // rest of the frame is chrome, not document content.\n markFrameSlot(frame.slot);\n bc.contentDOM?.appendChild(frame.dom);\n contentDOM = frame.slot;\n }\n contentDOM?.appendChild(ret.dom);\n\n if (children.length > 0) {\n contentDOM?.appendChild(\n serializeBlocksInternalHTML(editor, children, serializer, options),\n );\n }\n return bc.dom;\n}\n\nfunction serializeBlocks<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n blocks: PartialBlock<BSchema, I, S>[],\n serializer: DOMSerializer,\n options?: { document?: Document },\n) {\n const doc = options?.document ?? document;\n const fragment = doc.createDocumentFragment();\n\n for (const block of blocks) {\n const blockDOM = serializeBlock(editor, block, serializer, options);\n fragment.appendChild(blockDOM);\n }\n\n return fragment;\n}\n\nexport const serializeBlocksInternalHTML = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n blocks: PartialBlock<BSchema, I, S>[],\n serializer: DOMSerializer,\n options?: { document?: Document },\n) => {\n const BG_NODE = editor.pmSchema.nodes[\"blockGroup\"];\n\n const bg = BG_NODE.spec!.toDOM!(BG_NODE.create({})) as {\n dom: HTMLElement;\n contentDOM?: HTMLElement;\n };\n\n const fragment = serializeBlocks(editor, blocks, serializer, options);\n\n bg.contentDOM?.appendChild(fragment);\n\n return bg.dom;\n};\n","import { DOMSerializer, Schema } from \"prosemirror-model\";\n\nimport { PartialBlock } from \"../../../blocks/defaultBlocks.js\";\nimport { EMPTY_CELL_WIDTH } from \"../../../blocks/index.js\";\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { serializeBlocksInternalHTML } from \"./util/serializeBlocksInternalHTML.js\";\n\n// This is normally handled using decorations in the\n// `NumberedListIndexingDecorationPlugin`. This does not run when exporting, so\n// we have to add the necessary HTML attributes ourselves.\nconst addIndexToNumberedListItems = (element: HTMLElement) => {\n const numberedListItems = element.querySelectorAll(\n '[data-content-type=\"numberedListItem\"]',\n );\n numberedListItems.forEach((numberedListItem) => {\n const prevNumberedListItem = numberedListItem\n .closest(\".bn-block-outer\")\n ?.previousElementSibling?.querySelector(\n '[data-content-type=\"numberedListItem\"]',\n );\n\n if (!prevNumberedListItem) {\n numberedListItem.setAttribute(\n \"data-index\",\n numberedListItem.getAttribute(\"data-start\") || \"1\",\n );\n } else {\n const prevNumberedListItemIndex =\n prevNumberedListItem.getAttribute(\"data-index\");\n numberedListItem.setAttribute(\n \"data-index\",\n (parseInt(prevNumberedListItemIndex || \"0\") + 1).toString(),\n );\n }\n });\n\n return element;\n};\n\n// Makes the checkboxes in check list items read-only, as the HTML should be\n// static and therefore read-only when rendered.\nconst makeCheckListItemsReadOnly = (element: HTMLElement) => {\n const checkboxes: NodeListOf<HTMLInputElement> = element.querySelectorAll(\n '[data-content-type=\"checkListItem\"] input',\n );\n checkboxes.forEach((checkbox) => {\n checkbox.disabled = true;\n });\n\n return element;\n};\n\n// Forces toggle blocks (toggle headings, toggle list items) to be expanded.\n// This is because event listeners for the toggle button are lost when\n// serializing HTML elements to a string, so the button no longer works if the\n// HTML string is rendered out.\nconst forceToggleBlocksShow = (element: HTMLElement) => {\n const closedToggleButtons = element.querySelectorAll(\n '.bn-toggle-button[aria-expanded=\"false\"]',\n );\n closedToggleButtons.forEach((toggleButton) => {\n toggleButton.setAttribute(\"aria-expanded\", \"true\");\n });\n\n return element;\n};\n\n// Adds minimum cell widths, which would normally be done by the\n// `columnResizing` extension. This extension doesn't run when exporting to\n// HTML, so we have to add this manually.\nconst addTableMinCellWidths = (element: HTMLElement) => {\n const tables = element.querySelectorAll('[data-content-type=\"table\"] table');\n tables.forEach((table) => {\n table.setAttribute(\n \"style\",\n `--default-cell-min-width: ${EMPTY_CELL_WIDTH}px;`,\n );\n table.setAttribute(\"data-show-children\", \"true\");\n });\n\n return element;\n};\n\n// Adds table wrapping elements, which would normally be done by the\n// `columnResizing` extension. This extension doesn't run when exporting to\n// HTML, so we have to add this manually. This adds the correct padding to\n// tables.\nconst addTableWrappers = (element: HTMLElement) => {\n const tables = element.querySelectorAll('[data-content-type=\"table\"] table');\n tables.forEach((table) => {\n const tableWrapper = document.createElement(\"div\");\n tableWrapper.className = \"tableWrapper\";\n const tableWrapperInner = document.createElement(\"div\");\n tableWrapperInner.className = \"tableWrapper-inner\";\n\n tableWrapper.appendChild(tableWrapperInner);\n table.parentElement?.appendChild(tableWrapper);\n tableWrapper.appendChild(table);\n });\n\n return element;\n};\n\n// Adds trailing breaks to blocks with empty inline content. This is normally\n// done by ProseMirror, but only when rendering an actual editor. Without them,\n// empty inline content has a height of 0.\nconst addTrailingBreakToEmptyInlineContent = (element: HTMLElement) => {\n const emptyInlineContent = element.querySelectorAll(\n \".bn-inline-content:empty\",\n );\n emptyInlineContent.forEach((inlineContent) => {\n // We actually use a `span` instead of a `br` to avoid potential false\n // positives when parsing.\n const trailingBreak = document.createElement(\"span\");\n trailingBreak.className = \"ProseMirror-trailingBreak\";\n trailingBreak.setAttribute(\"style\", \"display: inline-block;\");\n\n inlineContent.appendChild(trailingBreak);\n });\n\n return element;\n};\n\n// Used to serialize BlockNote blocks and ProseMirror nodes to HTML without\n// losing data. Blocks are exported using the `toInternalHTML` method in their\n// `blockSpec`.\n//\n// The HTML created by this serializer is the same as what's rendered by the\n// editor to the DOM. This means that it retains the same structure as the\n// editor, including the `blockGroup` and `blockContainer` wrappers. This also\n// means that it can be converted back to the original blocks without any data\n// loss.\nexport const createInternalHTMLSerializer = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n schema: Schema,\n editor: BlockNoteEditor<BSchema, I, S>,\n) => {\n const serializer = DOMSerializer.fromSchema(schema);\n\n // Set of transforms to run on the output HTML element after serializing\n // blocks. These are used to add HTML elements, attributes, or class names\n // which would normally be done by extensions and plugins. Since these don't\n // run when converting blocks to HTML, tranforms are used to mock their\n // functionality so that the rendered HTML looks identical to that of a live\n // editor.\n const transforms: ((element: HTMLElement) => HTMLElement)[] = [\n addIndexToNumberedListItems,\n makeCheckListItemsReadOnly,\n forceToggleBlocksShow,\n addTableMinCellWidths,\n addTableWrappers,\n addTrailingBreakToEmptyInlineContent,\n ];\n\n return {\n serializeBlocks: (\n blocks: PartialBlock<BSchema, I, S>[],\n options: { document?: Document },\n ) => {\n let element = serializeBlocksInternalHTML(\n editor,\n blocks,\n serializer,\n options,\n );\n\n for (const transform of transforms) {\n element = transform(element);\n }\n\n return element.outerHTML;\n },\n };\n};\n","import { digestString } from \"lib0/hash/fnv1a\";\nimport type { User, UserStore } from \"./UserStore.js\";\n\n/**\n * Deterministic hash of a string to an unsigned 32-bit integer.\n */\nconst hashStr = (s: string): number => {\n let hash = 0;\n for (let i = 0; i < s.length; i++) {\n hash = Math.imul(31, hash) + s.charCodeAt(i);\n }\n return Math.abs(hash);\n};\n\n/**\n * Fallback palette used when a user has no resolved color of their own.\n *\n * Deliberately free of red and green: these colors tint *insertions* as well as\n * deletions, and diffs conventionally use red for deleted and green for\n * inserted content. A red insertion would read as a deletion, and a green\n * deletion as an insertion. The hues are spread far enough apart to stay\n * distinguishable for the most common forms of colour-vision deficiency.\n */\nexport const userColorPalette: Array<{ light: string; dark: string }> = [\n { light: \"#fff0c2\", dark: \"#8a6d1a\" }, // amber\n { light: \"#cdeffd\", dark: \"#0b6a8a\" }, // sky\n { light: \"#d6defd\", dark: \"#2948b3\" }, // blue\n { light: \"#eadcfb\", dark: \"#6b2fa3\" }, // violet\n { light: \"#f1e2d3\", dark: \"#7a4a1e\" }, // brown\n { light: \"#dfe4ea\", dark: \"#46525f\" }, // slate\n];\n\n/** The deterministic {@link userColorPalette} entry for a single user id. */\nexport const fallbackColorForUserId = (\n id: string,\n): { light: string; dark: string } =>\n userColorPalette[hashStr(id) % userColorPalette.length];\n\n/**\n * A user's own mark colors, or `undefined` when they have none.\n *\n * `color` is the saturated color the app already uses for that user (cursors,\n * avatars); `colorLight` is the pale background a mark is highlighted with. Most\n * applications only set the former, so derive the latter rather than fall back\n * to a palette entry that has nothing to do with the user's actual color — a\n * user whose cursor is green shouldn't have amber marks.\n */\nexport const userMarkColors = (\n user: Pick<User, \"color\" | \"colorLight\"> | undefined,\n): { light: string; dark: string } | undefined => {\n if (!user?.color) {\n return undefined;\n }\n return {\n light: user.colorLight ?? `color-mix(in srgb, ${user.color} 30%, white)`,\n dark: user.color,\n };\n};\n\n/**\n * The (first) user's {@link userMarkColors}, or their\n * {@link fallbackColorForUserId} palette entry. Used where a concrete color\n * string is needed (the portaled hover tooltip); marks themselves use the\n * cascaded {@link userColorVarNames} properties instead.\n */\nexport const colorsForUserIds = (\n userStore: UserStore,\n userIds: readonly string[] | undefined | null,\n): { light: string; dark: string } => {\n if (!userIds || userIds.length === 0) {\n return userColorPalette[0];\n }\n const firstId = userIds[0];\n return (\n userMarkColors(userStore.getUser(firstId)) ??\n fallbackColorForUserId(firstId)\n );\n};\n\n/**\n * Reduce a user id to a fixed-width `[0-9a-f]` token safe to embed in a CSS\n * custom-property name. Uses the (non-cryptographic) FNV-1a 32-bit hash; a\n * collision only means two authors share a highlight color.\n */\nexport const cssVarUserId = (id: string): string =>\n digestString(id).toString(16).padStart(8, \"0\");\n\n/**\n * The `--user-color-<key>-{light,dark}` custom-property names for a user. Set on\n * the editor root by `AttributionExtension`, read by the mark wrapper via\n * `var(..., <fallback>)`.\n */\nexport const userColorVarNames = (\n id: string,\n): { light: string; dark: string } => {\n const key = cssVarUserId(id);\n return {\n light: `--user-color-${key}-light`,\n dark: `--user-color-${key}-dark`,\n };\n};\n","// from https://raw.githubusercontent.com/ueberdosis/tiptap/develop/packages/core/src/EventEmitter.ts (MIT)\n\ntype StringKeyOf<T> = Extract<keyof T, string>;\ntype CallbackType<\n T extends Record<string, any>,\n EventName extends StringKeyOf<T>,\n> = T[EventName] extends any[] ? T[EventName] : [T[EventName]];\ntype CallbackFunction<\n T extends Record<string, any>,\n EventName extends StringKeyOf<T>,\n> = (...props: CallbackType<T, EventName>) => any;\n\nexport class EventEmitter<T extends Record<string, any>> {\n // eslint-disable-next-line @typescript-eslint/ban-types\n private callbacks: { [key: string]: Function[] } = {};\n\n public on<EventName extends StringKeyOf<T>>(\n event: EventName,\n fn: CallbackFunction<T, EventName>,\n ) {\n if (!this.callbacks[event]) {\n this.callbacks[event] = [];\n }\n\n this.callbacks[event].push(fn);\n\n return () => this.off(event, fn);\n }\n\n protected emit<EventName extends StringKeyOf<T>>(\n event: EventName,\n ...args: CallbackType<T, EventName>\n ) {\n const callbacks = this.callbacks[event];\n\n if (callbacks) {\n callbacks.forEach((callback) => callback.apply(this, args));\n }\n }\n\n public off<EventName extends StringKeyOf<T>>(\n event: EventName,\n fn?: CallbackFunction<T, EventName>,\n ) {\n const callbacks = this.callbacks[event];\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter((callback) => callback !== fn);\n } else {\n delete this.callbacks[event];\n }\n }\n }\n\n protected removeAllListeners(): void {\n this.callbacks = {};\n }\n}\n","import type { NodeType, Schema } from \"prosemirror-model\";\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n Transaction,\n} from \"prosemirror-state\";\nimport { CellSelection } from \"prosemirror-tables\";\n\nimport { Block } from \"../../../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../../../editor/BlockNoteEditor\";\nimport { BlockIdentifier } from \"../../../../schema/index.js\";\nimport {\n isLayoutNode,\n isNamedOnly,\n} from \"../../../../schema/blocks/children.js\";\nimport {\n getInsertionPos,\n getBlockInfoAt,\n getBlockInfoNearPos,\n getNodeId,\n} from \"../../../getBlockInfoFromPos.js\";\nimport { getNodeById } from \"../../../nodeUtil.js\";\nimport { insertBlocks } from \"../insertBlocks/insertBlocks.js\";\nimport { removeAndInsertBlocks } from \"../replaceBlocks/replaceBlocks.js\";\n\n/**\n * Dissolves `placeable: \"namedOnly\"` blocks into their children.\n *\n * A `namedOnly` block (a `column`, say) is defined only in terms of the\n * layout block that holds it, so it can't land anywhere a regular block goes —\n * moving one out of its layout block moves its children instead. Every other\n * block passes through as itself.\n */\nfunction dissolveLayoutOnlyBlocks(\n blocks: Block<any, any, any>[],\n pmSchema: Schema,\n): Block<any, any, any>[] {\n return blocks.flatMap((block) =>\n isNamedOnly(pmSchema.nodes[block.type])\n ? dissolveLayoutOnlyBlocks(block.children, pmSchema)\n : [block],\n );\n}\n\ntype BlockSelectionData = (\n | {\n type: \"text\";\n headBlockId: string;\n anchorOffset: number;\n headOffset: number;\n }\n | {\n type: \"node\";\n }\n | {\n type: \"cell\";\n anchorCellOffset: number;\n headCellOffset: number;\n }\n) & {\n anchorBlockId: string;\n};\n\n/**\n * `getBlockSelectionData` and `updateBlockSelectionFromData` are used to save\n * and restore the selection within a block, when the block is moved. This is\n * done by first saving the offsets of the anchor and head from the before\n * positions of their surrounding blocks, as well as the IDs of those blocks. We\n * can then recreate the selection by finding the blocks with those IDs, getting\n * their before positions, and adding the offsets to those positions.\n * @param editor The BlockNote editor instance to get the selection data from.\n */\nfunction getBlockSelectionData(\n editor: BlockNoteEditor<any, any, any>,\n): BlockSelectionData {\n return editor.transact((tr) => {\n const anchorBlockPosInfo = getBlockInfoNearPos(tr, tr.selection.anchor);\n\n const anchorBlockId = getNodeId(anchorBlockPosInfo.block.node, tr.doc);\n\n if (tr.selection instanceof CellSelection) {\n return {\n type: \"cell\" as const,\n anchorBlockId,\n anchorCellOffset:\n tr.selection.$anchorCell.pos - anchorBlockPosInfo.block.beforePos,\n headCellOffset:\n tr.selection.$headCell.pos - anchorBlockPosInfo.block.beforePos,\n };\n } else if (tr.selection instanceof NodeSelection) {\n return {\n type: \"node\" as const,\n anchorBlockId,\n };\n } else {\n const headBlockPosInfo = getBlockInfoNearPos(tr, tr.selection.head);\n\n return {\n type: \"text\" as const,\n anchorBlockId,\n headBlockId: getNodeId(headBlockPosInfo.block.node, tr.doc),\n anchorOffset: tr.selection.anchor - anchorBlockPosInfo.block.beforePos,\n headOffset: tr.selection.head - headBlockPosInfo.block.beforePos,\n };\n }\n });\n}\n\n/**\n * `getBlockSelectionData` and `updateBlockSelectionFromData` are used to save\n * and restore the selection within a block, when the block is moved. This is\n * done by first saving the offsets of the anchor and head from the before\n * positions of their surrounding blocks, as well as the IDs of those blocks. We\n * can then recreate the selection by finding the blocks with those IDs, getting\n * their before positions, and adding the offsets to those positions.\n * @param tr The transaction to update the selection in.\n * @param data The selection data to update the selection with (generated by\n * `getBlockSelectionData`).\n */\nfunction updateBlockSelectionFromData(\n tr: Transaction,\n data: BlockSelectionData,\n) {\n const anchorBlockPos = getNodeById(data.anchorBlockId, tr.doc)?.posBeforeNode;\n if (anchorBlockPos === undefined) {\n throw new Error(\n `Could not find block with ID ${data.anchorBlockId} to update selection`,\n );\n }\n\n let selection: Selection;\n if (data.type === \"cell\") {\n selection = CellSelection.create(\n tr.doc,\n anchorBlockPos + data.anchorCellOffset,\n anchorBlockPos + data.headCellOffset,\n );\n } else if (data.type === \"node\") {\n const blockInfo = getBlockInfoAt(tr.doc, anchorBlockPos);\n selection = NodeSelection.create(\n tr.doc,\n blockInfo.hasContent ? blockInfo.content.beforePos : anchorBlockPos,\n );\n } else {\n const headBlockPos = getNodeById(data.headBlockId, tr.doc)?.posBeforeNode;\n if (headBlockPos === undefined) {\n throw new Error(\n `Could not find block with ID ${data.headBlockId} to update selection`,\n );\n }\n\n selection = TextSelection.create(\n tr.doc,\n anchorBlockPos + data.anchorOffset,\n headBlockPos + data.headOffset,\n );\n }\n\n tr.setSelection(selection);\n}\n\n/**\n * Removes the given blocks from the editor, then inserts them before/after a\n * reference block.\n * @param editor The BlockNote editor instance to move the blocks in.\n * @param blocks The blocks to move.\n * @param referenceBlock The reference block to insert the blocks before/after.\n * @param placement Whether to insert the blocks before or after the reference\n * block.\n */\nexport function moveBlocks(\n editor: BlockNoteEditor<any, any, any>,\n blocks: Block<any, any, any>[],\n referenceBlock: BlockIdentifier,\n placement: \"before\" | \"after\",\n) {\n editor.transact((tr) => {\n // Don't fix columns/columnLists in the removal step. Since a move is a\n // rearrangement rather than a deletion, columns that it empties out are\n // deliberately left as-is instead of being collapsed - this keeps moves\n // free of side effects (and reversible by moving back), and matches\n // dragging a block out of a column, which doesn't collapse it either.\n // Fixing them mid-move also broke the following case:\n // <column>\n // <paragraph></paragraph>\n // <paragraph>Paragraph</paragraph>\n // </column>\n // When the non-empty block is moved up, the column is seen as empty and\n // collapsed in the removal step, so the following insertion fails.\n removeAndInsertBlocks(tr, blocks, [], { fixLayoutBlocks: false });\n insertBlocks<any, any, any>(\n tr,\n dissolveLayoutOnlyBlocks(blocks, editor.pmSchema),\n referenceBlock,\n placement,\n );\n });\n}\n\n/**\n * Removes the selected blocks from the editor, then inserts them before/after a\n * reference block. Also updates the selection to match the original selection\n * using `getBlockSelectionData` and `updateBlockSelectionFromData`.\n * @param editor The BlockNote editor instance to move the blocks in.\n * @param referenceBlock The reference block to insert the selected blocks\n * before/after.\n * @param placement Whether to insert the selected blocks before or after the\n * reference block.\n */\nexport function moveSelectedBlocksAndSelection(\n editor: BlockNoteEditor<any, any, any>,\n referenceBlock: BlockIdentifier,\n placement: \"before\" | \"after\",\n) {\n // We want this to be a single step in the undo history\n editor.transact((tr) => {\n const blocks = editor.getSelection()?.blocks || [\n editor.getTextCursorPosition().block,\n ];\n const selectionData = getBlockSelectionData(editor);\n\n moveBlocks(editor, blocks, referenceBlock, placement);\n\n updateBlockSelectionFromData(tr, selectionData);\n });\n}\n\n/** The first node type inserted after dissolving layout-only blocks. */\nfunction getMovedNodeType(\n editor: BlockNoteEditor<any, any, any>,\n block: Block<any, any, any>,\n): NodeType {\n const first = dissolveLayoutOnlyBlocks([block], editor.pmSchema)[0];\n const type = first && editor.pmSchema.nodes[first.type];\n return type && isLayoutNode(type)\n ? type\n : editor.pmSchema.nodes[\"blockContainer\"];\n}\n\n/**\n * Searches in document order for a placement accepted by the moved node's type.\n * Moving past a sibling with children enters its nearest child; reaching the\n * end of a sibling list moves outside its parent.\n */\nfunction getMovePlacement(\n editor: BlockNoteEditor<any, any, any>,\n nodeType: NodeType,\n direction: \"up\" | \"down\",\n sibling?: Block<any, any, any>,\n parent?: Block<any, any, any>,\n):\n | { referenceBlock: BlockIdentifier; placement: \"before\" | \"after\" }\n | undefined {\n const outside = direction === \"up\" ? \"before\" : \"after\";\n const inside = direction === \"up\" ? \"after\" : \"before\";\n while (sibling || parent) {\n const hasChildren = sibling && sibling.children.length > 0;\n const referenceBlock = sibling\n ? hasChildren\n ? sibling.children[direction === \"up\" ? sibling.children.length - 1 : 0]\n : sibling\n : parent!;\n const placement = hasChildren ? inside : outside;\n const valid = editor.transact((tr) => {\n const target = getNodeById(referenceBlock.id, tr.doc);\n return (\n target !== undefined &&\n getInsertionPos(\n tr.doc,\n getBlockInfoAt(tr.doc, target.posBeforeNode),\n placement,\n nodeType,\n ) !== null\n );\n });\n if (valid) {\n return { referenceBlock, placement };\n }\n parent = editor.getParentBlock(referenceBlock);\n sibling =\n placement === inside\n ? referenceBlock\n : direction === \"up\"\n ? editor.getPrevBlock(referenceBlock)\n : editor.getNextBlock(referenceBlock);\n }\n return undefined;\n}\n\nfunction moveBlocksInDirection(\n editor: BlockNoteEditor<any, any, any>,\n direction: \"up\" | \"down\",\n blockIdentifier?: BlockIdentifier,\n) {\n editor.transact(() => {\n let blocks: Block<any, any, any>[];\n if (blockIdentifier) {\n const block = editor.getBlock(blockIdentifier);\n if (!block) {\n return;\n }\n blocks = [block];\n } else {\n blocks = editor.getSelection()?.blocks || [\n editor.getTextCursorPosition().block,\n ];\n }\n\n // The last selected block anchors a downward move, but insertion always\n // starts with the first selected block.\n const sourceBlock = blocks[direction === \"up\" ? 0 : blocks.length - 1];\n const target = getMovePlacement(\n editor,\n getMovedNodeType(editor, blocks[0]),\n direction,\n direction === \"up\"\n ? editor.getPrevBlock(sourceBlock)\n : editor.getNextBlock(sourceBlock),\n editor.getParentBlock(sourceBlock),\n );\n if (!target) {\n return;\n }\n\n if (blockIdentifier) {\n moveBlocks(editor, blocks, target.referenceBlock, target.placement);\n } else {\n moveSelectedBlocksAndSelection(\n editor,\n target.referenceBlock,\n target.placement,\n );\n }\n });\n}\n\nexport function moveBlocksUp(\n editor: BlockNoteEditor<any, any, any>,\n blockIdentifier?: BlockIdentifier,\n) {\n moveBlocksInDirection(editor, \"up\", blockIdentifier);\n}\n\nexport function moveBlocksDown(\n editor: BlockNoteEditor<any, any, any>,\n blockIdentifier?: BlockIdentifier,\n) {\n moveBlocksInDirection(editor, \"down\", blockIdentifier);\n}\n","import { Fragment, Node, NodeRange, NodeType, Slice } from \"prosemirror-model\";\nimport { Transaction } from \"prosemirror-state\";\nimport { canJoin, liftTarget, ReplaceAroundStep } from \"prosemirror-transform\";\n\nimport { BlockNoteEditor } from \"../../../../editor/BlockNoteEditor.js\";\nimport { CHILD_CONTAINER_GROUP } from \"../../../../schema/blocks/children.js\";\nimport { nodeToBlock } from \"../../../nodeConversions/nodeToBlock.js\";\n\n/**\n * Whether `node` is the sibling list that nesting and unnesting operate on: a\n * node that holds child blocks, and can hold the kind of node being moved.\n *\n * `blockRange` stops at the *deepest* ancestor matching this, so the second\n * condition is load-bearing. A `columnList` holds child blocks, but only\n * `column`s — matching it would resolve the range at the columns themselves,\n * where `sinkItem`'s `nodeBefore` is a `column` rather than a `blockContainer`\n * and `liftItem`'s parent is a `blockGroup` rather than a `blockContainer`, so\n * both bail. Skipping it lets the walk continue out to the `blockGroup` the\n * list sits in, and Tab across two columns indents the list as a unit.\n */\nfunction holdsItems(node: Node, itemType: NodeType) {\n return (\n node.childCount > 0 &&\n node.type.isInGroup(CHILD_CONTAINER_GROUP) &&\n node.type.contentMatch.matchType(itemType) !== null\n );\n}\n\n/**\n * Modified version of prosemirror-schema-list's sinkItem.\n * https://github.com/ProseMirror/prosemirror-schema-list/blob/master/src/schema-list.ts\n *\n * Changes from the original:\n * 1. Range predicate checks node.type instead of firstChild.type\n * 2. nestedBefore checks groupType instead of parent.type\n * 3. Slice creates groupType instead of parent.type\n * 4. Operates on Transaction directly instead of state+dispatch\n * 5. Opens the slice into the previous sibling's child group, not into the\n * group's last child. The original cut one level deeper to keep `insert`\n * at 1; that failed when the last child was a layout block node (a column\n * list), which a `blockContainer` can't be joined onto.\n */\nfunction sinkItem(tr: Transaction, itemType: NodeType, groupType: NodeType) {\n const { $from, $to } = tr.selection;\n const range = $from.blockRange($to, (node) => holdsItems(node, itemType)); // change 1\n if (!range) {\n return false;\n }\n const startIndex = range.startIndex;\n if (startIndex === 0) {\n return false;\n }\n const parent = range.parent;\n const nodeBefore = parent.child(startIndex - 1);\n if (nodeBefore.type !== itemType) {\n return false;\n }\n const nestedBefore =\n nodeBefore.lastChild && nodeBefore.lastChild.type === groupType; // change 2\n // The slice opens into the previous sibling and, when it already has a child\n // group, into that group, so the block becomes its last child. (change 5)\n const depth = nestedBefore ? 2 : 1;\n const slice = new Slice(\n Fragment.from(itemType.create(null, Fragment.from(groupType.create()))), // change 3\n depth,\n 0,\n );\n\n const before = range.start;\n const after = range.end;\n\n // Nothing above can make the schema refuse this step: `parent` holds\n // regular blocks, so it may lose one (a layout block of any blocks has no\n // `min` above 1), and the slice only joins the previous sibling and its\n // group. A refusal here would be a bug, so it throws.\n tr.step(\n new ReplaceAroundStep(\n before - depth,\n after,\n before,\n after,\n slice,\n // `Slice.insertAt` adds the slice's open depth, so this lands at content\n // position 2: inside the group.\n 2 - depth,\n true,\n ),\n ).scrollIntoView();\n\n return true;\n}\n\nfunction nestCommand(editor: BlockNoteEditor<any, any, any>) {\n return (tr: Transaction) =>\n sinkItem(\n tr,\n editor.pmSchema.nodes[\"blockContainer\"],\n editor.pmSchema.nodes[\"blockGroup\"],\n );\n}\n\nexport function nestBlock(editor: BlockNoteEditor<any, any, any>) {\n return editor.transact(nestCommand(editor));\n}\n\n/**\n * Modified version of prosemirror-schema-list's liftToOuterList.\n * https://github.com/ProseMirror/prosemirror-schema-list/blob/master/src/schema-list.ts\n *\n * Changes from the original:\n * 1. Operates on Transaction directly instead of state+dispatch (TipTap compat)\n * 2. When the lifted block already has children (a groupType child), uses deeper\n * openStart/offset so siblings merge into the existing group instead of\n * creating a second one (which would violate blockContainer's schema)\n * 3. Uses groupType.create() instead of range.parent.copy() (same as sinkItem)\n */\nfunction liftToOuterList(\n tr: Transaction,\n itemType: NodeType,\n groupType: NodeType, // change 3\n range: NodeRange,\n) {\n const end = range.end;\n const endOfList = range.$to.end(range.depth);\n\n if (end < endOfList) {\n // There are siblings after the lifted items, which must become\n // children of the last item\n const blockBeingLifted = range.parent.child(range.endIndex - 1);\n const nestedAfter =\n blockBeingLifted.lastChild &&\n blockBeingLifted.lastChild.type === groupType; // change 2\n\n tr.step(\n new ReplaceAroundStep(\n end - (nestedAfter ? 2 : 1), // change 2: go deeper when merging into existing children\n endOfList,\n end,\n endOfList,\n new Slice(\n Fragment.from(\n itemType.create(null, groupType.create()), // change 3\n ),\n nestedAfter ? 2 : 1, // change 2: open deeper when merging into existing children\n 0,\n ),\n nestedAfter ? 0 : 1, // change 2: Slice.insertAt offsets by openStart, so 0+2=2 lands inside existing bg\n true,\n ),\n );\n range = new NodeRange(\n tr.doc.resolve(range.$from.pos),\n tr.doc.resolve(endOfList),\n range.depth,\n );\n }\n\n const target = liftTarget(range);\n if (target == null) {\n return false;\n }\n\n tr.lift(range, target);\n\n const $after = tr.doc.resolve(tr.mapping.map(end, -1) - 1);\n if (\n canJoin(tr.doc, $after.pos) &&\n $after.nodeBefore!.type === $after.nodeAfter!.type\n ) {\n tr.join($after.pos);\n }\n\n tr.scrollIntoView();\n return true;\n}\n\n/**\n * Modified version of prosemirror-schema-list's liftListItem.\n * https://github.com/ProseMirror/prosemirror-schema-list/blob/master/src/schema-list.ts\n *\n * Changes from the original:\n * 1. Range predicate checks node.type instead of firstChild.type (same as sinkItem)\n * 2. Passes groupType to liftToOuterList\n * 3. Operates on Transaction directly instead of state+dispatch\n * 4. Skips liftOutOfList (root-level blocks can't be unnested in BlockNote)\n */\nexport function liftItem(\n tr: Transaction,\n itemType: NodeType,\n groupType: NodeType, // change 2\n // Whether a block may be outdented out of `parent` (its\n // `keyboard.childrenCanOutdent` setting).\n canOutdentFrom: (parent: Node) => boolean,\n) {\n const { $from, $to } = tr.selection;\n const range = $from.blockRange($to, (node) => holdsItems(node, itemType)); // change 1\n if (!range) {\n return false;\n }\n\n const parent = $from.node(range.depth - 1);\n // A block whose children can't be outdented keeps them: unnesting stops at\n // its edge rather than lifting the block out of it.\n if (parent.type === itemType && !canOutdentFrom(parent)) {\n return false;\n }\n\n if (parent.type === itemType) {\n // Inside a parent node\n return liftToOuterList(tr, itemType, groupType, range); // change 2\n }\n\n // This is the \"liftOutOfList\" path — lifting out of a list entirely.\n // Not applicable to BlockNote (root-level blocks can't be unnested). // change 4\n return false;\n}\n\nfunction unnestCommand(editor: BlockNoteEditor<any, any, any>) {\n return (tr: Transaction) =>\n liftItem(\n tr,\n editor.pmSchema.nodes[\"blockContainer\"],\n editor.pmSchema.nodes[\"blockGroup\"],\n (parent) => {\n const block = nodeToBlock(parent, tr.doc);\n return editor.schema.blockSpecs[block.type].implementation.keyboard(\n block,\n ).childrenCanOutdent;\n },\n );\n}\n\nexport function unnestBlock(editor: BlockNoteEditor<any, any, any>) {\n return editor.transact(unnestCommand(editor));\n}\n\n// `canExec` hands the command a transaction it never dispatches, so \"can I\n// nest?\" is answered by nesting and throwing the result away. A second\n// statement of the preconditions would drift from the command it describes —\n// and did: it read a previous sibling's mere existence, so a layout block\n// before the cursor enabled the button while `nestBlock` did nothing.\nexport function canNestBlock(editor: BlockNoteEditor<any, any, any>) {\n return editor.canExec((state) => nestCommand(editor)(state.tr));\n}\n\nexport function canUnnestBlock(editor: BlockNoteEditor<any, any, any>) {\n return editor.canExec((state) => unnestCommand(editor)(state.tr));\n}\n","import type { Node } from \"prosemirror-model\";\nimport type { Block } from \"../../../blocks/defaultBlocks.js\";\nimport type {\n BlockIdentifier,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { getParentBlockInfo } from \"../../getBlockInfoFromPos.js\";\nimport { nodeToBlock } from \"../../nodeConversions/nodeToBlock.js\";\nimport { getNodeById } from \"../../nodeUtil.js\";\n\nexport function getBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n doc: Node,\n blockIdentifier: BlockIdentifier,\n): Block<BSchema, I, S> | undefined {\n const id =\n typeof blockIdentifier === \"string\" ? blockIdentifier : blockIdentifier.id;\n\n const posInfo = getNodeById(id, doc);\n if (!posInfo) {\n return undefined;\n }\n\n return nodeToBlock(posInfo.node, doc);\n}\n\nexport function getPrevBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n doc: Node,\n blockIdentifier: BlockIdentifier,\n): Block<BSchema, I, S> | undefined {\n const id =\n typeof blockIdentifier === \"string\" ? blockIdentifier : blockIdentifier.id;\n\n const posInfo = getNodeById(id, doc);\n if (!posInfo) {\n return undefined;\n }\n\n const $posBeforeNode = doc.resolve(posInfo.posBeforeNode);\n const nodeToConvert = $posBeforeNode.nodeBefore;\n if (!nodeToConvert) {\n return undefined;\n }\n\n return nodeToBlock(nodeToConvert, doc);\n}\n\nexport function getNextBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n doc: Node,\n blockIdentifier: BlockIdentifier,\n): Block<BSchema, I, S> | undefined {\n const id =\n typeof blockIdentifier === \"string\" ? blockIdentifier : blockIdentifier.id;\n const posInfo = getNodeById(id, doc);\n if (!posInfo) {\n return undefined;\n }\n\n const $posAfterNode = doc.resolve(\n posInfo.posBeforeNode + posInfo.node.nodeSize,\n );\n const nodeToConvert = $posAfterNode.nodeAfter;\n if (!nodeToConvert) {\n return undefined;\n }\n\n return nodeToBlock(nodeToConvert, doc);\n}\n\nexport function getParentBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n doc: Node,\n blockIdentifier: BlockIdentifier,\n): Block<BSchema, I, S> | undefined {\n const id =\n typeof blockIdentifier === \"string\" ? blockIdentifier : blockIdentifier.id;\n const posInfo = getNodeById(id, doc);\n if (!posInfo) {\n return undefined;\n }\n\n const parentInfo = getParentBlockInfo(doc, posInfo.posBeforeNode);\n if (!parentInfo) {\n return undefined;\n }\n\n return nodeToBlock(parentInfo.block.node, doc);\n}\n","import type { BlockPlacement } from \"../../api/getBlockInfoFromPos.js\";\nimport { insertBlocks } from \"../../api/blockManipulation/commands/insertBlocks/insertBlocks.js\";\nimport {\n moveBlocksDown,\n moveBlocksUp,\n} from \"../../api/blockManipulation/commands/moveBlocks/moveBlocks.js\";\nimport {\n canNestBlock,\n canUnnestBlock,\n nestBlock,\n unnestBlock,\n} from \"../../api/blockManipulation/commands/nestBlock/nestBlock.js\";\nimport { removeAndInsertBlocks } from \"../../api/blockManipulation/commands/replaceBlocks/replaceBlocks.js\";\nimport { updateBlock } from \"../../api/blockManipulation/commands/updateBlock/updateBlock.js\";\nimport {\n getBlock,\n getNextBlock,\n getParentBlock,\n getPrevBlock,\n} from \"../../api/blockManipulation/getBlock/getBlock.js\";\nimport { docToBlocks } from \"../../api/nodeConversions/nodeToBlock.js\";\nimport {\n Block,\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n PartialBlock,\n} from \"../../blocks/defaultBlocks.js\";\nimport {\n BlockIdentifier,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { BlockNoteEditor } from \"../BlockNoteEditor.js\";\n\nexport class BlockManager<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> {\n constructor(private editor: BlockNoteEditor<BSchema, ISchema, SSchema>) {}\n\n /**\n * Gets a snapshot of all top-level (non-nested) blocks in the editor.\n * @returns A snapshot of all top-level (non-nested) blocks in the editor.\n */\n public get document(): Block<BSchema, ISchema, SSchema>[] {\n return this.editor.transact((tr) => {\n return docToBlocks(tr.doc);\n });\n }\n\n /**\n * Gets a snapshot of an existing block from the editor.\n * @param blockIdentifier The identifier of an existing block that should be\n * retrieved.\n * @returns The block that matches the identifier, or `undefined` if no\n * matching block was found.\n */\n public getBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this.editor.transact((tr) => getBlock(tr.doc, blockIdentifier));\n }\n\n /**\n * Gets a snapshot of the previous sibling of an existing block from the\n * editor.\n * @param blockIdentifier The identifier of an existing block for which the\n * previous sibling should be retrieved.\n * @returns The previous sibling of the block that matches the identifier.\n * `undefined` if no matching block was found, or it's the first child/block\n * in the document.\n */\n public getPrevBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this.editor.transact((tr) => getPrevBlock(tr.doc, blockIdentifier));\n }\n\n /**\n * Gets a snapshot of the next sibling of an existing block from the editor.\n * @param blockIdentifier The identifier of an existing block for which the\n * next sibling should be retrieved.\n * @returns The next sibling of the block that matches the identifier.\n * `undefined` if no matching block was found, or it's the last child/block in\n * the document.\n */\n public getNextBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this.editor.transact((tr) => getNextBlock(tr.doc, blockIdentifier));\n }\n\n /**\n * Gets a snapshot of the parent of an existing block from the editor.\n * @param blockIdentifier The identifier of an existing block for which the\n * parent should be retrieved.\n * @returns The parent of the block that matches the identifier. `undefined`\n * if no matching block was found, or the block isn't nested.\n */\n public getParentBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this.editor.transact((tr) =>\n getParentBlock(tr.doc, blockIdentifier),\n );\n }\n\n /**\n * Traverses all blocks in the editor depth-first, and executes a callback for each.\n * @param callback The callback to execute for each block. Returning `false` stops the traversal.\n * @param reverse Whether the blocks should be traversed in reverse order.\n */\n public forEachBlock(\n callback: (block: Block<BSchema, ISchema, SSchema>) => boolean,\n reverse = false,\n ): void {\n const blocks = this.document.slice();\n\n if (reverse) {\n blocks.reverse();\n }\n\n function traverseBlockArray(\n blockArray: Block<BSchema, ISchema, SSchema>[],\n ): boolean {\n for (const block of blockArray) {\n if (callback(block) === false) {\n return false;\n }\n\n const children = reverse\n ? block.children.slice().reverse()\n : block.children;\n\n if (!traverseBlockArray(children)) {\n return false;\n }\n }\n\n return true;\n }\n\n traverseBlockArray(blocks);\n }\n\n /**\n * Inserts new blocks into the editor. If a block's `id` is undefined, BlockNote generates one automatically. Throws an\n * error if the reference block could not be found.\n * @param blocksToInsert An array of partial blocks that should be inserted.\n * @param referenceBlock An identifier for an existing block, at which the new blocks should be inserted.\n * @param placement Where the blocks go relative to the `referenceBlock`: as its previous (`\"before\"`) or next\n * (`\"after\"`) sibling, or nested inside it as its first (`\"first-child\"`) or last (`\"last-child\"`) children.\n */\n public insertBlocks(\n blocksToInsert: PartialBlock<BSchema, ISchema, SSchema>[],\n referenceBlock: BlockIdentifier,\n placement: BlockPlacement = \"before\",\n ) {\n return this.editor.transact((tr) =>\n insertBlocks(tr, blocksToInsert, referenceBlock, placement),\n );\n }\n\n /**\n * Updates an existing block in the editor. Since updatedBlock is a PartialBlock object, some fields might not be\n * defined. These undefined fields are kept as-is from the existing block. Throws an error if the block to update could\n * not be found.\n * @param blockToUpdate The block that should be updated.\n * @param update A partial block which defines how the existing block should be changed.\n */\n public updateBlock(\n blockToUpdate: BlockIdentifier,\n update: PartialBlock<BSchema, ISchema, SSchema>,\n ) {\n return this.editor.transact((tr) => updateBlock(tr, blockToUpdate, update));\n }\n\n /**\n * Removes existing blocks from the editor. Throws an error if any of the blocks could not be found.\n * @param blocksToRemove An array of identifiers for existing blocks that should be removed.\n */\n public removeBlocks(blocksToRemove: BlockIdentifier[]) {\n return this.editor.transact(\n (tr) => removeAndInsertBlocks(tr, blocksToRemove, []).removedBlocks,\n );\n }\n\n /**\n * Replaces existing blocks in the editor with new blocks. If the blocks that should be removed are not adjacent or\n * are at different nesting levels, `blocksToInsert` will be inserted at the position of the first block in\n * `blocksToRemove`. Throws an error if any of the blocks to remove could not be found.\n * @param blocksToRemove An array of blocks that should be replaced.\n * @param blocksToInsert An array of partial blocks to replace the old ones with.\n */\n public replaceBlocks(\n blocksToRemove: BlockIdentifier[],\n blocksToInsert: PartialBlock<BSchema, ISchema, SSchema>[],\n ) {\n return this.editor.transact((tr) =>\n removeAndInsertBlocks(tr, blocksToRemove, blocksToInsert),\n );\n }\n\n /**\n * Checks if the block containing the text cursor can be nested.\n */\n public canNestBlock() {\n return canNestBlock(this.editor);\n }\n\n /**\n * Nests the block containing the text cursor into the block above it.\n */\n public nestBlock() {\n nestBlock(this.editor);\n }\n\n /**\n * Checks if the block containing the text cursor is nested.\n */\n public canUnnestBlock() {\n return canUnnestBlock(this.editor);\n }\n\n /**\n * Lifts the block containing the text cursor out of its parent.\n */\n public unnestBlock() {\n unnestBlock(this.editor);\n }\n\n /**\n * Moves the selected blocks up. If the previous block has children, moves\n * them to the end of its children. If there is no previous block, but the\n * current blocks share a common parent, moves them out of & before it. If a\n * `blockIdentifier` is provided, that block is moved instead of the\n * selection, and the selection is left unchanged.\n */\n public moveBlocksUp(blockIdentifier?: BlockIdentifier) {\n return moveBlocksUp(this.editor, blockIdentifier);\n }\n\n /**\n * Moves the selected blocks down. If the next block has children, moves\n * them to the start of its children. If there is no next block, but the\n * current blocks share a common parent, moves them out of & after it. If a\n * `blockIdentifier` is provided, that block is moved instead of the\n * selection, and the selection is left unchanged.\n */\n public moveBlocksDown(blockIdentifier?: BlockIdentifier) {\n return moveBlocksDown(this.editor, blockIdentifier);\n }\n}\n","import type { BlockNoteEditor } from \"../BlockNoteEditor.js\";\nimport {\n getBlocksChangedByTransaction,\n type BlocksChanged,\n} from \"../../api/getBlocksChangedByTransaction.js\";\nimport { Transaction } from \"prosemirror-state\";\nimport { EventEmitter } from \"../../util/EventEmitter.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\n\n/**\n * A function that can be used to unsubscribe from an event.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * Options shared by the focus APIs (`isFocused`, `onFocusChange`).\n */\nexport type EditorFocusOptions = {\n /**\n * When true, the editor's own UI - toolbars, menus and popovers inside\n * its DOM boundary or registered portal elements - counts as focused,\n * answering \"is the user still interacting with this editor?\" rather than\n * \"does the content area hold DOM focus?\".\n *\n * Events then fire only when that combined state changes, and only once\n * focus movement has settled, so a handoff from the content area into a\n * popover's input reports no blur at all. The default reports raw\n * content-area focus.\n */\n includeEditorUI?: boolean;\n};\n\n/**\n * EventManager is a class which manages the events of the editor\n */\nexport class EventManager<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> extends EventEmitter<{\n onChange: [\n ctx: {\n editor: BlockNoteEditor<BSchema, I, S>;\n transaction: Transaction;\n appendedTransactions: Transaction[];\n },\n ];\n onSelectionChange: [\n ctx: { editor: BlockNoteEditor<BSchema, I, S>; transaction: Transaction },\n ];\n onFocusChange: [\n ctx: {\n editor: BlockNoteEditor<BSchema, I, S>;\n focused: boolean;\n event: FocusEvent;\n },\n ];\n onFocusChangeWithinUI: [\n ctx: {\n editor: BlockNoteEditor<BSchema, I, S>;\n focused: boolean;\n event: FocusEvent;\n },\n ];\n onMount: [ctx: { editor: BlockNoteEditor<BSchema, I, S> }];\n onUnmount: [ctx: { editor: BlockNoteEditor<BSchema, I, S> }];\n}> {\n constructor(private editor: BlockNoteEditor<BSchema, I, S>) {\n super();\n // We register tiptap events only once the editor is finished initializing\n // otherwise we would be trying to register events on a tiptap editor which does not exist yet\n editor.on(\"create\", () => {\n editor._tiptapEditor.on(\n \"update\",\n ({ transaction, appendedTransactions }) => {\n this.emit(\"onChange\", { editor, transaction, appendedTransactions });\n },\n );\n editor._tiptapEditor.on(\"selectionUpdate\", ({ transaction }) => {\n this.emit(\"onSelectionChange\", { editor, transaction });\n });\n editor._tiptapEditor.on(\"focus\", ({ event }) => {\n this.emit(\"onFocusChange\", { editor, focused: true, event });\n });\n editor._tiptapEditor.on(\"blur\", ({ event }) => {\n this.emit(\"onFocusChange\", { editor, focused: false, event });\n });\n editor._tiptapEditor.on(\"mount\", () => {\n this.emit(\"onMount\", { editor });\n });\n editor._tiptapEditor.on(\"unmount\", () => {\n this.emit(\"onUnmount\", { editor });\n });\n\n let unsubscribeUIFocusTracker: Unsubscribe | undefined;\n this.onMount(() => {\n unsubscribeUIFocusTracker = this.attachUIFocusTracker();\n });\n this.onUnmount(() => {\n if (unsubscribeUIFocusTracker) {\n unsubscribeUIFocusTracker();\n }\n });\n });\n }\n\n /**\n * Settled focus-within-UI tracking. Document-level listeners (attached on\n * editor mount, detached on unmount — a no-op per focus event is too\n * cheap to be worth gating on subscribers) cover the case tiptap events\n * can't: focus moving from the editor's own UI outside the content area\n * (including registered portal elements) to somewhere else entirely.\n * Blur-side changes are re-checked after the current task because\n * `document.activeElement` transiently becomes `<body>` during focus\n * handoffs (and `relatedTarget` is unreliable on mobile).\n */\n private attachUIFocusTracker(): Unsubscribe {\n if (typeof document === \"undefined\") {\n return () => {};\n }\n let wasLastFocused = this.editor.isFocused({ includeEditorUI: true });\n let settleUiFocusedTimeout: ReturnType<typeof setTimeout> | undefined;\n\n const settleUIFocus = (event: FocusEvent) => {\n const focused = this.editor.isFocused({ includeEditorUI: true });\n if (focused !== wasLastFocused) {\n wasLastFocused = focused;\n this.emit(\"onFocusChangeWithinUI\", {\n editor: this.editor,\n focused,\n event,\n });\n }\n };\n // On focusin the new element already holds focus, so the state can be\n // read immediately.\n const onFocusIn = (event: FocusEvent) => settleUIFocus(event);\n\n // On focusout it can't: `document.activeElement` is still the outgoing\n // element (and passes through `<body>` mid-handoff), and some UI\n // libraries restore focus asynchronously — the ariakit and shadcn link\n // popovers both do. The check therefore has to wait for the current task\n // to finish. A microtask is too early (verified: those popover tests go\n // red), and a frame would work but doesn't run in a background tab.\n const onFocusOut = (event: FocusEvent) => {\n clearTimeout(settleUiFocusedTimeout);\n settleUiFocusedTimeout = setTimeout(() => settleUIFocus(event));\n };\n\n document.addEventListener(\"focusin\", onFocusIn, true);\n document.addEventListener(\"focusout\", onFocusOut, true);\n return () => {\n clearTimeout(settleUiFocusedTimeout);\n document.removeEventListener(\"focusin\", onFocusIn, true);\n document.removeEventListener(\"focusout\", onFocusOut, true);\n };\n }\n\n /**\n * Register a callback that will be called when the editor changes.\n */\n public onChange(\n callback: (\n editor: BlockNoteEditor<BSchema, I, S>,\n ctx: {\n getChanges(): BlocksChanged<BSchema, I, S>;\n },\n ) => void,\n /**\n * If true, the callback will be triggered when the changes are caused by a remote user\n * @default true\n */\n includeUpdatesFromRemote = true,\n ): Unsubscribe {\n return this.on(\"onChange\", ({ transaction, appendedTransactions }) => {\n if (!includeUpdatesFromRemote && isRemoteTransaction(transaction)) {\n // don't trigger the callback if the changes are caused by a remote user\n return;\n }\n callback(this.editor, {\n getChanges() {\n return getBlocksChangedByTransaction<BSchema, I, S>(\n transaction,\n appendedTransactions,\n );\n },\n });\n });\n }\n\n /**\n * Register a callback that will be called when the selection changes.\n */\n public onSelectionChange(\n callback: (editor: BlockNoteEditor<BSchema, I, S>) => void,\n /**\n * If true, the callback will be triggered when the selection changes due to a yjs sync (i.e.: other user was typing)\n */\n includeSelectionChangedByRemote = false,\n ): Unsubscribe {\n return this.on(\"onSelectionChange\", ({ transaction }) => {\n if (\n !includeSelectionChangedByRemote &&\n isRemoteTransaction(transaction)\n ) {\n // don't trigger the callback if the selection changed because of a remote user\n return;\n }\n callback(this.editor);\n });\n }\n\n /**\n * Register a callback for focus changes. By default, this reports when the\n * editor's content area gains or loses DOM focus.\n *\n * Note that `focused: false` only means the content area itself blurred —\n * focus may have moved into the editor's own UI (e.g. a toolbar\n * popover's input). Pass `includeEditorUI: true` to report changes to\n * combined content and UI focus, allowing focus handoffs to settle.\n */\n public onFocusChange(\n callback: (\n editor: BlockNoteEditor<BSchema, I, S>,\n ctx: { focused: boolean; event: FocusEvent },\n ) => void,\n options?: EditorFocusOptions,\n ): Unsubscribe {\n return this.on(\n options?.includeEditorUI ? \"onFocusChangeWithinUI\" : \"onFocusChange\",\n ({ focused, event }) => callback(this.editor, { focused, event }),\n );\n }\n\n /**\n * Register a callback that will be called when the editor is mounted.\n */\n public onMount(\n callback: (ctx: { editor: BlockNoteEditor<BSchema, I, S> }) => void,\n ): Unsubscribe {\n return this.on(\"onMount\", callback);\n }\n\n /**\n * Register a callback that will be called when the editor is unmounted.\n */\n public onUnmount(\n callback: (ctx: { editor: BlockNoteEditor<BSchema, I, S> }) => void,\n ): Unsubscribe {\n return this.on(\"onUnmount\", callback);\n }\n}\n\nfunction isRemoteTransaction(transaction: Transaction): boolean {\n return !!transaction.getMeta(\"y-sync$\");\n}\n","function getChildIndex(node: Element) {\n return Array.prototype.indexOf.call(node.parentElement!.childNodes, node);\n}\n\nfunction isWhitespaceNode(node: Node) {\n return node.nodeType === 3 && !/\\S/.test(node.nodeValue || \"\");\n}\n\n/**\n * Step 1, Turns:\n *\n * <ul>\n * <li>item</li>\n * <li>\n * <ul>\n * <li>...</li>\n * <li>...</li>\n * </ul>\n * </li>\n *\n * Into:\n * <ul>\n * <li>item</li>\n * <ul>\n * <li>...</li>\n * <li>...</li>\n * </ul>\n * </ul>\n *\n */\nfunction liftNestedListsToParent(element: HTMLElement) {\n element.querySelectorAll(\"li > ul, li > ol\").forEach((list) => {\n const index = getChildIndex(list);\n const parentListItem = list.parentElement!;\n const siblingsAfter = Array.from(parentListItem.childNodes).slice(\n index + 1,\n );\n list.remove();\n siblingsAfter.forEach((sibling) => {\n sibling.remove();\n });\n\n parentListItem.insertAdjacentElement(\"afterend\", list);\n\n siblingsAfter.reverse().forEach((sibling) => {\n if (isWhitespaceNode(sibling)) {\n return;\n }\n const siblingContainer = document.createElement(\"li\");\n siblingContainer.append(sibling);\n list.insertAdjacentElement(\"afterend\", siblingContainer);\n });\n if (parentListItem.childNodes.length === 0) {\n parentListItem.remove();\n }\n });\n}\n\n/**\n * Step 2, Turns (output of liftNestedListsToParent):\n *\n * <li>item</li>\n * <ul>\n * <li>...</li>\n * <li>...</li>\n * </ul>\n *\n * Into:\n * <div>\n * <li>item</li>\n * <div data-node-type=\"blockGroup\">\n * <ul>\n * <li>...</li>\n * <li>...</li>\n * </ul>\n * </div>\n * </div>\n *\n * This resulting format is parsed\n */\nfunction createGroups(element: HTMLElement) {\n element.querySelectorAll(\"li + ul, li + ol\").forEach((list) => {\n const listItem = list.previousElementSibling as HTMLElement;\n const blockContainer = document.createElement(\"div\");\n\n listItem.insertAdjacentElement(\"afterend\", blockContainer);\n blockContainer.append(listItem);\n\n const blockGroup = document.createElement(\"div\");\n blockGroup.setAttribute(\"data-node-type\", \"blockGroup\");\n blockContainer.append(blockGroup);\n\n while (\n blockContainer.nextElementSibling?.nodeName === \"UL\" ||\n blockContainer.nextElementSibling?.nodeName === \"OL\"\n ) {\n blockGroup.append(blockContainer.nextElementSibling);\n }\n });\n}\n\n// prevent XSS, similar to https://github.com/ProseMirror/prosemirror-view/blob/1251b2b412656a2a06263e4187574beb43651273/src/clipboard.ts#L204\n// https://github.com/TypeCellOS/BlockNote/issues/601\nlet _detachedDoc: Document | null = null;\nfunction detachedDoc() {\n return (\n _detachedDoc ||\n (_detachedDoc = document.implementation.createHTMLDocument(\"title\"))\n );\n}\n\nexport function nestedListsToBlockNoteStructure(\n elementOrHTML: HTMLElement | string,\n) {\n if (typeof elementOrHTML === \"string\") {\n const element = detachedDoc().createElement(\"div\");\n element.innerHTML = elementOrHTML;\n elementOrHTML = element;\n }\n liftNestedListsToParent(elementOrHTML);\n createGroups(elementOrHTML);\n return elementOrHTML;\n}\n","/**\n * Checks if the given HTML element contains markers indicating it was\n * generated by Notion. Notion uses `\\n` in text nodes to represent hard\n * breaks, which is non-standard but intentional.\n *\n * Detected by the `<!-- notionvc: UUID -->` comment that Notion places\n * on the clipboard.\n */\nfunction isNotionHTML(element: HTMLElement): boolean {\n const walker = element.ownerDocument.createTreeWalker(\n element,\n // NodeFilter.SHOW_COMMENT\n 128,\n );\n\n let node: Node | null;\n while ((node = walker.nextNode())) {\n if (/^\\s*notionvc:/.test(node.nodeValue || \"\")) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Normalizes whitespace in text nodes by collapsing runs of whitespace\n * (including newlines) to single spaces, matching CSS white-space:normal\n * behavior.\n *\n * This is needed because ProseMirror's DOMParser, when `linebreakReplacement`\n * is set in the schema (as BlockNote does for hard breaks), converts `\\n`\n * characters in text nodes to hard break nodes instead of collapsing them.\n * This causes HTML source line wrapping (e.g. from MS Word) to create\n * visible line breaks in the editor.\n *\n * Skipped for sources like Notion that intentionally use `\\n` in text nodes\n * to represent hard breaks instead of `<br>` tags.\n *\n * Skips `<pre>` and `<code>` elements where whitespace should be preserved.\n */\nfunction normalizeTextNodeWhitespace(element: HTMLElement) {\n const preserveWSTags = new Set([\"PRE\", \"CODE\"]);\n const walker = element.ownerDocument.createTreeWalker(\n element,\n // NodeFilter.SHOW_TEXT\n 4,\n {\n acceptNode(node) {\n // Skip text nodes inside pre/code elements\n let parent = node.parentElement;\n while (parent && parent !== element) {\n if (preserveWSTags.has(parent.tagName)) {\n // NodeFilter.FILTER_REJECT\n return 2;\n }\n parent = parent.parentElement;\n }\n // NodeFilter.FILTER_ACCEPT\n return 1;\n },\n },\n );\n\n const textNodes: Text[] = [];\n let node: Node | null;\n while ((node = walker.nextNode())) {\n textNodes.push(node as Text);\n }\n\n for (const textNode of textNodes) {\n if (textNode.nodeValue && /[\\r\\n]/.test(textNode.nodeValue)) {\n textNode.nodeValue = textNode.nodeValue.replace(/[ \\t\\r\\n\\f]+/g, \" \");\n }\n }\n}\n\n/**\n * Normalizes whitespace in HTML text nodes to match standard CSS\n * white-space:normal behavior. Skipped for Notion HTML which intentionally\n * uses `\\n` for hard breaks.\n */\nexport function preprocessHTMLWhitespace(element: HTMLElement) {\n if (!isNotionHTML(element)) {\n normalizeTextNodeWhitespace(element);\n }\n}\n","import { DOMParser, Schema } from \"prosemirror-model\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\n\nimport { Block } from \"../../../blocks/defaultBlocks.js\";\nimport { EMPTY_BLOCK_PLACEHOLDER } from \"../../exporters/html/util/serializeBlocksExternalHTML.js\";\nimport { nodeToBlock } from \"../../nodeConversions/nodeToBlock.js\";\nimport { nestedListsToBlockNoteStructure } from \"./util/nestedLists.js\";\nimport { preprocessHTMLWhitespace } from \"./util/normalizeWhitespace.js\";\n\n/**\n * Removes the placeholder character that the external HTML exporter inserts\n * into empty inline-content blocks (see `EMPTY_BLOCK_PLACEHOLDER`). The\n * placeholder keeps such blocks from being dropped while the HTML is parsed;\n * stripping it here lets the block round trip back to genuinely empty content.\n */\nfunction stripEmptyBlockPlaceholder(content: any[]): any[] {\n const stripped: any[] = [];\n\n for (const item of content) {\n if (item.type === \"text\") {\n const text = item.text.split(EMPTY_BLOCK_PLACEHOLDER).join(\"\");\n if (text.length > 0) {\n stripped.push({ ...item, text });\n }\n } else if (Array.isArray(item.content)) {\n // Links and custom inline content that hold nested styled text.\n stripped.push({\n ...item,\n content: stripEmptyBlockPlaceholder(item.content),\n });\n } else {\n stripped.push(item);\n }\n }\n\n return stripped;\n}\n\nfunction stripEmptyBlockPlaceholderFromBlocks(blocks: Block<any, any, any>[]) {\n for (const block of blocks) {\n if (Array.isArray(block.content)) {\n (block as any).content = stripEmptyBlockPlaceholder(block.content);\n }\n if (block.children.length > 0) {\n stripEmptyBlockPlaceholderFromBlocks(block.children);\n }\n }\n}\n\nexport function HTMLToBlocks<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(html: string, pmSchema: Schema): Block<BSchema, I, S>[] {\n const htmlNode = nestedListsToBlockNoteStructure(html);\n preprocessHTMLWhitespace(htmlNode);\n const parser = DOMParser.fromSchema(pmSchema);\n\n // Other approach might be to use\n // const doc = pmSchema.nodes[\"doc\"].createAndFill()!;\n // and context: doc.resolve(3),\n\n const parentNode = parser.parse(htmlNode, {\n topNode: pmSchema.nodes[\"blockGroup\"].create(),\n });\n\n const blocks: Block<BSchema, I, S>[] = [];\n\n for (let i = 0; i < parentNode.childCount; i++) {\n blocks.push(nodeToBlock(parentNode.child(i), parentNode));\n }\n\n stripEmptyBlockPlaceholderFromBlocks(blocks);\n\n return blocks;\n}\n","import { isVideoUrl } from \"../../../util/string.js\";\nimport { findLinks } from \"../../../extensions/tiptap-extensions/Link/helpers/linkDetector.js\";\nimport { parseAutolinkLiteral } from \"./autolink.js\";\n\n/**\n * Custom markdown-to-HTML converter for BlockNote.\n * Replaces the unified/remark/rehype pipeline with a direct, minimal implementation\n * that handles exactly the markdown features BlockNote needs.\n */\n\n// ─── HTML Escaping ───────────────────────────────────────────────────────────\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction isAlphanumeric(char: string | undefined): boolean {\n if (!char) {\n return false;\n }\n return /\\w/.test(char);\n}\n\n/**\n * Returns true when an underscore delimiter at position `i` is \"intraword\",\n * meaning the characters on both sides are alphanumeric (e.g. `snake_case`).\n * In that case the underscore should NOT be treated as emphasis per CommonMark.\n */\nfunction isIntraword(text: string, i: number, delimLen: number): boolean {\n const before = i > 0 ? text[i - 1] : undefined;\n const after = i + delimLen < text.length ? text[i + delimLen] : undefined;\n return isAlphanumeric(before) && isAlphanumeric(after);\n}\n\n// ─── Inline Parser ───────────────────────────────────────────────────────────\n\ntype InlineTokenizer = (\n text: string,\n i: number,\n allowLinks: boolean,\n) => { html: string; end: number } | null;\n\nfunction tryBackslashEscape(\n text: string,\n i: number,\n): { html: string; end: number } | null {\n if (text[i] !== \"\\\\\" || i + 1 >= text.length) {\n return null;\n }\n const next = text[i + 1];\n // Hard line break: backslash at end of line\n if (next === \"\\n\") {\n return { html: \"<br>\\n\", end: i + 2 };\n }\n // Escapable characters\n if (\"\\\\`*_{}[]()#+-.!~|>\".includes(next)) {\n return { html: escapeHtml(next), end: i + 2 };\n }\n return null;\n}\n\nfunction tryInlineCode(\n text: string,\n i: number,\n): { html: string; end: number } | null {\n if (text[i] !== \"`\") {\n return null;\n }\n return parseInlineCode(text, i);\n}\n\nfunction tryImage(\n text: string,\n i: number,\n): { html: string; end: number } | null {\n if (text[i] !== \"!\" || text[i + 1] !== \"[\") {\n return null;\n }\n return parseImage(text, i);\n}\n\nfunction tryLink(\n text: string,\n i: number,\n): { html: string; end: number } | null {\n if (text[i] !== \"[\") {\n return null;\n }\n return parseLink(text, i);\n}\n\nfunction tryAutolink(\n text: string,\n i: number,\n): { html: string; end: number } | null {\n const rest = text.substring(i);\n\n // CommonMark autolinks: <scheme:destination> and <email@example.com>.\n if (text[i] === \"<\") {\n const urlMatch = rest.match(/^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\\s<>]*)>/);\n if (urlMatch) {\n const url = urlMatch[1];\n return {\n html: `<a href=\"${escapeHtml(url)}\">${escapeHtml(url)}</a>`,\n end: i + urlMatch[0].length,\n };\n }\n\n const emailMatch = rest.match(/^<([^\\s<>]+)>/);\n const email = emailMatch?.[1];\n const detectedEmail = email\n ? findLinks(email).find(\n (match) =>\n match.type === \"email\" &&\n match.start === 0 &&\n match.end === email.length,\n )\n : undefined;\n if (emailMatch && email && detectedEmail) {\n return {\n html: `<a href=\"${escapeHtml(detectedEmail.href)}\">${escapeHtml(email)}</a>`,\n end: i + emailMatch[0].length,\n };\n }\n\n return null;\n }\n\n // GFM autolink literals. Only start at a word boundary, so URL-like text\n // embedded in a larger word remains plain text.\n if (i > 0 && /[a-zA-Z0-9_]/.test(text[i - 1])) {\n return null;\n }\n\n const literalMatch = rest.match(/^(https?:\\/\\/|www\\.)[^\\s<>]+/i);\n if (!literalMatch) {\n return null;\n }\n\n const autolink = parseAutolinkLiteral(literalMatch[0]);\n if (!autolink) {\n return null;\n }\n\n return {\n html: `<a href=\"${escapeHtml(autolink.href)}\">${escapeHtml(autolink.value)}</a>`,\n end: i + autolink.value.length,\n };\n}\n\nfunction tryStrikethrough(\n text: string,\n i: number,\n allowLinks: boolean,\n): { html: string; end: number } | null {\n if (text[i] !== \"~\" || text[i + 1] !== \"~\") {\n return null;\n }\n return parseDelimited(text, i, \"~~\", \"<del>\", \"</del>\", allowLinks);\n}\n\nfunction tryBoldItalic(\n text: string,\n i: number,\n allowLinks: boolean,\n): { html: string; end: number } | null {\n if (\n (text[i] === \"*\" && text[i + 1] === \"*\" && text[i + 2] === \"*\") ||\n (text[i] === \"_\" &&\n text[i + 1] === \"_\" &&\n text[i + 2] === \"_\" &&\n !isIntraword(text, i, 3))\n ) {\n const delimiter = text.substring(i, i + 3);\n return parseDelimited(\n text,\n i,\n delimiter,\n \"<strong><em>\",\n \"</em></strong>\",\n allowLinks,\n );\n }\n return null;\n}\n\nfunction tryBold(\n text: string,\n i: number,\n allowLinks: boolean,\n): { html: string; end: number } | null {\n if (\n (text[i] === \"*\" && text[i + 1] === \"*\") ||\n (text[i] === \"_\" && text[i + 1] === \"_\" && !isIntraword(text, i, 2))\n ) {\n const delimiter = text.substring(i, i + 2);\n return parseDelimited(\n text,\n i,\n delimiter,\n \"<strong>\",\n \"</strong>\",\n allowLinks,\n );\n }\n return null;\n}\n\nfunction tryItalic(\n text: string,\n i: number,\n allowLinks: boolean,\n): { html: string; end: number } | null {\n if (text[i] === \"*\" || (text[i] === \"_\" && !isIntraword(text, i, 1))) {\n return parseDelimited(text, i, text[i], \"<em>\", \"</em>\", allowLinks);\n }\n return null;\n}\n\nfunction trySoftBreak(\n text: string,\n i: number,\n): { html: string; end: number } | null {\n if (text[i] === \"\\n\") {\n return { html: \"<br>\\n\", end: i + 1 };\n }\n return null;\n}\n\n// Inline raw HTML: pass through tags, comments, CDATA, processing\n// instructions, and declarations verbatim so authors can mix HTML into\n// markdown (e.g. `text <em>foo</em> more`). Anything that doesn't match\n// these shapes falls through and gets HTML-escaped as plain text.\nconst INLINE_HTML_TAG_RE =\n /^<\\/?[a-zA-Z][a-zA-Z0-9-]*(?:\\s+[a-zA-Z_:][a-zA-Z0-9_.:-]*(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'=<>`]+))?)*\\s*\\/?>/;\nconst HTML_COMMENT_RE = /^<!--[\\s\\S]*?-->/;\nconst HTML_CDATA_RE = /^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>/;\nconst HTML_PI_RE = /^<\\?[\\s\\S]*?\\?>/;\nconst HTML_DECL_RE = /^<![A-Za-z][\\s\\S]*?>/;\n\nfunction tryInlineHtml(\n text: string,\n i: number,\n): { html: string; end: number } | null {\n if (text[i] !== \"<\") {\n return null;\n }\n const rest = text.substring(i);\n for (const re of [\n HTML_COMMENT_RE,\n HTML_CDATA_RE,\n HTML_PI_RE,\n HTML_DECL_RE,\n INLINE_HTML_TAG_RE,\n ]) {\n const m = rest.match(re);\n if (m) {\n return { html: m[0], end: i + m[0].length };\n }\n }\n return null;\n}\n\n/** Characters that can start an inline syntax token. */\nconst SPECIAL_CHARS = new Set(\"\\\\`![~*_\\n<\");\n\nfunction canStartInlineToken(text: string, position: number): boolean {\n const char = text[position];\n if (SPECIAL_CHARS.has(char)) {\n return true;\n }\n if (char === \"h\") {\n return (\n text.startsWith(\"http://\", position) ||\n text.startsWith(\"https://\", position)\n );\n }\n if (char === \"w\") {\n return text.startsWith(\"www.\", position);\n }\n return false;\n}\n\n/**\n * Ordered array of inline tokenizers, tried in priority order.\n * The first match wins.\n */\nconst inlineTokenizers: InlineTokenizer[] = [\n tryBackslashEscape,\n tryInlineCode,\n tryImage,\n tryLink,\n tryAutolink,\n tryStrikethrough,\n tryBoldItalic, // *** / ___\n tryBold, // ** / __\n tryItalic, // * / _\n tryInlineHtml,\n trySoftBreak,\n];\n\nconst linkTextTokenizers = inlineTokenizers.filter(\n (tokenizer) => tokenizer !== tryLink && tokenizer !== tryAutolink,\n);\n\n/**\n * Parse inline markdown syntax and return HTML.\n * Handles: bold, italic, bold+italic, strikethrough, inline code,\n * links, images (with video detection), hard line breaks, backslash escapes.\n */\nfunction parseInline(text: string, allowLinks = true): string {\n let result = \"\";\n let i = 0;\n const tokenizers = allowLinks ? inlineTokenizers : linkTextTokenizers;\n\n while (i < text.length) {\n // Hard line break: 2+ trailing spaces immediately before a newline.\n // (The other hard-break form, backslash + newline, is handled by\n // tryBackslashEscape.) Strip the trailing spaces from the accumulated\n // result before emitting the <br>.\n if (\n text[i] === \"\\n\" &&\n i >= 2 &&\n text[i - 1] === \" \" &&\n text[i - 2] === \" \"\n ) {\n result = result.replace(/ +$/, \"\");\n result += \"<br>\\n\";\n i++;\n continue;\n }\n\n // Try each tokenizer in priority order\n let matched = false;\n if (canStartInlineToken(text, i)) {\n for (const tokenizer of tokenizers) {\n const r = tokenizer(text, i, allowLinks);\n if (r) {\n result += r.html;\n i = r.end;\n matched = true;\n break;\n }\n }\n }\n\n if (!matched) {\n // Batch consecutive plain-text characters and escape once\n const runStart = i;\n i++;\n while (i < text.length && !canStartInlineToken(text, i)) {\n i++;\n }\n result += escapeHtml(text.substring(runStart, i));\n }\n }\n\n return result;\n}\n\nfunction parseInlineCode(\n text: string,\n start: number,\n): { html: string; end: number } | null {\n // Count opening backticks\n let openCount = 0;\n let i = start;\n while (i < text.length && text[i] === \"`\") {\n openCount++;\n i++;\n }\n\n // Find matching closing backticks\n let j = i;\n while (j < text.length) {\n if (text[j] === \"`\") {\n let closeCount = 0;\n const closeStart = j;\n while (j < text.length && text[j] === \"`\") {\n closeCount++;\n j++;\n }\n if (closeCount === openCount) {\n let code = text.substring(i, closeStart);\n // Per CommonMark: line endings inside a code span are converted to\n // single spaces, then if the result starts AND ends with a space and\n // is not all-spaces, one leading + trailing space is stripped (so\n // `` ` `foo` ` `` is `<code>`foo`</code>`).\n code = code.replace(/\\n/g, \" \");\n if (\n code.length >= 2 &&\n code[0] === \" \" &&\n code[code.length - 1] === \" \" &&\n /[^ ]/.test(code)\n ) {\n code = code.substring(1, code.length - 1);\n }\n return {\n html: `<code>${escapeHtml(code)}</code>`,\n end: j,\n };\n }\n } else {\n j++;\n }\n }\n return null;\n}\n\nfunction parseImage(\n text: string,\n start: number,\n): { html: string; end: number } | null {\n // ![alt](url) or ![alt](url \"title\")\n // Use balanced bracket matching to handle nested/escaped brackets in alt text\n const altEnd = findClosingBracket(text, start + 1);\n if (altEnd === -1) {\n return null;\n }\n const altStart = start + 2; // after ![\n\n if (text[altEnd + 1] !== \"(\") {\n return null;\n }\n\n const urlStart = altEnd + 2;\n const parenEnd = findClosingParen(text, urlStart - 1);\n if (parenEnd === -1) {\n return null;\n }\n\n const alt = text.substring(altStart, altEnd);\n const { url, title } = parseDestinationAndTitle(\n text.substring(urlStart, parenEnd),\n );\n\n if (isVideoUrl(url)) {\n // Use the alt text as the video's display name (falling back to the\n // title) so a video link written with the standard `![name](url)` form\n // round-trips into BlockNote's video block. Captioned videos go through\n // raw `<figure>` HTML instead, see htmlToMarkdown.serializeMediaFigure.\n const name = alt || title;\n return {\n html: `<video src=\"${escapeHtml(url)}\"${name ? ` data-name=\"${escapeHtml(name)}\"` : \"\"} data-url=\"${escapeHtml(url)}\" controls></video>`,\n end: parenEnd + 1,\n };\n }\n\n const titleAttr = title !== undefined ? ` title=\"${escapeHtml(title)}\"` : \"\";\n return {\n html: `<img src=\"${escapeHtml(url)}\" alt=\"${escapeHtml(alt)}\"${titleAttr}>`,\n end: parenEnd + 1,\n };\n}\n\nfunction parseLink(\n text: string,\n start: number,\n): { html: string; end: number } | null {\n // [text](url)\n const textStart = start + 1;\n const textEnd = findClosingBracket(text, start);\n if (textEnd === -1) {\n return null;\n }\n\n if (text[textEnd + 1] !== \"(\") {\n return null;\n }\n\n const urlStart = textEnd + 2;\n const parenEnd = findClosingParen(text, textEnd + 1);\n if (parenEnd === -1) {\n return null;\n }\n\n const linkText = text.substring(textStart, textEnd);\n const { url, title } = parseDestinationAndTitle(\n text.substring(urlStart, parenEnd),\n );\n\n const titleAttr = title !== undefined ? ` title=\"${escapeHtml(title)}\"` : \"\";\n return {\n html: `<a href=\"${escapeHtml(url)}\"${titleAttr}>${parseInline(linkText, false)}</a>`,\n end: parenEnd + 1,\n };\n}\n\nfunction findClosingBracket(text: string, openPos: number): number {\n let depth = 0;\n for (let i = openPos; i < text.length; i++) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i++; // skip escaped\n continue;\n }\n if (text[i] === \"[\") {\n depth++;\n }\n if (text[i] === \"]\") {\n depth--;\n if (depth === 0) {\n return i;\n }\n }\n }\n return -1;\n}\n\nfunction findClosingParen(text: string, openPos: number): number {\n let depth = 0;\n for (let i = openPos; i < text.length; i++) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i++;\n continue;\n }\n if (text[i] === \"(\") {\n depth++;\n }\n if (text[i] === \")\") {\n depth--;\n if (depth === 0) {\n return i;\n }\n }\n }\n return -1;\n}\n\n/**\n * Parse the inside of `(...)` from a link/image (the URL and optional title).\n * Handles three URL forms:\n * - bare: `/uri` or `/uri \"title\"`\n * - angle-bracket: `<url>` or `<url> \"title\"` (brackets are stripped)\n * And three title-quote forms: `\"...\"`, `'...'`, `(...)`.\n */\nfunction parseDestinationAndTitle(raw: string): {\n url: string;\n title?: string;\n} {\n raw = raw.trim();\n let url: string;\n let rest: string;\n\n if (raw.startsWith(\"<\")) {\n const close = raw.indexOf(\">\");\n if (close === -1) {\n // Unmatched `<` — treat the whole thing as the URL minus the `<`.\n url = raw.substring(1);\n rest = \"\";\n } else {\n url = raw.substring(1, close);\n rest = raw.substring(close + 1).trim();\n }\n } else {\n // Split at first unescaped whitespace.\n let split = raw.length;\n for (let i = 0; i < raw.length; i++) {\n if (raw[i] === \"\\\\\" && i + 1 < raw.length) {\n i++;\n continue;\n }\n if (raw[i] === \" \" || raw[i] === \"\\t\" || raw[i] === \"\\n\") {\n split = i;\n break;\n }\n }\n url = raw.substring(0, split);\n rest = raw.substring(split).trim();\n }\n\n let title: string | undefined;\n if (rest.length > 0) {\n const titleMatch = rest.match(/^\"([^\"]*)\"$|^'([^']*)'$|^\\(([^)]*)\\)$/);\n if (titleMatch) {\n title = titleMatch[1] ?? titleMatch[2] ?? titleMatch[3];\n }\n }\n\n return { url, title };\n}\n\nfunction parseDelimited(\n text: string,\n start: number,\n delimiter: string,\n openTag: string,\n closeTag: string,\n allowLinks: boolean,\n): { html: string; end: number } | null {\n const len = delimiter.length;\n const afterOpen = start + len;\n\n if (afterOpen >= text.length) {\n return null;\n }\n\n // Opening delimiter must not be followed by whitespace\n if (text[afterOpen] === \" \" || text[afterOpen] === \"\\t\") {\n return null;\n }\n\n // Find closing delimiter\n let j = afterOpen;\n while (j < text.length) {\n // Skip escaped characters\n if (text[j] === \"\\\\\" && j + 1 < text.length) {\n j += 2;\n continue;\n }\n\n if (text.substring(j, j + len) === delimiter) {\n // Closing delimiter must not be preceded by whitespace\n if (text[j - 1] === \" \" || text[j - 1] === \"\\t\") {\n j++;\n continue;\n }\n\n // For single-char delimiters, don't accept closer if it's part of a\n // multi-char run (e.g., don't treat the * in ** as italic closer)\n if (\n len === 1 &&\n ((j > 0 &&\n text[j - 1] === delimiter[0] &&\n !(j >= 2 && text[j - 2] === \"\\\\\")) ||\n (j + len < text.length && text[j + len] === delimiter[0]))\n ) {\n j++;\n continue;\n }\n\n const inner = text.substring(afterOpen, j);\n if (inner.length === 0) {\n j++;\n continue;\n }\n\n return {\n html: openTag + parseInline(inner, allowLinks) + closeTag,\n end: j + len,\n };\n }\n j++;\n }\n\n return null;\n}\n\n// ─── Block-Level Types ───────────────────────────────────────────────────────\n\ninterface BlockToken {\n type: string;\n}\n\ninterface HeadingToken extends BlockToken {\n type: \"heading\";\n level: number;\n content: string;\n}\n\ninterface ParagraphToken extends BlockToken {\n type: \"paragraph\";\n content: string;\n}\n\ninterface CodeBlockToken extends BlockToken {\n type: \"codeBlock\";\n language: string;\n code: string;\n}\n\ninterface BlockquoteToken extends BlockToken {\n type: \"blockquote\";\n content: string;\n}\n\ninterface HorizontalRuleToken extends BlockToken {\n type: \"hr\";\n}\n\ninterface ListItemToken extends BlockToken {\n type: \"listItem\";\n listType: \"bullet\" | \"ordered\" | \"task\";\n indent: number;\n content: string;\n start?: number; // for ordered lists\n checked?: boolean; // for task lists\n childContent?: string; // recursively parsed content within this item\n}\n\ninterface TableToken extends BlockToken {\n type: \"table\";\n headers: string[];\n rows: string[][];\n alignments: (\"left\" | \"center\" | \"right\" | null)[];\n}\n\ninterface RawHtmlToken extends BlockToken {\n type: \"rawHtml\";\n content: string;\n}\n\ntype Token =\n | HeadingToken\n | ParagraphToken\n | CodeBlockToken\n | BlockquoteToken\n | HorizontalRuleToken\n | ListItemToken\n | TableToken\n | RawHtmlToken;\n\n/**\n * HTML block-level tag names (from the CommonMark type-6 list, plus `audio`\n * which BlockNote serializes as raw HTML since markdown has no shorthand\n * for it). When a line starts with `<` followed by one of these tag names,\n * the run of non-blank lines is emitted verbatim as raw HTML rather than\n * wrapped in a paragraph.\n */\nconst HTML_BLOCK_TAGS = new Set([\n \"address\",\n \"article\",\n \"aside\",\n \"audio\",\n \"base\",\n \"basefont\",\n \"blockquote\",\n \"body\",\n \"caption\",\n \"center\",\n \"col\",\n \"colgroup\",\n \"dd\",\n \"details\",\n \"dialog\",\n \"dir\",\n \"div\",\n \"dl\",\n \"dt\",\n \"fieldset\",\n \"figcaption\",\n \"figure\",\n \"footer\",\n \"form\",\n \"frame\",\n \"frameset\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"head\",\n \"header\",\n \"hr\",\n \"html\",\n \"iframe\",\n \"legend\",\n \"li\",\n \"link\",\n \"main\",\n \"menu\",\n \"menuitem\",\n \"nav\",\n \"noframes\",\n \"ol\",\n \"optgroup\",\n \"option\",\n \"p\",\n \"param\",\n \"section\",\n \"source\",\n \"summary\",\n \"table\",\n \"tbody\",\n \"td\",\n \"tfoot\",\n \"th\",\n \"thead\",\n \"title\",\n \"tr\",\n \"track\",\n \"ul\",\n]);\n\nfunction isHtmlBlockStart(line: string): boolean {\n // <!-- ..., <?..., <![CDATA[..., <!DOCTYPE, etc.\n if (/^ {0,3}<(!--|\\?|![A-Za-z]|!\\[CDATA\\[)/.test(line)) {\n return true;\n }\n const m = line.match(/^ {0,3}<\\/?([a-zA-Z][a-zA-Z0-9-]*)(?:\\s|\\/?>|$)/);\n if (!m) {\n return false;\n }\n return HTML_BLOCK_TAGS.has(m[1].toLowerCase());\n}\n\n// ─── Block-Level Tokenizer ──────────────────────────────────────────────────\n\nfunction tokenize(markdown: string): Token[] {\n const lines = markdown.split(\"\\n\");\n const tokens: Token[] = [];\n let i = 0;\n let prevLineWasBlank = true; // treat start of document as after blank\n\n while (i < lines.length) {\n const line = lines[i];\n\n // Blank line — skip\n if (line.trim() === \"\") {\n prevLineWasBlank = true;\n i++;\n continue;\n }\n\n // Fenced code block (0-3 leading spaces allowed per CommonMark)\n const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);\n if (fenceMatch) {\n const fence = fenceMatch[1];\n const fenceChar = fence[0];\n const fenceLen = fence.length;\n const language = fenceMatch[2].trim();\n const codeLines: string[] = [];\n i++;\n while (i < lines.length) {\n const closingMatch = lines[i].match(\n new RegExp(`^ {0,3}${fenceChar}{${fenceLen},}\\\\s*$`),\n );\n if (closingMatch) {\n i++;\n break;\n }\n codeLines.push(lines[i]);\n i++;\n }\n tokens.push({\n type: \"codeBlock\",\n language: language || \"\",\n code: codeLines.join(\"\\n\"),\n });\n prevLineWasBlank = false;\n continue;\n }\n\n // ATX Heading.\n // - Closing `#` sequence requires a preceding space (so `### foo###`\n // keeps the trailing #s as text, while `### foo ###` strips them).\n // - Trailing whitespace is always stripped from the heading content.\n const headingMatch = line.match(/^(#{1,6})\\s+(.+?)(?:\\s+#+\\s*|\\s*)$/);\n if (headingMatch) {\n tokens.push({\n type: \"heading\",\n level: headingMatch[1].length,\n content: headingMatch[2],\n });\n prevLineWasBlank = false;\n i++;\n continue;\n }\n\n // Horizontal rule: ---, ***, ___ (3+ chars, optionally with spaces)\n if (/^(\\s{0,3})([-*_])\\s*(\\2\\s*){2,}$/.test(line)) {\n // Setext H2: --- immediately after a paragraph (no blank line between)\n const prevToken = tokens[tokens.length - 1];\n if (\n !prevLineWasBlank &&\n line.trim().match(/^-+$/) &&\n prevToken &&\n prevToken.type === \"paragraph\"\n ) {\n const para = prevToken as ParagraphToken;\n tokens[tokens.length - 1] = {\n type: \"heading\",\n level: 2,\n content: para.content,\n };\n prevLineWasBlank = false;\n i++;\n continue;\n }\n tokens.push({ type: \"hr\" });\n prevLineWasBlank = false;\n i++;\n continue;\n }\n\n // Setext heading detection: check if next line is === or ---\n if (i + 1 < lines.length) {\n const nextLine = lines[i + 1];\n if (/^={1,}\\s*$/.test(nextLine) && line.trim().length > 0) {\n tokens.push({\n type: \"heading\",\n level: 1,\n content: line.trim(),\n });\n prevLineWasBlank = false;\n i += 2;\n continue;\n }\n // Setext H2 --- handled in HR section above\n }\n\n // Table: detect by looking for separator row\n const tableResult = tryParseTable(lines, i);\n if (tableResult) {\n tokens.push(tableResult.token);\n i = tableResult.nextLine;\n prevLineWasBlank = false;\n continue;\n }\n\n // Blockquote\n if (/^\\s{0,3}>/.test(line)) {\n const quoteLines: string[] = [];\n while (i < lines.length && /^\\s{0,3}>/.test(lines[i])) {\n // Remove the > prefix\n quoteLines.push(lines[i].replace(/^\\s{0,3}>\\s?/, \"\"));\n i++;\n }\n // Lazy continuation: collect non-blank lines that don't start a new\n // block-level element (per CommonMark spec)\n while (i < lines.length) {\n const cur = lines[i];\n if (cur.trim() === \"\") {\n break;\n }\n // Stop on block-level markers\n if (/^\\s{0,3}>/.test(cur)) {\n break;\n } // new blockquote\n if (/^(#{1,6})\\s/.test(cur)) {\n break;\n } // heading\n if (/^(`{3,}|~{3,})/.test(cur)) {\n break;\n } // code fence\n if (/^(\\s{0,3})([-*_])\\s*(\\2\\s*){2,}$/.test(cur)) {\n break;\n } // hr\n if (/^\\s*([-*+]|\\d+[.)])\\s+/.test(cur)) {\n break;\n } // list item\n if (/^\\s*\\|(.+\\|)+\\s*$/.test(cur)) {\n break;\n } // table\n quoteLines.push(cur);\n i++;\n }\n tokens.push({\n type: \"blockquote\",\n content: quoteLines.join(\"\\n\"),\n });\n prevLineWasBlank = false;\n continue;\n }\n\n // List item (bullet, ordered, or task)\n const listItemMatch = line.match(\n /^(\\s*)([-*+]|\\d+[.)])(\\s+)(\\[[ xX]\\] )?(.*)$/,\n );\n if (listItemMatch) {\n const indent = listItemMatch[1].length;\n const marker = listItemMatch[2];\n const markerSpaces = listItemMatch[3];\n const checkbox = listItemMatch[4];\n const firstLineContent = listItemMatch[5];\n\n let listType: \"bullet\" | \"ordered\" | \"task\";\n let start: number | undefined;\n let checked: boolean | undefined;\n\n if (checkbox) {\n listType = \"task\";\n checked = checkbox.trim() !== \"[ ]\";\n } else if (/^\\d+[.)]$/.test(marker)) {\n listType = \"ordered\";\n start = parseInt(marker, 10);\n } else {\n listType = \"bullet\";\n }\n\n // Content indent = column where content actually starts\n const contentIndent =\n indent +\n marker.length +\n markerSpaces.length +\n (checkbox ? checkbox.length : 0);\n\n // Minimum indent for child content: anything indented past the marker\n // (sub-lists can start at indent > marker position)\n const minChildIndent = indent + 1;\n\n // Helper to check if a line belongs to this list item\n const belongsToItem = (lineStr: string): boolean => {\n if (lineStr.trim() === \"\") {\n return true;\n } // blank lines checked separately\n const lineInd = lineStr.match(/^\\s*/)![0].length;\n // Lines at contentIndent are continuation text\n if (lineInd >= contentIndent) {\n return true;\n }\n // Lines between marker and content column that start a sub-list\n if (\n lineInd >= minChildIndent &&\n lineStr.match(/^\\s*([-*+]|\\d+[.)])\\s+/)\n ) {\n return true;\n }\n return false;\n };\n\n // Consume ALL subsequent lines that belong to this list item\n i++;\n const subLines: string[] = [];\n while (i < lines.length) {\n const cur = lines[i];\n\n if (cur.trim() === \"\") {\n // Blank line: include if followed by content that belongs to this item\n let lookAhead = i + 1;\n while (lookAhead < lines.length && lines[lookAhead].trim() === \"\") {\n lookAhead++;\n }\n if (lookAhead < lines.length && belongsToItem(lines[lookAhead])) {\n subLines.push(\"\");\n i++;\n continue;\n }\n break;\n }\n\n if (!belongsToItem(cur)) {\n break;\n }\n\n // Strip indent: for lines at contentIndent+, strip contentIndent chars;\n // for sub-list lines between minChildIndent and contentIndent, strip minChildIndent\n const lineIndent = cur.match(/^\\s*/)![0].length;\n if (lineIndent >= contentIndent) {\n subLines.push(cur.substring(contentIndent));\n } else {\n // Sub-list item between minChildIndent and contentIndent\n subLines.push(cur.substring(minChildIndent));\n }\n i++;\n }\n\n // Build the list item token\n // If there are sub-lines, they become child content (recursively tokenized)\n // Don't trim — preserve relative indentation of sub-lines\n const childContent = subLines.join(\"\\n\").replace(/^\\n+|\\n+$/g, \"\");\n tokens.push({\n type: \"listItem\",\n listType,\n indent,\n content: firstLineContent.trim(),\n start,\n checked,\n childContent: childContent || undefined,\n });\n prevLineWasBlank = false;\n continue;\n }\n\n // Block-level raw HTML: a line starting with `<tag>` (block-level tag),\n // `<!-- ... -->`, `<?...?>`, `<!DOCTYPE ...>`, or `<![CDATA[...]]>`.\n // Lines are emitted verbatim until the next blank line.\n if (isHtmlBlockStart(line)) {\n const htmlLines: string[] = [];\n while (i < lines.length && lines[i].trim() !== \"\") {\n htmlLines.push(lines[i]);\n i++;\n }\n tokens.push({\n type: \"rawHtml\",\n content: htmlLines.join(\"\\n\"),\n });\n prevLineWasBlank = false;\n continue;\n }\n\n // Paragraph (default)\n const paraLines: string[] = [line];\n i++;\n while (i < lines.length) {\n const nextLine = lines[i];\n // Stop paragraph on blank line\n if (nextLine.trim() === \"\") {\n break;\n }\n // Stop on block-level element\n if (/^(#{1,6})\\s/.test(nextLine)) {\n break;\n }\n if (/^(`{3,}|~{3,})/.test(nextLine)) {\n break;\n }\n if (/^\\s{0,3}>/.test(nextLine)) {\n break;\n }\n if (/^(\\s{0,3})([-*_])\\s*(\\2\\s*){2,}$/.test(nextLine)) {\n break;\n }\n if (/^\\s*([-*+]|\\d+[.)])\\s+/.test(nextLine)) {\n break;\n }\n if (/^\\s*\\|(.+\\|)+\\s*$/.test(nextLine)) {\n break;\n }\n if (isHtmlBlockStart(nextLine)) {\n break;\n }\n // Check if next-next line is setext marker\n if (\n i + 1 < lines.length &&\n /^[=-]+\\s*$/.test(lines[i + 1]) &&\n nextLine.trim().length > 0\n ) {\n break;\n }\n paraLines.push(nextLine);\n i++;\n }\n // CommonMark allows up to 3 leading spaces of indent on paragraph lines.\n // Also strip trailing whitespace from the final line so a trailing\n // hard-break sequence (` \\n` at end of paragraph) doesn't leak as\n // literal trailing spaces in the rendered output.\n tokens.push({\n type: \"paragraph\",\n content: paraLines\n .map((l) => l.replace(/^ {1,3}/, \"\"))\n .join(\"\\n\")\n .replace(/[ \\t]+$/, \"\"),\n });\n prevLineWasBlank = false;\n }\n\n return tokens;\n}\n\nfunction tryParseTable(\n lines: string[],\n start: number,\n): { token: TableToken; nextLine: number } | null {\n // A table needs at least a header row and a separator row\n if (start + 1 >= lines.length) {\n return null;\n }\n\n const headerLine = lines[start];\n const separatorLine = lines[start + 1];\n\n // Check separator line format: | --- | --- | or --- | --- (outer pipes optional)\n // Must contain at least one pipe and only dashes, colons, pipes, and whitespace\n if (\n !separatorLine.includes(\"|\") ||\n !/^\\s*\\|?\\s*:?-+:?\\s*(\\|\\s*:?-+:?\\s*)*\\|?\\s*$/.test(separatorLine)\n ) {\n return null;\n }\n\n // Check header line has at least one pipe (required to distinguish from plain text)\n if (!headerLine.includes(\"|\")) {\n return null;\n }\n\n const headers = parsePipeCells(headerLine);\n const alignments = parseAlignments(separatorLine);\n\n const rows: string[][] = [];\n let i = start + 2;\n while (i < lines.length) {\n const line = lines[i];\n if (!line.includes(\"|\")) {\n break;\n }\n rows.push(parsePipeCells(line));\n i++;\n }\n\n return {\n token: {\n type: \"table\",\n headers,\n rows,\n alignments,\n },\n nextLine: i,\n };\n}\n\nfunction parsePipeCells(line: string): string[] {\n // Trim leading/trailing pipes and split\n const trimmed = line.trim();\n const withoutOuterPipes = trimmed.startsWith(\"|\")\n ? trimmed.substring(1)\n : trimmed;\n const content = withoutOuterPipes.endsWith(\"|\")\n ? withoutOuterPipes.substring(0, withoutOuterPipes.length - 1)\n : withoutOuterPipes;\n\n // Split by pipes, handling escaped pipes\n const cells: string[] = [];\n let current = \"\";\n for (let i = 0; i < content.length; i++) {\n if (\n content[i] === \"\\\\\" &&\n i + 1 < content.length &&\n content[i + 1] === \"|\"\n ) {\n current += \"|\";\n i++;\n } else if (content[i] === \"|\") {\n cells.push(current.trim());\n current = \"\";\n } else {\n current += content[i];\n }\n }\n cells.push(current.trim());\n\n return cells;\n}\n\nfunction parseAlignments(\n separatorLine: string,\n): (\"left\" | \"center\" | \"right\" | null)[] {\n const cells = parsePipeCells(separatorLine);\n return cells.map((cell) => {\n const trimmed = cell.trim();\n const left = trimmed.startsWith(\":\");\n const right = trimmed.endsWith(\":\");\n if (left && right) {\n return \"center\";\n }\n if (right) {\n return \"right\";\n }\n if (left) {\n return \"left\";\n }\n return null;\n });\n}\n\n// ─── HTML Emitter ────────────────────────────────────────────────────────────\n\nfunction tokensToHtml(tokens: Token[]): string {\n let html = \"\";\n let i = 0;\n\n while (i < tokens.length) {\n const token = tokens[i];\n\n switch (token.type) {\n case \"heading\": {\n const t = token as HeadingToken;\n html += `<h${t.level}>${parseInline(t.content)}</h${t.level}>`;\n i++;\n break;\n }\n\n case \"paragraph\": {\n const t = token as ParagraphToken;\n html += `<p>${parseInline(t.content)}</p>`;\n i++;\n break;\n }\n\n case \"codeBlock\": {\n const t = token as CodeBlockToken;\n const langAttr = t.language\n ? ` data-language=\"${escapeHtml(t.language)}\"`\n : \"\";\n html += `<pre><code${langAttr}>${escapeHtml(t.code)}</code></pre>`;\n i++;\n break;\n }\n\n case \"blockquote\": {\n const t = token as BlockquoteToken;\n // Recursively parse blockquote content as markdown\n const innerTokens = tokenize(t.content);\n const innerHtml = tokensToHtml(innerTokens);\n html += `<blockquote>${innerHtml}</blockquote>`;\n i++;\n break;\n }\n\n case \"hr\":\n html += `<hr>`;\n i++;\n break;\n\n case \"listItem\": {\n // Collect consecutive list items and build nested list structure\n const listHtml = emitListItems(tokens, i);\n html += listHtml.html;\n i = listHtml.nextIndex;\n break;\n }\n\n case \"table\": {\n const t = token as TableToken;\n html += emitTable(t);\n i++;\n break;\n }\n\n case \"rawHtml\": {\n const t = token as RawHtmlToken;\n html += t.content;\n i++;\n break;\n }\n\n default:\n i++;\n }\n }\n\n return html;\n}\n\nfunction emitListItems(\n tokens: Token[],\n startIdx: number,\n): { html: string; nextIndex: number } {\n let html = \"\";\n let i = startIdx;\n let currentListType: \"bullet\" | \"ordered\" | null = null;\n\n while (i < tokens.length && tokens[i].type === \"listItem\") {\n const item = tokens[i] as ListItemToken;\n const effectiveType = getEffectiveListType(item.listType);\n\n // Check if we need to switch list type\n if (currentListType !== null && currentListType !== effectiveType) {\n // Close current list, open new one\n html += `</${currentListType === \"ordered\" ? \"ol\" : \"ul\"}>`;\n currentListType = null;\n }\n\n // Open list if needed\n if (currentListType === null) {\n if (effectiveType === \"ordered\") {\n const startAttr =\n item.start !== undefined && item.start !== 1\n ? ` start=\"${item.start}\"`\n : \"\";\n html += `<ol${startAttr}>`;\n } else {\n html += `<ul>`;\n }\n currentListType = effectiveType;\n }\n\n // Emit list item\n if (item.listType === \"task\") {\n const checkedAttr = item.checked ? \" checked\" : \"\";\n html += `<li><input type=\"checkbox\" disabled${checkedAttr}><p>${parseInline(item.content)}</p>`;\n } else {\n html += `<li><p>${parseInline(item.content)}</p>`;\n }\n\n // Render child content (nested items, continuation paragraphs, etc.)\n if (item.childContent) {\n const childTokens = tokenize(item.childContent);\n html += tokensToHtml(childTokens);\n }\n\n html += `</li>`;\n i++;\n }\n\n // Close the list\n if (currentListType !== null) {\n html += `</${currentListType === \"ordered\" ? \"ol\" : \"ul\"}>`;\n }\n\n return { html, nextIndex: i };\n}\n\nfunction getEffectiveListType(\n listType: \"bullet\" | \"ordered\" | \"task\",\n): \"bullet\" | \"ordered\" {\n return listType === \"ordered\" ? \"ordered\" : \"bullet\";\n}\n\nfunction emitTable(table: TableToken): string {\n let html = \"<table>\";\n\n // BlockNote tables have no required header row, but the markdown table\n // syntax does. When we serialize a headerless BlockNote table to markdown\n // we emit an empty header row; on re-parse, treat that empty header as\n // \"no header\" so the round-trip is stable (issue #739).\n const headerIsEmpty = table.headers.every((h) => h.trim() === \"\");\n const colCount = table.headers.length;\n\n if (!headerIsEmpty) {\n html += \"<thead><tr>\";\n for (let c = 0; c < colCount; c++) {\n const align = table.alignments[c];\n const alignAttr = align ? ` align=\"${align}\"` : \"\";\n html += `<th${alignAttr}>${parseInline(table.headers[c])}</th>`;\n }\n html += \"</tr></thead>\";\n }\n\n if (table.rows.length > 0) {\n html += \"<tbody>\";\n for (const row of table.rows) {\n html += \"<tr>\";\n for (let c = 0; c < colCount; c++) {\n const cell = c < row.length ? row[c] : \"\";\n const align = table.alignments[c];\n const alignAttr = align ? ` align=\"${align}\"` : \"\";\n html += `<td${alignAttr}>${parseInline(cell)}</td>`;\n }\n html += \"</tr>\";\n }\n html += \"</tbody>\";\n }\n\n html += \"</table>\";\n return html;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Convert a markdown string to an HTML string.\n * This is a direct replacement for the unified/remark/rehype pipeline.\n */\nexport function markdownToHtml(markdown: string): string {\n const tokens = tokenize(markdown);\n return tokensToHtml(tokens);\n}\n","import { Schema } from \"prosemirror-model\";\n\nimport { Block } from \"../../../blocks/defaultBlocks.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { HTMLToBlocks } from \"../html/parseHTML.js\";\nimport { markdownToHtml } from \"./markdownToHtml.js\";\n\nexport function markdownToHTML(markdown: string): string {\n return markdownToHtml(markdown);\n}\n\nexport function markdownToBlocks<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(markdown: string, pmSchema: Schema): Block<BSchema, I, S>[] {\n const htmlString = markdownToHTML(markdown);\n\n return HTMLToBlocks(htmlString, pmSchema);\n}\n","import { createExternalHTMLExporter } from \"../../api/exporters/html/externalHTMLExporter.js\";\nimport { createInternalHTMLSerializer } from \"../../api/exporters/html/internalHTMLSerializer.js\";\nimport { blocksToMarkdown } from \"../../api/exporters/markdown/markdownExporter.js\";\nimport { HTMLToBlocks } from \"../../api/parsers/html/parseHTML.js\";\nimport {\n markdownToBlocks,\n markdownToHTML,\n} from \"../../api/parsers/markdown/parseMarkdown.js\";\nimport {\n Block,\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n PartialBlock,\n} from \"../../blocks/defaultBlocks.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { BlockNoteEditor } from \"../BlockNoteEditor.js\";\n\nexport class ExportManager<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> {\n constructor(private editor: BlockNoteEditor<BSchema, ISchema, SSchema>) {}\n\n /**\n * Exports blocks into a simplified HTML string. To better conform to HTML standards, children of blocks which aren't list\n * items are un-nested in the output HTML.\n *\n * @param blocks An array of blocks that should be serialized into HTML.\n * @returns The blocks, serialized as an HTML string.\n */\n public blocksToHTMLLossy(\n blocks: PartialBlock<BSchema, ISchema, SSchema>[] = this.editor.document,\n ): string {\n const exporter = createExternalHTMLExporter(\n this.editor.pmSchema,\n this.editor,\n );\n return exporter.exportBlocks(blocks, {});\n }\n\n /**\n * Serializes blocks into an HTML string in the format that would normally be rendered by the editor.\n *\n * Use this method if you want to server-side render HTML (for example, a blog post that has been edited in BlockNote)\n * and serve it to users without loading the editor on the client (i.e.: displaying the blog post)\n *\n * @param blocks An array of blocks that should be serialized into HTML.\n * @returns The blocks, serialized as an HTML string.\n */\n public blocksToFullHTML(\n blocks: PartialBlock<BSchema, ISchema, SSchema>[] = this.editor.document,\n ): string {\n const exporter = createInternalHTMLSerializer(\n this.editor.pmSchema,\n this.editor,\n );\n return exporter.serializeBlocks(blocks, {});\n }\n\n /**\n * Parses blocks from an HTML string. Tries to create `Block` objects out of any HTML block-level elements, and\n * `InlineNode` objects from any HTML inline elements, though not all element types are recognized. If BlockNote\n * doesn't recognize an HTML element's tag, it will parse it as a paragraph or plain text.\n * @param html The HTML string to parse blocks from.\n * @returns The blocks parsed from the HTML string.\n */\n public tryParseHTMLToBlocks(\n html: string,\n ): Block<BSchema, ISchema, SSchema>[] {\n return HTMLToBlocks(html, this.editor.pmSchema);\n }\n\n /**\n * Serializes blocks into a Markdown string. The output is simplified as Markdown does not support all features of\n * BlockNote - children of blocks which aren't list items are un-nested and certain styles are removed.\n * @param blocks An array of blocks that should be serialized into Markdown.\n * @returns The blocks, serialized as a Markdown string.\n */\n public blocksToMarkdownLossy(\n blocks: PartialBlock<BSchema, ISchema, SSchema>[] = this.editor.document,\n ): string {\n return blocksToMarkdown(blocks, this.editor.pmSchema, this.editor, {});\n }\n\n /**\n * Creates a list of blocks from a Markdown string. Tries to create `Block` and `InlineNode` objects based on\n * Markdown syntax, though not all symbols are recognized. If BlockNote doesn't recognize a symbol, it will parse it\n * as text.\n * @param markdown The Markdown string to parse blocks from.\n * @returns The blocks parsed from the Markdown string.\n */\n public tryParseMarkdownToBlocks(\n markdown: string,\n ): Block<BSchema, ISchema, SSchema>[] {\n return markdownToBlocks(markdown, this.editor.pmSchema);\n }\n\n /**\n * Paste HTML into the editor. Defaults to converting HTML to BlockNote HTML.\n * @param html The HTML to paste.\n * @param raw Whether to paste the HTML as is, or to convert it to BlockNote HTML.\n */\n public pasteHTML(html: string, raw = false) {\n let htmlToPaste = html;\n if (!raw) {\n const blocks = this.tryParseHTMLToBlocks(html);\n htmlToPaste = this.blocksToFullHTML(blocks);\n }\n if (!htmlToPaste) {\n return;\n }\n this.editor.prosemirrorView?.pasteHTML(htmlToPaste);\n }\n\n /**\n * Paste text into the editor. Defaults to interpreting text as markdown.\n * @param text The text to paste.\n */\n public pasteText(text: string) {\n return this.editor.prosemirrorView?.pasteText(text);\n }\n\n /**\n * Paste markdown into the editor.\n * @param markdown The markdown to paste.\n */\n public pasteMarkdown(markdown: string) {\n const html = markdownToHTML(markdown);\n return this.pasteHTML(html);\n }\n}\n","import { type Transaction } from \"prosemirror-state\";\nimport type { TextCursorPosition } from \"../../../editor/cursorPositionTypes.js\";\nimport type {\n BlockIdentifier,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport {\n blockEdgeSelection,\n getBlockInfoFromNode,\n getBlockInfoFromSelection,\n getParentBlockInfo,\n} from \"../../getBlockInfoFromPos.js\";\nimport { nodeToBlock } from \"../../nodeConversions/nodeToBlock.js\";\nimport { getNodeById } from \"../../nodeUtil.js\";\n\nexport function getTextCursorPosition<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(tr: Transaction): TextCursorPosition<BSchema, I, S> {\n const { block } = getBlockInfoFromSelection(tr);\n\n const resolvedPos = tr.doc.resolve(block.beforePos);\n // Gets previous blockContainer node at the same nesting level, if the current node isn't the first child.\n const prevNode = resolvedPos.nodeBefore;\n\n // Gets next blockContainer node at the same nesting level, if the current node isn't the last child.\n const nextNode = tr.doc.resolve(block.afterPos).nodeAfter;\n\n // Gets the parent block's node, if the current block is nested.\n const parentNode = getParentBlockInfo(tr.doc, block.beforePos)?.block.node;\n\n return {\n block: nodeToBlock(block.node, tr.doc),\n prevBlock: prevNode === null ? undefined : nodeToBlock(prevNode, tr.doc),\n nextBlock: nextNode === null ? undefined : nodeToBlock(nextNode, tr.doc),\n parentBlock:\n parentNode === undefined ? undefined : nodeToBlock(parentNode, tr.doc),\n };\n}\n\nexport function setTextCursorPosition(\n tr: Transaction,\n targetBlock: BlockIdentifier,\n placement: \"start\" | \"end\" = \"start\",\n) {\n const id = typeof targetBlock === \"string\" ? targetBlock : targetBlock.id;\n\n const posInfo = getNodeById(id, tr.doc);\n if (!posInfo) {\n throw new Error(`Block with ID ${id} not found`);\n }\n\n tr.setSelection(\n blockEdgeSelection(\n tr.doc,\n getBlockInfoFromNode(posInfo.node, posInfo.posBeforeNode),\n placement,\n ),\n );\n}\n","export const acceptedMIMETypes = [\n \"vscode-editor-data\",\n \"blocknote/html\",\n \"text/markdown\",\n \"text/html\",\n \"text/plain\",\n \"Files\",\n] as const;\n","import { Block, PartialBlock } from \"../../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { getBlockInfoNearPos, getNodeId } from \"../../getBlockInfoFromPos.js\";\nimport { acceptedMIMETypes } from \"./acceptedMIMETypes.js\";\n\nfunction checkFileExtensionsMatch(\n fileExtension1: string,\n fileExtension2: string,\n) {\n if (!fileExtension1.startsWith(\".\") || !fileExtension2.startsWith(\".\")) {\n throw new Error(`The strings provided are not valid file extensions.`);\n }\n\n return fileExtension1 === fileExtension2;\n}\n\nfunction checkMIMETypesMatch(mimeType1: string, mimeType2: string) {\n const types1 = mimeType1.split(\"/\");\n const types2 = mimeType2.split(\"/\");\n\n if (types1.length !== 2) {\n throw new Error(`The string ${mimeType1} is not a valid MIME type.`);\n }\n if (types2.length !== 2) {\n throw new Error(`The string ${mimeType2} is not a valid MIME type.`);\n }\n\n if (types1[1] === \"*\" || types2[1] === \"*\") {\n return types1[0] === types2[0];\n }\n if (types1[0] === \"*\" || types2[0] === \"*\") {\n return types1[1] === types2[1];\n }\n\n return types1[0] === types2[0] && types1[1] === types2[1];\n}\n\nfunction insertOrUpdateBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n referenceBlock: Block<BSchema, I, S>,\n newBlock: PartialBlock<BSchema, I, S>,\n placement: \"before\" | \"after\" = \"after\",\n) {\n let insertedBlockId: string | undefined;\n\n if (\n Array.isArray(referenceBlock.content) &&\n referenceBlock.content.length === 0\n ) {\n insertedBlockId = editor.updateBlock(referenceBlock, newBlock).id;\n } else {\n insertedBlockId = editor.insertBlocks(\n [newBlock],\n referenceBlock,\n placement,\n )[0].id;\n }\n\n return insertedBlockId;\n}\n\nexport async function handleFileInsertion<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(event: DragEvent | ClipboardEvent, editor: BlockNoteEditor<BSchema, I, S>) {\n if (!editor.uploadFile) {\n // eslint-disable-next-line no-console\n console.warn(\n \"Attempted ot insert file, but uploadFile is not set in the BlockNote editor options\",\n );\n return;\n }\n\n const dataTransfer =\n \"dataTransfer\" in event ? event.dataTransfer : event.clipboardData;\n if (dataTransfer === null) {\n return;\n }\n\n let format: (typeof acceptedMIMETypes)[number] | null = null;\n for (const mimeType of acceptedMIMETypes) {\n if (dataTransfer.types.includes(mimeType)) {\n format = mimeType;\n break;\n }\n }\n if (format !== \"Files\") {\n return;\n }\n\n const items = dataTransfer.items;\n if (!items) {\n return;\n }\n\n event.preventDefault();\n\n for (let i = 0; i < items.length; i++) {\n // Gets file block corresponding to MIME type.\n let fileBlockType = \"file\";\n for (const blockSpec of Object.values(editor.schema.blockSpecs)) {\n for (const mimeType of blockSpec.implementation.meta.fileBlockAccept ||\n []) {\n const isFileExtension = mimeType.startsWith(\".\");\n const file = items[i].getAsFile();\n\n if (file) {\n if (\n (!isFileExtension &&\n file.type &&\n checkMIMETypesMatch(items[i].type, mimeType)) ||\n (isFileExtension &&\n checkFileExtensionsMatch(\n \".\" + file.name.split(\".\").pop(),\n mimeType,\n ))\n ) {\n fileBlockType = blockSpec.config.type;\n break;\n }\n }\n }\n }\n\n const file = items[i].getAsFile();\n if (file) {\n const fileBlock = {\n type: fileBlockType,\n props: {\n name: file.name,\n },\n } as PartialBlock<BSchema, I, S>;\n\n let insertedBlockId: string | undefined = undefined;\n\n if (event.type === \"paste\") {\n const currentBlock = editor.getTextCursorPosition().block;\n insertedBlockId = insertOrUpdateBlock(editor, currentBlock, fileBlock);\n } else if (event.type === \"drop\") {\n const coords = {\n left: (event as DragEvent).clientX,\n top: (event as DragEvent).clientY,\n };\n\n const pos = editor.prosemirrorView.posAtCoords(coords);\n\n if (!pos) {\n return;\n }\n\n insertedBlockId = editor.transact((tr) => {\n const blockInfo = getBlockInfoNearPos(tr, pos.pos);\n const id = getNodeId(blockInfo.block.node, tr.doc);\n // TODO technically data-id will always be the non-rewritten id, so there might be multiple in the document.\n // getNodeId might find the wrong one (aka point to a deleted node when it should be a non-deleted on)\n // This is acceptable right now, given that we don't expect edits on the document content\n const blockElement = editor.domElement?.querySelector(\n `[data-id=\"${id}\"]`,\n );\n\n const blockRect = blockElement?.getBoundingClientRect();\n\n const existingBlock = editor.getBlock(id);\n if (!existingBlock) {\n return;\n }\n\n return insertOrUpdateBlock(\n editor,\n existingBlock,\n fileBlock,\n blockRect && (blockRect.top + blockRect.bottom) / 2 > coords.top\n ? \"before\"\n : \"after\",\n );\n });\n } else {\n return;\n }\n\n if (!insertedBlockId) {\n return;\n }\n\n const updateData = await editor.uploadFile(file, insertedBlockId);\n\n const updatedFileBlock =\n typeof updateData === \"string\"\n ? ({\n props: {\n url: updateData,\n },\n } as PartialBlock<BSchema, I, S>)\n : { ...updateData };\n\n editor.updateBlock(insertedBlockId, updatedFileBlock);\n }\n }\n}\n","import { Extension } from \"@tiptap/core\";\nimport { Plugin } from \"prosemirror-state\";\n\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { acceptedMIMETypes } from \"./acceptedMIMETypes.js\";\nimport { handleFileInsertion } from \"./handleFileInsertion.js\";\n\nexport const createDropFileExtension = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n) =>\n Extension.create<{ editor: BlockNoteEditor<BSchema, I, S> }, undefined>({\n name: \"dropFile\",\n addProseMirrorPlugins() {\n return [\n new Plugin({\n props: {\n handleDOMEvents: {\n drop(_view, event) {\n if (!editor.isEditable) {\n return;\n }\n\n let format: (typeof acceptedMIMETypes)[number] | null = null;\n for (const mimeType of acceptedMIMETypes) {\n if (event.dataTransfer!.types.includes(mimeType)) {\n format = mimeType;\n break;\n }\n }\n if (format === null) {\n return true;\n }\n\n if (format === \"Files\") {\n void handleFileInsertion(event, editor);\n return true;\n }\n\n return false;\n },\n },\n },\n }),\n ];\n },\n });\n","// Headings H1-H6.\nconst h1 = /(^|\\n) {0,3}#{1,6} {1,8}[^\\n]{1,64}\\r?\\n\\r?\\n\\s{0,32}\\S/;\n\n// Bold, italic, underline, strikethrough, highlight.\nconst bold =\n /(_|__|\\*|\\*\\*|~~|==|\\+\\+)(?!\\s)(?:[^\\s](?:.{0,62}[^\\s])?|\\S)(?=\\1)/;\n\n// Basic inline link (also captures images).\nconst link = /\\[[^\\]]{1,128}\\]\\(https?:\\/\\/\\S{1,999}\\)/;\n\n// Inline code.\nconst code = /(?:\\s|^)`(?!\\s)(?:[^\\s`](?:[^`]{0,46}[^\\s`])?|[^\\s`])`([^\\w]|$)/;\n\n// Unordered list.\nconst ul = /(?:^|\\n)\\s{0,5}-\\s{1}[^\\n]+\\n\\s{0,15}-\\s/;\n\n// Ordered list.\nconst ol = /(?:^|\\n)\\s{0,5}\\d+\\.\\s{1}[^\\n]+\\n\\s{0,15}\\d+\\.\\s/;\n\n// Horizontal rule.\nconst hr = /\\n{2} {0,3}-{2,48}\\n{2}/;\n\n// Fenced code block.\nconst fences =\n /(?:\\n|^)(```|~~~|\\$\\$)(?!`|~)[^\\s]{0,64} {0,64}[^\\n]{0,64}\\n[\\s\\S]{0,9999}?\\s*\\1 {0,64}(?:\\n+|$)/;\n\n// Classical underlined H1 and H2 headings.\nconst title = /(?:\\n|^)(?!\\s)\\w[^\\n]{0,64}\\r?\\n(-|=)\\1{0,64}\\n\\n\\s{0,64}(\\w|$)/;\n\n// Blockquote.\nconst blockquote =\n /(?:^|(\\r?\\n\\r?\\n))( {0,3}>[^\\n]{1,333}\\n){1,999}($|(\\r?\\n))/;\n\n// Table Header\nconst tableHeader = /^\\s*\\|(.+\\|)+\\s*$/m;\n\n// Table Divider\nconst tableDivider = /^\\s*\\|(\\s*[-:]+[-:]\\s*\\|)+\\s*$/m;\n\n// Table Row\nconst tableRow = /^\\s*\\|(.+\\|)+\\s*$/m;\n\n/**\n * Returns `true` if the source text might be a markdown document.\n *\n * @param src Source text to analyze.\n */\nexport const isMarkdown = (src: string): boolean =>\n h1.test(src) ||\n bold.test(src) ||\n link.test(src) ||\n code.test(src) ||\n ul.test(src) ||\n ol.test(src) ||\n hr.test(src) ||\n fences.test(src) ||\n title.test(src) ||\n blockquote.test(src) ||\n tableHeader.test(src) ||\n tableDivider.test(src) ||\n tableRow.test(src);\n","import { EditorView } from \"prosemirror-view\";\n\nexport function handleVSCodePaste(event: ClipboardEvent, view: EditorView) {\n const { schema } = view.state;\n\n if (!event.clipboardData) {\n return false;\n }\n\n const text = event.clipboardData!.getData(\"text/plain\");\n\n if (!text) {\n return false;\n }\n\n if (!schema.nodes.codeBlock) {\n return false;\n }\n\n const vscode = event.clipboardData!.getData(\"vscode-editor-data\");\n const vscodeData = vscode ? JSON.parse(vscode) : undefined;\n const language = vscodeData?.mode;\n\n if (!language) {\n return false;\n }\n\n // strip carriage return chars from text pasted as code\n // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd\n view.pasteHTML(\n `<pre><code class=\"language-${language}\">${text.replace(\n /\\r\\n?/g,\n \"\\n\",\n )}</code></pre>`,\n );\n\n return true;\n}\n","import { Extension } from \"@tiptap/core\";\nimport { Plugin } from \"prosemirror-state\";\n\nimport type {\n BlockNoteEditor,\n BlockNoteEditorOptions,\n} from \"../../../editor/BlockNoteEditor\";\nimport { isMarkdown } from \"../../parsers/markdown/detectMarkdown.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { acceptedMIMETypes } from \"./acceptedMIMETypes.js\";\nimport { handleFileInsertion } from \"./handleFileInsertion.js\";\nimport { handleVSCodePaste } from \"./handleVSCodePaste.js\";\n\nfunction defaultPasteHandler({\n event,\n editor,\n prioritizeMarkdownOverHTML,\n plainTextAsMarkdown,\n}: {\n event: ClipboardEvent;\n editor: BlockNoteEditor<any, any, any>;\n prioritizeMarkdownOverHTML: boolean;\n plainTextAsMarkdown: boolean;\n}) {\n // Special case for code blocks, as they do not support any rich text\n // formatting, so we force pasting plain text.\n const isInCodeBlock = editor.transact(\n (tr) =>\n tr.selection.$from.parent.type.spec.code &&\n tr.selection.$to.parent.type.spec.code,\n );\n\n if (isInCodeBlock) {\n const data = event.clipboardData?.getData(\"text/plain\");\n\n if (data) {\n editor.pasteText(data);\n\n return true;\n }\n }\n\n let format: (typeof acceptedMIMETypes)[number] | undefined;\n for (const mimeType of acceptedMIMETypes) {\n if (event.clipboardData!.types.includes(mimeType)) {\n format = mimeType;\n break;\n }\n }\n\n if (!format) {\n return true;\n }\n\n if (format === \"vscode-editor-data\") {\n // If VSCode clipboard data cannot be parsed as a code block, try parsing\n // `text/plain` as a fallback.\n if (handleVSCodePaste(event, editor.prosemirrorView)) {\n return true;\n }\n\n format = \"text/plain\";\n }\n\n if (format === \"Files\") {\n void handleFileInsertion(event, editor);\n return true;\n }\n\n const data = event.clipboardData!.getData(format);\n\n if (format === \"blocknote/html\") {\n // Is blocknote/html, so no need to convert it\n editor.pasteHTML(data, true);\n return true;\n }\n\n if (format === \"text/markdown\") {\n editor.pasteMarkdown(data);\n return true;\n }\n\n if (prioritizeMarkdownOverHTML) {\n // Use plain text instead of HTML if it looks like Markdown\n const plainText = event.clipboardData!.getData(\"text/plain\");\n\n if (isMarkdown(plainText)) {\n editor.pasteMarkdown(plainText);\n return true;\n }\n }\n\n if (format === \"text/html\") {\n editor.pasteHTML(data);\n return true;\n }\n\n if (plainTextAsMarkdown) {\n editor.pasteMarkdown(data);\n return true;\n }\n\n editor.pasteText(data);\n return true;\n}\n\nexport const createPasteFromClipboardExtension = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n pasteHandler: Exclude<\n BlockNoteEditorOptions<any, any, any>[\"pasteHandler\"],\n undefined\n >,\n) =>\n Extension.create({\n name: \"pasteFromClipboard\",\n addProseMirrorPlugins() {\n return [\n new Plugin({\n props: {\n handleDOMEvents: {\n paste(_view, event) {\n event.preventDefault();\n\n if (!editor.isEditable) {\n return;\n }\n\n return pasteHandler({\n event,\n editor,\n defaultPasteHandler: ({\n prioritizeMarkdownOverHTML = true,\n plainTextAsMarkdown = true,\n } = {}) => {\n return defaultPasteHandler({\n event,\n editor,\n prioritizeMarkdownOverHTML,\n plainTextAsMarkdown,\n });\n },\n });\n },\n },\n },\n }),\n ];\n },\n });\n","import { Extension } from \"@tiptap/core\";\nimport { Fragment, Node } from \"prosemirror-model\";\nimport { NodeSelection, Plugin } from \"prosemirror-state\";\nimport { CellSelection } from \"prosemirror-tables\";\nimport type { EditorView } from \"prosemirror-view\";\n\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { createExternalHTMLExporter } from \"../../exporters/html/externalHTMLExporter.js\";\nimport { cleanHTMLToMarkdown } from \"../../exporters/markdown/markdownExporter.js\";\nimport { fragmentToBlocks } from \"../../nodeConversions/fragmentToBlocks.js\";\nimport {\n contentNodeToInlineContent,\n contentNodeToTableContent,\n} from \"../../nodeConversions/nodeToBlock.js\";\n\nfunction fragmentToExternalHTML<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n view: EditorView,\n selectedFragment: Fragment,\n editor: BlockNoteEditor<BSchema, I, S>,\n) {\n let isWithinBlockContent = false;\n const isWithinTable = view.state.selection instanceof CellSelection;\n\n if (!isWithinTable) {\n // Checks whether block ancestry should be included when creating external\n // HTML. If the selection is within a block content node, the block ancestry\n // is excluded as we only care about the inline content.\n const fragmentWithoutParents = view.state.doc.slice(\n view.state.selection.from,\n view.state.selection.to,\n false,\n ).content;\n\n const children = [];\n for (let i = 0; i < fragmentWithoutParents.childCount; i++) {\n children.push(fragmentWithoutParents.child(i));\n }\n\n isWithinBlockContent =\n children.find(\n (child) =>\n child.type.isInGroup(\"bnBlock\") ||\n child.type.name === \"blockGroup\" ||\n child.type.spec.group === \"blockContent\",\n ) === undefined;\n if (isWithinBlockContent) {\n selectedFragment = fragmentWithoutParents;\n }\n }\n\n let externalHTML: string;\n\n const externalHTMLExporter = createExternalHTMLExporter(\n view.state.schema,\n editor,\n );\n\n if (isWithinTable) {\n if (selectedFragment.firstChild?.type.name === \"table\") {\n // contentNodeToTableContent expects the fragment of the content of a table, not the table node itself\n // but cellselection.content() returns the table node itself if all cells and columns are selected\n selectedFragment = selectedFragment.firstChild.content;\n }\n\n // first convert selection to blocknote-style table content, and then\n // pass this to the exporter\n const ic = contentNodeToTableContent(\n selectedFragment as any,\n editor.schema.inlineContentSchema,\n editor.schema.styleSchema,\n );\n\n // Wrap in table to ensure correct parsing by spreadsheet applications\n externalHTML = `<table>${externalHTMLExporter.exportInlineContent(\n ic as any,\n {},\n )}</table>`;\n } else if (isWithinBlockContent) {\n // first convert selection to blocknote-style inline content, and then\n // pass this to the exporter\n const ic = contentNodeToInlineContent(\n selectedFragment as any,\n editor.schema.inlineContentSchema,\n editor.schema.styleSchema,\n );\n externalHTML = externalHTMLExporter.exportInlineContent(ic, {});\n } else {\n const blocks = fragmentToBlocks<BSchema, I, S>(selectedFragment);\n externalHTML = externalHTMLExporter.exportBlocks(blocks, {});\n }\n return externalHTML;\n}\n\nexport function selectedFragmentToHTML<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n view: EditorView,\n editor: BlockNoteEditor<BSchema, I, S>,\n): {\n clipboardHTML: string;\n externalHTML: string;\n markdown: string;\n} {\n // Checks if a `blockContent` node is being copied and expands\n // the selection to the parent `blockContainer` node. This is\n // for the use-case in which only a block without content is\n // selected, e.g. an image block.\n if (\n \"node\" in view.state.selection &&\n (view.state.selection.node as Node).type.spec.group === \"blockContent\"\n ) {\n editor.transact((tr) =>\n tr.setSelection(\n new NodeSelection(tr.doc.resolve(view.state.selection.from - 1)),\n ),\n );\n }\n\n // Uses default ProseMirror clipboard serialization.\n const clipboardHTML: string = view.serializeForClipboard(\n view.state.selection.content(),\n ).dom.innerHTML;\n\n const selectedFragment = view.state.selection.content().content;\n\n const externalHTML = fragmentToExternalHTML<BSchema, I, S>(\n view,\n selectedFragment,\n editor,\n );\n\n // Code blocks are treated differently for copying: text/plain is the raw\n // selected text instead of markdown.\n const { $from, $to } = view.state.selection;\n const parentBlockType = $from.parent.type.name;\n const parentBlockSpec =\n editor.schema.blockSpecs[parentBlockType as keyof BSchema];\n const isPurelyInsideCodeBlock =\n $from.sameParent($to) && parentBlockSpec?.implementation.meta.code === true;\n\n const markdown = isPurelyInsideCodeBlock\n ? view.state.doc.textBetween($from.pos, $to.pos)\n : cleanHTMLToMarkdown(externalHTML);\n\n return { clipboardHTML, externalHTML, markdown };\n}\n\nconst checkIfSelectionInNonEditableBlock = (view: EditorView) => {\n // Use ProseMirror's internal selection state to check for empty selection.\n // window.getSelection() returns null or a collapsed selection inside Shadow\n // DOM (Firefox, Safari, and Chromium edge cases), causing this guard to\n // misfire and silently skip clipboard writes. view.state.selection is always\n // accurate regardless of DOM mode.\n if (view.state.selection.empty) {\n return true;\n }\n\n // Let browser handle event if it's within a non-editable\n // \"island\". This means it's in selectable content within a\n // non-editable block. We only need to check one node as it's\n // not possible for the browser selection to start in an\n // editable block and end in a non-editable one.\n const selection = window.getSelection();\n if (selection && !selection.isCollapsed) {\n let node = selection.focusNode;\n while (node) {\n if (\n node instanceof HTMLElement &&\n node.getAttribute(\"contenteditable\") === \"false\"\n ) {\n return true;\n }\n\n node = node.parentElement;\n }\n }\n\n return false;\n};\n\nconst copyToClipboard = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n view: EditorView,\n event: ClipboardEvent,\n) => {\n // Stops the default browser copy behaviour.\n event.preventDefault();\n event.clipboardData!.clearData();\n\n const { clipboardHTML, externalHTML, markdown } = selectedFragmentToHTML(\n view,\n editor,\n );\n\n // TODO: Writing to other MIME types not working in Safari for\n // some reason.\n event.clipboardData!.setData(\"blocknote/html\", clipboardHTML);\n event.clipboardData!.setData(\"text/html\", externalHTML);\n event.clipboardData!.setData(\"text/plain\", markdown);\n};\n\nexport const createCopyToClipboardExtension = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n) =>\n Extension.create<{ editor: BlockNoteEditor<BSchema, I, S> }, undefined>({\n name: \"copyToClipboard\",\n addProseMirrorPlugins() {\n return [\n new Plugin({\n props: {\n handleDOMEvents: {\n copy(view, event) {\n if (checkIfSelectionInNonEditableBlock(view)) {\n return true;\n }\n\n copyToClipboard(editor, view, event);\n // Prevent default PM handler to be called\n return true;\n },\n cut(view, event) {\n if (checkIfSelectionInNonEditableBlock(view)) {\n return true;\n }\n\n copyToClipboard(editor, view, event);\n if (view.editable) {\n view.dispatch(view.state.tr.deleteSelection());\n }\n // Prevent default PM handler to be called\n return true;\n },\n // This is for the use-case in which only a block without content\n // is selected, e.g. an image block, and dragged (not using the\n // drag handle).\n dragstart(view, event) {\n // Checks if a `NodeSelection` is active.\n if (!(\"node\" in view.state.selection)) {\n return;\n }\n\n // Checks if a `blockContent` node is being dragged.\n if (\n (view.state.selection.node as Node).type.spec.group !==\n \"blockContent\"\n ) {\n return;\n }\n\n // Expands the selection to the parent `blockContainer` node.\n editor.transact((tr) =>\n tr.setSelection(\n new NodeSelection(\n tr.doc.resolve(view.state.selection.from - 1),\n ),\n ),\n );\n\n // Stops the default browser drag start behaviour.\n event.preventDefault();\n event.dataTransfer!.clearData();\n\n const { clipboardHTML, externalHTML, markdown } =\n selectedFragmentToHTML(view, editor);\n\n // TODO: Writing to other MIME types not working in Safari for\n // some reason.\n event.dataTransfer!.setData(\"blocknote/html\", clipboardHTML);\n event.dataTransfer!.setData(\"text/html\", externalHTML);\n event.dataTransfer!.setData(\"text/plain\", markdown);\n\n // Prevent default PM handler to be called\n return true;\n },\n },\n },\n }),\n ];\n },\n });\n","import { Extension } from \"@tiptap/core\";\nimport { getBackgroundColorAttribute } from \"../../../blocks/defaultProps.js\";\n\nexport const BackgroundColorExtension = Extension.create({\n name: \"blockBackgroundColor\",\n\n addGlobalAttributes() {\n return [\n {\n types: [\"tableCell\", \"tableHeader\"],\n attributes: {\n backgroundColor: getBackgroundColorAttribute(),\n },\n },\n ];\n },\n});\n","// Stripped down version of the TipTap HardBreak extension:\n// https://github.com/ueberdosis/tiptap/blob/f3258d9ee5fb7979102fe63434f6ea4120507311/packages/extension-hard-break/src/hard-break.ts#L80\n// Changes:\n// - Removed options\n// - Removed keyboard shortcuts & moved them to the `KeyboardShortcutsExtension`\n// - Removed `setHardBreak` command (added a simpler version in the Shift+Enter\n// handler in `KeyboardShortcutsExtension`).\n// - Added priority\nimport { mergeAttributes, Node } from \"@tiptap/core\";\n\nexport const HardBreak = Node.create({\n name: \"hardBreak\",\n\n inline: true,\n\n group: \"inline\",\n\n selectable: false,\n\n linebreakReplacement: true,\n\n priority: 10,\n\n parseHTML() {\n return [{ tag: \"br\" }];\n },\n\n renderHTML({ HTMLAttributes }) {\n return [\"br\", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];\n },\n\n renderText() {\n return \"\\n\";\n },\n});\n","import { Fragment } from \"prosemirror-model\";\nimport {\n EditorState,\n Selection,\n TextSelection,\n Transaction,\n} from \"prosemirror-state\";\n\nimport {\n type BlockInfo,\n getBlockInfoAt,\n getLastDescendantBlockInfo,\n getParentBlockInfo,\n getPrevBlockInfo,\n} from \"../../../getBlockInfoFromPos.js\";\n\ntype ContentBlockInfo = Extract<BlockInfo, { hasContent: true }>;\n\n/**\n * Returns the content to append, or undefined when the blocks cannot merge.\n * Only inline content merges, into inline content: a block with plain-text\n * content (e.g. a code block) never takes merged text.\n */\nexport function getMergeContent(\n current: ContentBlockInfo,\n next: ContentBlockInfo,\n): Fragment | undefined {\n return current.contentKind === \"inline\" && next.contentKind === \"inline\"\n ? next.content.node.content\n : undefined;\n}\n\n/** Merge a first child into its parent, promoting descendants into its place. */\nfunction mergeIntoParent(\n state: EditorState,\n dispatch: ((tr: Transaction) => void) | undefined,\n parent: ContentBlockInfo,\n child: ContentBlockInfo,\n): boolean {\n if (!parent.children) {\n return false;\n }\n const content = getMergeContent(parent, child);\n if (\n content === undefined ||\n (content.size > 0 &&\n !parent.content.node.type.validContent(\n parent.content.node.content.append(content),\n ))\n ) {\n return false;\n }\n\n if (dispatch) {\n const tr = state.tr;\n if (parent.children.node.childCount === 1 && !child.children) {\n tr.delete(parent.children.beforePos, parent.children.afterPos);\n } else {\n tr.replaceWith(\n child.block.beforePos,\n child.block.afterPos,\n child.children?.node.content ?? Fragment.empty,\n );\n }\n const cursorPos = parent.contentEnd;\n if (content.size > 0) {\n tr.insert(cursorPos, content);\n }\n tr.setSelection(Selection.near(tr.doc.resolve(cursorPos), -1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n}\n\n/**\n * Merges the block starting at `posBetweenBlocks` into the block visually\n * above it, by deleting the boundary between the two.\n *\n * @param posBetweenBlocks The position of the boundary between the two blocks:\n * the position just before the outer node of the block being merged upwards,\n * i.e. its `BlockInfo`'s `block.beforePos`. The block above is found by walking\n * back from there: the previous sibling's deepest descendant, or the parent\n * when the block is its first child.\n * @returns A tiptap command that returns `false` (leaving the doc untouched)\n * when the two blocks can't merge: no compatible text block above. The block\n * above may be empty. With the same type and props, the block moves up into\n * its place. Otherwise the text takes the empty block's type and props (and\n * id), as in Notion.\n */\nexport const mergeBlocksCommand =\n (posBetweenBlocks: number) =>\n ({\n state,\n dispatch,\n }: {\n state: EditorState;\n dispatch: ((tr: Transaction) => void) | undefined;\n }) => {\n const nextBlockInfo = getBlockInfoAt(state.doc, posBetweenBlocks);\n if (!nextBlockInfo.hasContent) {\n return false;\n }\n\n const prevSibling = getPrevBlockInfo(\n state.doc,\n nextBlockInfo.block.beforePos,\n );\n if (!prevSibling) {\n const parent = getParentBlockInfo(\n state.doc,\n nextBlockInfo.block.beforePos,\n );\n if (!parent?.hasContent) {\n return false;\n }\n return mergeIntoParent(state, dispatch, parent, nextBlockInfo);\n }\n\n // The block we merge into is the last descendant of the previous block:\n // visually, that's the block directly above the boundary.\n const prevBlockInfo = getLastDescendantBlockInfo(prevSibling);\n if (!prevBlockInfo.hasContent) {\n return false;\n }\n if (getMergeContent(prevBlockInfo, nextBlockInfo) === undefined) {\n return false;\n }\n\n // An empty block above with the same type and props adds nothing: the\n // block moves up into its place, keeping its id and children (#550).\n if (\n prevBlockInfo.isContentEmpty &&\n prevBlockInfo.content.node.sameMarkup(nextBlockInfo.content.node)\n ) {\n if (dispatch) {\n const tr = state.tr\n .delete(nextBlockInfo.block.beforePos, nextBlockInfo.block.afterPos)\n .replaceWith(\n prevBlockInfo.block.beforePos,\n prevBlockInfo.block.afterPos,\n nextBlockInfo.block.node,\n );\n tr.setSelection(\n TextSelection.create(tr.doc, prevBlockInfo.contentStart),\n );\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n\n // Lift children before removing their parent. `state.tr` here is not a\n // fresh transaction: tiptap's chainable state (`createChainableState`)\n // returns the one transaction the command runs in from every `tr` read,\n // so this lift and the delete below are dispatched together. The \"Second\n // block has children\" test in mergeBlocks.test.ts pins that the lifted\n // children survive the merge.\n if (dispatch && nextBlockInfo.children) {\n const childBlocksRange = state.doc\n .resolve(nextBlockInfo.children.childrenStart)\n .blockRange(state.doc.resolve(nextBlockInfo.children.childrenEnd));\n\n // A block's children always sit at the same depth in the same parent, so\n // they form a block range. No range means the doc is malformed, which is\n // a bug rather than a case to merge around.\n if (!childBlocksRange) {\n throw new Error(\n \"Children of a block are expected to form a block range\",\n );\n }\n\n state.tr.lift(\n childBlocksRange,\n state.doc.resolve(nextBlockInfo.block.beforePos).depth,\n );\n }\n\n // Deletes the boundary between the two blocks. Can be thought of as\n // removing the closing tags of the first block and the opening tags of the\n // second one to stitch them together.\n if (dispatch) {\n dispatch(\n state.tr.delete(prevBlockInfo.contentEnd, nextBlockInfo.contentStart),\n );\n }\n\n return true;\n };\n","import { EditorState, Transaction } from \"prosemirror-state\";\n\nimport {\n getBlockInfoFromNode,\n getNearestBlockPos,\n} from \"../../../getBlockInfoFromPos.js\";\nimport { getPmSchema } from \"../../../pmUtil.js\";\n\nexport const splitBlockCommand = (\n posInBlock: number,\n keepType?: boolean,\n keepProps?: boolean,\n keepChildren?: boolean,\n) => {\n return ({\n state,\n dispatch,\n }: {\n state: EditorState;\n dispatch: ((args?: any) => any) | undefined;\n }) => {\n if (dispatch) {\n return splitBlockTr(\n state.tr,\n posInBlock,\n keepType,\n keepProps,\n keepChildren,\n );\n }\n\n return true;\n };\n};\n\nexport const splitBlockTr = (\n tr: Transaction,\n posInBlock: number,\n keepType?: boolean,\n keepProps?: boolean,\n keepChildren?: boolean,\n): boolean => {\n const nearestBlockContainerPos = getNearestBlockPos(tr.doc, posInBlock);\n\n const info = getBlockInfoFromNode(\n nearestBlockContainerPos.node,\n nearestBlockContainerPos.posBeforeNode,\n );\n\n if (!info.hasContent) {\n return false;\n }\n const schema = getPmSchema(tr);\n\n const types = [\n {\n type: info.block.node.type, // always keep blockcontainer type\n attrs: keepProps ? { ...info.block.node.attrs, id: undefined } : {},\n },\n {\n type: keepType ? info.content.node.type : schema.nodes[\"paragraph\"],\n attrs: keepProps ? { ...info.content.node.attrs } : {},\n },\n ];\n\n // The children follow the text after the caret into the second block, as\n // `tr.split` leaves them. With `keepChildren` they move back to the first\n // half, within the same undo step. At the start, the whole content goes to\n // the second block, and the children with it.\n const children =\n keepChildren && posInBlock !== info.contentStart\n ? info.children\n : undefined;\n if (children) {\n tr.delete(children.beforePos, children.afterPos);\n }\n tr.split(posInBlock, 2, types);\n if (children) {\n const original = tr.doc.nodeAt(info.block.beforePos);\n if (!original?.firstChild) {\n throw new Error(\"Split lost its original block\");\n }\n tr.insert(\n info.block.beforePos + 1 + original.firstChild.nodeSize,\n children.node,\n );\n }\n\n return true;\n};\n","import { type ChainedCommands, Extension } from \"@tiptap/core\";\nimport { Fragment, type Node } from \"prosemirror-model\";\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n Transaction,\n} from \"prosemirror-state\";\n\nimport {\n mergeBlocksCommand,\n getMergeContent,\n} from \"../../../api/blockManipulation/commands/mergeBlocks/mergeBlocks.js\";\nimport {\n liftItem,\n nestBlock,\n unnestBlock,\n} from \"../../../api/blockManipulation/commands/nestBlock/nestBlock.js\";\nimport { fixLayoutBlocksById } from \"../../../api/blockManipulation/layoutBlocks/fixLayoutBlock.js\";\nimport { nodeToBlock } from \"../../../api/nodeConversions/nodeToBlock.js\";\nimport { isLayoutNode } from \"../../../schema/blocks/children.js\";\nimport { splitBlockCommand } from \"../../../api/blockManipulation/commands/splitBlock/splitBlock.js\";\nimport { updateBlockCommand } from \"../../../api/blockManipulation/commands/updateBlock/updateBlock.js\";\nimport {\n type BlockInfo,\n ascendToInsertablePos,\n getInsertionPos,\n getAncestorLayoutBlocks,\n getFirstLeafBlock,\n getBlockInfoAt,\n getBlockInfoFromNode,\n getBlockInfoFromSelection,\n getLastDescendantBlockInfo,\n getNextBlockInfo,\n getParentBlockInfo,\n getPrevBlockInfo,\n blockEdgeSelection,\n} from \"../../../api/getBlockInfoFromPos.js\";\nimport { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport { FilePanelExtension } from \"../../FilePanel/FilePanel.js\";\nimport { FormattingToolbarExtension } from \"../../FormattingToolbar/FormattingToolbar.js\";\n\n// Move a block across a layout block boundary, repair its former ancestors, and\n// map the caret through any repairs that change the insertion position.\nfunction moveBlockOutAndPlaceCaret(\n tr: Transaction,\n block: BlockInfo[\"block\"],\n insertAt: number,\n) {\n const layoutBlocksToFix = getAncestorLayoutBlocks(tr.doc, block.beforePos);\n tr.delete(block.beforePos, block.afterPos);\n const insertionPos = tr.mapping.map(insertAt);\n tr.insert(insertionPos, block.node);\n const stepsBeforeFix = tr.steps.length;\n fixLayoutBlocksById(tr, layoutBlocksToFix);\n tr.setSelection(\n TextSelection.near(\n tr.doc.resolve(tr.mapping.slice(stepsBeforeFix).map(insertionPos) + 1),\n ),\n );\n}\n\n// Delete a following block, retaining its children and any compatible text.\n// A sole child also removes its child group instead of leaving an empty body.\nfunction deleteBlockAndAppendContent(\n chain: ChainedCommands,\n current: Extract<BlockInfo, { hasContent: true }>,\n next: Extract<BlockInfo, { hasContent: true }>,\n remove: Pick<BlockInfo[\"block\"], \"beforePos\" | \"afterPos\"> = next.block,\n) {\n return chain\n .insertContentAt(\n next.block.afterPos,\n next.children?.node.content || Fragment.empty,\n )\n .deleteRange({ from: remove.beforePos, to: remove.afterPos })\n .insertContentAt(current.contentEnd, getMergeContent(current, next) ?? null)\n .setTextSelection(current.contentEnd)\n .scrollIntoView()\n .run();\n}\n\nexport const KeyboardShortcutsExtension = Extension.create<{\n editor: BlockNoteEditor<any, any, any>;\n tabBehavior: \"prefer-navigate-ui\" | \"prefer-indent\";\n selectAllBehavior: \"block-first\" | \"document\";\n}>({\n priority: 50,\n\n // TODO: The shortcuts need a refactor. Do we want to use a command priority\n // design as there is now, or clump the logic into a single function?\n addKeyboardShortcuts() {\n const bnEditor = this.options.editor;\n // The `keyboard` settings of the block that `node` holds, in `doc`.\n function keyboardOf(node: Node, doc: Node) {\n const block = nodeToBlock(node, doc);\n return bnEditor.schema.blockSpecs[block.type].implementation.keyboard(\n block,\n );\n }\n function canOutdentFrom(doc: Node) {\n return (parent: Node) => keyboardOf(parent, doc).childrenCanOutdent;\n }\n // handleBackspace is partially adapted from https://github.com/ueberdosis/tiptap/blob/ed56337470efb4fd277128ab7ef792b37cfae992/packages/core/src/extensions/keymap.ts\n const handleBackspace = () =>\n this.editor.commands.first(({ chain, commands }) => [\n // Deletes the selection if it's not empty.\n () => commands.deleteSelection(),\n // Undoes an input rule if one was triggered in the last editor state change.\n () => commands.undoInputRule(),\n // Resets the block (`keyboard.resetsTo`, a paragraph by default) if the\n // selection is at the start of the block and the block isn't already\n // in that form.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n\n const selectionAtBlockStart =\n state.selection.from === blockInfo.contentStart;\n if (!selectionAtBlockStart) {\n return false;\n }\n\n const resetsTo = keyboardOf(\n blockInfo.block.node,\n state.doc,\n ).resetsTo;\n const content = blockInfo.content.node;\n const alreadyReset =\n content.type.name === resetsTo.type &&\n Object.entries(resetsTo.props ?? {}).every(\n ([prop, value]) => content.attrs[prop] === value,\n );\n if (alreadyReset) {\n return false;\n }\n\n return commands.command(\n updateBlockCommand(blockInfo.block.beforePos, resetsTo as any),\n );\n }),\n // Merges at the start of the block, into the preceding sibling\n // (or its deepest descendant) or parent. Both must have inline content.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n const { block: blockContainer } = blockInfo;\n\n const prevSibling = getPrevBlockInfo(\n state.doc,\n blockInfo.block.beforePos,\n );\n // A preceding layout block takes the move branch below. Otherwise\n // the block merges into the block above (its last descendant), or\n // into its parent when it has no previous sibling;\n // mergeBlocksCommand decides whether their contents are\n // compatible.\n if (prevSibling && !prevSibling.hasContent) {\n return false;\n }\n\n const selectionAtBlockStart =\n state.selection.from === blockInfo.contentStart;\n const selectionEmpty = state.selection.empty;\n\n const posBetweenBlocks = blockContainer.beforePos;\n\n if (selectionAtBlockStart && selectionEmpty) {\n return chain()\n .command(mergeBlocksCommand(posBetweenBlocks))\n .scrollIntoView()\n .run();\n }\n\n return false;\n }),\n // Move into the preceding layout block's trailing slot, or out of the\n // current layout block when this is its first block.\n () =>\n commands.command(({ state, tr, dispatch }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (\n !blockInfo.hasContent ||\n state.selection.from !== blockInfo.contentStart\n ) {\n return false;\n }\n\n const blockType = blockInfo.block.node.type;\n let target = getPrevBlockInfo(tr.doc, blockInfo.block.beforePos);\n let insertionPos: number | undefined;\n if (target) {\n if (target.hasContent) {\n return false;\n }\n } else {\n const $pos = tr.doc.resolve(blockInfo.block.beforePos);\n if (!isLayoutNode($pos.parent.type)) {\n return false;\n }\n const $layoutBlockPos = tr.doc.resolve($pos.before());\n // Between columns, move into the previous column. Outside a\n // layout block, move above the closest boundary that accepts us.\n const prevSibling = $layoutBlockPos.nodeBefore;\n if (\n isLayoutNode($layoutBlockPos.parent.type) &&\n prevSibling &&\n isLayoutNode(prevSibling.type)\n ) {\n target = getBlockInfoFromNode(\n prevSibling,\n $layoutBlockPos.pos - prevSibling.nodeSize,\n );\n } else {\n insertionPos = ascendToInsertablePos(\n tr.doc,\n $layoutBlockPos.pos,\n blockType,\n );\n }\n }\n if (target) {\n insertionPos = getInsertionPos(\n tr.doc,\n target,\n \"last-child\",\n blockType,\n )?.pos;\n }\n if (insertionPos === undefined) {\n return false;\n }\n if (dispatch) {\n moveBlockOutAndPlaceCaret(tr, blockInfo.block, insertionPos);\n }\n return true;\n }),\n // Removes an empty inline block when merging is impossible. Its\n // children take its place; the cursor moves to the preceding block.\n () =>\n commands.command(({ state, tr, dispatch }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (\n !blockInfo.hasContent ||\n !state.selection.empty ||\n blockInfo.contentKind !== \"inline\" ||\n !blockInfo.isContentEmpty\n ) {\n return false;\n }\n const prevBlockInfo = getPrevBlockInfo(\n state.doc,\n blockInfo.block.beforePos,\n );\n const parent = !prevBlockInfo\n ? getParentBlockInfo(state.doc, blockInfo.block.beforePos)\n : undefined;\n const target = prevBlockInfo\n ? getLastDescendantBlockInfo(prevBlockInfo)\n : parent;\n if (!target?.hasContent) {\n return false;\n }\n if (dispatch) {\n if (\n parent?.children?.node.childCount === 1 &&\n !blockInfo.children\n ) {\n tr.delete(parent.children.beforePos, parent.children.afterPos);\n } else {\n tr.replaceWith(\n blockInfo.block.beforePos,\n blockInfo.block.afterPos,\n blockInfo.children?.node.content ?? Fragment.empty,\n );\n }\n tr.setSelection(\n target.contentKind === \"none\"\n ? NodeSelection.create(tr.doc, target.content.beforePos)\n : TextSelection.near(tr.doc.resolve(target.contentEnd), -1),\n );\n tr.scrollIntoView();\n }\n return true;\n }),\n // Deletes previous block if it contains no content and isn't a table,\n // when the selection is empty and at the start of the block. Moves the\n // current block into the deleted block's place.\n () =>\n commands.command(({ state, tr, dispatch }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n\n if (!blockInfo.hasContent) {\n return false;\n }\n\n const selectionAtBlockStart =\n state.selection.from === blockInfo.contentStart;\n const selectionEmpty = state.selection.empty;\n\n const prevBlockInfo = getPrevBlockInfo(\n state.doc,\n blockInfo.block.beforePos,\n );\n\n if (prevBlockInfo && selectionAtBlockStart && selectionEmpty) {\n // An emptied layout block has no content to merge with, so the\n // guard below rejects it — the merge branch above only fires\n // for a previous block with content of its own.\n const bottomBlock = getLastDescendantBlockInfo(prevBlockInfo);\n\n if (!bottomBlock.hasContent) {\n return false;\n }\n\n const prevBlockNotTableAndNoContent =\n bottomBlock.contentKind === \"none\" ||\n (bottomBlock.contentKind === \"inline\" &&\n bottomBlock.isContentEmpty);\n\n if (prevBlockNotTableAndNoContent) {\n if (dispatch) {\n tr.delete(\n blockInfo.block.beforePos,\n blockInfo.block.afterPos,\n );\n tr.replaceWith(\n bottomBlock.block.beforePos,\n bottomBlock.block.afterPos,\n blockInfo.block.node,\n );\n tr.setSelection(\n TextSelection.near(\n tr.doc.resolve(bottomBlock.block.beforePos + 2),\n ),\n );\n tr.scrollIntoView();\n }\n return true;\n }\n }\n\n return false;\n }),\n // If no merge/deletion is possible (for example beside a table or\n // under an image), unindent instead of trapping the cursor or losing text.\n () =>\n commands.command(({ state, tr }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (\n !blockInfo.hasContent ||\n !state.selection.empty ||\n state.selection.from !== blockInfo.contentStart\n ) {\n return false;\n }\n return liftItem(\n tr,\n tr.doc.type.schema.nodes[\"blockContainer\"],\n tr.doc.type.schema.nodes[\"blockGroup\"],\n canOutdentFrom(tr.doc),\n );\n }),\n ]);\n\n const handleDelete = () =>\n this.editor.commands.first(({ chain, commands }) => [\n // Deletes the selection if it's not empty.\n () => commands.deleteSelection(),\n // Deletes the first child block and un-nests its children, if the\n // selection is empty and at the end of the current block. If both the\n // parent and child blocks have inline content, the child block's\n // content is appended to the parent's. The child block's own children\n // are unindented before it's deleted.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent || !blockInfo.children) {\n return false;\n }\n const { children } = blockInfo;\n\n // A block can have an empty children node (the `childContainer`\n // group), but then there is no first child to pull anything out\n // of.\n if (children.node.childCount === 0) {\n return false;\n }\n\n const selectionAtBlockEnd =\n state.selection.from === blockInfo.contentEnd;\n const selectionEmpty = state.selection.empty;\n\n const firstChildBlockInfo = getBlockInfoAt(\n state.doc,\n children.childrenStart,\n );\n if (!firstChildBlockInfo.hasContent) {\n return false;\n }\n\n if (selectionAtBlockEnd && selectionEmpty) {\n return deleteBlockAndAppendContent(\n chain(),\n blockInfo,\n firstChildBlockInfo,\n children.node.childCount === 1\n ? children\n : firstChildBlockInfo.block,\n );\n }\n\n return false;\n }),\n // Merges block with the next one (at the same nesting level or lower),\n // if one exists, the block has no children, and the selection is at the\n // end of the block.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n const { block: blockContainer } = blockInfo;\n\n const nextBlockInfo = getNextBlockInfo(\n state.doc,\n blockInfo.block.beforePos,\n );\n if (!nextBlockInfo || !nextBlockInfo.hasContent) {\n return false;\n }\n\n const selectionAtBlockEnd =\n state.selection.from === blockInfo.contentEnd;\n const selectionEmpty = state.selection.empty;\n\n const posBetweenBlocks = blockContainer.afterPos;\n\n if (selectionAtBlockEnd && selectionEmpty) {\n return chain()\n .command(mergeBlocksCommand(posBetweenBlocks))\n .scrollIntoView()\n .run();\n }\n\n return false;\n }),\n // Pull the next leaf across a layout block boundary. It may be inside\n // the next sibling layout block, or follow the layout blocks we're leaving.\n () =>\n commands.command(({ state, tr, dispatch }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (\n !blockInfo.hasContent ||\n state.selection.from !== blockInfo.contentEnd\n ) {\n return false;\n }\n\n let $boundary = tr.doc.resolve(blockInfo.block.afterPos);\n while (\n !$boundary.nodeAfter &&\n $boundary.depth > 0 &&\n isLayoutNode($boundary.parent.type)\n ) {\n $boundary = tr.doc.resolve($boundary.after());\n }\n const nextNode = $boundary.nodeAfter;\n if (!nextNode) {\n return false;\n }\n\n const crossedBoundary = $boundary.pos !== blockInfo.block.afterPos;\n if (!crossedBoundary && !isLayoutNode(nextNode.type)) {\n return false;\n }\n const target = getFirstLeafBlock(\n getBlockInfoFromNode(nextNode, $boundary.pos),\n );\n if (!target) {\n return false;\n }\n\n if (dispatch) {\n moveBlockOutAndPlaceCaret(\n tr,\n target.block,\n blockInfo.block.afterPos,\n );\n }\n return true;\n }),\n // Deletes the next block at either the same or lower nesting level, if\n // the selection is empty and at the end of the block. If both the\n // current and next blocks have inline content, the next block's\n // content is appended to the current block's. The next block's own\n // children are unindented before it's deleted.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n\n const selectionAtBlockEnd =\n state.selection.from === blockInfo.contentEnd;\n const selectionEmpty = state.selection.empty;\n\n if (selectionAtBlockEnd && selectionEmpty) {\n let nextBlockInfo: BlockInfo | undefined;\n let ancestor: BlockInfo | undefined = blockInfo;\n while (ancestor) {\n nextBlockInfo = getNextBlockInfo(\n state.doc,\n ancestor.block.beforePos,\n );\n if (nextBlockInfo) {\n break;\n }\n ancestor = getParentBlockInfo(\n state.doc,\n ancestor.block.beforePos,\n );\n }\n if (!nextBlockInfo || !nextBlockInfo.hasContent) {\n return false;\n }\n\n return deleteBlockAndAppendContent(\n chain(),\n blockInfo,\n nextBlockInfo,\n nextBlockInfo.block,\n );\n }\n\n return false;\n }),\n // Deletes the current block if it's an empty block with inline content,\n // and moves the selection to the next block.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n\n const blockEmpty =\n blockInfo.isContentEmpty && blockInfo.contentKind === \"inline\";\n\n if (blockEmpty) {\n const nextBlockInfo = getNextBlockInfo(\n state.doc,\n blockInfo.block.beforePos,\n );\n if (!nextBlockInfo || !nextBlockInfo.hasContent) {\n return false;\n }\n\n const chainedCommands = chain();\n\n chainedCommands.command(({ tr }) => {\n tr.setSelection(\n blockEdgeSelection(tr.doc, nextBlockInfo, \"start\"),\n );\n return true;\n });\n\n return chainedCommands\n .deleteRange({\n from: blockInfo.block.beforePos,\n to: blockInfo.block.afterPos,\n })\n .scrollIntoView()\n .run();\n }\n\n return false;\n }),\n // Deletes next block if it contains no content and isn't a table,\n // when the selection is empty and at the end of the block. Moves the\n // current block into the deleted block's place.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n\n if (!blockInfo.hasContent) {\n return false;\n }\n\n const selectionAtBlockEnd =\n state.selection.from === blockInfo.contentEnd;\n const selectionEmpty = state.selection.empty;\n\n const nextBlockInfo = getNextBlockInfo(\n state.doc,\n blockInfo.block.beforePos,\n );\n if (!nextBlockInfo) {\n return false;\n }\n if (!nextBlockInfo.hasContent) {\n return false;\n }\n\n if (nextBlockInfo && selectionAtBlockEnd && selectionEmpty) {\n const nextBlockNotTableAndNoContent =\n nextBlockInfo.contentKind === \"none\" ||\n (nextBlockInfo.contentKind === \"inline\" &&\n nextBlockInfo.isContentEmpty);\n\n if (nextBlockNotTableAndNoContent) {\n return chain()\n .deleteRange({\n from: nextBlockInfo.block.beforePos,\n to: nextBlockInfo.block.afterPos,\n })\n .insertContentAt(\n blockInfo.block.afterPos,\n nextBlockInfo.children?.node.content ?? null,\n )\n .run();\n }\n }\n\n return false;\n }),\n ]);\n\n const handleEnter = (withShift = false) => {\n return this.editor.commands.first(({ commands, tr }) => [\n // Resets an empty block (`keyboard.resetsTo`) if it resets on Enter\n // (`keyboard.emptyEnterResets`), e.g. an empty list item turns into a\n // paragraph. Its children stay.\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (\n !blockInfo.hasContent ||\n !state.selection.empty ||\n !blockInfo.isContentEmpty\n ) {\n return false;\n }\n const keyboard = keyboardOf(blockInfo.block.node, state.doc);\n if (!keyboard.emptyEnterResets) {\n return false;\n }\n return commands.command(\n updateBlockCommand(\n blockInfo.block.beforePos,\n keyboard.resetsTo as any,\n ),\n );\n }),\n // Removes a level of nesting if the block is empty & indented, while the selection is also empty & at the start\n // of the block.\n () =>\n commands.command(({ state, tr }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n const { block: blockContainer } = blockInfo;\n\n const { depth } = state.doc.resolve(blockContainer.beforePos);\n\n const selectionAtBlockStart =\n state.selection.$anchor.parentOffset === 0;\n const selectionEmpty =\n state.selection.anchor === state.selection.head;\n const blockEmpty = blockInfo.isContentEmpty;\n const blockIndented = depth > 1;\n\n if (\n selectionAtBlockStart &&\n selectionEmpty &&\n blockEmpty &&\n blockIndented\n ) {\n // Only outdents where the parent says so\n // (`keyboard.emptyChildEnter: \"outdent\"`); otherwise the block\n // leaves at the end, or a new child is added, further down.\n const parent = getParentBlockInfo(\n state.doc,\n blockContainer.beforePos,\n );\n if (\n parent &&\n keyboardOf(parent.block.node, state.doc).emptyChildEnter !==\n \"outdent\"\n ) {\n return false;\n }\n return liftItem(\n tr,\n tr.doc.type.schema.nodes[\"blockContainer\"],\n tr.doc.type.schema.nodes[\"blockGroup\"],\n canOutdentFrom(tr.doc),\n );\n }\n\n return false;\n }),\n // Creates a hard break if the block is configured to do so\n // (`keyboard.enter` / `keyboard.shiftEnter`).\n () =>\n commands.command(({ state }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n\n const blockSpec =\n this.options.editor.schema.blockSpecs[blockInfo.blockNoteType];\n\n const keyboard = keyboardOf(blockInfo.block.node, state.doc);\n\n if (\n // Enter as a line break makes Shift-Enter one too.\n keyboard.enter === \"line-break\" ||\n (withShift && keyboard.shiftEnter === \"line-break\")\n ) {\n // \"plain\" blocks (e.g. code/math/diagram source) hold text only\n // (their content is `text*`), which can't contain a `hardBreak`\n // node - inserting one would split the block into a new one.\n // They represent line breaks as literal newline characters.\n if (blockSpec?.config?.content === \"plain\") {\n tr.insertText(\"\\n\", tr.selection.head);\n return true;\n }\n\n const marks =\n tr.storedMarks ||\n tr.selection.$head\n .marks()\n .filter((m) =>\n this.editor.extensionManager.splittableMarks.includes(\n m.type.name,\n ),\n );\n\n tr.insert(\n tr.selection.head,\n tr.doc.type.schema.nodes.hardBreak.create(),\n ).ensureMarks(marks);\n return true;\n }\n\n return false;\n }),\n // If the block is empty and the last child of a block whose empty\n // children exit at the end (`keyboard.emptyChildEnter:\n // \"exit-at-end\"`, the default for layout blocks), moves the block out\n // (double Enter exits the layout block). The block lands at the nearest enclosing position that\n // accepts it. E.g. out of a column it skips the columnList, which\n // holds only columns, and lands below it. Without this, Enter only\n // ever creates new blocks within the layout block, so the cursor could\n // never leave a trailing layout block. Shift+Enter still adds spacing\n // inside a layout block. The first block of a body stays put: it is\n // where the body begins, not a way out of it.\n () =>\n commands.command(({ state, tr, dispatch }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n\n const selectionEmpty =\n state.selection.anchor === state.selection.head;\n const blockEmpty = blockInfo.isContentEmpty;\n if (!selectionEmpty || !blockEmpty) {\n return false;\n }\n\n const $pos = tr.doc.resolve(blockInfo.block.beforePos);\n // Only fires on the layout block's last child.\n if (tr.doc.resolve(blockInfo.block.afterPos).nodeAfter !== null) {\n return false;\n }\n\n const owner = getParentBlockInfo(tr.doc, blockInfo.block.beforePos);\n if (!owner) {\n return false;\n }\n if (\n keyboardOf(owner.block.node, tr.doc).emptyChildEnter !==\n \"exit-at-end\"\n ) {\n return false;\n }\n // The first block of a body stays put: it is where the body\n // begins, not a way out of it. (A layout block's own first child has\n // no such role, so it may still leave.)\n if ($pos.index() === 0 && owner.hasContent) {\n return false;\n }\n\n const ownerAfterPos = ascendToInsertablePos(\n tr.doc,\n owner.block.afterPos,\n state.schema.nodes[\"blockContainer\"],\n \"after\",\n );\n if (ownerAfterPos === undefined) {\n return false;\n }\n\n if (dispatch) {\n moveBlockOutAndPlaceCaret(tr, blockInfo.block, ownerAfterPos);\n tr.scrollIntoView();\n }\n\n return true;\n }),\n // Creates a new block and moves the selection to it if the current one is empty, while the selection is also\n // empty & at the start of the block.\n () =>\n commands.command(({ state, dispatch, tr }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n const { block: blockContainer } = blockInfo;\n\n const selectionAtBlockStart =\n state.selection.$anchor.parentOffset === 0;\n const selectionEmpty =\n state.selection.anchor === state.selection.head;\n const blockEmpty = blockInfo.isContentEmpty;\n\n if (\n selectionAtBlockStart &&\n selectionEmpty &&\n blockEmpty &&\n keyboardOf(blockInfo.block.node, state.doc).enter !==\n \"into-children\"\n ) {\n const newBlockInsertionPos = blockContainer.afterPos;\n const newBlockContentPos = newBlockInsertionPos + 2;\n\n if (dispatch) {\n // Creates a new block with the children of the current block,\n // if it has any.\n const newBlock = state.schema.nodes[\n \"blockContainer\"\n ].createAndFill(\n undefined,\n [\n state.schema.nodes[\"paragraph\"].createAndFill() ||\n undefined,\n blockInfo.children?.node,\n ].filter((node) => node !== undefined),\n )!;\n\n // Inserts the new block and moves the selection to it.\n tr.insert(newBlockInsertionPos, newBlock)\n .setSelection(\n new TextSelection(tr.doc.resolve(newBlockContentPos)),\n )\n .scrollIntoView();\n\n // Deletes old block's children, as they have been moved to\n // the new one.\n if (blockInfo.children) {\n tr.delete(\n blockInfo.children.beforePos,\n blockInfo.children.afterPos,\n );\n }\n }\n\n return true;\n }\n\n return false;\n }),\n // Enter at the start of non-empty content inserts an empty block above\n // it: the same type when the block's splits keep their type (lists),\n // a paragraph otherwise, with default props. The block itself, with\n // its id, props (e.g. a checklist item's checked state) and children,\n // stays where it is (#550).\n () =>\n commands.command(({ state, tr, dispatch }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (\n !blockInfo.hasContent ||\n blockInfo.contentKind === \"table\" ||\n !state.selection.empty ||\n blockInfo.isContentEmpty ||\n state.selection.from !== blockInfo.contentStart\n ) {\n return false;\n }\n\n if (dispatch) {\n const contentType = keyboardOf(blockInfo.block.node, state.doc)\n .splitKeepsType\n ? blockInfo.content.node.type\n : state.schema.nodes[\"paragraph\"];\n const newBlock = state.schema.nodes[\"blockContainer\"].create(\n undefined,\n contentType.create(),\n );\n tr.insert(blockInfo.block.beforePos, newBlock).scrollIntoView();\n }\n\n return true;\n }),\n // Enter in the content of a block whose Enter goes into its children\n // (`keyboard.enter: \"into-children\"`, e.g. an open toggle) starts its\n // children rather than splitting the block in two: whatever follows\n // the cursor becomes the first child, and the existing children stay\n // where they are.\n () =>\n commands.command(({ state, tr, dispatch }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n\n if (\n keyboardOf(blockInfo.block.node, state.doc).enter !==\n \"into-children\"\n ) {\n return false;\n }\n if (!state.selection.empty) {\n return false;\n }\n if (\n state.selection.from < blockInfo.contentStart ||\n state.selection.from > blockInfo.contentEnd\n ) {\n return false;\n }\n\n if (dispatch) {\n // Everything after the cursor moves into the new block, so\n // splitting the title mid-way puts its tail at the top of the\n // body instead of handing the body to a new sibling.\n const tail = blockInfo.content.node.cut(\n state.selection.from - blockInfo.contentStart,\n );\n const newBlock = state.schema.nodes[\"blockContainer\"].create(\n undefined,\n state.schema.nodes[\"paragraph\"].create(undefined, tail.content),\n );\n\n tr.delete(state.selection.from, blockInfo.contentEnd);\n\n const body = getBlockInfoAt(\n tr.doc,\n blockInfo.block.beforePos,\n ).children;\n // Without a body yet, one is created around the new block.\n const insertPos = body\n ? body.childrenStart\n : tr.mapping.map(blockInfo.content.afterPos);\n tr.insert(\n insertPos,\n body\n ? newBlock\n : state.schema.nodes[\"blockGroup\"].create(\n undefined,\n newBlock,\n ),\n )\n .setSelection(\n new TextSelection(tr.doc.resolve(insertPos + (body ? 2 : 3))),\n )\n .scrollIntoView();\n }\n\n return true;\n }),\n // Splits the current block, moving content inside that's after the cursor to a new text block below. Also\n // deletes the selection beforehand, if it's not empty.\n () =>\n commands.command(({ state, chain }) => {\n const blockInfo = getBlockInfoFromSelection(state);\n if (!blockInfo.hasContent) {\n return false;\n }\n\n const selectionAtBlockStart =\n state.selection.$anchor.parentOffset === 0;\n const blockEmpty = blockInfo.isContentEmpty;\n\n if (!blockEmpty) {\n const keyboard = keyboardOf(blockInfo.block.node, state.doc);\n const keepType = selectionAtBlockStart || keyboard.splitKeepsType;\n chain()\n .deleteSelection()\n .command(\n splitBlockCommand(\n state.selection.from,\n keepType,\n selectionAtBlockStart,\n keyboard.splitKeepsChildren,\n ),\n )\n .scrollIntoView()\n .run();\n\n return true;\n }\n\n return false;\n }),\n ]);\n };\n\n const options = this.options;\n function handleTab(shift: boolean) {\n const { editor, tabBehavior } = options;\n if (\n tabBehavior !== \"prefer-indent\" &&\n (editor.getExtension(FormattingToolbarExtension)?.store.state ||\n editor.getExtension(FilePanelExtension)?.store.state !== undefined)\n ) {\n // Let the browser navigate into and out of an open toolbar.\n return false;\n }\n return shift ? unnestBlock(editor) : nestBlock(editor);\n }\n\n return {\n Backspace: handleBackspace,\n Delete: handleDelete,\n Enter: () => handleEnter(),\n \"Shift-Enter\": () => handleEnter(true),\n Tab: () => handleTab(false),\n \"Shift-Tab\": () => handleTab(true),\n \"Shift-Mod-ArrowUp\": () => {\n this.options.editor.moveBlocksUp();\n return true;\n },\n \"Shift-Mod-ArrowDown\": () => {\n this.options.editor.moveBlocksDown();\n return true;\n },\n \"Mod-z\": () => this.options.editor.undo(),\n \"Mod-y\": () => this.options.editor.redo(),\n \"Shift-Mod-z\": () => this.options.editor.redo(),\n \"Mod-a\": () => {\n const view = this.editor.view;\n const { doc, selection, tr } = view.state;\n\n // By default, the first `Mod-a` selects the current block's content,\n // and any subsequent `Mod-a` expands the selection to the whole\n // document. We use `TextSelection`s rather than an `AllSelection` for the\n // whole-document case as the latter creates from/to positions outside a\n // block, causing errors when calling e.g. `getBlock`.\n const wholeDocSelection = TextSelection.between(\n Selection.atStart(doc).$from,\n Selection.atEnd(doc).$to,\n );\n\n if (this.options.selectAllBehavior === \"document\") {\n view.dispatch(tr.setSelection(wholeDocSelection));\n return true;\n }\n\n // Selection covering just the current block's content. `between` snaps\n // to the nearest inline positions inside the block, so it also handles\n // blocks whose content isn't directly inline - e.g. table blocks, where\n // it spans from the first cell to the last. Blocks without any inline\n // content (e.g. images) are ignored, as `between` would then spill\n // outside the block, and select-all falls through to the whole document.\n let blockSelection: Selection | undefined;\n const blockInfo = getBlockInfoFromSelection(view.state);\n if (blockInfo.hasContent) {\n const contentFrom = blockInfo.contentStart;\n const contentTo = blockInfo.contentEnd;\n const candidate = TextSelection.between(\n doc.resolve(contentFrom),\n doc.resolve(contentTo),\n );\n\n if (\n !candidate.empty &&\n candidate.from >= contentFrom &&\n candidate.to <= contentTo\n ) {\n blockSelection = candidate;\n }\n }\n\n // Expands to the whole document when there's no selectable block content\n // to select first, when the selection already extends beyond the current\n // block, or when the current block's content is already fully selected.\n const selectWholeDoc =\n !blockSelection ||\n selection.from < blockSelection.from ||\n selection.to > blockSelection.to ||\n (selection.from === blockSelection.from &&\n selection.to === blockSelection.to);\n\n if (blockSelection && !selectWholeDoc) {\n tr.setSelection(blockSelection).scrollIntoView();\n } else {\n tr.setSelection(wholeDocSelection);\n }\n\n view.dispatch(tr);\n\n return true;\n },\n };\n },\n});\n","import { Extension } from \"@tiptap/core\";\n\nexport const TextAlignmentExtension = Extension.create({\n name: \"textAlignment\",\n\n addGlobalAttributes() {\n return [\n {\n // Generally text alignment is handled through props using the custom\n // blocks API. Tables are the only blocks that are created as TipTap\n // nodes and ported to blocks, so we need to add text alignment in a\n // separate extension.\n types: [\"tableCell\", \"tableHeader\"],\n attributes: {\n textAlignment: {\n default: \"left\",\n parseHTML: (element) => {\n return element.getAttribute(\"data-text-alignment\");\n },\n renderHTML: (attributes) => {\n if (attributes.textAlignment === \"left\") {\n return {};\n }\n return {\n \"data-text-alignment\": attributes.textAlignment,\n };\n },\n },\n },\n },\n ];\n },\n});\n","import { Extension } from \"@tiptap/core\";\nimport { getTextColorAttribute } from \"../../../blocks/defaultProps.js\";\n\nexport const TextColorExtension = Extension.create({\n name: \"blockTextColor\",\n\n addGlobalAttributes() {\n return [\n {\n types: [\"table\", \"tableCell\", \"tableHeader\"],\n attributes: {\n textColor: getTextColorAttribute(),\n },\n },\n ];\n },\n});\n","// From DOMPurify\n// https://github.com/cure53/DOMPurify/blob/main/src/regexp.ts\nexport const UNICODE_WHITESPACE_PATTERN =\n \"[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]\";\n\nexport const UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN);\nexport const UNICODE_WHITESPACE_REGEX_END = new RegExp(\n `${UNICODE_WHITESPACE_PATTERN}$`,\n);\nexport const UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(\n UNICODE_WHITESPACE_PATTERN,\n \"g\",\n);\n","import type { NodeWithPos } from \"@tiptap/core\";\nimport { findChildrenInRange, getMarksBetween } from \"@tiptap/core\";\nimport type { MarkType } from \"@tiptap/pm/model\";\nimport { Plugin, PluginKey } from \"@tiptap/pm/state\";\nimport { combineTransactionSteps } from \"../../../../api/combineTransactionSteps.js\";\nimport { getChangedRanges } from \"../../../../api/getChangedRanges.js\";\nimport type { LinkMatch } from \"./linkDetector.js\";\nimport { tokenizeLink } from \"./linkDetector.js\";\n\nimport {\n UNICODE_WHITESPACE_REGEX,\n UNICODE_WHITESPACE_REGEX_END,\n} from \"./whitespace.js\";\n\n/**\n * Check if the provided tokens form a valid link structure, which can either be a single link token\n * or a link token surrounded by parentheses or square brackets.\n */\nfunction isValidLinkStructure(tokens: LinkMatch[]) {\n if (tokens.length === 1) {\n return tokens[0].isLink;\n }\n\n if (tokens.length === 3 && tokens[1].isLink) {\n return [\"()\", \"[]\"].includes(tokens[0].value + tokens[2].value);\n }\n\n return false;\n}\n\ntype AutolinkOptions = {\n type: MarkType;\n defaultProtocol: string;\n validate: (url: string) => boolean;\n shouldAutoLink: (url: string) => boolean;\n};\n\n/**\n * Plugin that automatically adds link marks when typing URLs.\n */\nexport function autolink(options: AutolinkOptions): Plugin {\n return new Plugin({\n key: new PluginKey(\"autolink\"),\n appendTransaction: (transactions, oldState, newState) => {\n const docChanges =\n transactions.some((transaction) => transaction.docChanged) &&\n !oldState.doc.eq(newState.doc);\n\n const preventAutolink = transactions.some((transaction) =>\n transaction.getMeta(\"preventAutolink\"),\n );\n\n if (!docChanges || preventAutolink) {\n return;\n }\n\n const { tr } = newState;\n const transform = combineTransactionSteps(oldState.doc, transactions);\n const changes = getChangedRanges(transform);\n\n changes.forEach(({ newRange }) => {\n const nodesInChangedRanges = findChildrenInRange(\n newState.doc,\n newRange,\n (node) => node.isTextblock,\n );\n\n let textBlock: NodeWithPos | undefined;\n let textBeforeWhitespace: string | undefined;\n\n if (nodesInChangedRanges.length > 1) {\n textBlock = nodesInChangedRanges[0];\n textBeforeWhitespace = newState.doc.textBetween(\n textBlock.pos,\n textBlock.pos + textBlock.node.nodeSize,\n undefined,\n \" \",\n );\n } else if (nodesInChangedRanges.length) {\n const endText = newState.doc.textBetween(\n newRange.from,\n newRange.to,\n \" \",\n \" \",\n );\n if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) {\n return;\n }\n textBlock = nodesInChangedRanges[0];\n textBeforeWhitespace = newState.doc.textBetween(\n textBlock.pos,\n newRange.to,\n undefined,\n \" \",\n );\n }\n\n if (textBlock && textBeforeWhitespace) {\n const wordsBeforeWhitespace = textBeforeWhitespace\n .split(UNICODE_WHITESPACE_REGEX)\n .filter(Boolean);\n\n if (wordsBeforeWhitespace.length <= 0) {\n return;\n }\n\n const lastWordBeforeSpace =\n wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];\n const lastWordAndBlockOffset =\n textBlock.pos +\n textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);\n\n if (!lastWordBeforeSpace) {\n return;\n }\n\n const linksBeforeSpace = tokenizeLink(\n lastWordBeforeSpace,\n options.defaultProtocol,\n );\n\n if (!isValidLinkStructure(linksBeforeSpace)) {\n return;\n }\n\n linksBeforeSpace\n .filter((link) => link.isLink)\n .map((link) => ({\n ...link,\n from: lastWordAndBlockOffset + link.start + 1,\n to: lastWordAndBlockOffset + link.end + 1,\n }))\n // ignore link inside code mark\n .filter((link) => {\n if (!newState.schema.marks.code) {\n return true;\n }\n\n return !newState.doc.rangeHasMark(\n link.from,\n link.to,\n newState.schema.marks.code,\n );\n })\n .filter((link) => options.validate(link.value))\n .filter((link) => options.shouldAutoLink(link.value))\n .forEach((link) => {\n if (\n getMarksBetween(link.from, link.to, newState.doc).some(\n (item) => item.mark.type === options.type,\n )\n ) {\n return;\n }\n\n tr.addMark(\n link.from,\n link.to,\n options.type.create({\n href: link.href,\n }),\n );\n });\n }\n });\n\n if (!tr.steps.length) {\n return;\n }\n\n return tr;\n },\n });\n}\n","import type { Editor } from \"@tiptap/core\";\nimport { getAttributes } from \"@tiptap/core\";\nimport type { MarkType } from \"@tiptap/pm/model\";\nimport { Plugin, PluginKey } from \"@tiptap/pm/state\";\nimport type { BlockNoteEditor } from \"../../../../editor/BlockNoteEditor.js\";\n\ntype ClickHandlerOptions = {\n type: MarkType;\n tiptapEditor: Editor;\n editor?: BlockNoteEditor<any, any, any>;\n onClick?: (\n event: MouseEvent,\n editor: BlockNoteEditor<any, any, any>,\n ) => boolean | void;\n};\n\nexport function clickHandler(options: ClickHandlerOptions): Plugin {\n return new Plugin({\n key: new PluginKey(\"handleClickLink\"),\n props: {\n handleClick: (view, _pos, event) => {\n if (event.button !== 0) {\n return false;\n }\n\n if (!view.editable) {\n return false;\n }\n\n let link: HTMLAnchorElement | null = null;\n\n if (\n event.target instanceof HTMLAnchorElement &&\n // Differentiate between link inline content and read-only links.\n event.target.getAttribute(\"data-inline-content-type\") === \"link\"\n ) {\n link = event.target;\n } else {\n const target = event.target as HTMLElement | null;\n if (!target) {\n return false;\n }\n\n const root = options.tiptapEditor.view.dom;\n\n // Intentionally limit the lookup to the editor root.\n // Using tag names like DIV as boundaries breaks with custom NodeViews,\n link = target.closest<HTMLAnchorElement>(\n 'a[data-inline-content-type=\"link\"]',\n );\n\n if (link && !root.contains(link)) {\n link = null;\n }\n }\n\n if (!link) {\n return false;\n }\n\n if (options.onClick) {\n if (!options.editor) {\n throw new Error(\"BlockNoteEditor not found in Link click handler\");\n }\n const result = options.onClick(event, options.editor);\n return result ?? true;\n }\n\n const attrs = getAttributes(view.state, options.type.name);\n const href = link.href ?? attrs.href;\n const target = link.target ?? attrs.target;\n\n if (href) {\n window.open(href, target);\n return true;\n }\n\n return false;\n },\n },\n });\n}\n","import type { Editor } from \"@tiptap/core\";\nimport type { MarkType } from \"@tiptap/pm/model\";\nimport { Plugin, PluginKey } from \"@tiptap/pm/state\";\nimport { findLinks } from \"./linkDetector.js\";\n\ntype PasteHandlerOptions = {\n editor: Editor;\n defaultProtocol: string;\n type: MarkType;\n shouldAutoLink?: (url: string) => boolean;\n isValidLink: (href: string) => boolean;\n};\n\nexport function pasteHandler(options: PasteHandlerOptions): Plugin {\n return new Plugin({\n key: new PluginKey(\"handlePasteLink\"),\n props: {\n handlePaste: (view, _event, slice) => {\n const { shouldAutoLink, isValidLink } = options;\n const { state } = view;\n const { selection } = state;\n const { empty } = selection;\n\n if (empty) {\n return false;\n }\n\n let textContent = \"\";\n\n slice.content.forEach((node) => {\n textContent += node.textContent;\n });\n\n const link = findLinks(textContent, {\n defaultProtocol: options.defaultProtocol,\n }).find((item) => item.isLink && item.value === textContent);\n\n if (\n !textContent ||\n !link ||\n !isValidLink(link.value) ||\n (shouldAutoLink !== undefined && !shouldAutoLink(link.value))\n ) {\n return false;\n }\n\n return options.editor.commands.setMark(options.type, {\n href: link.href,\n });\n },\n },\n });\n}\n","import type { PasteRuleMatch } from \"@tiptap/core\";\nimport { Mark, markPasteRule, mergeAttributes } from \"@tiptap/core\";\nimport type { Plugin } from \"@tiptap/pm/state\";\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport { createExtension } from \"../../../editor/BlockNoteExtension.js\";\nimport { autolink } from \"./helpers/autolink.js\";\nimport { findLinks } from \"./helpers/linkDetector.js\";\nimport { clickHandler } from \"./helpers/clickHandler.js\";\nimport { pasteHandler } from \"./helpers/pasteHandler.js\";\nimport { UNICODE_WHITESPACE_REGEX_GLOBAL } from \"./helpers/whitespace.js\";\n\nconst DEFAULT_PROTOCOL = \"https\";\n\n// Pre-compiled regex for URI protocol validation.\n// Allows: http, https, ftp, ftps, mailto, tel, callto, sms, cid, xmpp\nconst ALLOWED_URI_REGEX =\n // eslint-disable-next-line no-useless-escape\n /^(?:(?:http|https|ftp|ftps|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))/i;\n\nexport function isAllowedUri(uri: string | undefined): boolean {\n if (!uri) {\n return true;\n }\n const cleaned = uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, \"\");\n return ALLOWED_URI_REGEX.test(cleaned);\n}\n\n/**\n * Determine whether a detected URL should be auto-linked.\n * URLs with explicit protocols are always auto-linked.\n * Bare hostnames must have a TLD (no IP addresses or single words).\n */\nfunction shouldAutoLink(url: string): boolean {\n const hasProtocol = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(url);\n const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url);\n\n if (hasProtocol || (hasMaybeProtocol && !url.includes(\"@\"))) {\n return true;\n }\n // Strip userinfo (user:pass@) if present, then extract hostname\n const urlWithoutUserinfo = url.includes(\"@\") ? url.split(\"@\").pop()! : url;\n const hostname = urlWithoutUserinfo.split(/[/?#:]/)[0];\n\n // Don't auto-link IP addresses without protocol\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname)) {\n return false;\n }\n // Don't auto-link single-word hostnames without TLD (e.g., \"localhost\")\n if (!/\\./.test(hostname)) {\n return false;\n }\n return true;\n}\n\nexport type LinkOptions = {\n HTMLAttributes: Record<string, any>;\n editor?: BlockNoteEditor<any, any, any>;\n onClick?: (\n event: MouseEvent,\n editor: BlockNoteEditor<any, any, any>,\n ) => boolean | void;\n isValidLink: (href: string) => boolean;\n};\n\n/**\n * BlockNote Link mark extension.\n */\nexport const Link = Mark.create<LinkOptions>({\n name: \"link\",\n\n keepOnSplit: false,\n\n exitable: true,\n\n inclusive: false,\n\n addOptions() {\n return {\n HTMLAttributes: {\n target: \"_blank\",\n rel: \"noopener noreferrer nofollow\",\n className: \"bn-inline-content-section\",\n \"data-inline-content-type\": \"link\",\n },\n editor: undefined,\n onClick: undefined,\n isValidLink: isAllowedUri,\n };\n },\n\n addAttributes() {\n return {\n href: {\n default: null,\n parseHTML(element) {\n return element.getAttribute(\"href\");\n },\n },\n };\n },\n\n parseHTML() {\n const isValidLink = this.options.isValidLink;\n return [\n {\n tag: \"a[href]\",\n getAttrs: (dom) => {\n const href = (dom as HTMLElement).getAttribute(\"href\");\n if (!href || !isValidLink(href)) {\n return false;\n }\n return null;\n },\n },\n ];\n },\n\n renderHTML({ HTMLAttributes }) {\n if (!this.options.isValidLink(HTMLAttributes.href)) {\n return [\n \"a\",\n mergeAttributes(\n {\n ...HTMLAttributes,\n href: \"\",\n },\n this.options.HTMLAttributes,\n ),\n 0,\n ];\n }\n\n return [\n \"a\",\n mergeAttributes(HTMLAttributes, this.options.HTMLAttributes),\n 0,\n ];\n },\n\n addPasteRules() {\n const isValidLink = this.options.isValidLink;\n return [\n markPasteRule({\n find: (text) => {\n const foundLinks: PasteRuleMatch[] = [];\n\n if (text) {\n const links = findLinks(text, {\n defaultProtocol: DEFAULT_PROTOCOL,\n }).filter((item) => item.isLink && isValidLink(item.value));\n\n for (const link of links) {\n if (!shouldAutoLink(link.value)) {\n continue;\n }\n\n foundLinks.push({\n text: link.value,\n data: { href: link.href },\n index: link.start,\n });\n }\n }\n\n return foundLinks;\n },\n type: this.type,\n getAttributes: (match) => ({\n href: match.data?.href,\n }),\n }),\n ];\n },\n\n addProseMirrorPlugins() {\n const plugins: Plugin[] = [];\n\n plugins.push(\n autolink({\n type: this.type,\n defaultProtocol: DEFAULT_PROTOCOL,\n validate: this.options.isValidLink,\n shouldAutoLink,\n }),\n );\n\n plugins.push(\n clickHandler({\n type: this.type,\n tiptapEditor: this.editor,\n editor: this.options.editor,\n onClick: this.options.onClick,\n }),\n );\n\n plugins.push(\n pasteHandler({\n editor: this.editor,\n defaultProtocol: DEFAULT_PROTOCOL,\n type: this.type,\n shouldAutoLink,\n isValidLink: this.options.isValidLink,\n }),\n );\n\n return plugins;\n },\n});\n\ntype LinkExtensionOptions = {\n HTMLAttributes?: Record<string, any>;\n onClick?: (\n event: MouseEvent,\n editor: BlockNoteEditor<any, any, any>,\n ) => boolean | void;\n isValidLink?: (href: string) => boolean;\n};\n\n/**\n * BlockNote extension wrapping the {@link Link} TipTap mark. Wrapping the mark\n * lets other extensions order their click handlers relative to the link click\n * handler via `runsBefore: [\"link\"]`.\n */\nexport const LinkExtension = createExtension<any, LinkExtensionOptions>(\n ({ editor, options }) => {\n return {\n key: \"link\",\n tiptapExtensions: [\n Link.configure({\n HTMLAttributes: options.HTMLAttributes ?? {},\n editor,\n onClick: options.onClick,\n ...(options.isValidLink ? { isValidLink: options.isValidLink } : {}),\n }),\n ],\n } as const;\n },\n);\n","import { Node } from \"@tiptap/core\";\nimport { CHILD_CONTAINER_GROUP } from \"../schema/blocks/children.js\";\nimport { BlockNoteDOMAttributes } from \"../schema/index.js\";\nimport { mergeCSSClasses } from \"../util/browser.js\";\nimport { suggestionMarks } from \"./suggestionMarks.js\";\n\nexport const BlockGroup = Node.create<{\n domAttributes?: BlockNoteDOMAttributes;\n}>({\n name: \"blockGroup\",\n group: CHILD_CONTAINER_GROUP,\n content: \"blockGroupChild+\",\n marks() {\n return suggestionMarks(this.editor);\n },\n parseHTML() {\n return [\n {\n tag: \"div\",\n getAttrs: (element) => {\n if (typeof element === \"string\") {\n return false;\n }\n\n if (element.getAttribute(\"data-node-type\") === \"blockGroup\") {\n // Null means the element matches, but we don't want to add any attributes to the node.\n return null;\n }\n\n return false;\n },\n },\n ];\n },\n\n renderHTML({ HTMLAttributes }) {\n const blockGroupHTMLAttributes = {\n ...(this.options.domAttributes?.blockGroup || {}),\n ...HTMLAttributes,\n };\n const blockGroup = document.createElement(\"div\");\n blockGroup.className = mergeCSSClasses(\n \"bn-block-group\",\n blockGroupHTMLAttributes.class,\n );\n blockGroup.setAttribute(\"data-node-type\", \"blockGroup\");\n for (const [attribute, value] of Object.entries(blockGroupHTMLAttributes)) {\n if (attribute !== \"class\") {\n blockGroup.setAttribute(attribute, value);\n }\n }\n\n return {\n dom: blockGroup,\n contentDOM: blockGroup,\n };\n },\n});\n","import { Node } from \"@tiptap/core\";\nimport { suggestionMarks } from \"./suggestionMarks.js\";\n\nexport const Doc = Node.create({\n name: \"doc\",\n topNode: true,\n content: \"blockGroup\",\n marks() {\n return suggestionMarks(this.editor);\n },\n});\n","import {\n AnyExtension as AnyTiptapExtension,\n extensions,\n Node,\n Extension as TiptapExtension,\n} from \"@tiptap/core\";\nimport { Text } from \"@tiptap/extension-text\";\nimport { Gapcursor } from \"@tiptap/extensions/gap-cursor\";\nimport { createDropFileExtension } from \"../../../api/clipboard/fromClipboard/fileDropExtension.js\";\nimport { createPasteFromClipboardExtension } from \"../../../api/clipboard/fromClipboard/pasteExtension.js\";\nimport { createCopyToClipboardExtension } from \"../../../api/clipboard/toClipboard/copyExtension.js\";\nimport {\n BlockChangeExtension,\n DropCursorExtension,\n FilePanelExtension,\n FormattingToolbarExtension,\n HistoryExtension,\n InlineContentBoundaryEditExtension,\n LinkToolbarExtension,\n NodeSelectionKeyboardExtension,\n PlaceholderExtension,\n PositionMappingExtension,\n PreviousBlockTypeExtension,\n ReadOnlyExtension,\n ShowSelectionExtension,\n SideMenuExtension,\n SourceBlockWithPreviewExtension,\n SourceInlineContentWithPreviewExtension,\n SuggestionMenu,\n TableHandlesExtension,\n TrailingNodeExtension,\n} from \"../../../extensions/index.js\";\nimport {\n BackgroundColorExtension,\n HardBreak,\n KeyboardShortcutsExtension,\n LinkExtension,\n TextAlignmentExtension,\n TextColorExtension,\n UniqueID,\n} from \"../../../extensions/tiptap-extensions/index.js\";\nimport { BlockContainer, BlockGroup, Doc } from \"../../../pm-nodes/index.js\";\nimport type {\n BlockNoteEditor,\n BlockNoteEditorOptions,\n} from \"../../BlockNoteEditor.js\";\nimport type { ExtensionFactoryInstance } from \"../../BlockNoteExtension.js\";\n\n/**\n * Get all the Tiptap extensions BlockNote is configured with by default\n */\nexport function getDefaultTiptapExtensions(\n editor: BlockNoteEditor<any, any, any>,\n options: BlockNoteEditorOptions<any, any, any>,\n) {\n const tiptapExtensions: AnyTiptapExtension[] = [\n extensions.ClipboardTextSerializer,\n extensions.Commands,\n extensions.Editable,\n extensions.FocusEvents,\n extensions.Tabindex,\n Gapcursor,\n\n UniqueID.configure({\n // everything from bnBlock group (nodes that represent a BlockNote block should have an id)\n types: [\n \"blockContainer\",\n // Only layout blocks own their ID; titled blocks use blockContainer.\n ...Object.values(editor.schema.blockSpecs)\n .filter((spec) => spec.config.layoutOnly === true)\n .map((spec) => spec.config.type),\n ],\n setIdAttribute: options.setIdAttribute,\n isWithinEditor: editor.isWithinEditor,\n }),\n HardBreak,\n Text,\n\n // marks:\n ...(Object.values(editor.schema.styleSpecs).map((styleSpec) => {\n return styleSpec.implementation.mark.configure({\n editor: editor,\n });\n }) as any[]),\n\n TextColorExtension,\n\n BackgroundColorExtension,\n TextAlignmentExtension,\n\n // make sure escape blurs editor, so that we can tab to other elements in the host page (accessibility)\n TiptapExtension.create({\n name: \"OverrideEscape\",\n addKeyboardShortcuts: () => {\n return {\n Escape: () => {\n if (editor.getExtension(SuggestionMenu)?.shown()) {\n // escape should close the suggestion menu, but not blur the editor\n return false;\n }\n editor.blur();\n return true;\n },\n };\n },\n }),\n\n // nodes\n Doc,\n BlockContainer.configure({\n editor: editor,\n domAttributes: options.domAttributes,\n }),\n KeyboardShortcutsExtension.configure({\n editor: editor,\n tabBehavior: options.tabBehavior,\n selectAllBehavior: options.selectAllBehavior ?? \"block-first\",\n }),\n BlockGroup.configure({\n domAttributes: options.domAttributes,\n }),\n ...Object.values(editor.schema.inlineContentSpecs)\n .filter((a) => a.config !== \"link\" && a.config !== \"text\")\n .map((inlineContentSpec) => {\n return inlineContentSpec.implementation!.node.configure({\n editor: editor,\n });\n }),\n\n ...Object.values(editor.schema.blockSpecs).flatMap((blockSpec) => {\n return [\n // the node extension implementations\n ...(\"node\" in blockSpec.implementation\n ? [\n (blockSpec.implementation.node as Node).configure({\n editor: editor,\n domAttributes: options.domAttributes,\n }),\n ]\n : []),\n ];\n }),\n createCopyToClipboardExtension(editor),\n createPasteFromClipboardExtension(\n editor,\n options.pasteHandler ||\n ((context: {\n defaultPasteHandler: (context?: {\n prioritizeMarkdownOverHTML?: boolean;\n plainTextAsMarkdown?: boolean;\n }) => boolean | undefined;\n }) => context.defaultPasteHandler()),\n ),\n createDropFileExtension(editor),\n ];\n\n return tiptapExtensions;\n}\n\nexport function getDefaultExtensions(\n editor: BlockNoteEditor<any, any, any>,\n options: BlockNoteEditorOptions<any, any, any>,\n) {\n const extensions = [\n BlockChangeExtension(),\n DropCursorExtension(options),\n FilePanelExtension(options),\n FormattingToolbarExtension(options),\n LinkExtension({\n HTMLAttributes: options.links?.HTMLAttributes ?? {},\n onClick: options.links?.onClick,\n ...(options.links?.isValidLink\n ? { isValidLink: options.links.isValidLink }\n : {}),\n }),\n LinkToolbarExtension(options),\n NodeSelectionKeyboardExtension(),\n PlaceholderExtension(options),\n ReadOnlyExtension({ editable: options._tiptapOptions?.editable }),\n ShowSelectionExtension(options),\n SideMenuExtension(options),\n SourceBlockWithPreviewExtension(),\n SourceInlineContentWithPreviewExtension(),\n SuggestionMenu(options),\n HistoryExtension(),\n InlineContentBoundaryEditExtension(),\n PositionMappingExtension(),\n ...(options.trailingBlock !== false ? [TrailingNodeExtension()] : []),\n ] as ExtensionFactoryInstance[];\n\n if (\"table\" in editor.schema.blockSpecs) {\n extensions.push(TableHandlesExtension(options));\n }\n\n if (options.animations !== false) {\n extensions.push(PreviousBlockTypeExtension());\n }\n\n return extensions;\n}\n","import {\n InputRule,\n inputRules as inputRulesPlugin,\n} from \"@handlewithcare/prosemirror-inputrules\";\nimport {\n AnyExtension as AnyTiptapExtension,\n Extension as TiptapExtension,\n} from \"@tiptap/core\";\nimport { keydownHandler } from \"@tiptap/pm/keymap\";\nimport { Plugin, PluginKey, TextSelection } from \"prosemirror-state\";\nimport { updateBlockTr } from \"../../../api/blockManipulation/commands/updateBlock/updateBlock.js\";\nimport { setTextCursorPosition } from \"../../../api/blockManipulation/selections/textCursorPosition.js\";\nimport {\n getBlockInfoFromSelection,\n getNodeId,\n} from \"../../../api/getBlockInfoFromPos.js\";\nimport { sortByDependencies } from \"../../../util/topo-sort.js\";\nimport type {\n BlockNoteEditor,\n BlockNoteEditorOptions,\n} from \"../../BlockNoteEditor.js\";\nimport type {\n Extension,\n ExtensionFactoryInstance,\n ExtensionFactory,\n} from \"../../BlockNoteExtension.js\";\nimport { originalFactorySymbol } from \"./symbol.js\";\nimport {\n getDefaultExtensions,\n getDefaultTiptapExtensions,\n} from \"./extensions.js\";\n\nexport type ExtensionSelector =\n | Extension\n | ExtensionFactory\n | string\n | undefined;\nexport type ExtensionSelection = ExtensionSelector | ExtensionSelector[];\n\nexport class ExtensionManager {\n /**\n * A set of extension keys which are disabled by the options\n */\n private disabledExtensions = new Set<string>();\n /**\n * A list of all the extensions that are registered to the editor\n */\n private extensions: Extension[] = [];\n /**\n * A map of all the abort controllers for each extension that has an init method defined\n */\n private abortMap = new Map<Extension, AbortController>();\n /**\n * A map of all the extension factories that are registered to the editor\n */\n private extensionFactories = new Map<ExtensionFactory, Extension>();\n /**\n * Because a single blocknote extension can both have it's own prosemirror plugins & additional generated ones (e.g. keymap & input rules plugins)\n * We need to keep track of all the plugins for each extension, so that we can remove them when the extension is unregistered\n */\n private extensionPlugins: Map<Extension, Plugin[]> = new Map();\n private runtimeExtensions = new Set<Extension>();\n /**\n * Maps an extension key to the set of extension keys that declared it as a\n * dependency via `blockNoteExtensions`. A sub-extension is a dependency of\n * the extension that declares it, so it must run *before* its parent(s).\n */\n private blockNoteExtensionDependents: Map<string, Set<string>> = new Map();\n\n constructor(\n private editor: BlockNoteEditor<any, any, any>,\n private options: BlockNoteEditorOptions<any, any, any>,\n ) {\n /**\n * When the editor is first mounted, we need to initialize all the extensions\n */\n editor.onMount(() => {\n for (const extension of this.extensions) {\n this.mountExtension(extension);\n }\n });\n\n /**\n * When the editor is unmounted, we need to abort all the extensions' abort controllers\n */\n editor.onUnmount(() => {\n for (const [extension, abortController] of this.abortMap.entries()) {\n // No longer track the abort controller for this extension\n this.abortMap.delete(extension);\n // Abort each extension's abort controller\n abortController.abort();\n }\n });\n\n // TODO do disabled extensions need to be only for editor base extensions? Or all of them?\n this.disabledExtensions = new Set(options.disableExtensions || []);\n\n // Add the default extensions\n for (const extension of getDefaultExtensions(this.editor, this.options)) {\n this.addExtension(extension);\n }\n\n // Add the extensions from the options\n for (const extension of this.options.extensions ?? []) {\n this.addExtension(extension);\n }\n\n // Add the extensions from blocks specs\n for (const block of Object.values(this.editor.schema.blockSpecs)) {\n for (const extension of block.extensions ?? []) {\n this.addExtension(extension);\n }\n }\n }\n\n private mountExtension(extension: Extension): void {\n if (!extension.mount || this.abortMap.has(extension)) {\n return;\n }\n const controller = new window.AbortController();\n this.abortMap.set(extension, controller);\n const cleanup = extension.mount({\n dom: this.editor.prosemirrorView.dom,\n root: this.editor.prosemirrorView.root,\n signal: controller.signal,\n });\n if (cleanup) {\n if (controller.signal.aborted) {\n cleanup();\n } else {\n controller.signal.addEventListener(\"abort\", cleanup, { once: true });\n }\n }\n }\n\n /**\n * Register one or more extensions to the editor after the editor is initialized.\n *\n * This allows users to switch on & off extensions \"at runtime\".\n */\n public registerExtension(\n extension:\n | Extension\n | ExtensionFactoryInstance\n | (Extension | ExtensionFactoryInstance)[],\n ): void {\n this.replaceExtension(undefined, extension);\n }\n\n /**\n * Register an extension to the editor\n * @param extension - The extension to register\n * @returns The extension instance\n */\n private addExtension(\n extension: Extension | ExtensionFactoryInstance,\n /**\n * When this extension is being added as a dependency declared in another\n * extension's `blockNoteExtensions`, this is the key of that declaring\n * (parent) extension.\n */\n parentKey?: string,\n ): Extension | undefined {\n let instance: Extension;\n if (typeof extension === \"function\") {\n instance = extension({ editor: this.editor });\n } else {\n instance = extension;\n }\n\n if (!instance || this.disabledExtensions.has(instance.key)) {\n return undefined as any;\n }\n\n // A sub-extension declared via `blockNoteExtensions` must run before the\n // extension that declares it. We record this dependency before the\n // de-duplication check below, so that it applies even when multiple\n // extensions declare the same sub-extension (and all but the first are\n // de-duplicated).\n if (parentKey) {\n let dependents = this.blockNoteExtensionDependents.get(instance.key);\n if (!dependents) {\n dependents = new Set();\n this.blockNoteExtensionDependents.set(instance.key, dependents);\n }\n dependents.add(parentKey);\n }\n\n // De-duplicate by key: if an extension with the same key is already\n // registered, don't register it again. This allows an extension to declare\n // a dependency on another extension via `blockNoteExtensions` without\n // conflicting when the user (or another extension) registers that same\n // extension directly. The first registration wins.\n if (this.extensions.some((e) => e.key === instance.key)) {\n return undefined as any;\n }\n\n // Now that we know that the extension is not disabled, we can add it to the extension factories\n const originalFactory = (instance as any)[originalFactorySymbol] as (\n ...args: any[]\n ) => ExtensionFactoryInstance;\n\n if (typeof originalFactory === \"function\") {\n this.extensionFactories.set(originalFactory, instance);\n }\n\n this.extensions.push(instance);\n\n if (instance.blockNoteExtensions) {\n for (const subExtension of instance.blockNoteExtensions) {\n this.addExtension(subExtension, instance.key);\n }\n }\n\n return instance as any;\n }\n\n /**\n * Resolve an extension or a list of extensions into a list of extension instances\n * @param toResolve - The extension or list of extensions to resolve\n * @returns A list of extension instances\n */\n private resolveExtensions(\n toResolve:\n | undefined\n | string\n | Extension\n | ExtensionFactory\n | (Extension | ExtensionFactory | string | undefined)[],\n ): Extension[] {\n const extensions = [] as Extension[];\n if (typeof toResolve === \"function\") {\n const instance = this.extensionFactories.get(toResolve);\n if (instance) {\n extensions.push(instance);\n }\n } else if (Array.isArray(toResolve)) {\n for (const extension of toResolve) {\n extensions.push(...this.resolveExtensions(extension));\n }\n } else if (typeof toResolve === \"object\" && \"key\" in toResolve) {\n extensions.push(toResolve);\n } else if (typeof toResolve === \"string\") {\n const instance = this.extensions.find((e) => e.key === toResolve);\n if (instance) {\n extensions.push(instance);\n }\n }\n return extensions;\n }\n\n /**\n * Unregister an extension from the editor\n * @param toUnregister - The extension to unregister\n * @returns The removed instance, or the removed instances for an array.\n */\n public unregisterExtension<const T extends ExtensionFactory>(\n toUnregister: T,\n ): ReturnType<ReturnType<T>> | undefined;\n public unregisterExtension<const T extends Extension>(\n toUnregister: T,\n ): T | undefined;\n public unregisterExtension(toUnregister: ExtensionSelector[]): Extension[];\n public unregisterExtension(\n toUnregister: ExtensionSelector,\n ): Extension | undefined;\n public unregisterExtension(\n toUnregister: ExtensionSelection,\n ): Extension | Extension[] | undefined;\n public unregisterExtension(\n toUnregister: ExtensionSelection,\n ): Extension | Extension[] | undefined {\n const removed = [...new Set(this.resolveExtensions(toUnregister))].filter(\n (extension) => this.extensions.includes(extension),\n );\n if (removed.length) {\n this.replaceExtension(removed, []);\n }\n return Array.isArray(toUnregister) ? removed : removed[0];\n }\n\n /**\n * Atomically replace extension instances in the editor.\n * @param toUnregister - The extensions to unregister, can be a string key, an extension instance, an extension factory, or an array of any of those\n * @param toRegister - The extensions to register, can be an extension instance, an extension factory, or an array of any of those\n * @param options.resetPluginStateFor - Plugin keys whose state must be initialized afresh instead of carried across the replacement\n * @returns void\n */\n public replaceExtension(\n toUnregister:\n | undefined\n | string\n | Extension\n | ExtensionFactory\n | (Extension | ExtensionFactory | string | undefined)[],\n toRegister:\n | Extension\n | ExtensionFactoryInstance\n | (Extension | ExtensionFactoryInstance)[],\n options?: { resetPluginStateFor: readonly PluginKey[] },\n ): void {\n // ---- Remove phase (no updatePlugins call) ----\n const extensionsToRemove = this.resolveExtensions(toUnregister);\n\n if (toUnregister && !extensionsToRemove.length) {\n // eslint-disable-next-line no-console\n console.warn(`No extensions found to unregister`, toUnregister);\n }\n\n let didWarnUnregister = false;\n // We collect both plugin references and plugin keys to remove.\n // Key-based matching is needed because re-entrant dispatches (e.g. from\n // y-prosemirror view hooks) can replace plugin instances in the ProseMirror\n // state with new objects that share the same key, making reference-based\n // matching unreliable.\n const pluginRefsToRemove = new Set<Plugin>();\n const pluginKeysToRemove = new Set<string>();\n for (const extension of extensionsToRemove) {\n this.extensions = this.extensions.filter((e) => e !== extension);\n this.extensionFactories.forEach((instance, factory) => {\n if (instance === extension) {\n this.extensionFactories.delete(factory);\n }\n });\n this.abortMap.get(extension)?.abort();\n this.abortMap.delete(extension);\n\n const plugins = this.extensionPlugins.get(extension);\n plugins?.forEach((plugin) => {\n pluginRefsToRemove.add(plugin);\n const key = (plugin as any).spec?.key;\n const keyStr = typeof key === \"object\" && key ? key.key : key;\n if (typeof keyStr === \"string\") {\n pluginKeysToRemove.add(keyStr);\n }\n });\n this.extensionPlugins.delete(extension);\n this.runtimeExtensions.delete(extension);\n\n if (extension.tiptapExtensions && !didWarnUnregister) {\n didWarnUnregister = true;\n // eslint-disable-next-line no-console\n console.warn(\n `Extension ${extension.key} has tiptap extensions, but they will not be removed. Please separate the extension into multiple extensions if you want to remove them, or re-initialize the editor.`,\n toUnregister,\n );\n }\n }\n\n // ---- Add phase (no updatePlugins call) ----\n const newExtensions = ([] as (Extension | ExtensionFactoryInstance)[])\n .concat(toRegister)\n .filter(Boolean) as (Extension | ExtensionFactoryInstance)[];\n\n const registeredExtensions = newExtensions\n .map((ext) => this.addExtension(ext))\n .filter(Boolean) as Extension[];\n\n const pluginsToAdd: Plugin[] = [];\n for (const extension of registeredExtensions) {\n this.runtimeExtensions.add(extension);\n if (extension?.tiptapExtensions) {\n // eslint-disable-next-line no-console\n console.warn(\n `Extension ${extension.key} has tiptap extensions, but these cannot be changed after initializing the editor. Please separate the extension into multiple extensions if you want to add them, or re-initialize the editor.`,\n extension,\n );\n }\n\n if (extension?.inputRules?.length) {\n // eslint-disable-next-line no-console\n console.warn(\n `Extension ${extension.key} has input rules, but these cannot be changed after initializing the editor. Please separate the extension into multiple extensions if you want to add them, or re-initialize the editor.`,\n extension,\n );\n }\n\n this.getProsemirrorPluginsFromExtension(extension).plugins.forEach(\n (plugin) => {\n pluginsToAdd.push(plugin);\n },\n );\n }\n\n // ---- Single atomic plugin update for replacement or an explicit reset ----\n if (\n pluginRefsToRemove.size ||\n pluginKeysToRemove.size ||\n pluginsToAdd.length ||\n options?.resetPluginStateFor.length\n ) {\n this.updatePlugins(\n (plugins) => [\n ...plugins.filter((plugin) => {\n // Fast path: exact reference match\n if (pluginRefsToRemove.has(plugin)) {\n return false;\n }\n // Fallback: match by key string (handles cases where plugin instances\n // in the state differ from the ones we tracked)\n if (pluginKeysToRemove.size) {\n const key = (plugin as any).spec?.key;\n const keyStr = typeof key === \"object\" && key ? key.key : key;\n if (\n typeof keyStr === \"string\" &&\n pluginKeysToRemove.has(keyStr)\n ) {\n return false;\n }\n }\n return true;\n }),\n ...pluginsToAdd,\n ],\n options?.resetPluginStateFor,\n );\n }\n if (!this.editor.headless) {\n for (const extension of registeredExtensions) {\n this.mountExtension(extension);\n }\n }\n }\n\n /**\n * Allows resetting the current prosemirror state's plugins\n * @param update - A function that takes the current plugins and returns the new plugins\n * @returns void\n */\n private updatePlugins(\n update: (plugins: Plugin[]) => Plugin[],\n resetPluginStateFor?: readonly PluginKey[],\n ): void {\n const currentState = this.editor.prosemirrorState;\n // Reconfigure an intermediate state off-view to drop selected keyed state.\n // New plugins initialize before any view hooks can see a torn binding, and\n // the view receives only the final, complete plugin set.\n const resetKeys = new Set(resetPluginStateFor);\n const baseState = resetKeys.size\n ? currentState.reconfigure({\n plugins: currentState.plugins.filter(\n (plugin) => !plugin.spec.key || !resetKeys.has(plugin.spec.key),\n ),\n })\n : currentState;\n const state = baseState.reconfigure({\n plugins: update(currentState.plugins.slice()),\n });\n\n this.editor.prosemirrorView.updateState(state);\n }\n\n /**\n * Get all the extensions that are registered to the editor\n */\n public getTiptapExtensions(): AnyTiptapExtension[] {\n // Start with the default tiptap extensions\n const tiptapExtensions = getDefaultTiptapExtensions(\n this.editor,\n this.options,\n ).filter((extension) => !this.disabledExtensions.has(extension.name));\n\n const getPriority = sortByDependencies(\n this.extensions.map((extension) => {\n // A sub-extension declared via `blockNoteExtensions` must run before the\n // extension(s) that declared it, so we merge those parents into its\n // `runsBefore`.\n const dependents = this.blockNoteExtensionDependents.get(extension.key);\n if (!dependents?.size) {\n return extension;\n }\n return {\n key: extension.key,\n runsBefore: [...(extension.runsBefore ?? []), ...dependents],\n };\n }),\n );\n\n const inputRulesByPriority = new Map<number, InputRule[]>();\n for (const extension of this.extensions) {\n if (extension.tiptapExtensions) {\n tiptapExtensions.push(...extension.tiptapExtensions);\n }\n\n const priority = getPriority(extension.key);\n\n const { plugins: prosemirrorPlugins, inputRules } =\n this.getProsemirrorPluginsFromExtension(extension);\n // Sometimes a blocknote extension might need to make additional prosemirror plugins, so we generate them here\n if (prosemirrorPlugins.length) {\n tiptapExtensions.push(\n TiptapExtension.create({\n name: extension.key,\n priority,\n // Removed extensions have no plugins in the map. Replacements and\n // re-registrations belong to the runtime wrapper below instead.\n addProseMirrorPlugins: () =>\n this.runtimeExtensions.has(extension)\n ? []\n : (this.extensionPlugins.get(extension) ?? []),\n }),\n );\n }\n if (inputRules.length) {\n if (!inputRulesByPriority.has(priority)) {\n inputRulesByPriority.set(priority, []);\n }\n inputRulesByPriority.get(priority)!.push(...inputRules);\n }\n }\n\n // Runtime additions have no construction-time Tiptap wrapper. Like\n // registerExtension's plugin update, append their already-created plugins.\n tiptapExtensions.push(\n TiptapExtension.create({\n name: \"blocknote-runtime-extensions\",\n priority: Number.NEGATIVE_INFINITY,\n addProseMirrorPlugins: () =>\n this.extensions\n .filter((extension) => this.runtimeExtensions.has(extension))\n .flatMap((extension) => this.extensionPlugins.get(extension) ?? []),\n }),\n );\n\n // Collect all input rules into 1 extension to reduce conflicts\n tiptapExtensions.push(\n TiptapExtension.create({\n name: \"blocknote-input-rules\",\n addProseMirrorPlugins() {\n const rules = [] as InputRule[];\n Array.from(inputRulesByPriority.keys())\n // We sort the rules by their priority (the key)\n .sort((a, b) => a - b)\n .reverse()\n .forEach((priority) => {\n // Append in reverse priority order\n rules.push(...inputRulesByPriority.get(priority)!);\n });\n const inputRules = inputRulesPlugin({ rules });\n // Sidecar plugin: triggers the same input rules on Enter by\n // delegating to the inputRules plugin's handleTextInput with a\n // synthetic \"\\n\" insertion. The handlewithcare regex `\\s$` already\n // matches `\\n`, so any rule that fires on space fires on Enter too.\n // We call its handleTextInput directly (rather than via\n // view.someProp) so other plugins don't observe the synthetic input,\n // and so the rule's undo metadata is keyed to the same plugin\n // instance that Tiptap's `commands.undoInputRule` reads from.\n const inputRulesEnter = new Plugin({\n props: {\n handleKeyDown(view, event) {\n if (event.key !== \"Enter\") {\n return false;\n }\n // Only trigger on plain Enter — modifier combos like\n // Shift/Cmd/Ctrl/Alt+Enter are reserved for other handlers\n // (e.g. soft-break, submit) and should fall through.\n if (\n event.shiftKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.altKey\n ) {\n return false;\n }\n const { $cursor } = view.state.selection as TextSelection;\n if (!$cursor) {\n return false;\n }\n return !!inputRules.props.handleTextInput?.call(\n inputRules,\n view,\n $cursor.pos,\n $cursor.pos,\n \"\\n\",\n () =>\n view.state.tr.insertText(\"\\n\", $cursor.pos, $cursor.pos),\n );\n },\n },\n });\n return [inputRules, inputRulesEnter];\n },\n }),\n );\n\n // Add any tiptap extensions from the `_tiptapOptions`\n for (const extension of this.options._tiptapOptions?.extensions ?? []) {\n tiptapExtensions.push(extension);\n }\n\n return tiptapExtensions;\n }\n\n /**\n * This maps a blocknote extension into an array of Prosemirror plugins if it has any of the following:\n * - plugins\n * - keyboard shortcuts\n * - input rules\n */\n private getProsemirrorPluginsFromExtension(extension: Extension): {\n plugins: Plugin[];\n inputRules: InputRule[];\n } {\n const plugins: Plugin[] = [...(extension.prosemirrorPlugins ?? [])];\n const inputRules: InputRule[] = [];\n if (\n !extension.prosemirrorPlugins?.length &&\n !Object.keys(extension.keyboardShortcuts || {}).length &&\n !extension.inputRules?.length\n ) {\n // We can bail out early if the extension has no features to add to the tiptap editor\n return { plugins, inputRules };\n }\n\n this.extensionPlugins.set(extension, plugins);\n\n if (extension.inputRules?.length) {\n inputRules.push(\n ...extension.inputRules.map((inputRule) => {\n return new InputRule(\n inputRule.find,\n (state, match, start, end) => {\n const replaceWith = inputRule.replace({\n match,\n range: { from: start, to: end },\n editor: this.editor,\n });\n if (replaceWith) {\n const tr = state.tr;\n const blockInfo = getBlockInfoFromSelection(tr);\n\n if (\n !blockInfo.hasContent ||\n this.editor.schema.blockSchema[blockInfo.blockNoteType]\n ?.content !== \"inline\"\n ) {\n return null;\n }\n\n tr.deleteRange(start, end);\n updateBlockTr(tr, blockInfo.block.beforePos, replaceWith);\n // updateBlockTr's replaceWith path leaves the selection after\n // the new block when the content is replaced wholesale (e.g.\n // when the rule returns content: []). Move the cursor back\n // inside the new block so the user can keep typing.\n setTextCursorPosition(\n tr,\n getNodeId(blockInfo.block.node, tr.doc),\n \"start\",\n );\n return tr;\n }\n return null;\n },\n { undoable: true },\n );\n }),\n );\n }\n\n if (Object.keys(extension.keyboardShortcuts || {}).length) {\n let currentEvent: KeyboardEvent | undefined;\n const handleKeyDown = keydownHandler(\n Object.fromEntries(\n Object.entries(extension.keyboardShortcuts!).map(\n ([key, callback]) => [\n key,\n () => {\n if (!currentEvent) {\n throw new Error(\n \"Keyboard shortcut called outside handleKeyDown\",\n );\n }\n return callback({ editor: this.editor, event: currentEvent });\n },\n ],\n ),\n ),\n );\n plugins.push(\n new Plugin({\n props: {\n handleKeyDown: (view, event) => {\n const previousEvent = currentEvent;\n currentEvent = event;\n try {\n return handleKeyDown(view, event);\n } finally {\n currentEvent = previousEvent;\n }\n },\n },\n }),\n );\n }\n\n return { plugins, inputRules };\n }\n\n /**\n * Get all extensions\n */\n public getExtensions(): Map<string, Extension> {\n return new Map(\n this.extensions.map((extension) => [extension.key, extension]),\n );\n }\n\n /**\n * Get a specific extension by it's instance\n */\n public getExtension<\n const Ext extends Extension | ExtensionFactory = Extension,\n >(\n extension: string,\n ):\n | (Ext extends Extension\n ? Ext\n : Ext extends ExtensionFactory\n ? ReturnType<ReturnType<Ext>>\n : never)\n | undefined;\n public getExtension<const T extends ExtensionFactory>(\n extension: T,\n ): ReturnType<ReturnType<T>> | undefined;\n public getExtension<const T extends ExtensionFactory | string = string>(\n extension: T,\n ):\n | (T extends ExtensionFactory\n ? ReturnType<ReturnType<T>>\n : T extends string\n ? Extension\n : never)\n | undefined {\n if (typeof extension === \"string\") {\n const instance = this.extensions.find((e) => e.key === extension);\n if (!instance) {\n return undefined;\n }\n return instance as any;\n } else if (typeof extension === \"function\") {\n const instance = this.extensionFactories.get(extension);\n if (!instance) {\n return undefined;\n }\n return instance as any;\n }\n throw new Error(`Invalid extension type: ${typeof extension}`);\n }\n\n /**\n * Check if an extension exists\n */\n public hasExtension(key: string | Extension | ExtensionFactory): boolean {\n if (typeof key === \"string\") {\n return this.extensions.some((e) => e.key === key);\n } else if (typeof key === \"object\" && \"key\" in key) {\n return this.extensions.some((e) => e.key === key.key);\n } else if (typeof key === \"function\") {\n return this.extensionFactories.has(key);\n }\n return false;\n }\n}\n","import type { Node, ResolvedPos } from \"prosemirror-model\";\n\n/**\n * Expands a range (start to end) to include the rest of the word if it starts or ends within a word\n */\nexport function expandPMRangeToWords(\n doc: Node,\n range: { $from: ResolvedPos; $to: ResolvedPos },\n) {\n let { $from, $to } = range;\n\n // Expand Start\n // If the selection starts with a word character or punctuation, check if we need to expand left to include the rest of the word\n if ($from.pos > $from.start() && $from.pos < doc.content.size) {\n const charAfterStart = doc.textBetween($from.pos, $from.pos + 1);\n if (/^[\\w\\p{P}]$/u.test(charAfterStart)) {\n const textBefore = doc.textBetween($from.start(), $from.pos);\n const wordMatch = textBefore.match(/[\\w\\p{P}]+$/u);\n if (wordMatch) {\n $from = doc.resolve($from.pos - wordMatch[0].length);\n }\n }\n }\n\n // Expand End\n // If the selection ends with a word characte or punctuation, check if we need to expand right to include the rest of the word\n if ($to.pos < $to.end() && $to.pos > 0) {\n const charBeforeEnd = doc.textBetween($to.pos - 1, $to.pos);\n if (/^[\\w\\p{P}]$/u.test(charBeforeEnd)) {\n const textAfter = doc.textBetween($to.pos, $to.end());\n const wordMatch = textAfter.match(/^[\\w\\p{P}]+/u);\n if (wordMatch) {\n $to = doc.resolve($to.pos + wordMatch[0].length);\n }\n }\n }\n return { $from, $to, from: $from.pos, to: $to.pos };\n}\n","import { TextSelection, type Transaction } from \"prosemirror-state\";\nimport { Block } from \"../../../blocks/defaultBlocks.js\";\nimport { Selection } from \"../../../editor/selectionTypes.js\";\nimport {\n BlockIdentifier,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { CHILD_CONTAINER_GROUP } from \"../../../schema/blocks/children.js\";\nimport { expandPMRangeToWords } from \"../../../util/expandToWords.js\";\nimport {\n blockEdgePos,\n getBlockInfoFromNode,\n getNearestBlockPos,\n} from \"../../getBlockInfoFromPos.js\";\nimport {\n nodeToBlock,\n prosemirrorSliceToSlicedBlocks,\n} from \"../../nodeConversions/nodeToBlock.js\";\nimport { getNodeById } from \"../../nodeUtil.js\";\n\nexport function getSelection<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(tr: Transaction): Selection<BSchema, I, S> | undefined {\n // Return undefined if the selection is collapsed or a node is selected.\n if (tr.selection.empty || \"node\" in tr.selection) {\n return undefined;\n }\n\n const $startBlockBeforePos = tr.doc.resolve(\n getNearestBlockPos(tr.doc, tr.selection.from).posBeforeNode,\n );\n const $endBlockBeforePos = tr.doc.resolve(\n getNearestBlockPos(tr.doc, tr.selection.to).posBeforeNode,\n );\n\n // Converts the node at the given index and depth around `$startBlockBeforePos`\n // to a block. Used to get blocks at given indices at the shared depth and\n // at the depth of `$startBlockBeforePos`.\n const indexToBlock = (\n index: number,\n depth?: number,\n ): Block<BSchema, I, S> => {\n const pos = $startBlockBeforePos.posAtIndex(index, depth);\n const node = tr.doc.resolve(pos).nodeAfter;\n\n if (!node) {\n throw new Error(\n `Error getting selection - node not found at position ${pos}`,\n );\n }\n\n return nodeToBlock(node, tr.doc);\n };\n\n const blocks: Block<BSchema, I, S>[] = [];\n // Minimum depth at which the blocks share a common ancestor.\n const sharedDepth = $startBlockBeforePos.sharedDepth($endBlockBeforePos.pos);\n const startIndex = $startBlockBeforePos.index(sharedDepth);\n const endIndex = $endBlockBeforePos.index(sharedDepth);\n\n // In most cases, we want to return the blocks spanned by the selection at the\n // shared depth. However, when the block in which the selection starts is at a\n // higher depth than the shared depth, we omit the first block at the shared\n // depth. Instead, we include the first block at its depth, and any blocks at\n // a higher index up to the shared depth. The following example illustrates\n // this:\n // - id-0\n // - id-1\n // - >|id-2\n // - id-3\n // - id-4\n // - id-5\n // - id-6\n // - id-7\n // - id-8\n // - id-9|<\n // - id-10\n // Here, each block is represented by its ID, and the selection is represented\n // by the `>|` and `|<` markers. So the selection starts in block `id-2` and\n // ends in block `id-8`. In this case, the shared depth is 0, since the blocks\n // `id-6`, `id-7`, and `id-8` set the shared depth, as they are the least\n // nested blocks spanned by the selection. Therefore, these blocks are all\n // added to the `blocks` array. However, the selection starts in block `id-2`,\n // which is at a higher depth than the shared depth. So we add block `id-2` to\n // the `blocks` array, as well as any later siblings (in this case, `id-3`),\n // and move up one level of depth. The ancestor of block `id-2` at this depth\n // is block `id-1`, so we add all its later siblings to the `blocks` array as\n // well, again moving up one level of depth. Since we're now at the shared\n // depth, we are done. The final `blocks` array for this example would be:\n // [ id-2, id-3, id-4, id-6, id-7, id-8, id-9 ]\n if ($startBlockBeforePos.depth > sharedDepth) {\n // Adds the block that the selection starts in.\n blocks.push(nodeToBlock($startBlockBeforePos.nodeAfter!, tr.doc));\n\n // Traverses all depths from the depth of the block in which the selection\n // starts, up to the shared depth.\n for (let depth = $startBlockBeforePos.depth; depth > sharedDepth; depth--) {\n const parentNode = $startBlockBeforePos.node(depth);\n\n if (parentNode.type.isInGroup(CHILD_CONTAINER_GROUP)) {\n const startIndexAtDepth = $startBlockBeforePos.index(depth) + 1;\n const childCountAtDepth = $startBlockBeforePos.node(depth).childCount;\n\n // Adds all blocks after the index of the block in which the selection\n // starts (or its ancestors at lower depths).\n for (let i = startIndexAtDepth; i < childCountAtDepth; i++) {\n blocks.push(indexToBlock(i, depth));\n }\n }\n }\n } else {\n // Adds the first block spanned by the selection at the shared depth.\n blocks.push(indexToBlock(startIndex, sharedDepth));\n }\n\n // Adds all blocks spanned by the selection at the shared depth, excluding\n // the first.\n for (let i = startIndex + 1; i <= endIndex; i++) {\n blocks.push(indexToBlock(i, sharedDepth));\n }\n\n if (blocks.length === 0) {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string\n `Error getting selection - selection doesn't span any blocks (${tr.selection})`,\n );\n }\n\n return {\n blocks,\n };\n}\n\nexport function setSelection(\n tr: Transaction,\n startBlock: BlockIdentifier,\n endBlock: BlockIdentifier,\n) {\n const startBlockId =\n typeof startBlock === \"string\" ? startBlock : startBlock.id;\n const endBlockId = typeof endBlock === \"string\" ? endBlock : endBlock.id;\n\n if (startBlockId === endBlockId) {\n throw new Error(\n `Attempting to set selection with the same anchor and head blocks (id ${startBlockId})`,\n );\n }\n const anchorPosInfo = getNodeById(startBlockId, tr.doc);\n if (!anchorPosInfo) {\n throw new Error(`Block with ID ${startBlockId} not found`);\n }\n const headPosInfo = getNodeById(endBlockId, tr.doc);\n if (!headPosInfo) {\n throw new Error(`Block with ID ${endBlockId} not found`);\n }\n\n const anchorBlockInfo = getBlockInfoFromNode(\n anchorPosInfo.node,\n anchorPosInfo.posBeforeNode,\n );\n const headBlockInfo = getBlockInfoFromNode(\n headPosInfo.node,\n headPosInfo.posBeforeNode,\n );\n\n const startPos = blockEdgePos(anchorBlockInfo, \"start\");\n if (startPos === null) {\n throw new Error(\n `Attempting to set selection anchor in block without content (id ${startBlockId})`,\n );\n }\n const endPos = blockEdgePos(headBlockInfo, \"end\");\n if (endPos === null) {\n throw new Error(\n `Attempting to set selection head in block without content (id ${endBlockId})`,\n );\n }\n\n // TODO: We should polish up the `MultipleNodeSelection` and use that instead.\n // Right now it's missing a few things like a jsonID and styling to show\n // which nodes are selected. `TextSelection` is ok for now, but has the\n // restriction that the start/end blocks must have content.\n tr.setSelection(TextSelection.create(tr.doc, startPos, endPos));\n}\n\nexport function getSelectionCutBlocks(tr: Transaction, expandToWords = false) {\n // TODO: fix image node selection\n\n const range = expandToWords\n ? expandPMRangeToWords(tr.doc, tr.selection)\n : tr.selection;\n\n let start = range.$from;\n let end = range.$to;\n\n // the selection moves below are used to make sure `prosemirrorSliceToSlicedBlocks` returns\n // the correct information about whether content is cut at the start or end of a block\n\n // if the end is at the end of a node (|</span></p>) move it forward so we include all closing tags (</span></p>|)\n while (end.parentOffset >= end.parent.nodeSize - 2 && end.depth > 0) {\n end = tr.doc.resolve(end.pos + 1);\n }\n\n // if the end is at the start of an empty node (</span></p><p>|) move it backwards so we drop empty start tags (</span></p>|)\n while (end.parentOffset === 0 && end.depth > 0) {\n end = tr.doc.resolve(end.pos - 1);\n }\n\n // if the start is at the start of a node (<p><span>|) move it backwards so we include all open tags (|<p><span>)\n while (start.parentOffset === 0 && start.depth > 0) {\n start = tr.doc.resolve(start.pos - 1);\n }\n\n // if the start is at the end of a node (|</p><p><span>|) move it forwards so we drop all closing tags (|<p><span>)\n while (start.parentOffset >= start.parent.nodeSize - 2 && start.depth > 0) {\n start = tr.doc.resolve(start.pos + 1);\n }\n\n const selectionInfo = prosemirrorSliceToSlicedBlocks(\n tr.doc.slice(start.pos, end.pos, true),\n );\n\n return {\n _meta: {\n startPos: start.pos,\n endPos: end.pos,\n },\n ...selectionInfo,\n };\n}\n","import { isNodeSelection, posToDOMRect } from \"@tiptap/core\";\nimport {\n getSelection,\n getSelectionCutBlocks,\n setSelection,\n} from \"../../api/blockManipulation/selections/selection.js\";\nimport {\n getTextCursorPosition,\n setTextCursorPosition,\n} from \"../../api/blockManipulation/selections/textCursorPosition.js\";\nimport {\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n} from \"../../blocks/defaultBlocks.js\";\nimport {\n BlockIdentifier,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { BlockNoteEditor } from \"../BlockNoteEditor.js\";\nimport { TextCursorPosition } from \"../cursorPositionTypes.js\";\nimport { Selection } from \"../selectionTypes.js\";\n\nexport class SelectionManager<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> {\n constructor(private editor: BlockNoteEditor<BSchema, ISchema, SSchema>) {}\n\n /**\n * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)\n * that the selection spans across.\n *\n * If the selection starts / ends halfway through a block, the returned data will contain the entire block.\n */\n public getSelection(): Selection<BSchema, ISchema, SSchema> | undefined {\n return this.editor.transact((tr) => getSelection(tr));\n }\n\n /**\n * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)\n * that the selection spans across.\n *\n * If the selection starts / ends halfway through a block, the returned block will be\n * only the part of the block that is included in the selection.\n */\n public getSelectionCutBlocks(expandToWords = false) {\n return this.editor.transact((tr) =>\n getSelectionCutBlocks(tr, expandToWords),\n );\n }\n\n /**\n * Sets the selection to a range of blocks.\n * @param startBlock The identifier of the block that should be the start of the selection.\n * @param endBlock The identifier of the block that should be the end of the selection.\n */\n public setSelection(startBlock: BlockIdentifier, endBlock: BlockIdentifier) {\n return this.editor.transact((tr) => setSelection(tr, startBlock, endBlock));\n }\n\n /**\n * Gets a snapshot of the current text cursor position.\n * @returns A snapshot of the current text cursor position.\n */\n public getTextCursorPosition(): TextCursorPosition<\n BSchema,\n ISchema,\n SSchema\n > {\n return this.editor.transact((tr) => getTextCursorPosition(tr));\n }\n\n /**\n * Sets the text cursor position to the start or end of an existing block. Throws an error if the target block could\n * not be found.\n * @param targetBlock The identifier of an existing block that the text cursor should be moved to.\n * @param placement Whether the text cursor should be placed at the start or end of the block.\n */\n public setTextCursorPosition(\n targetBlock: BlockIdentifier,\n placement: \"start\" | \"end\" = \"start\",\n ) {\n return this.editor.transact((tr) =>\n setTextCursorPosition(tr, targetBlock, placement),\n );\n }\n\n /**\n * Gets the bounding box of the current selection.\n */\n public getSelectionBoundingBox() {\n if (!this.editor.prosemirrorView) {\n return undefined;\n }\n\n const { selection } = this.editor.prosemirrorState;\n\n // support for CellSelections\n const { ranges } = selection;\n const from = Math.min(...ranges.map((range) => range.$from.pos));\n const to = Math.max(...ranges.map((range) => range.$to.pos));\n\n if (isNodeSelection(selection)) {\n const node = this.editor.prosemirrorView.nodeDOM(from) as HTMLElement;\n if (node) {\n return node.getBoundingClientRect();\n }\n }\n\n return posToDOMRect(\n this.editor.prosemirrorView,\n from,\n to,\n ).toJSON() as DOMRect;\n }\n}\n","import { Command, Transaction } from \"prosemirror-state\";\nimport { ReadOnlyExtension } from \"../../extensions/ReadOnly/ReadOnly.js\";\nimport type { HistoryExtension } from \"../../extensions/History/History.js\";\nimport { BlockNoteEditor } from \"../BlockNoteEditor.js\";\n\nexport class StateManager {\n constructor(private editor: BlockNoteEditor<any, any, any>) {}\n\n /**\n * Stores the currently active transaction, which is the accumulated transaction from all {@link dispatch} calls during a {@link transact} calls\n */\n private activeTransaction: Transaction | null = null;\n\n /**\n * For any command that can be executed, you can check if it can be executed by calling `editor.can(command)`.\n * @example\n * ```ts\n * if (editor.can(editor.undo)) {\n * // show button\n * } else {\n * // hide button\n * }\n */\n public can(cb: () => boolean) {\n try {\n this.isInCan = true;\n return cb();\n } finally {\n this.isInCan = false;\n }\n }\n\n // Flag to indicate if we're in a `can` call\n private isInCan = false;\n\n /**\n * Execute a prosemirror command. This is mostly for backwards compatibility with older code.\n *\n * @note You should prefer the {@link transact} method when possible, as it will automatically handle the dispatching of the transaction and work across blocknote transactions.\n *\n * @example\n * ```ts\n * editor.exec((state, dispatch, view) => {\n * dispatch(state.tr.insertText(\"Hello, world!\"));\n * });\n * ```\n */\n public exec(command: Command) {\n if (this.activeTransaction) {\n throw new Error(\n \"`exec` should not be called within a `transact` call, move the `exec` call outside of the `transact` call\",\n );\n }\n if (this.isInCan) {\n return this.canExec(command);\n }\n const state = this.prosemirrorState;\n const view = this.prosemirrorView;\n const dispatch = (tr: Transaction) => this.prosemirrorView.dispatch(tr);\n\n return command(state, dispatch, view);\n }\n\n /**\n * Check if a command can be executed. A command should return `false` if it is not valid in the current state.\n *\n * @example\n * ```ts\n * if (editor.canExec(command)) {\n * // show button\n * } else {\n * // hide button\n * }\n * ```\n */\n public canExec(command: Command): boolean {\n if (this.activeTransaction) {\n throw new Error(\n \"`canExec` should not be called within a `transact` call, move the `canExec` call outside of the `transact` call\",\n );\n }\n const state = this.prosemirrorState;\n const view = this.prosemirrorView;\n\n return command(state, undefined, view);\n }\n\n /**\n * Execute a function within a \"blocknote transaction\".\n * All changes to the editor within the transaction will be grouped together, so that\n * we can dispatch them as a single operation (thus creating only a single undo step)\n *\n * @note There is no need to dispatch the transaction, as it will be automatically dispatched when the callback is complete.\n *\n * @example\n * ```ts\n * // All changes to the editor will be grouped together\n * editor.transact((tr) => {\n * tr.insertText(\"Hello, world!\");\n * // These two operations will be grouped together in a single undo step\n * editor.transact((tr) => {\n * tr.insertText(\"Hello, world!\");\n * });\n * });\n * ```\n */\n public transact<T>(\n callback: (\n /**\n * The current active transaction, this will automatically be dispatched to the editor when the callback is complete\n * If another `transact` call is made within the callback, it will be passed the same transaction as the parent call.\n */\n tr: Transaction,\n ) => T,\n ): T {\n if (this.activeTransaction) {\n // Already in a transaction, so we can just callback immediately\n return callback(this.activeTransaction);\n }\n\n try {\n // Enter transaction mode, by setting a starting transaction\n this.activeTransaction = this.editor._tiptapEditor.state.tr;\n\n // Capture all dispatch'd transactions\n const result = callback(this.activeTransaction);\n\n // Any transactions captured by the `dispatch` call will be stored in `this.activeTransaction`\n const activeTr = this.activeTransaction;\n\n this.activeTransaction = null;\n if (\n activeTr &&\n // Only dispatch if the transaction was actually modified in some way\n (activeTr.docChanged ||\n activeTr.selectionSet ||\n activeTr.scrolledIntoView ||\n activeTr.storedMarksSet ||\n !activeTr.isGeneric)\n ) {\n // Dispatch the transaction if it was modified\n this.prosemirrorView.dispatch(activeTr);\n }\n\n return result;\n } finally {\n // We wrap this in a finally block to ensure we don't disable future transactions just because of an error in the callback\n this.activeTransaction = null;\n }\n }\n /**\n * Get the underlying prosemirror state\n * @note Prefer using `editor.transact` to read the current editor state, as that will ensure the state is up to date\n * @see https://prosemirror.net/docs/ref/#state.EditorState\n */\n public get prosemirrorState() {\n if (this.activeTransaction) {\n throw new Error(\n \"`prosemirrorState` should not be called within a `transact` call, move the `prosemirrorState` call outside of the `transact` call or use `editor.transact` to read the current editor state\",\n );\n }\n return this.editor._tiptapEditor.state;\n }\n\n /**\n * Get the underlying prosemirror view\n * @see https://prosemirror.net/docs/ref/#view.EditorView\n */\n public get prosemirrorView() {\n return this.editor._tiptapEditor.view;\n }\n\n public isFocused() {\n return this.prosemirrorView?.hasFocus() || false;\n }\n\n public focus() {\n this.prosemirrorView?.focus();\n }\n\n /**\n * Checks if the editor is currently editable, or if it's locked.\n * @returns True if the editor is editable, false otherwise.\n */\n public get isEditable(): boolean {\n if (!this.editor._tiptapEditor) {\n if (!this.editor.headless) {\n throw new Error(\"no editor, but also not headless?\");\n }\n return false;\n }\n if (this.editor.headless) {\n // No live view while unmounted, so tiptap can't consult plugin props\n // (its unmounted view stub reports editable: true). Mirror the\n // ReadOnly plugin's `editable` prop directly so the application\n // preference and feature restrictions still read back correctly,\n // e.g. for static/server-side rendering via block render functions.\n const state = this.editor.getExtension(ReadOnlyExtension)?.store.state;\n if (state) {\n return state.isEditable && state.enabledSet.size === 0;\n }\n }\n return this.editor._tiptapEditor.isEditable === undefined\n ? true\n : this.editor._tiptapEditor.isEditable;\n }\n\n /**\n * Sets the application's editable preference without releasing feature restrictions.\n * @param editable True to make the editor editable, or false to lock it.\n */\n public set isEditable(editable: boolean) {\n if (!this.editor._tiptapEditor) {\n if (!this.editor.headless) {\n throw new Error(\"no editor, but also not headless?\");\n }\n // not relevant on headless\n return;\n }\n this.editor.getExtension(ReadOnlyExtension)!.setEditable(editable);\n }\n\n /**\n * Undo the last action.\n */\n public undo(): boolean {\n // Purposefully not using the UndoPlugin to not import y-prosemirror when not needed\n const undoPlugin =\n this.editor.getExtension<typeof HistoryExtension>(\"yUndo\");\n if (undoPlugin) {\n return this.exec(undoPlugin.undoCommand);\n }\n\n const historyPlugin =\n this.editor.getExtension<typeof HistoryExtension>(\"history\");\n if (historyPlugin) {\n return this.exec(historyPlugin.undoCommand);\n }\n\n throw new Error(\"No undo plugin found\");\n }\n\n /**\n * Redo the last action.\n */\n public redo() {\n const undoPlugin =\n this.editor.getExtension<typeof HistoryExtension>(\"yUndo\");\n if (undoPlugin) {\n return this.exec(undoPlugin.redoCommand);\n }\n\n const historyPlugin =\n this.editor.getExtension<typeof HistoryExtension>(\"history\");\n if (historyPlugin) {\n return this.exec(historyPlugin.redoCommand);\n }\n\n throw new Error(\"No redo plugin found\");\n }\n}\n","import { selectionToInsertionEnd } from \"@tiptap/core\";\nimport { Node } from \"prosemirror-model\";\n\nimport type { Transaction } from \"prosemirror-state\";\n\n// similar to tiptap insertContentAt\nexport function insertContentAt(\n tr: Transaction,\n position: number | { from: number; to: number },\n nodes: Node[],\n options: {\n updateSelection: boolean;\n } = { updateSelection: true },\n) {\n // don’t dispatch an empty fragment because this can lead to strange errors\n // if (content.toString() === \"<>\") {\n // return true;\n // }\n\n let { from, to } =\n typeof position === \"number\"\n ? { from: position, to: position }\n : { from: position.from, to: position.to };\n\n let isOnlyTextContent = true;\n let isOnlyBlockContent = true;\n // const nodes = isFragment(content) ? content : [content];\n\n let text = \"\";\n\n nodes.forEach((node) => {\n // check if added node is valid\n node.check();\n\n if (isOnlyTextContent && node.isText && node.marks.length === 0) {\n text += node.text;\n } else {\n isOnlyTextContent = false;\n }\n\n isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;\n });\n\n // check if we can replace the wrapping node by\n // the newly inserted content\n // example:\n // replace an empty paragraph by an inserted image\n // instead of inserting the image below the paragraph\n if (from === to && isOnlyBlockContent) {\n const { parent } = tr.doc.resolve(from);\n const isEmptyTextBlock =\n parent.isTextblock && !parent.type.spec.code && !parent.childCount;\n\n if (isEmptyTextBlock) {\n from -= 1;\n to += 1;\n }\n }\n\n // if there is only plain text we have to use `insertText`\n // because this will keep the current marks\n if (isOnlyTextContent) {\n // if value is string, we can use it directly\n // otherwise if it is an array, we have to join it\n // if (Array.isArray(value)) {\n // tr.insertText(value.map((v) => v.text || \"\").join(\"\"), from, to);\n // } else if (typeof value === \"object\" && !!value && !!value.text) {\n // tr.insertText(value.text, from, to);\n // } else {\n // tr.insertText(value as string, from, to);\n // }\n tr.insertText(text, from, to);\n } else {\n tr.replaceWith(from, to, nodes);\n }\n\n // set cursor at end of inserted content\n if (options.updateSelection) {\n selectionToInsertionEnd(tr, tr.steps.length - 1, -1);\n }\n\n return true;\n}\n","import { getMarkRange } from \"@tiptap/core\";\nimport { insertContentAt } from \"../../api/blockManipulation/insertContentAt.js\";\nimport { inlineContentToNodes } from \"../../api/nodeConversions/blockToNode.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n PartialInlineContent,\n StyleSchema,\n Styles,\n} from \"../../schema/index.js\";\nimport {\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n} from \"../../blocks/defaultBlocks.js\";\nimport { UnreachableCaseError } from \"../../util/typescript.js\";\nimport { BlockNoteEditor } from \"../BlockNoteEditor.js\";\n\nexport class StyleManager<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> {\n constructor(private editor: BlockNoteEditor<BSchema, ISchema, SSchema>) {}\n\n /**\n * Insert a piece of content at the current cursor position.\n *\n * @param content can be a string, or array of partial inline content elements\n */\n public insertInlineContent(\n content: PartialInlineContent<ISchema, SSchema>,\n { updateSelection = false }: { updateSelection?: boolean } = {},\n ) {\n const nodes = inlineContentToNodes(content, this.editor.pmSchema);\n\n this.editor.transact((tr) => {\n insertContentAt(\n tr,\n {\n from: tr.selection.from,\n to: tr.selection.to,\n },\n nodes,\n {\n updateSelection,\n },\n );\n });\n }\n\n /**\n * Gets the active text styles at the text cursor position or at the end of the current selection if it's active.\n */\n public getActiveStyles() {\n return this.editor.transact((tr) => {\n const styles: Styles<SSchema> = {};\n const marks =\n // Also track active marks that are not in the document. E.g. the bold mark can be selected\n // so that typing applies bold text, even if the text cursor isn't already within bold text.\n (tr.selection.empty && tr.storedMarks) || tr.selection.$to.marks();\n\n for (const mark of marks) {\n const config = this.editor.schema.styleSchema[mark.type.name];\n if (!config) {\n if (\n // Links are not considered styles in blocknote\n mark.type.name !== \"link\" &&\n // \"blocknoteIgnore\" tagged marks (such as comments) are also not considered BlockNote \"styles\"\n !mark.type.spec.blocknoteIgnore\n ) {\n // eslint-disable-next-line no-console\n console.warn(\"mark not found in styleschema\", mark.type.name);\n }\n\n continue;\n }\n if (config.propSchema === \"boolean\") {\n (styles as any)[config.type] = true;\n } else {\n (styles as any)[config.type] = mark.attrs.stringValue;\n }\n }\n\n return styles;\n });\n }\n\n /**\n * Adds styles to the currently selected content.\n * @param styles The styles to add.\n */\n public addStyles(styles: Styles<SSchema>) {\n for (const [style, value] of Object.entries(styles)) {\n const config = this.editor.schema.styleSchema[style];\n if (!config) {\n throw new Error(`style ${style} not found in styleSchema`);\n }\n if (config.propSchema === \"boolean\") {\n this.editor._tiptapEditor.commands.setMark(style);\n } else if (config.propSchema === \"string\") {\n this.editor._tiptapEditor.commands.setMark(style, {\n stringValue: value,\n });\n } else {\n throw new UnreachableCaseError(config.propSchema);\n }\n }\n }\n\n /**\n * Removes styles from the currently selected content.\n * @param styles The styles to remove.\n */\n public removeStyles(styles: Styles<SSchema>) {\n for (const style of Object.keys(styles)) {\n this.editor._tiptapEditor.commands.unsetMark(style);\n }\n }\n\n /**\n * Toggles styles on the currently selected content.\n * @param styles The styles to toggle.\n */\n public toggleStyles(styles: Styles<SSchema>) {\n for (const [style, value] of Object.entries(styles)) {\n const config = this.editor.schema.styleSchema[style];\n if (!config) {\n throw new Error(`style ${style} not found in styleSchema`);\n }\n if (config.propSchema === \"boolean\") {\n this.editor._tiptapEditor.commands.toggleMark(style);\n } else if (config.propSchema === \"string\") {\n this.editor._tiptapEditor.commands.toggleMark(style, {\n stringValue: value,\n });\n } else {\n throw new UnreachableCaseError(config.propSchema);\n }\n }\n }\n\n /**\n * Gets the currently selected text.\n */\n public getSelectedText() {\n return this.editor.transact((tr) => {\n return tr.doc.textBetween(tr.selection.from, tr.selection.to);\n });\n }\n\n /**\n * Find the link mark and its range at the given position, including at\n * either edge of the link.\n * Returns undefined if there is no link at that position.\n */\n public getLinkMarkAtPos(pos: number) {\n return this.editor.transact((tr) => {\n // The link mark is not inclusive, so `$pos.marks()` leaves it out at\n // both ends of a link, and callers compensated with `pos + 1`, which\n // covers the left end only. tiptap's `getMarkRange` looks at the node\n // after `pos` and then the one before, so it finds the link at both\n // ends; the mark itself is read off the node the range starts with.\n const linkType = this.editor.pmSchema.marks[\"link\"];\n const range = getMarkRange(tr.doc.resolve(pos), linkType);\n if (!range) {\n return undefined;\n }\n const linkMark = tr.doc\n .nodeAt(range.from)\n ?.marks.find((mark) => mark.type === linkType);\n if (!linkMark) {\n return undefined;\n }\n\n return {\n href: linkMark.attrs.href as string,\n from: range.from,\n to: range.to,\n text: tr.doc.textBetween(range.from, range.to),\n };\n });\n }\n\n /**\n * Gets the URL of the link the current selection starts in, or `undefined`\n * if it does not start in one.\n */\n public getSelectedLinkUrl() {\n return this.editor.transact((tr) => {\n // The node the selection starts in, on purpose not `getLinkMarkAtPos`\n // (which also looks at the node before `from`): a selection starting\n // right after a link must not pre-fill the link form with that link's\n // URL. A `from + 1` lookup would miss the right end of a link (a\n // selection of its last character, or a one-character link, reads as\n // no link).\n const node = tr.doc.nodeAt(tr.selection.from);\n const linkMark = node?.marks.find((mark) => mark.type.name === \"link\");\n return linkMark?.attrs.href as string | undefined;\n });\n }\n\n /**\n * Creates a new link to replace the selected content.\n * @param url The link URL.\n * @param text The text to display the link with.\n */\n public createLink(url: string, text?: string) {\n if (url === \"\") {\n return;\n }\n\n this.editor.transact((tr) => {\n const { from, to } = tr.selection;\n const linkMark = this.editor.pmSchema.mark(\"link\", { href: url });\n\n if (text) {\n tr.insertText(text, from, to).addMark(\n from,\n from + text.length,\n linkMark,\n );\n } else {\n tr.addMark(from, to, linkMark);\n }\n });\n }\n\n /**\n * Updates the link at the given position with a new URL and text.\n * @param url The new link URL.\n * @param text The new text to display.\n * @param position The position inside the link to edit. Defaults to the current selection anchor.\n */\n public editLink(\n url: string,\n text: string,\n position = this.editor.transact((tr) => tr.selection.anchor),\n ) {\n this.editor.transact((tr) => {\n const linkData = this.getLinkMarkAtPos(position);\n const { from, to } = linkData || {\n from: tr.selection.from,\n to: tr.selection.to,\n };\n\n const linkMark = this.editor.pmSchema.mark(\"link\", { href: url });\n const existingText = tr.doc.textBetween(from, to);\n if (text !== existingText) {\n tr.insertText(text, from, to);\n }\n tr.addMark(from, from + text.length, linkMark);\n });\n this.editor.prosemirrorView.focus();\n }\n\n /**\n * Removes the link at the given position, keeping the text.\n * @param position The position inside the link to remove. Defaults to the current selection anchor.\n */\n public deleteLink(\n position = this.editor.transact((tr) => tr.selection.anchor),\n ) {\n this.editor.transact((tr) => {\n const linkData = this.getLinkMarkAtPos(position);\n const { from, to } = linkData || {\n from: tr.selection.from,\n to: tr.selection.to,\n };\n\n tr.removeMark(from, to, this.editor.pmSchema.marks[\"link\"]).setMeta(\n \"preventAutolink\",\n true,\n );\n });\n this.editor.prosemirrorView.focus();\n }\n}\n","import { Fragment, Schema, Slice } from \"@tiptap/pm/model\";\nimport { EditorView } from \"@tiptap/pm/view\";\n\nimport { getBlockInfoFromSelection } from \"../api/getBlockInfoFromPos.js\";\nimport { findParentNodeClosestToPos } from \"@tiptap/core\";\n\n/**\n * Checks if the current selection is inside a table cell.\n * Returns the depth of the tableCell/tableHeader node if found, -1 otherwise.\n */\nfunction isInTableCell(view: EditorView): boolean {\n return (\n findParentNodeClosestToPos(view.state.selection.$from, (n) => {\n return n.type.name === \"tableCell\" || n.type.name === \"tableHeader\";\n }) !== undefined\n );\n}\n\n/**\n * Converts block content to inline content with hard breaks.\n * This is used when pasting into table cells which can only contain inline content.\n */\nfunction convertBlocksToInlineContent(\n fragment: Fragment,\n schema: Schema,\n): Fragment {\n const hardBreak = schema.nodes.hardBreak;\n let result = Fragment.empty;\n\n fragment.forEach((node) => {\n if (node.isTextblock && node.childCount > 0) {\n // Extract inline content from paragraphs, headings, etc.\n result = result.append(node.content);\n result = result.addToEnd(hardBreak.create());\n } else if (node.isText) {\n result = result.addToEnd(node);\n } else if (node.isBlock && node.childCount > 0) {\n // Recurse into block containers, blockGroups, etc.\n result = result.append(\n convertBlocksToInlineContent(node.content, schema),\n );\n result = result.addToEnd(hardBreak.create());\n }\n });\n\n // Remove trailing hard break\n if (result.lastChild?.type === hardBreak) {\n result = result.cut(0, result.size - 1);\n }\n\n return result;\n}\n\n// helper function to remove a child from a fragment\nfunction removeChild(node: Fragment, n: number) {\n const children: any[] = [];\n node.forEach((child, _, i) => {\n if (i !== n) {\n children.push(child);\n }\n });\n return Fragment.from(children);\n}\n\n/**\n * Wrap adjacent tableRow items in a table.\n *\n * This makes sure the content that we paste is always a table (and not a tableRow)\n * A table works better for the remaing paste handling logic, as it's actually a content node\n */\nexport function wrapTableRows(f: Fragment, schema: Schema) {\n const newItems: any[] = [];\n for (let i = 0; i < f.childCount; i++) {\n if (f.child(i).type.name === \"tableRow\") {\n if (\n newItems.length > 0 &&\n newItems[newItems.length - 1].type.name === \"table\"\n ) {\n // append to existing table\n const prevTable = newItems[newItems.length - 1];\n const newTable = prevTable.copy(prevTable.content.addToEnd(f.child(i)));\n newItems[newItems.length - 1] = newTable;\n } else {\n // create new table to wrap tableRow with\n const newTable = schema.nodes.table.createChecked(\n undefined,\n f.child(i),\n );\n newItems.push(newTable);\n }\n } else {\n newItems.push(f.child(i));\n }\n }\n f = Fragment.from(newItems);\n return f;\n}\n\n/**\n * fix for https://github.com/ProseMirror/prosemirror/issues/1430#issuecomment-1822570821\n *\n * This fix wraps pasted ProseMirror nodes in their own `blockContainer` nodes\n * in most cases. This is to ensure that ProseMirror inserts them as separate\n * blocks, which it sometimes doesn't do because it doesn't have enough context\n * about the hierarchy of the pasted nodes. The issue can be seen when pasting\n * e.g. an image or two consecutive paragraphs, where PM tries to nest the\n * pasted block(s) when it shouldn't.\n *\n * However, the fix is not applied in a few cases. See `shouldApplyFix` for\n * which cases are excluded.\n */\nexport function transformPasted(slice: Slice, view: EditorView) {\n let f = Fragment.from(slice.content);\n f = wrapTableRows(f, view.state.schema);\n\n const retyped = retypeLeadingParagraphForEmptyTarget(f, view, slice);\n if (retyped) {\n return retyped;\n }\n\n // `tableParagraph` only exists in schemas with the default table blocks. A\n // schema with a custom table implementation (e.g. container-block cells,\n // which hold real blocks and need no inline conversion) skips this branch.\n const tableParagraph = view.state.schema.nodes.tableParagraph;\n if (tableParagraph && isInTableCell(view)) {\n let hasTableContent = false;\n f.descendants((node) => {\n if (node.type.isInGroup(\"tableContent\")) {\n hasTableContent = true;\n }\n });\n if (\n !hasTableContent &&\n // is the content valid for a table paragraph?\n !tableParagraph.validContent(f)\n ) {\n // if not, convert the content to inline content\n return new Slice(\n convertBlocksToInlineContent(f, view.state.schema),\n 0,\n 0,\n );\n }\n }\n\n if (!shouldApplyFix(f, view)) {\n // Don't apply the fix.\n return new Slice(f, slice.openStart, slice.openEnd);\n }\n\n for (let i = 0; i < f.childCount; i++) {\n if (f.child(i).type.spec.group === \"blockContent\") {\n const content = [f.child(i)];\n\n // when there is a blockGroup with lists, it should be nested in the new blockcontainer\n // (if we remove this if-block, the nesting bug will be fixed, but lists won't be nested correctly)\n if (\n i + 1 < f.childCount &&\n f.child(i + 1).type.name === \"blockGroup\" // TODO\n ) {\n const nestedChild = f\n .child(i + 1)\n .child(0)\n .child(0);\n\n if (\n nestedChild.type.name === \"bulletListItem\" ||\n nestedChild.type.name === \"numberedListItem\" ||\n nestedChild.type.name === \"checkListItem\"\n ) {\n content.push(f.child(i + 1));\n f = removeChild(f, i + 1);\n }\n }\n const container = view.state.schema.nodes.blockContainer.createChecked(\n undefined,\n content,\n );\n f = f.replaceChild(i, container);\n }\n }\n return new Slice(f, slice.openStart, slice.openEnd);\n}\n\n/**\n * Pasting plain text into an empty inline-content block (e.g. an empty\n * bullet list item) would normally replace that block with a paragraph:\n * BlockNote's serializer always wraps content in\n * `blockGroup > blockContainer > <block>`, producing a closed slice that\n * ProseMirror inserts as a new block rather than splicing inline.\n *\n * To preserve the empty block's type, retype the leading paragraph in the\n * slice to match the target block. Subsequent blocks in the slice are left\n * alone and end up as siblings.\n *\n * Scoped to: empty, non-paragraph, inline-content target + paragraph leading\n * the slice. A non-empty target already gives ProseMirror a valid inline\n * insertion point so it splices correctly on its own; non-paragraph leading\n * blocks (heading, list item, …) carry semantic meaning the user picked, so\n * we keep the existing replace behavior.\n */\nfunction retypeLeadingParagraphForEmptyTarget(\n fragment: Fragment,\n view: EditorView,\n slice: Slice,\n): Slice | null {\n if (isInTableCell(view)) {\n return null;\n }\n\n // `transformPasted` is also called for drop events, where the slice will be\n // inserted at the drop position rather than the current selection. In that\n // case the selection-derived target is wrong, so bail out and let the\n // default behavior handle drops.\n if (view.dragging) {\n return null;\n }\n\n const blockInfo = getBlockInfoFromSelection(view.state);\n if (\n !blockInfo.hasContent ||\n blockInfo.content.node.type.name === \"paragraph\" ||\n blockInfo.contentKind !== \"inline\" ||\n !blockInfo.isContentEmpty\n ) {\n return null;\n }\n const target = blockInfo.content.node;\n\n const blockGroup = fragment.firstChild;\n const blockContainer = blockGroup?.firstChild;\n const leading = blockContainer?.firstChild;\n if (\n blockGroup?.type.name !== \"blockGroup\" ||\n blockContainer?.type.name !== \"blockContainer\" ||\n leading?.type.name !== \"paragraph\"\n ) {\n return null;\n }\n\n const retyped = target.type.create(target.attrs, leading.content);\n const newBlockContainer = blockContainer.copy(\n blockContainer.content.replaceChild(0, retyped),\n );\n const newBlockGroup = blockGroup.copy(\n blockGroup.content.replaceChild(0, newBlockContainer),\n );\n return new Slice(\n fragment.replaceChild(0, newBlockGroup),\n slice.openStart,\n slice.openEnd,\n );\n}\n\n/**\n * Used in `transformPasted` to check if the fix there should be applied, i.e.\n * if the pasted fragment should be wrapped in a `blockContainer` node. This\n * will explicitly tell ProseMirror to treat it as a separate block.\n */\nfunction shouldApplyFix(fragment: Fragment, view: EditorView) {\n const nodeHasSingleChild = fragment.childCount === 1;\n const nodeHasInlineContent =\n fragment.firstChild?.type.spec.content === \"inline*\";\n const nodeHasTableContent =\n fragment.firstChild?.type.spec.content === \"tableRow+\";\n\n if (nodeHasSingleChild) {\n if (nodeHasInlineContent) {\n // Case when we paste a single node with inline content, e.g. a paragraph\n // or heading. We want to insert the content in-line for better UX instead\n // of a separate block, so we return false.\n return false;\n }\n\n if (nodeHasTableContent) {\n // Not ideal that we check selection here, as `transformPasted` is called\n // for both paste and drop events. Drop events can potentially cause\n // issues as they don't always happen at the current selection.\n const blockInfo = getBlockInfoFromSelection(view.state);\n if (blockInfo.hasContent) {\n const selectedBlockHasTableContent = blockInfo.contentKind === \"table\";\n\n // Case for when we paste a single node with table content, i.e. a\n // table. Normally, we return true as we want to ensure the table is\n // inserted as a separate block. However, if the selection is in an\n // existing table, we return false, as we want the content of the pasted\n // table to be added to the existing one for better UX.\n return !selectedBlockHasTableContent;\n }\n }\n }\n\n return true;\n}\n","import {\n createDocument,\n EditorOptions,\n FocusPosition,\n getSchema,\n Editor as TiptapEditor,\n} from \"@tiptap/core\";\nimport { type Command, type Transaction } from \"@tiptap/pm/state\";\nimport { Node, Schema } from \"prosemirror-model\";\nimport type { BlockPlacement } from \"../api/getBlockInfoFromPos.js\";\nimport type { BlocksChanged } from \"../api/getBlocksChangedByTransaction.js\";\nimport { blockToNode } from \"../api/nodeConversions/blockToNode.js\";\nimport {\n Block,\n BlockNoteSchema,\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n PartialBlock,\n} from \"../blocks/index.js\";\nimport {\n BlockChangeExtension,\n DropCursorOptions,\n SideMenuOptions,\n} from \"../extensions/index.js\";\nimport { UniqueID } from \"../extensions/tiptap-extensions/UniqueID/UniqueID.js\";\nimport type { Dictionary } from \"../i18n/dictionary.js\";\nimport { en } from \"../i18n/locales/index.js\";\nimport type {\n BlockIdentifier,\n BlockNoteDOMAttributes,\n BlockSchema,\n BlockSpecs,\n CustomBlockNoteSchema,\n InlineContentSchema,\n InlineContentSpecs,\n PartialInlineContent,\n Styles,\n StyleSchema,\n StyleSpecs,\n} from \"../schema/index.js\";\nimport \"../style.css\";\nimport { mergeCSSClasses } from \"../util/browser.js\";\nimport { EventEmitter } from \"../util/EventEmitter.js\";\nimport type { NoInfer } from \"../util/typescript.js\";\nimport {\n Extension,\n ExtensionFactory,\n ExtensionFactoryInstance,\n} from \"./BlockNoteExtension.js\";\nimport type { TextCursorPosition } from \"./cursorPositionTypes.js\";\nimport {\n BlockManager,\n EditorFocusOptions,\n EventManager,\n ExportManager,\n ExtensionManager,\n SelectionManager,\n StateManager,\n StyleManager,\n} from \"./managers/index.js\";\nimport type { Selection } from \"./selectionTypes.js\";\nimport type {\n ExtensionSelection,\n ExtensionSelector,\n} from \"./managers/ExtensionManager/index.js\";\nimport { transformPasted } from \"./transformPasted.js\";\n\nexport type BlockCache<\n BSchema extends BlockSchema = any,\n ISchema extends InlineContentSchema = any,\n SSchema extends StyleSchema = any,\n> = WeakMap<Node, Block<BSchema, ISchema, SSchema>>;\n\nexport interface BlockNoteEditorOptions<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n> {\n /**\n * Whether changes to blocks (like indentation, creating lists, changing headings) should be animated or not. Defaults to `true`.\n *\n * @default true\n */\n animations?: boolean;\n\n /**\n * Whether the editor should be focused automatically when it's created.\n *\n * @default false\n */\n autofocus?: FocusPosition;\n\n /**\n * Use default BlockNote font and reset the styles of <p> <li> <h1> elements etc., that are used in BlockNote.\n *\n * @default true\n */\n defaultStyles?: boolean;\n\n /**\n * A dictionary object containing translations for the editor.\n *\n * See [Localization / i18n](https://www.blocknotejs.org/docs/advanced/localization) for more info.\n *\n * @remarks `Dictionary` is a type that contains all the translations for the editor.\n */\n dictionary?: Dictionary & Record<string, any>;\n\n /**\n * Disable internal extensions (based on keys / extension name).\n *\n * @note Advanced\n */\n disableExtensions?: string[];\n\n /**\n * An object containing attributes that should be added to HTML elements of the editor.\n *\n * See [Adding DOM Attributes](https://www.blocknotejs.org/docs/theming#adding-dom-attributes) for more info.\n *\n * @example { editor: { class: \"my-editor-class\" } }\n * @remarks `Record<string, Record<string, string>>`\n */\n domAttributes?: Partial<BlockNoteDOMAttributes>;\n\n /**\n * Options for configuring the drop cursor behavior when dragging and dropping blocks.\n * Allows customization of cursor appearance and drop position computation through hooks.\n * @remarks `DropCursorOptions`\n */\n dropCursor?: DropCursorOptions;\n\n /**\n * Options for the side menu, the menu with the drag handle and \"+\" button\n * next to the block under the mouse.\n * @remarks `SideMenuOptions`\n */\n sideMenu?: SideMenuOptions;\n\n /**\n * The content that should be in the editor when it's created, represented as an array of {@link PartialBlock} objects.\n *\n * See [Partial Blocks](https://www.blocknotejs.org/docs/editor-api/manipulating-blocks#partial-blocks) for more info.\n *\n * @remarks `PartialBlock[]`\n */\n initialContent?: PartialBlock<\n NoInfer<BSchema>,\n NoInfer<ISchema>,\n NoInfer<SSchema>\n >[];\n\n /**\n * Options for configuring how links behave in the editor.\n */\n links?: {\n /**\n * HTML attributes to add to rendered link elements.\n *\n * @default {}\n * @example { class: \"my-link-class\", target: \"_blank\" }\n */\n HTMLAttributes?: Record<string, any>;\n /**\n * Custom handler invoked when a link is clicked. If left `undefined`,\n * links are opened in a new window on click. If provided, the default\n * open-on-click behavior is disabled and this function is called instead.\n *\n * Return `false` to let ProseMirror continue handling the click event.\n * Returning `true` or nothing (the default) marks the event as handled.\n */\n onClick?: (\n event: MouseEvent,\n editor: BlockNoteEditor<any, any, any>,\n ) => boolean | void;\n /**\n * Callback that decides whether a given `href` is a valid link. Applied at\n * every gate where a link enters the document: HTML import, HTML export,\n * paste, and autolink. Useful for supporting additional URI schemes (e.g.\n * `vscode:`, `myapp:`) or tightening the default allowlist.\n *\n * Defaults to `isAllowedUri`, which allows\n * `http|https|ftp|ftps|mailto|tel|callto|sms|cid|xmpp`. Import\n * `isAllowedUri` from `@blocknote/core` to layer on top of the default.\n *\n * @example\n * ```ts\n * import { isAllowedUri } from \"@blocknote/core\";\n *\n * BlockNoteEditor.create({\n * links: {\n * isValidLink: (href) =>\n * isAllowedUri(href) || href.startsWith(\"myapp:\"),\n * },\n * });\n * ```\n */\n isValidLink?: (href: string) => boolean;\n };\n\n /**\n * @deprecated, provide placeholders via dictionary instead\n * @internal\n */\n placeholders?: Record<string, string | undefined>;\n\n /**\n * Custom paste handler that can be used to override the default paste behavior.\n *\n * See [Paste Handling](https://www.blocknotejs.org/docs/advanced/paste-handling) for more info.\n *\n * @remarks `PasteHandler`\n * @returns The function should return `true` if the paste event was handled, otherwise it should return `false` if it should be canceled or `undefined` if it should be handled by another handler.\n *\n * @example\n * ```ts\n * pasteHandler: ({ defaultPasteHandler }) => {\n * return defaultPasteHandler({ pasteBehavior: \"prefer-html\" });\n * }\n * ```\n */\n pasteHandler?: (context: {\n event: ClipboardEvent;\n editor: BlockNoteEditor<\n NoInfer<BSchema>,\n NoInfer<ISchema>,\n NoInfer<SSchema>\n >;\n /**\n * The default paste handler\n * @param context The context object\n * @returns Whether the paste event was handled or not\n */\n defaultPasteHandler: (context?: {\n /**\n * Whether to prioritize Markdown content in `text/plain` over `text/html` when pasting from the clipboard.\n * @default true\n */\n prioritizeMarkdownOverHTML?: boolean;\n /**\n * Whether to parse `text/plain` content from the clipboard as Markdown content.\n * @default true\n */\n plainTextAsMarkdown?: boolean;\n }) => boolean | undefined;\n }) => boolean | undefined;\n\n /**\n * Resolve a URL of a file block to one that can be displayed or downloaded. This can be used for creating authenticated URL or\n * implementing custom protocols / schemes\n * @returns The URL that's\n */\n resolveFileUrl?: (url: string) => Promise<string>;\n\n /**\n * The schema of the editor. The schema defines which Blocks, InlineContent, and Styles are available in the editor.\n *\n * See [Custom Schemas](https://www.blocknotejs.org/docs/custom-schemas) for more info.\n * @remarks `BlockNoteSchema`\n */\n schema: CustomBlockNoteSchema<BSchema, ISchema, SSchema>;\n\n /**\n * A flag indicating whether to set an HTML ID for every block\n *\n * When set to `true`, on each block an id attribute will be set with the block id\n * Otherwise, the HTML ID attribute will not be set.\n *\n * (note that the id is always set on the `data-id` attribute)\n */\n setIdAttribute?: boolean;\n\n /**\n * Determines behavior when pressing Cmd+A (Mac) or Ctrl+A (Windows/Linux).\n * - `\"block-first\"`: Selects the current block's content first, then the whole document on a subsequent press.\n * - `\"document\"`: Selects the whole document immediately.\n * Selecting the current block scrolls it into view; selecting the whole document preserves the scroll position.\n * @default \"block-first\"\n */\n selectAllBehavior?: \"block-first\" | \"document\";\n\n /**\n * Determines behavior when pressing Tab (or Shift-Tab) while multiple blocks are selected and a toolbar is open.\n * - `\"prefer-navigate-ui\"`: Changes focus to the toolbar. User must press Escape to close toolbar before indenting blocks. Better for keyboard accessibility.\n * - `\"prefer-indent\"`: Always indents selected blocks, regardless of toolbar state. Keyboard navigation of toolbars not possible.\n * @default \"prefer-navigate-ui\"\n */\n tabBehavior?: \"prefer-navigate-ui\" | \"prefer-indent\";\n\n /**\n * Allows enabling / disabling features of tables.\n *\n * See [Tables](https://www.blocknotejs.org/docs/editor-basics/document-structure#tables) for more info.\n *\n * @remarks `TableConfig`\n */\n tables?: {\n /**\n * Whether to allow splitting and merging cells within a table.\n *\n * @default false\n */\n splitCells?: boolean;\n /**\n * Whether to allow changing the background color of cells.\n *\n * @default false\n */\n cellBackgroundColor?: boolean;\n /**\n * Whether to allow changing the text color of cells.\n *\n * @default false\n */\n cellTextColor?: boolean;\n /**\n * Whether to allow changing cells into headers.\n *\n * @default false\n */\n headers?: boolean;\n };\n\n /**\n * When the editor document doesn't end in an empty paragraph block, this option causes the editor to render an element simulating one.\n * When clicked by the user, it gets turned into an actual block at the end of the document. This element is not shown when the option is `false`.\n *\n * @default true\n */\n trailingBlock?: boolean;\n\n /**\n * The `uploadFile` method is what the editor uses when files need to be uploaded (for example when selecting an image to upload).\n * This method should set when creating the editor as this is application-specific.\n *\n * `undefined` means the application doesn't support file uploads.\n *\n * @param file The file that should be uploaded.\n * @returns The URL of the uploaded file OR an object containing props that should be set on the file block (such as an id)\n * @remarks `(file: File) => Promise<UploadFileResult>`\n */\n uploadFile?: (\n file: File,\n blockId?: string,\n ) => Promise<string | Record<string, any>>;\n\n /**\n * additional tiptap options, undocumented\n * @internal\n */\n _tiptapOptions?: Partial<EditorOptions>;\n\n /**\n * Register extensions to the editor.\n *\n * See [Extensions](/docs/features/extensions) for more info.\n *\n * @remarks `ExtensionFactory[]`\n */\n extensions?: Array<ExtensionFactoryInstance>;\n}\n\nconst blockNoteTipTapOptions = {\n enableInputRules: true,\n enablePasteRules: true,\n enableCoreExtensions: false,\n};\n\nexport class BlockNoteEditor<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> extends EventEmitter<{\n create: void;\n /** Emitted when the editor is permanently destroyed, not on unmount. */\n destroy: void;\n}> {\n /**\n * The underlying prosemirror schema\n */\n public readonly pmSchema: Schema;\n\n public readonly _tiptapEditor: TiptapEditor & {\n contentComponent: any;\n isEditorContentInitialized?: boolean;\n };\n\n /**\n * Used by React to store a reference to an `ElementRenderer` helper utility to make sure we can render React elements\n * in the correct context (used by `ReactRenderUtil`)\n */\n public elementRenderer: ((node: any, container: HTMLElement) => void) | null =\n null;\n\n /**\n * Cache of all blocks. This makes sure we don't have to \"recompute\" blocks if underlying Prosemirror Nodes haven't changed.\n * This is especially useful when we want to keep track of the same block across multiple operations,\n * with this cache, blocks stay the same object reference (referential equality with ===).\n */\n public blockCache: BlockCache = new WeakMap();\n\n /**\n * The dictionary contains translations for the editor.\n */\n public readonly dictionary: Dictionary & Record<string, any>;\n\n /**\n * The schema of the editor. The schema defines which Blocks, InlineContent, and Styles are available in the editor.\n */\n public readonly schema: BlockNoteSchema<BSchema, ISchema, SSchema>;\n\n public readonly blockImplementations: BlockSpecs;\n public readonly inlineContentImplementations: InlineContentSpecs;\n public readonly styleImplementations: StyleSpecs;\n\n /**\n * The `uploadFile` method is what the editor uses when files need to be uploaded (for example when selecting an image to upload).\n * This method should set when creating the editor as this is application-specific.\n *\n * `undefined` means the application doesn't support file uploads.\n *\n * @param file The file that should be uploaded.\n * @returns The URL of the uploaded file OR an object containing props that should be set on the file block (such as an id)\n */\n public readonly uploadFile:\n | ((file: File, blockId?: string) => Promise<string | Record<string, any>>)\n | undefined;\n\n private onUploadStartCallbacks: ((blockId?: string) => void)[] = [];\n private onUploadEndCallbacks: ((blockId?: string) => void)[] = [];\n\n public readonly resolveFileUrl?: (url: string) => Promise<string>;\n /**\n * Editor settings\n */\n public readonly settings: {\n tables: {\n splitCells: boolean;\n cellBackgroundColor: boolean;\n cellTextColor: boolean;\n headers: boolean;\n };\n };\n public static create<\n Options extends Partial<BlockNoteEditorOptions<any, any, any>> | undefined,\n >(\n options?: Options,\n ): Options extends {\n schema: CustomBlockNoteSchema<infer BSchema, infer ISchema, infer SSchema>;\n }\n ? BlockNoteEditor<BSchema, ISchema, SSchema>\n : BlockNoteEditor<\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema\n > {\n return new BlockNoteEditor(options ?? {}) as any;\n }\n\n protected constructor(\n protected readonly options: Partial<\n BlockNoteEditorOptions<BSchema, ISchema, SSchema>\n >,\n ) {\n super();\n\n this.dictionary = options.dictionary || en;\n this.settings = {\n tables: {\n splitCells: options?.tables?.splitCells ?? false,\n cellBackgroundColor: options?.tables?.cellBackgroundColor ?? false,\n cellTextColor: options?.tables?.cellTextColor ?? false,\n headers: options?.tables?.headers ?? false,\n },\n };\n\n // apply defaults\n const newOptions = {\n defaultStyles: true,\n schema:\n options.schema ||\n (BlockNoteSchema.create() as unknown as CustomBlockNoteSchema<\n BSchema,\n ISchema,\n SSchema\n >),\n ...options,\n placeholders: {\n ...this.dictionary.placeholders,\n ...options.placeholders,\n },\n };\n\n this.schema = newOptions.schema;\n this.blockImplementations = newOptions.schema.blockSpecs;\n this.inlineContentImplementations = newOptions.schema.inlineContentSpecs;\n this.styleImplementations = newOptions.schema.styleSpecs;\n\n // TODO this should just be an extension\n if (newOptions.uploadFile) {\n const uploadFile = newOptions.uploadFile;\n this.uploadFile = async (file, blockId) => {\n this.onUploadStartCallbacks.forEach((callback) =>\n callback.apply(this, [blockId]),\n );\n try {\n return await uploadFile(file, blockId);\n } finally {\n this.onUploadEndCallbacks.forEach((callback) =>\n callback.apply(this, [blockId]),\n );\n }\n };\n }\n\n this.resolveFileUrl = newOptions.resolveFileUrl;\n\n this._eventManager = new EventManager(this as any);\n this._extensionManager = new ExtensionManager(this, newOptions);\n\n const tiptapExtensions = this._extensionManager.getTiptapExtensions();\n\n const tiptapOptions: EditorOptions = {\n ...blockNoteTipTapOptions,\n ...newOptions._tiptapOptions,\n // ReadOnlyExtension owns editability, including the initial application preference.\n editable: true,\n element: null,\n autofocus: newOptions.autofocus ?? false,\n extensions: tiptapExtensions,\n editorProps: {\n scrollMargin: { top: 72, bottom: 72, left: 0, right: 0 },\n ...newOptions._tiptapOptions?.editorProps,\n attributes: {\n // As of TipTap v2.5.0 the tabIndex is removed when the editor is not\n // editable, so you can't focus it. We want to revert this as we have\n // UI behaviour that relies on it.\n tabIndex: \"0\",\n // eslint-disable-next-line @typescript-eslint/no-misused-spread\n ...newOptions._tiptapOptions?.editorProps?.attributes,\n ...newOptions.domAttributes?.editor,\n class: mergeCSSClasses(\n \"bn-editor\",\n newOptions.defaultStyles ? \"bn-default-styles\" : \"\",\n newOptions.domAttributes?.editor?.class || \"\",\n ),\n },\n transformPasted,\n },\n } as any;\n\n try {\n const initialContent = newOptions.initialContent || [\n {\n type: \"paragraph\",\n id: UniqueID.options.generateID(),\n },\n ];\n\n if (!Array.isArray(initialContent) || initialContent.length === 0) {\n throw new Error(\n \"initialContent must be a non-empty array of blocks, received: \" +\n JSON.stringify(initialContent),\n );\n }\n const schema = getSchema(tiptapOptions.extensions!);\n // `blockToNode` (via `isPlainContentNodeType`) resolves the block schema\n // through `schema.cached.blockNoteEditor`, so stamp it on this throwaway\n // schema now — the real `pmSchema` is stamped separately below.\n schema.cached.blockNoteEditor = this;\n const pmNodes = initialContent.map((b) =>\n blockToNode(b, schema, this.schema.styleSchema).toJSON(),\n );\n const doc = createDocument(\n {\n type: \"doc\",\n content: [\n {\n type: \"blockGroup\",\n content: pmNodes,\n },\n ],\n },\n schema,\n tiptapOptions.parseOptions,\n );\n\n // `blockToNode` is lenient, and `createDocument` builds from JSON\n // without validating, so without this check the initial document is\n // never validated. A container below its `children.min` would reach\n // the editor and stay there, while the same blocks passed to\n // `insertBlocks` would have been rejected.\n doc.check();\n\n this._tiptapEditor = new TiptapEditor({\n ...tiptapOptions,\n content: doc.toJSON(),\n }) as any;\n this.pmSchema = this._tiptapEditor.schema;\n } catch (e) {\n throw new Error(\n \"Error creating document from blocks passed as `initialContent`\",\n { cause: e },\n );\n }\n\n this.pmSchema.cached.blockNoteEditor = this;\n\n this._tiptapEditor.on(\"mount\", () => {\n this.headless = false;\n });\n this._tiptapEditor.on(\"unmount\", () => {\n this.headless = true;\n });\n this._tiptapEditor.on(\"destroy\", () => {\n this.emit(\"destroy\");\n });\n\n // Initialize managers\n this._blockManager = new BlockManager(this as any);\n\n this._exportManager = new ExportManager(this as any);\n this._selectionManager = new SelectionManager(this as any);\n this._stateManager = new StateManager(this as any);\n this._styleManager = new StyleManager(this as any);\n\n this.emit(\"create\");\n }\n\n // Manager instances\n private readonly _blockManager: BlockManager<any, any, any>;\n private readonly _eventManager: EventManager<any, any, any>;\n private readonly _exportManager: ExportManager<any, any, any>;\n private readonly _extensionManager: ExtensionManager;\n private readonly _selectionManager: SelectionManager<any, any, any>;\n private readonly _stateManager: StateManager;\n private readonly _styleManager: StyleManager<any, any, any>;\n\n /**\n * BlockNote extensions that are added to the editor, keyed by the extension key\n */\n public get extensions() {\n return this._extensionManager.getExtensions();\n }\n\n /**\n * Execute a prosemirror command. This is mostly for backwards compatibility with older code.\n *\n * @note You should prefer the {@link transact} method when possible, as it will automatically handle the dispatching of the transaction and work across blocknote transactions.\n *\n * @example\n * ```ts\n * editor.exec((state, dispatch, view) => {\n * dispatch(state.tr.insertText(\"Hello, world!\"));\n * });\n * ```\n */\n public exec(command: Command) {\n return this._stateManager.exec(command);\n }\n\n /**\n * Check if a command can be executed. A command should return `false` if it is not valid in the current state.\n *\n * @example\n * ```ts\n * if (editor.canExec(command)) {\n * // show button\n * } else {\n * // hide button\n * }\n * ```\n */\n public canExec(command: Command): boolean {\n return this._stateManager.canExec(command);\n }\n\n /**\n * Execute a function within a \"blocknote transaction\".\n * All changes to the editor within the transaction will be grouped together, so that\n * we can dispatch them as a single operation (thus creating only a single undo step)\n *\n * @note There is no need to dispatch the transaction, as it will be automatically dispatched when the callback is complete.\n *\n * @example\n * ```ts\n * // All changes to the editor will be grouped together\n * editor.transact((tr) => {\n * tr.insertText(\"Hello, world!\");\n * // These two operations will be grouped together in a single undo step\n * editor.transact((tr) => {\n * tr.insertText(\"Hello, world!\");\n * });\n * });\n * ```\n */\n public transact<T>(\n callback: (\n /**\n * The current active transaction, this will automatically be dispatched to the editor when the callback is complete\n * If another `transact` call is made within the callback, it will be passed the same transaction as the parent call.\n */\n tr: Transaction,\n ) => T,\n ): T {\n return this._stateManager.transact(callback);\n }\n\n /**\n * Remove extension(s) and return the removed instance(s) for later registration.\n * Removed ProseMirror plugin state is not retained.\n */\n public unregisterExtension<const T extends ExtensionFactory>(\n extension: T,\n ): ReturnType<ReturnType<T>> | undefined;\n public unregisterExtension<const T extends Extension>(\n extension: T,\n ): T | undefined;\n public unregisterExtension(extensions: ExtensionSelector[]): Extension[];\n public unregisterExtension(\n extension: ExtensionSelector,\n ): Extension | undefined;\n public unregisterExtension(\n extension: ExtensionSelection,\n ): Extension | Extension[] | undefined;\n public unregisterExtension(\n extension: ExtensionSelection,\n ): Extension | Extension[] | undefined {\n return this._extensionManager.unregisterExtension(extension);\n }\n\n /**\n * Register extension(s) to the editor\n */\n public registerExtension: ExtensionManager[\"registerExtension\"] = (\n ...args: Parameters<ExtensionManager[\"registerExtension\"]>\n ) => this._extensionManager.registerExtension(...args) as any;\n\n /**\n * Atomically unregister old extensions and register new ones in a single\n * plugin update, avoiding re-entrant dispatch issues.\n */\n public replaceExtension: ExtensionManager[\"replaceExtension\"] = (\n ...args: Parameters<ExtensionManager[\"replaceExtension\"]>\n ) => this._extensionManager.replaceExtension(...args);\n\n /**\n * Get an extension from the editor\n */\n // Declared as an explicit intersection of the two `ExtensionManager`\n // overloads rather than `ExtensionManager[\"getExtension\"]`: indexed access on\n // an overloaded method collapses the signatures, which widened the factory\n // overload's `ReturnType<ReturnType<T>>` result to `any` (losing e.g. a\n // returned extension's `store` type).\n public getExtension: (<\n const Ext extends Extension | ExtensionFactory = Extension,\n >(\n extension: string,\n ) =>\n | (Ext extends Extension\n ? Ext\n : Ext extends ExtensionFactory\n ? ReturnType<ReturnType<Ext>>\n : never)\n | undefined) &\n (<const T extends ExtensionFactory>(\n extension: T,\n ) => ReturnType<ReturnType<T>> | undefined) = ((extension: any) =>\n this._extensionManager.getExtension(extension)) as any;\n\n /**\n * Mount the editor to a DOM element.\n *\n * @param element The DOM element to mount the editor's contenteditable into.\n *\n * Floating UI rendered next to the contenteditable counts as within the\n * editor already; UI rendered outside its DOM tree has to be registered with\n * {@link registerPortalElement} so {@link isWithinEditor} recognizes it.\n *\n * @warning Not needed to call manually when using React, use BlockNoteView to take care of mounting\n */\n public mount = (element: HTMLElement) => {\n this._tiptapEditor.mount({ mount: element });\n // TipTap's ReactRenderer uses this flag to render new node/mark views\n // synchronously. Otherwise, inserting React-styled text can place the\n // caret before it because its contentDOM is not attached yet.\n this._tiptapEditor.isEditorContentInitialized = true;\n };\n\n /**\n * Unmount the editor from the DOM element it is bound to\n */\n public unmount = () => {\n this._tiptapEditor.isEditorContentInitialized = false;\n this._tiptapEditor.unmount();\n };\n\n /**\n * Get the underlying prosemirror state\n * @note Prefer using `editor.transact` to read the current editor state, as that will ensure the state is up to date\n * @see https://prosemirror.net/docs/ref/#state.EditorState\n */\n public get prosemirrorState() {\n return this._stateManager.prosemirrorState;\n }\n\n /**\n * Get the underlying prosemirror view\n * @see https://prosemirror.net/docs/ref/#view.EditorView\n */\n public get prosemirrorView() {\n return this._stateManager.prosemirrorView;\n }\n\n public get domElement() {\n if (this.headless) {\n return undefined;\n }\n return this.prosemirrorView?.dom as HTMLDivElement | undefined;\n }\n\n // Portal elements registered by the view layer, with reference counts so\n // several UI elements can share one (e.g. multiple popovers portalling into\n // the same custom element).\n private _portalElements = new Map<HTMLElement, number>();\n\n /**\n * Registers an element as a portal element for this editor's floating UI, so\n * {@link isWithinEditor} treats its contents as part of the editor. The view\n * layer calls this for each portal element it designates (see\n * `PortalElementOverride` in `@blocknote/react`) — without it, UI portalled outside\n * the editor's DOM tree would be considered outside the editor.\n * Registrations are reference-counted; release with\n * {@link unregisterPortalElement}.\n */\n public registerPortalElement = (element: HTMLElement) => {\n this._portalElements.set(\n element,\n (this._portalElements.get(element) ?? 0) + 1,\n );\n };\n\n /**\n * Releases a registration made with {@link registerPortalElement}. The element\n * stops counting as part of the editor once every registration for it has\n * been released.\n */\n public unregisterPortalElement = (element: HTMLElement) => {\n const count = this._portalElements.get(element);\n if (count === undefined) {\n return;\n }\n\n if (count <= 1) {\n this._portalElements.delete(element);\n } else {\n this._portalElements.set(element, count - 1);\n }\n };\n\n /**\n * Checks whether a DOM element belongs to this editor — inside the editor's\n * DOM tree, or inside any portal element registered via\n * {@link registerPortalElement} (used for floating UI elements like menus and\n * toolbars, which may portal outside the editor's DOM tree).\n *\n * The DOM-tree check starts at the content area's *parent*, so that UI the\n * host app renders as `BlockNoteView` children counts too — React places\n * those beside the content (see the \"Static Formatting Toolbar\" example).\n * The boundary is whatever the element passed to `editor.mount()` has as\n * its parent: `BlockNoteView` always provides a wrapper; mounting bare into\n * `<body>`, as the vanilla-JS docs do, makes the whole page count as within\n * the editor.\n */\n public isWithinEditor = (element: Element): boolean => {\n if (this.domElement?.parentElement?.contains(element)) {\n return true;\n }\n\n for (const portalElement of this._portalElements.keys()) {\n if (portalElement.contains(element)) {\n return true;\n }\n }\n\n return false;\n };\n\n public isFocused(options?: EditorFocusOptions) {\n if (this.headless) {\n return false;\n }\n const contentFocused = this.prosemirrorView?.hasFocus() || false;\n if (!options?.includeEditorUI) {\n return contentFocused;\n }\n const active =\n typeof document !== \"undefined\" ? document.activeElement : null;\n return contentFocused || (!!active && this.isWithinEditor(active));\n }\n\n public headless = true;\n\n /**\n * Focus on the editor\n */\n public focus() {\n if (this.headless) {\n return;\n }\n this.prosemirrorView.focus();\n }\n\n /**\n * Blur the editor\n */\n public blur() {\n if (this.headless) {\n return;\n }\n this.domElement?.blur();\n }\n\n // TODO move to extension\n public onUploadStart(callback: (blockId?: string) => void) {\n this.onUploadStartCallbacks.push(callback);\n\n return () => {\n const index = this.onUploadStartCallbacks.indexOf(callback);\n if (index > -1) {\n this.onUploadStartCallbacks.splice(index, 1);\n }\n };\n }\n\n public onUploadEnd(callback: (blockId?: string) => void) {\n this.onUploadEndCallbacks.push(callback);\n\n return () => {\n const index = this.onUploadEndCallbacks.indexOf(callback);\n if (index > -1) {\n this.onUploadEndCallbacks.splice(index, 1);\n }\n };\n }\n\n /**\n * @deprecated, use `editor.document` instead\n */\n public get topLevelBlocks(): Block<BSchema, ISchema, SSchema>[] {\n return this.document;\n }\n\n /**\n * Gets a snapshot of all top-level (non-nested) blocks in the editor.\n * @returns A snapshot of all top-level (non-nested) blocks in the editor.\n */\n public get document(): Block<BSchema, ISchema, SSchema>[] {\n return this._blockManager.document;\n }\n\n /**\n * Gets a snapshot of an existing block from the editor.\n * @param blockIdentifier The identifier of an existing block that should be\n * retrieved.\n * @returns The block that matches the identifier, or `undefined` if no\n * matching block was found.\n */\n public getBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this._blockManager.getBlock(blockIdentifier);\n }\n\n /**\n * Gets a snapshot of the previous sibling of an existing block from the\n * editor.\n * @param blockIdentifier The identifier of an existing block for which the\n * previous sibling should be retrieved.\n * @returns The previous sibling of the block that matches the identifier.\n * `undefined` if no matching block was found, or it's the first child/block\n * in the document.\n */\n public getPrevBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this._blockManager.getPrevBlock(blockIdentifier);\n }\n\n /**\n * Gets a snapshot of the next sibling of an existing block from the editor.\n * @param blockIdentifier The identifier of an existing block for which the\n * next sibling should be retrieved.\n * @returns The next sibling of the block that matches the identifier.\n * `undefined` if no matching block was found, or it's the last child/block in\n * the document.\n */\n public getNextBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this._blockManager.getNextBlock(blockIdentifier);\n }\n\n /**\n * Gets a snapshot of the parent of an existing block from the editor.\n * @param blockIdentifier The identifier of an existing block for which the\n * parent should be retrieved.\n * @returns The parent of the block that matches the identifier. `undefined`\n * if no matching block was found, or the block isn't nested.\n */\n public getParentBlock(\n blockIdentifier: BlockIdentifier,\n ): Block<BSchema, ISchema, SSchema> | undefined {\n return this._blockManager.getParentBlock(blockIdentifier);\n }\n\n /**\n * Traverses all blocks in the editor depth-first, and executes a callback for each.\n * @param callback The callback to execute for each block. Returning `false` stops the traversal.\n * @param reverse Whether the blocks should be traversed in reverse order.\n */\n public forEachBlock(\n callback: (block: Block<BSchema, ISchema, SSchema>) => boolean,\n reverse = false,\n ): void {\n this._blockManager.forEachBlock(callback, reverse);\n }\n\n /**\n * Executes a callback whenever the editor's contents change.\n * @param callback The callback to execute.\n *\n * @deprecated use {@link BlockNoteEditor.onChange} instead\n */\n public onEditorContentChange(callback: () => void) {\n this._tiptapEditor.on(\"update\", callback);\n }\n\n /**\n * Executes a callback whenever the editor's selection changes.\n * @param callback The callback to execute.\n *\n * @deprecated use `onSelectionChange` instead\n */\n public onEditorSelectionChange(callback: () => void) {\n this._tiptapEditor.on(\"selectionUpdate\", callback);\n }\n\n /**\n * Executes a callback before any change is applied to the editor, allowing you to cancel the change.\n * @param callback The callback to execute.\n * @returns A function to remove the callback.\n */\n public onBeforeChange(\n callback: (context: {\n getChanges: () => BlocksChanged<BSchema, ISchema, SSchema>;\n tr: Transaction;\n }) => boolean | void,\n ): () => void {\n return this._extensionManager\n .getExtension(BlockChangeExtension)!\n .subscribe(callback);\n }\n\n /**\n * Gets a snapshot of the current text cursor position.\n * @returns A snapshot of the current text cursor position.\n */\n public getTextCursorPosition(): TextCursorPosition<\n BSchema,\n ISchema,\n SSchema\n > {\n return this._selectionManager.getTextCursorPosition();\n }\n\n /**\n * Sets the text cursor position to the start or end of an existing block. Throws an error if the target block could\n * not be found.\n * @param targetBlock The identifier of an existing block that the text cursor should be moved to.\n * @param placement Whether the text cursor should be placed at the start or end of the block.\n */\n public setTextCursorPosition(\n targetBlock: BlockIdentifier,\n placement: \"start\" | \"end\" = \"start\",\n ) {\n return this._selectionManager.setTextCursorPosition(targetBlock, placement);\n }\n\n /**\n * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)\n * that the selection spans across.\n *\n * If the selection starts / ends halfway through a block, the returned data will contain the entire block.\n */\n public getSelection(): Selection<BSchema, ISchema, SSchema> | undefined {\n return this._selectionManager.getSelection();\n }\n\n /**\n * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)\n * that the selection spans across.\n *\n * If the selection starts / ends halfway through a block, the returned block will be\n * only the part of the block that is included in the selection.\n */\n public getSelectionCutBlocks(expandToWords = false) {\n return this._selectionManager.getSelectionCutBlocks(expandToWords);\n }\n\n /**\n * Sets the selection to a range of blocks.\n * @param startBlock The identifier of the block that should be the start of the selection.\n * @param endBlock The identifier of the block that should be the end of the selection.\n */\n public setSelection(startBlock: BlockIdentifier, endBlock: BlockIdentifier) {\n return this._selectionManager.setSelection(startBlock, endBlock);\n }\n\n /**\n * Checks if the editor is currently editable, or if it's locked.\n * @returns True if the editor is editable, false otherwise.\n */\n public get isEditable(): boolean {\n return this._stateManager.isEditable;\n }\n\n /**\n * Sets the application's editable preference. Feature read-only restrictions\n * still apply when set to true.\n * Plugins can temporarily prevent editing without changing this setting.\n * The getter reports whether editing is currently allowed by both.\n * @param editable True to make the editor editable, or false to lock it.\n */\n public set isEditable(editable: boolean) {\n this._stateManager.isEditable = editable;\n }\n\n /**\n * Inserts new blocks into the editor. If a block's `id` is undefined, BlockNote generates one automatically. Throws an\n * error if the reference block could not be found.\n * @param blocksToInsert An array of partial blocks that should be inserted.\n * @param referenceBlock An identifier for an existing block, at which the new blocks should be inserted.\n * @param placement Where the blocks go relative to the `referenceBlock`: as its previous (`\"before\"`) or next\n * (`\"after\"`) sibling, or nested inside it as its first (`\"first-child\"`) or last (`\"last-child\"`) children. Throws\n * an error if the `referenceBlock` (or its parent, for `\"before\"`/`\"after\"`) doesn't accept the blocks there.\n */\n public insertBlocks(\n blocksToInsert: PartialBlock<BSchema, ISchema, SSchema>[],\n referenceBlock: BlockIdentifier,\n placement: BlockPlacement = \"before\",\n ) {\n return this._blockManager.insertBlocks(\n blocksToInsert,\n referenceBlock,\n placement,\n );\n }\n\n /**\n * Updates an existing block in the editor. Since updatedBlock is a PartialBlock object, some fields might not be\n * defined. These undefined fields are kept as-is from the existing block. Throws an error if the block to update could\n * not be found.\n * @param blockToUpdate The block that should be updated.\n * @param update A partial block which defines how the existing block should be changed.\n */\n public updateBlock(\n blockToUpdate: BlockIdentifier,\n update: PartialBlock<BSchema, ISchema, SSchema>,\n ) {\n return this._blockManager.updateBlock(blockToUpdate, update);\n }\n\n /**\n * Removes existing blocks from the editor. Throws an error if any of the blocks could not be found.\n * @param blocksToRemove An array of identifiers for existing blocks that should be removed.\n */\n public removeBlocks(blocksToRemove: BlockIdentifier[]) {\n return this._blockManager.removeBlocks(blocksToRemove);\n }\n\n /**\n * Replaces existing blocks in the editor with new blocks. If the blocks that should be removed are not adjacent or\n * are at different nesting levels, `blocksToInsert` will be inserted at the position of the first block in\n * `blocksToRemove`. Throws an error if any of the blocks to remove could not be found.\n * @param blocksToRemove An array of blocks that should be replaced.\n * @param blocksToInsert An array of partial blocks to replace the old ones with.\n */\n public replaceBlocks(\n blocksToRemove: BlockIdentifier[],\n blocksToInsert: PartialBlock<BSchema, ISchema, SSchema>[],\n ) {\n return this._blockManager.replaceBlocks(blocksToRemove, blocksToInsert);\n }\n\n /**\n * Undo the last action.\n */\n public undo(): boolean {\n return this._stateManager.undo();\n }\n\n /**\n * Redo the last action.\n */\n public redo(): boolean {\n return this._stateManager.redo();\n }\n\n /**\n * Insert a piece of content at the current cursor position.\n *\n * @param content can be a string, or array of partial inline content elements\n */\n public insertInlineContent(\n content: PartialInlineContent<ISchema, SSchema>,\n { updateSelection = false }: { updateSelection?: boolean } = {},\n ) {\n this._styleManager.insertInlineContent(content, { updateSelection });\n }\n\n /**\n * Gets the active text styles at the text cursor position or at the end of the current selection if it's active.\n */\n public getActiveStyles(): Styles<SSchema> {\n return this._styleManager.getActiveStyles();\n }\n\n /**\n * Adds styles to the currently selected content.\n * @param styles The styles to add.\n */\n public addStyles(styles: Styles<SSchema>) {\n this._styleManager.addStyles(styles);\n }\n\n /**\n * Removes styles from the currently selected content.\n * @param styles The styles to remove.\n */\n public removeStyles(styles: Styles<SSchema>) {\n this._styleManager.removeStyles(styles);\n }\n\n /**\n * Toggles styles on the currently selected content.\n * @param styles The styles to toggle.\n */\n public toggleStyles(styles: Styles<SSchema>) {\n this._styleManager.toggleStyles(styles);\n }\n\n /**\n * Gets the currently selected text.\n */\n public getSelectedText() {\n return this._styleManager.getSelectedText();\n }\n\n /**\n * Gets the URL of the link the current selection starts in, or `undefined`\n * if it does not start in one.\n */\n public getSelectedLinkUrl() {\n return this._styleManager.getSelectedLinkUrl();\n }\n\n /**\n * Creates a new link to replace the selected content.\n * @param url The link URL.\n * @param text The text to display the link with.\n */\n public createLink(url: string, text?: string) {\n this._styleManager.createLink(url, text);\n }\n\n /**\n * Find the link mark and its range at the given position.\n * Returns undefined if there is no link at that position.\n */\n public getLinkMarkAtPos(pos: number) {\n return this._styleManager.getLinkMarkAtPos(pos);\n }\n\n /**\n * Updates the link at the given position with a new URL and text.\n * @param url The new link URL.\n * @param text The new text to display.\n * @param position The position inside the link to edit. Defaults to the current selection anchor.\n */\n public editLink(url: string, text: string, position?: number) {\n this._styleManager.editLink(url, text, position);\n }\n\n /**\n * Removes the link at the given position, keeping the text.\n * @param position The position inside the link to remove. Defaults to the current selection anchor.\n */\n public deleteLink(position?: number) {\n this._styleManager.deleteLink(position);\n }\n\n /**\n * Checks if the block containing the text cursor can be nested.\n */\n public canNestBlock() {\n return this._blockManager.canNestBlock();\n }\n\n /**\n * Nests the block containing the text cursor into the block above it.\n */\n public nestBlock() {\n this._blockManager.nestBlock();\n }\n\n /**\n * Checks if the block containing the text cursor is nested.\n */\n public canUnnestBlock() {\n return this._blockManager.canUnnestBlock();\n }\n\n /**\n * Lifts the block containing the text cursor out of its parent.\n */\n public unnestBlock() {\n this._blockManager.unnestBlock();\n }\n\n /**\n * Moves the selected blocks up. If the previous block has children, moves\n * them to the end of its children. If there is no previous block, but the\n * current blocks share a common parent, moves them out of & before it. If a\n * `blockIdentifier` is provided, that block is moved instead of the\n * selection, and the selection is left unchanged.\n */\n public moveBlocksUp(blockIdentifier?: BlockIdentifier) {\n return this._blockManager.moveBlocksUp(blockIdentifier);\n }\n\n /**\n * Moves the selected blocks down. If the next block has children, moves\n * them to the start of its children. If there is no next block, but the\n * current blocks share a common parent, moves them out of & after it. If a\n * `blockIdentifier` is provided, that block is moved instead of the\n * selection, and the selection is left unchanged.\n */\n public moveBlocksDown(blockIdentifier?: BlockIdentifier) {\n return this._blockManager.moveBlocksDown(blockIdentifier);\n }\n\n /**\n * Exports blocks into a simplified HTML string. To better conform to HTML standards, children of blocks which aren't list\n * items are un-nested in the output HTML.\n *\n * @param blocks An array of blocks that should be serialized into HTML.\n * @returns The blocks, serialized as an HTML string.\n */\n public blocksToHTMLLossy(\n blocks: PartialBlock<BSchema, ISchema, SSchema>[] = this.document,\n ): string {\n return this._exportManager.blocksToHTMLLossy(blocks);\n }\n\n /**\n * Serializes blocks into an HTML string in the format that would normally be rendered by the editor.\n *\n * Use this method if you want to server-side render HTML (for example, a blog post that has been edited in BlockNote)\n * and serve it to users without loading the editor on the client (i.e.: displaying the blog post)\n *\n * @param blocks An array of blocks that should be serialized into HTML.\n * @returns The blocks, serialized as an HTML string.\n */\n public blocksToFullHTML(\n blocks: PartialBlock<BSchema, ISchema, SSchema>[] = this.document,\n ): string {\n return this._exportManager.blocksToFullHTML(blocks);\n }\n\n /**\n * Parses blocks from an HTML string. Tries to create `Block` objects out of any HTML block-level elements, and\n * `InlineNode` objects from any HTML inline elements, though not all element types are recognized. If BlockNote\n * doesn't recognize an HTML element's tag, it will parse it as a paragraph or plain text.\n * @param html The HTML string to parse blocks from.\n * @returns The blocks parsed from the HTML string.\n */\n public tryParseHTMLToBlocks(\n html: string,\n ): Block<BSchema, ISchema, SSchema>[] {\n return this._exportManager.tryParseHTMLToBlocks(html);\n }\n\n /**\n * Serializes blocks into a Markdown string. The output is simplified as Markdown does not support all features of\n * BlockNote - children of blocks which aren't list items are un-nested and certain styles are removed.\n * @param blocks An array of blocks that should be serialized into Markdown.\n * @returns The blocks, serialized as a Markdown string.\n */\n public blocksToMarkdownLossy(\n blocks: PartialBlock<BSchema, ISchema, SSchema>[] = this.document,\n ): string {\n return this._exportManager.blocksToMarkdownLossy(blocks);\n }\n\n /**\n * Creates a list of blocks from a Markdown string. Tries to create `Block` and `InlineNode` objects based on\n * Markdown syntax, though not all symbols are recognized. If BlockNote doesn't recognize a symbol, it will parse it\n * as text.\n * @param markdown The Markdown string to parse blocks from.\n * @returns The blocks parsed from the Markdown string.\n */\n public tryParseMarkdownToBlocks(\n markdown: string,\n ): Block<BSchema, ISchema, SSchema>[] {\n return this._exportManager.tryParseMarkdownToBlocks(markdown);\n }\n\n /**\n * A callback function that runs whenever the editor's contents change.\n *\n * @param callback The callback to execute.\n * @returns A function to remove the callback.\n */\n public onChange(\n callback: (\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n context: {\n /**\n * Returns the blocks that were inserted, updated, or deleted by the change that occurred.\n */\n getChanges(): BlocksChanged<BSchema, ISchema, SSchema>;\n },\n ) => void,\n /**\n * If true, the callback will be triggered when the changes are caused by a remote user\n * @default true\n */\n includeUpdatesFromRemote?: boolean,\n ) {\n return this._eventManager.onChange(callback, includeUpdatesFromRemote);\n }\n\n /**\n * A callback function that runs whenever the text cursor position or selection changes.\n *\n * @param callback The callback to execute.\n * @returns A function to remove the callback.\n */\n public onSelectionChange(\n callback: (editor: BlockNoteEditor<BSchema, ISchema, SSchema>) => void,\n includeSelectionChangedByRemote?: boolean,\n ) {\n return this._eventManager.onSelectionChange(\n callback,\n includeSelectionChangedByRemote,\n );\n }\n\n /**\n * A callback function that runs when focus changes. By default, this reports\n * when the editor's content area gains or loses DOM focus.\n *\n * Note that `focused: false` only means the content area itself blurred —\n * focus may have moved into the editor's own UI (e.g. a toolbar\n * popover's input). Pass `includeEditorUI: true` to report changes to\n * combined content and UI focus, allowing focus handoffs to settle.\n *\n * @param callback The callback to execute.\n * @returns A function to remove the callback.\n */\n public onFocusChange(\n callback: (\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n context: { focused: boolean; event: FocusEvent },\n ) => void,\n options?: EditorFocusOptions,\n ) {\n return this._eventManager.onFocusChange(callback, options);\n }\n\n /**\n * A callback function that runs when the editor has been mounted.\n *\n * This can be useful for plugins to initialize themselves after the editor has been mounted.\n *\n * @param callback The callback to execute.\n * @returns A function to remove the callback.\n */\n public onMount(\n callback: (ctx: {\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>;\n }) => void,\n ) {\n return this._eventManager.onMount(callback);\n }\n\n /**\n * A callback function that runs when the editor has been unmounted.\n *\n * This can be useful for plugins to clean up themselves after the editor has been unmounted.\n *\n * @param callback The callback to execute.\n * @returns A function to remove the callback.\n */\n public onUnmount(\n callback: (ctx: {\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>;\n }) => void,\n ) {\n return this._eventManager.onUnmount(callback);\n }\n\n /**\n * Gets the bounding box of the current selection.\n * @returns The bounding box of the current selection.\n */\n public getSelectionBoundingBox() {\n return this._selectionManager.getSelectionBoundingBox();\n }\n\n public get isEmpty() {\n const doc = this.document;\n // Note: only works for paragraphs as default blocks (but for now this is default in blocknote)\n // checking prosemirror directly might be faster\n return (\n doc.length === 0 ||\n (doc.length === 1 &&\n doc[0].type === \"paragraph\" &&\n (doc[0].content as any).length === 0)\n );\n }\n\n /**\n * Paste HTML into the editor. Defaults to converting HTML to BlockNote HTML.\n * @param html The HTML to paste.\n * @param raw Whether to paste the HTML as is, or to convert it to BlockNote HTML.\n */\n public pasteHTML(html: string, raw = false) {\n this._exportManager.pasteHTML(html, raw);\n }\n\n /**\n * Paste text into the editor. Defaults to interpreting text as markdown.\n * @param text The text to paste.\n */\n public pasteText(text: string) {\n return this._exportManager.pasteText(text);\n }\n\n /**\n * Paste markdown into the editor.\n * @param markdown The markdown to paste.\n */\n public pasteMarkdown(markdown: string) {\n return this._exportManager.pasteMarkdown(markdown);\n }\n}\n","import { BlockNoteSchema } from \"../blocks/BlockNoteSchema.js\";\nimport { COLORS_DEFAULT } from \"../editor/defaultColors.js\";\nimport type { Dictionary } from \"../i18n/dictionary.js\";\nimport { en } from \"../i18n/locales/index.js\";\nimport {\n BlockNoDefaults,\n BlockSchema,\n InlineContent,\n InlineContentSchema,\n StyleSchema,\n StyledText,\n Styles,\n} from \"../schema/index.js\";\n\nimport type {\n BlockMapping,\n InlineContentMapping,\n StyleMapping,\n} from \"./mapping.js\";\n\nexport type ExporterOptions = {\n /**\n * A function that can be used to resolve files, images, etc.\n * Exporters might need the binary contents of files like images,\n * which might not always be available from the same origin as the main page.\n * You can use this option to proxy requests through a server you control\n * to avoid cross-origin (CORS) issues.\n *\n * @default uses a BlockNote hosted proxy (https://corsproxy.api.blocknotejs.org/)\n * @param url - The URL of the file to resolve\n * @returns A Promise that resolves to a string (the URL to use instead of the original)\n * or a Blob (you can return the Blob directly if you have already fetched it)\n */\n resolveFileUrl?: (url: string) => Promise<string | Blob>;\n /**\n * Colors to use for background of blocks, font colors, and highlight colors\n */\n colors: typeof COLORS_DEFAULT;\n /**\n * The strings an exporter renders into the produced document (file link\n * texts, error placeholders). Accepts a locale from\n * `@blocknote/core/locales` or an editor dictionary; block packages that\n * ship their own exporter strings (e.g. math, diagram) read their sections\n * from this same object, exactly as they do from an editor dictionary.\n *\n * @default the English strings\n */\n dictionary?: { exporter: Dictionary[\"exporter\"] } & {\n // Block packages read their own sections (e.g. `math`, `diagram`) from\n // the same object; their types live with those packages.\n [blockDictionary: string]: unknown;\n };\n};\nexport abstract class Exporter<\n B extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n RB,\n RI,\n RS,\n TS,\n> {\n public constructor(\n protected readonly schema: BlockNoteSchema<B, I, S>,\n protected readonly mappings: {\n blockMapping: BlockMapping<B, I, S, RB, RI>;\n inlineContentMapping: InlineContentMapping<I, S, RI, TS>;\n styleMapping: StyleMapping<S, RS>;\n },\n public readonly options: ExporterOptions,\n ) {}\n\n /**\n * Whether the block's mapping places its children itself (a `{ withChildren }`\n * mapping). Otherwise the exporter places them after the block.\n */\n public placesChildren(block: { type: string }): boolean {\n const mapping = this.mappings.blockMapping[block.type];\n return typeof mapping === \"object\" && mapping !== null;\n }\n\n /**\n * The strings this exporter renders into the produced document - the\n * `exporter` section of the configured dictionary (the `dictionary`\n * option of {@link ExporterOptions}), or the English defaults.\n */\n public get dictionary(): Dictionary[\"exporter\"] {\n return this.options.dictionary?.exporter ?? en.exporter;\n }\n\n public async resolveFile(url: string) {\n if (!this.options?.resolveFileUrl) {\n return this.fetchBlob(url);\n }\n const ret = await this.options.resolveFileUrl(url);\n if (ret instanceof Blob) {\n return ret;\n }\n return this.fetchBlob(ret);\n }\n\n /**\n * Fetch a URL as a Blob, throwing a clear error on a non-OK response. Without\n * this an error page (404 / rate-limit / proxy failure) would be returned as\n * the file's bytes and silently embedded as a corrupt image. An unreachable\n * file is an environment failure, not expected input, so it fails the export\n * loudly (see the error-handling conventions in AGENTS.md) rather than\n * degrading the document silently.\n */\n private async fetchBlob(url: string): Promise<Blob> {\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(\n `Failed to fetch file \"${url}\": ${res.status} ${res.statusText}`,\n );\n }\n return res.blob();\n }\n\n public mapStyles(styles: Styles<S>) {\n const stylesArray = Object.entries(styles).map(([key, value]) => {\n const mapping = this.mappings.styleMapping[key];\n if (!mapping) {\n throw new Error(\n `Exporter is missing a style mapping for style \"${key}\". If this style comes from a separate package, spread that package's exporter mappings into your styleMapping.`,\n );\n }\n const mappedStyle = mapping(value, this);\n return mappedStyle;\n });\n return stylesArray;\n }\n\n public mapInlineContent(inlineContent: InlineContent<I, S>) {\n const mapping = this.mappings.inlineContentMapping[inlineContent.type];\n if (!mapping) {\n throw new Error(\n `Exporter is missing an inline content mapping for inline content type \"${inlineContent.type}\". If this inline content comes from a separate package, spread that package's exporter mappings into your inlineContentMapping.`,\n );\n }\n return mapping(inlineContent, this);\n }\n\n public transformInlineContent(inlineContentArray: InlineContent<I, S>[]) {\n return inlineContentArray.map((ic) => this.mapInlineContent(ic));\n }\n\n public abstract transformStyledText(styledText: StyledText<S>): TS;\n\n public async mapBlock(\n block: BlockNoDefaults<B, I, S>,\n nestingLevel: number,\n numberedListIndex: number,\n children?: Array<Awaited<RB>>,\n ) {\n const mapping = this.mappings.blockMapping[block.type];\n if (!mapping) {\n throw new Error(\n `Exporter is missing a block mapping for block type \"${block.type}\". If this block comes from a separate package, spread that package's exporter mappings into your blockMapping.`,\n );\n }\n if (typeof mapping === \"function\") {\n // A layout block's children belong inside it, which only a\n // `{ withChildren }` mapping can do. Fail early rather than export them\n // after it.\n // TODO: remove once the `BlockMapping` type requires `{ withChildren }`\n // for layout blocks (`createBlockSpec` doesn't keep `layoutOnly: true` in the\n // config type yet).\n const spec = this.schema.blockSpecs[block.type];\n if (spec !== undefined && spec.config.layoutOnly === true) {\n throw new Error(\n `The mapping for layout block type \"${block.type}\" must be a \\`{ withChildren }\\` mapping, which places the block's children.`,\n );\n }\n return mapping(block, this, nestingLevel, numberedListIndex);\n }\n return mapping.withChildren(\n block,\n this,\n nestingLevel,\n numberedListIndex,\n children ?? [],\n );\n }\n}\n","/**\n * An image generated during export (e.g. a rendered formula or diagram): the\n * encoded image bytes plus the dimensions to display it at.\n *\n * The bytes (rather than e.g. a data URL string or a `Blob`) are the source\n * of truth: they carry no encoding ambiguity, work in every environment, and\n * are readable synchronously - each output format converts them at its own\n * boundary (data URL for HTML-based targets, raw bytes for DOCX, base64 for\n * email attachments).\n */\nexport type ExportImage = {\n /** MIME type of `data`, e.g. `\"image/png\"` or `\"image/svg+xml\"`. */\n mimeType: string;\n /** The encoded image bytes. */\n data: Uint8Array;\n /**\n * Dimensions to display the image at, in the target format's units (CSS\n * pixels, points, ...). For raster images, `data`'s own pixel dimensions\n * may be larger - images are often rendered at 2-4x for sharpness.\n */\n width: number;\n height: number;\n};\n\n/**\n * Encodes bytes as base64. This papers over a platform gap: until\n * `Uint8Array.prototype.toBase64()` (ES2026) is available in every runtime\n * BlockNote supports, the only universal built-in is `btoa`, which takes\n * binary *strings*. Uses `toBase64` when the runtime has it.\n */\nexport function bytesToBase64(bytes: Uint8Array): string {\n if (\"toBase64\" in bytes && typeof bytes.toBase64 === \"function\") {\n return (bytes as Uint8Array & { toBase64(): string }).toBase64();\n }\n\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\n/**\n * Encodes an {@link ExportImage}'s bytes as a base64 data URL, for targets\n * that take image sources as URLs (HTML `src` attributes, react-pdf image\n * sources, ...).\n */\nexport function exportImageToDataURL(image: ExportImage): string {\n return `data:${image.mimeType};base64,${bytesToBase64(image.data)}`;\n}\n","import { BlockNoteSchema } from \"../blocks/BlockNoteSchema.js\";\nimport {\n BlockFromConfigNoChildren,\n BlockSchema,\n InlineContentFromConfig,\n InlineContentSchema,\n StyleSchema,\n Styles,\n} from \"../schema/index.js\";\nimport type { Exporter } from \"./Exporter.js\";\n\n/**\n * Defines a mapping from all block types with a schema to a result type `R`.\n * Each block type maps to either:\n * - a function that renders the block itself. The exporter places the\n * block's children after it, nested as the format does it; or\n * - `{ withChildren }`, a function that renders the block *and* its\n * children, which it receives already rendered as its last argument. For\n * blocks whose children are part of them, like a column or a callout's\n * body. Layout blocks must use it.\n */\nexport type BlockMapping<\n B extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n RB,\n RI,\n> = {\n [K in keyof B]:\n | BlockMappingFunction<B[K], I, S, RB, RI>\n | { withChildren: BlockMappingWithChildrenFunction<B[K], I, S, RB, RI> };\n};\n\nexport type BlockMappingFunction<\n C extends BlockSchema[string],\n I extends InlineContentSchema,\n S extends StyleSchema,\n RB,\n RI,\n> = (\n block: BlockFromConfigNoChildren<C, I, S>,\n // we don't know the exact types that are supported by the exporter at this point,\n // because the mapping only knows about converting certain types (which might be a subset of the supported types)\n // this is why there are many `any` types here (same for types below)\n exporter: Exporter<any, any, any, RB, RI, any, any>,\n nestingLevel: number,\n numberedListIndex?: number,\n) => RB | Promise<RB>;\n\n/** A `{ withChildren }` mapping: it also receives the block's rendered children. */\nexport type BlockMappingWithChildrenFunction<\n C extends BlockSchema[string],\n I extends InlineContentSchema,\n S extends StyleSchema,\n RB,\n RI,\n> = (\n block: BlockFromConfigNoChildren<C, I, S>,\n exporter: Exporter<any, any, any, RB, RI, any, any>,\n nestingLevel: number,\n numberedListIndex: number | undefined,\n children: Array<Awaited<RB>>,\n) => RB | Promise<RB>;\n\n/**\n * Defines a mapping from all inline content types with a schema to a result type R.\n */\nexport type InlineContentMapping<\n I extends InlineContentSchema,\n S extends StyleSchema,\n RI,\n TS,\n> = {\n [K in keyof I]: (\n inlineContent: InlineContentFromConfig<I[K], S>,\n // Deliberately loose on the schema generics, like `BlockMapping` above -\n // otherwise a mapping declared for one schema can't be reused (e.g.\n // spread) in a mapping for a schema with different types.\n exporter: Exporter<any, any, any, any, RI, any, TS>,\n ) => RI;\n};\n\n/**\n * Defines a mapping from all style types with a schema to a result type R.\n */\nexport type StyleMapping<S extends StyleSchema, RS> = {\n [K in keyof S]: (\n style: Styles<S>[K],\n exporter: Exporter<any, any, any, any, any, RS, any>,\n ) => RS;\n};\n\n/**\n * The mapping factory is a utility function to easily create mappings for\n * a BlockNoteSchema. Using the factory makes it easier to get typescript code completion etc.\n */\nexport function mappingFactory<\n B extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(_schema: BlockNoteSchema<B, I, S>) {\n return {\n createBlockMapping: <R, RI>(mapping: BlockMapping<B, I, S, R, RI>) =>\n mapping,\n createInlineContentMapping: <R, RS>(\n mapping: InlineContentMapping<I, S, R, RS>,\n ) => mapping,\n createStyleMapping: <R>(mapping: StyleMapping<S, R>) => mapping,\n };\n}\n","/**\n * Combines items by group. This can be used to combine multiple slash menu item arrays,\n * while making sure that items from the same group are adjacent to each other.\n */\nexport function combineByGroup<T extends { group?: string }>(\n items: T[],\n ...additionalItemsArray: {\n group?: string;\n }[][]\n) {\n const combinedItems = [...items];\n for (const additionalItems of additionalItemsArray) {\n for (const additionalItem of additionalItems) {\n const lastItemWithSameGroup = combinedItems.findLastIndex(\n (item) => item.group === additionalItem.group,\n );\n if (lastItemWithSameGroup === -1) {\n combinedItems.push(additionalItem as T);\n } else {\n combinedItems.splice(lastItemWithSameGroup + 1, 0, additionalItem as T);\n }\n }\n }\n return combinedItems;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+iBA,SAAgB,GACd,GACQ;CAKR,OAJI,OAAO,KAAY,WACd,IAGF,EACJ,KAAK,MAAU,OAAO,KAAS,WAAW,IAAO,EAAK,IAAK,CAAC,CAC5D,KAAK,EAAE;AACZ;;;ACjbA,SAAS,GAAmB,GAAsB;CAKhD,OAJI,EAAQ,QAAQ,iBAAiB,IAC5B,IAGF,EAAQ,cAA2B,iBAAiB,KAAK;AAClE;AAGA,SAAS,GAAmB,GAAiB,GAAgB;CAC3D,OAAO,GAAU,WAAW,CAAM,CAAC,CAAC,MAAM,GAAI;EAC5C,SAAS,EAAO,MAAM,UAAU,OAAO;EACvC,oBAAoB;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