@blocknote/core 0.55.0 → 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 (460) 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-DaEUT0O1.js → blocks-COYcDVg7.js} +1572 -1156
  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.js +12 -12
  19. package/dist/{en-BAn9gxr-.js → en-Ch-vvt5e.js} +36 -2
  20. package/dist/en-Ch-vvt5e.js.map +1 -0
  21. package/dist/en-N5lu0-j8.cjs +2 -0
  22. package/dist/en-N5lu0-j8.cjs.map +1 -0
  23. package/dist/extensions-BbM81hHa.js +3069 -0
  24. package/dist/extensions-BbM81hHa.js.map +1 -0
  25. package/dist/extensions-D_WkAfSt.cjs +58 -0
  26. package/dist/extensions-D_WkAfSt.cjs.map +1 -0
  27. package/dist/extensions.cjs +1 -1
  28. package/dist/extensions.js +4 -4
  29. package/dist/locales.cjs +1 -1
  30. package/dist/locales.cjs.map +1 -1
  31. package/dist/locales.js +771 -23
  32. package/dist/locales.js.map +1 -1
  33. package/dist/src-4OQT3z5S.cjs +23 -0
  34. package/dist/src-4OQT3z5S.cjs.map +1 -0
  35. package/dist/{src-D5w0XAHX.js → src-BmLsLZfE.js} +1390 -1278
  36. package/dist/src-BmLsLZfE.js.map +1 -0
  37. package/dist/style.css +1 -1
  38. package/dist/webpack-stats.json +1 -1
  39. package/dist/y.cjs +1 -1
  40. package/dist/y.cjs.map +1 -1
  41. package/dist/y.js +1284 -554
  42. package/dist/y.js.map +1 -1
  43. package/dist/yjs.cjs +1 -1
  44. package/dist/yjs.cjs.map +1 -1
  45. package/dist/yjs.js +189 -148
  46. package/dist/yjs.js.map +1 -1
  47. package/package.json +8 -8
  48. package/src/api/blockManipulation/commands/insertBlocks/insertBlocks.ts +45 -6
  49. package/src/api/blockManipulation/commands/insertBlocks/insertPlacement.test.ts +217 -0
  50. package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.test.ts +113 -9
  51. package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.ts +151 -163
  52. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.test.ts +47 -31
  53. package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.ts +122 -181
  54. package/src/api/blockManipulation/commands/nestBlock/nestBlock.test.ts +256 -0
  55. package/src/api/blockManipulation/commands/nestBlock/nestBlock.ts +80 -40
  56. package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.test.ts +71 -0
  57. package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.ts +39 -31
  58. package/src/api/blockManipulation/commands/splitBlock/splitBlock.test.ts +221 -8
  59. package/src/api/blockManipulation/commands/splitBlock/splitBlock.ts +40 -8
  60. package/src/api/blockManipulation/commands/updateBlock/updateBlock.test.ts +272 -40
  61. package/src/api/blockManipulation/commands/updateBlock/updateBlock.ts +138 -117
  62. package/src/api/blockManipulation/getBlock/getBlock.ts +4 -11
  63. package/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.ts +173 -0
  64. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.ts +293 -0
  65. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.ts +145 -0
  66. package/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.ts +783 -0
  67. package/src/api/blockManipulation/layoutBlocks/plainBlocks.test.ts +180 -0
  68. package/src/api/blockManipulation/layoutBlocks/titledBlocks.test.ts +365 -0
  69. package/src/api/blockManipulation/selections/selection.ts +20 -53
  70. package/src/api/blockManipulation/selections/textCursorPosition.ts +17 -72
  71. package/src/api/blockManipulation/setupTestEnv.ts +38 -6
  72. package/src/api/clipboard/fromClipboard/handleFileInsertion.ts +4 -4
  73. package/src/api/clipboard/toClipboard/copyExtension.ts +3 -3
  74. package/src/api/combineTransactionSteps.ts +22 -0
  75. package/src/api/exporters/html/externalHTMLExporter.ts +1 -1
  76. package/src/api/exporters/html/internalHTMLSerializer.ts +4 -4
  77. package/src/api/exporters/html/util/serializeBlocksExternalHTML.ts +111 -36
  78. package/src/api/exporters/html/util/serializeBlocksInternalHTML.ts +51 -21
  79. package/src/api/exporters/markdown/htmlToMarkdown.ts +12 -1
  80. package/src/api/exporters/markdown/markdownExporter.ts +1 -1
  81. package/src/api/getBlockInfoFromPos.test.ts +428 -3
  82. package/src/api/getBlockInfoFromPos.ts +531 -129
  83. package/src/api/getBlocksChangedByTransaction.test.ts +7 -7
  84. package/src/api/getBlocksChangedByTransaction.ts +3 -3
  85. package/src/api/{getChangedRange.ts → getChangedRangeWithAttrs.ts} +2 -2
  86. package/src/api/getChangedRanges.test.ts +391 -0
  87. package/src/api/getChangedRanges.ts +368 -0
  88. package/src/api/nodeConversions/blockToNode.ts +44 -16
  89. package/src/api/nodeConversions/fragmentToBlocks.ts +29 -44
  90. package/src/api/nodeConversions/nodeToBlock.ts +120 -68
  91. package/src/api/nodeUtil.ts +1 -1
  92. package/src/api/parsers/markdown/autolink.ts +23 -0
  93. package/src/api/parsers/markdown/markdownToHtml.ts +115 -11
  94. package/src/blocks/Code/block.test.ts +4 -4
  95. package/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.ts +6 -1
  96. package/src/blocks/Heading/block.ts +54 -15
  97. package/src/blocks/ListItem/BulletListItem/block.ts +6 -4
  98. package/src/blocks/ListItem/CheckListItem/block.test.ts +2 -2
  99. package/src/blocks/ListItem/CheckListItem/block.ts +6 -4
  100. package/src/blocks/ListItem/NumberedListItem/IndexingPlugin.ts +14 -17
  101. package/src/blocks/ListItem/NumberedListItem/block.ts +6 -4
  102. package/src/blocks/ListItem/ToggleListItem/block.ts +23 -12
  103. package/src/blocks/Table/block.ts +2 -10
  104. package/src/blocks/ToggleWrapper/createToggleFrame.ts +126 -0
  105. package/src/blocks/ToggleWrapper/toggleBlocks.browser.test.ts +1056 -0
  106. package/src/blocks/defaultBlockTypeItems.test.ts +70 -0
  107. package/src/blocks/defaultBlockTypeItems.ts +99 -0
  108. package/src/blocks/defaultBlocks.test.ts +67 -0
  109. package/src/blocks/defaultBlocks.ts +7 -1
  110. package/src/blocks/index.ts +2 -1
  111. package/src/editor/Block.css +286 -154
  112. package/src/editor/BlockNoteEditor.node.test.ts +35 -0
  113. package/src/editor/BlockNoteEditor.test.ts +2 -2
  114. package/src/editor/BlockNoteEditor.ts +71 -9
  115. package/src/editor/BlockNoteExtension.ts +5 -5
  116. package/src/editor/blockColors.browser.test.ts +127 -0
  117. package/src/editor/editor.css +60 -0
  118. package/src/editor/managers/BlockManager.ts +4 -3
  119. package/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.ts +45 -0
  120. package/src/editor/managers/ExtensionManager/ExtensionManager.node.test.ts +209 -0
  121. package/src/editor/managers/ExtensionManager/extensions.ts +10 -1
  122. package/src/editor/managers/ExtensionManager/index.ts +135 -68
  123. package/src/editor/managers/StateManager.ts +14 -4
  124. package/src/editor/transformPasted.ts +14 -13
  125. package/src/exporter/Exporter.test.ts +70 -1
  126. package/src/exporter/Exporter.ts +34 -4
  127. package/src/exporter/mapping.ts +41 -10
  128. package/src/extensions/DropCursor/DropCursor.ts +119 -6
  129. package/src/extensions/DropCursor/dropIntoChildren.ts +80 -0
  130. package/src/extensions/FormattingToolbar/FormattingToolbar.ts +7 -1
  131. package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.ts +190 -0
  132. package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.ts +41 -4
  133. package/src/extensions/Placeholder/Placeholder.test.ts +23 -0
  134. package/src/extensions/Placeholder/Placeholder.ts +8 -7
  135. package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +36 -0
  136. package/src/extensions/PreviousBlockType/PreviousBlockType.ts +8 -4
  137. package/src/extensions/ReadOnly/ReadOnly.test.ts +181 -0
  138. package/src/extensions/ReadOnly/ReadOnly.ts +73 -0
  139. package/src/extensions/SideMenu/SideMenu.ts +401 -764
  140. package/src/extensions/SideMenu/blockDropHandling.ts +372 -0
  141. package/src/extensions/SideMenu/blockGeometry.browser.test.ts +148 -0
  142. package/src/extensions/SideMenu/blockGeometry.test.ts +46 -0
  143. package/src/extensions/SideMenu/blockGeometry.ts +53 -0
  144. package/src/extensions/SideMenu/dragging.ts +19 -32
  145. package/src/extensions/SideMenu/sideMenuHover.test.ts +36 -0
  146. package/src/extensions/SideMenu/sideMenuHover.ts +270 -0
  147. package/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts +5 -4
  148. package/src/extensions/SuggestionMenu/SuggestionMenu.ts +10 -1
  149. package/src/extensions/SuggestionMenu/getDefaultSlashMenuItems.ts +36 -136
  150. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.ts +14 -4
  151. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts +1 -1
  152. package/src/extensions/SyntaxHighlighting/shiki.ts +1 -1
  153. package/src/extensions/TableHandles/TableHandles.ts +4 -6
  154. package/src/extensions/Versioning/Versioning.browser.test.ts +151 -0
  155. package/src/extensions/Versioning/Versioning.node.test.ts +177 -0
  156. package/src/extensions/Versioning/Versioning.ts +145 -612
  157. package/src/extensions/Versioning/__test__/result.ts +12 -0
  158. package/src/extensions/Versioning/comparison.test.ts +40 -0
  159. package/src/extensions/Versioning/createVersioning.test.ts +867 -0
  160. package/src/extensions/Versioning/createVersioning.ts +499 -0
  161. package/src/extensions/Versioning/formatVersionDate.ts +24 -0
  162. package/src/extensions/Versioning/inMemoryVersioning.test.ts +533 -430
  163. package/src/extensions/Versioning/inMemoryVersioning.ts +246 -251
  164. package/src/extensions/Versioning/index.ts +4 -0
  165. package/src/extensions/Versioning/scrollScheduling.test.ts +51 -0
  166. package/src/extensions/Versioning/scrollToFirstChange.test.ts +320 -0
  167. package/src/extensions/Versioning/scrollToFirstChange.ts +139 -0
  168. package/src/extensions/Versioning/types.ts +219 -0
  169. package/src/extensions/Versioning/versioningState.ts +154 -0
  170. package/src/extensions/blockDOM.browser.test.ts +102 -0
  171. package/src/extensions/blockDOM.test.ts +178 -0
  172. package/src/extensions/blockDOM.ts +135 -0
  173. package/src/extensions/index.ts +2 -0
  174. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.ts +1719 -53
  175. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +645 -531
  176. package/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.ts +152 -0
  177. package/src/extensions/tiptap-extensions/Link/helpers/autolink.ts +4 -9
  178. package/src/extensions/tiptap-extensions/UniqueID/UniqueID.test.ts +10 -24
  179. package/src/extensions/tiptap-extensions/UniqueID/UniqueID.ts +22 -19
  180. package/src/fonts/inter.browser.test.ts +57 -0
  181. package/src/fonts/inter.css +111 -0
  182. package/src/i18n/locales/ar.ts +32 -0
  183. package/src/i18n/locales/de.ts +32 -0
  184. package/src/i18n/locales/en.ts +32 -0
  185. package/src/i18n/locales/es.ts +32 -0
  186. package/src/i18n/locales/fa.ts +32 -0
  187. package/src/i18n/locales/fr.ts +32 -0
  188. package/src/i18n/locales/he.ts +32 -0
  189. package/src/i18n/locales/hr.ts +32 -0
  190. package/src/i18n/locales/is.ts +32 -0
  191. package/src/i18n/locales/it.ts +32 -0
  192. package/src/i18n/locales/ja.ts +32 -0
  193. package/src/i18n/locales/ko.ts +32 -0
  194. package/src/i18n/locales/nl.ts +32 -0
  195. package/src/i18n/locales/no.ts +32 -0
  196. package/src/i18n/locales/pl.ts +32 -0
  197. package/src/i18n/locales/pt.ts +32 -0
  198. package/src/i18n/locales/ru.ts +32 -0
  199. package/src/i18n/locales/sk.ts +32 -0
  200. package/src/i18n/locales/uk.ts +32 -0
  201. package/src/i18n/locales/uz.ts +32 -0
  202. package/src/i18n/locales/vi.ts +32 -0
  203. package/src/i18n/locales/zh-tw.ts +32 -0
  204. package/src/i18n/locales/zh.ts +32 -0
  205. package/src/index.ts +13 -3
  206. package/src/pm-nodes/BlockContainer.test.ts +101 -0
  207. package/src/pm-nodes/BlockContainer.ts +110 -1
  208. package/src/pm-nodes/BlockGroup.ts +2 -1
  209. package/src/pm-nodes/README.md +2 -0
  210. package/src/schema/blocks/children.test.ts +288 -0
  211. package/src/schema/blocks/children.ts +136 -0
  212. package/src/schema/blocks/createSpec.browser.test.ts +176 -0
  213. package/src/schema/blocks/createSpec.test.ts +231 -0
  214. package/src/schema/blocks/createSpec.ts +493 -267
  215. package/src/schema/blocks/frame.test.ts +112 -0
  216. package/src/schema/blocks/frame.ts +337 -0
  217. package/src/schema/blocks/internal.ts +50 -17
  218. package/src/schema/blocks/keyboard.ts +154 -0
  219. package/src/schema/blocks/layoutBlockAttributes.ts +29 -0
  220. package/src/schema/blocks/meta.test.ts +53 -0
  221. package/src/schema/blocks/meta.ts +35 -0
  222. package/src/schema/blocks/renderFrame.test.ts +691 -0
  223. package/src/schema/blocks/types.ts +285 -21
  224. package/src/schema/blocks/validateChildren.ts +156 -0
  225. package/src/schema/dataAttributes.test.ts +72 -0
  226. package/src/schema/dataAttributes.ts +69 -0
  227. package/src/schema/index.ts +3 -0
  228. package/src/schema/inlineContent/internal.ts +7 -12
  229. package/src/schema/markGroups.ts +34 -2
  230. package/src/schema/schema.ts +8 -1
  231. package/src/user/userColors.test.ts +108 -0
  232. package/src/user/userColors.ts +42 -13
  233. package/src/y/comments/RESTYjsThreadStore.ts +1 -1
  234. package/src/y/comments/YjsThreadStore.test.ts +1 -1
  235. package/src/y/comments/YjsThreadStore.ts +27 -27
  236. package/src/y/comments/YjsThreadStoreBase.ts +2 -2
  237. package/src/y/comments/yjsHelpers.ts +11 -11
  238. package/src/y/extensions/AttributionExtension.test.ts +271 -2
  239. package/src/y/extensions/AttributionExtension.ts +146 -123
  240. package/src/y/extensions/DiffVersioningExtension.test.ts +67 -18
  241. package/src/y/extensions/DiffVersioningExtension.ts +95 -123
  242. package/src/y/extensions/EmptyDocBinding.test.ts +282 -0
  243. package/src/y/extensions/ForkYDoc.node.test.ts +77 -0
  244. package/src/y/extensions/ForkYDoc.test.ts +93 -2
  245. package/src/y/extensions/ForkYDoc.ts +22 -13
  246. package/src/y/extensions/History.test.ts +125 -0
  247. package/src/y/extensions/RelativePositionMapping.test.ts +35 -0
  248. package/src/y/extensions/RelativePositionMapping.ts +7 -11
  249. package/src/y/extensions/Versioning.node.test.ts +126 -0
  250. package/src/y/extensions/Versioning.test.ts +110 -401
  251. package/src/y/extensions/Versioning.ts +66 -107
  252. package/src/y/extensions/YAttributionMarks.ts +111 -9
  253. package/src/y/extensions/YCursorPlugin.ts +3 -0
  254. package/src/y/extensions/YSync.node.test.ts +75 -0
  255. package/src/y/extensions/YSync.ts +76 -4
  256. package/src/y/extensions/YSyncRemount.test.ts +99 -0
  257. package/src/y/extensions/blockMatchNodes.ts +20 -29
  258. package/src/y/extensions/index.ts +10 -26
  259. package/src/y/extensions/legacyYjsDocBinding.test.ts +652 -0
  260. package/src/y/extensions/nestingChanges.test.ts +326 -0
  261. package/src/y/extensions/persistentBlockGroups.test.ts +1709 -0
  262. package/src/y/extensions/persistentBlockGroups.ts +953 -0
  263. package/src/y/extensions/snapshotCodec.test.ts +105 -0
  264. package/src/y/extensions/snapshotCodec.ts +39 -0
  265. package/src/y/extensions/snapshotPreview.test.ts +201 -0
  266. package/src/y/extensions/snapshotPreview.ts +292 -0
  267. package/src/y/extensions/tableReshape.test.ts +121 -0
  268. package/src/y/extensions/v1BindingSnapshotDiff.test.ts +121 -0
  269. package/src/y/extensions/versionDiffAttribution.test.ts +944 -0
  270. package/src/y/extensions/versionDiffPerformance.test.ts +101 -0
  271. package/src/y/index.ts +1 -0
  272. package/src/y/utils.test.ts +289 -22
  273. package/src/y/utils.ts +167 -43
  274. package/src/y/versioning/__test__/fixtures/activity-all-after.json +5 -5
  275. package/src/y/versioning/__test__/fixtures/activity-all.json +3 -3
  276. package/src/y/versioning/__test__/fixtures/activity-filtered-after.json +2 -2
  277. package/src/y/versioning/__test__/yhub.test.ts +902 -721
  278. package/src/y/versioning/index.ts +6 -1
  279. package/src/y/versioning/yhub.ts +316 -603
  280. package/src/y/versioning/yhubClient.ts +345 -0
  281. package/src/yjs/comments/RESTYjsThreadStore.test.ts +10 -0
  282. package/src/yjs/extensions/FixUpSchema.ts +11 -0
  283. package/src/yjs/extensions/ForkYDoc.browser.test.ts +84 -0
  284. package/src/yjs/extensions/ForkYDoc.node.test.ts +231 -0
  285. package/src/yjs/extensions/ForkYDoc.test.ts +68 -1
  286. package/src/yjs/extensions/ForkYDoc.ts +57 -39
  287. package/src/yjs/extensions/Versioning.test.ts +345 -530
  288. package/src/yjs/extensions/Versioning.ts +111 -68
  289. package/src/yjs/extensions/index.ts +1 -1
  290. package/src/yjs/index.ts +4 -0
  291. package/types/src/api/blockManipulation/commands/insertBlocks/insertBlocks.d.ts +2 -1
  292. package/types/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.d.ts +24 -24
  293. package/types/src/api/blockManipulation/commands/nestBlock/nestBlock.d.ts +3 -2
  294. package/types/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.d.ts +1 -1
  295. package/types/src/api/blockManipulation/commands/splitBlock/splitBlock.d.ts +2 -2
  296. package/types/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.d.ts +34 -0
  297. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.d.ts +1 -0
  298. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.d.ts +460 -0
  299. package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.d.ts +1 -0
  300. package/types/src/api/blockManipulation/layoutBlocks/plainBlocks.test.d.ts +1 -0
  301. package/types/src/api/blockManipulation/layoutBlocks/titledBlocks.test.d.ts +1 -0
  302. package/types/src/api/blockManipulation/setupTestEnv.d.ts +15 -69
  303. package/types/src/api/combineTransactionSteps.d.ts +12 -0
  304. package/types/src/api/getBlockInfoFromPos.d.ts +218 -44
  305. package/types/src/api/{getChangedRange.d.ts → getChangedRangeWithAttrs.d.ts} +1 -1
  306. package/types/src/api/getChangedRanges.d.ts +23 -0
  307. package/types/src/api/getChangedRanges.test.d.ts +1 -0
  308. package/types/src/api/nodeConversions/fragmentToBlocks.d.ts +0 -3
  309. package/types/src/api/parsers/markdown/autolink.d.ts +5 -0
  310. package/types/src/blocks/ToggleWrapper/createToggleFrame.d.ts +29 -0
  311. package/types/src/blocks/ToggleWrapper/toggleBlocks.browser.test.d.ts +1 -0
  312. package/types/src/blocks/defaultBlockTypeItems.d.ts +37 -0
  313. package/types/src/blocks/defaultBlockTypeItems.test.d.ts +1 -0
  314. package/types/src/blocks/defaultBlocks.test.d.ts +1 -0
  315. package/types/src/blocks/index.d.ts +2 -1
  316. package/types/src/editor/BlockNoteEditor.d.ts +36 -8
  317. package/types/src/editor/BlockNoteEditor.node.test.d.ts +1 -0
  318. package/types/src/editor/blockColors.browser.test.d.ts +1 -0
  319. package/types/src/editor/managers/BlockManager.d.ts +4 -3
  320. package/types/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.d.ts +1 -0
  321. package/types/src/editor/managers/ExtensionManager/ExtensionManager.node.test.d.ts +1 -0
  322. package/types/src/editor/managers/ExtensionManager/index.d.ts +15 -3
  323. package/types/src/editor/managers/StateManager.d.ts +1 -1
  324. package/types/src/editor/transformPasted.d.ts +1 -1
  325. package/types/src/exporter/Exporter.d.ts +11 -4
  326. package/types/src/exporter/mapping.d.ts +13 -1
  327. package/types/src/extensions/DropCursor/DropCursor.d.ts +1 -1
  328. package/types/src/extensions/DropCursor/dropIntoChildren.d.ts +38 -0
  329. package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.d.ts +1 -1
  330. package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.d.ts +1 -0
  331. package/types/src/extensions/Placeholder/Placeholder.test.d.ts +1 -0
  332. package/types/src/extensions/ReadOnly/ReadOnly.d.ts +21 -0
  333. package/types/src/extensions/ReadOnly/ReadOnly.test.d.ts +1 -0
  334. package/types/src/extensions/SideMenu/SideMenu.d.ts +49 -88
  335. package/types/src/extensions/SideMenu/blockDropHandling.d.ts +11 -0
  336. package/types/src/extensions/SideMenu/blockGeometry.browser.test.d.ts +1 -0
  337. package/types/src/extensions/SideMenu/blockGeometry.d.ts +22 -0
  338. package/types/src/extensions/SideMenu/blockGeometry.test.d.ts +1 -0
  339. package/types/src/extensions/SideMenu/dragging.d.ts +0 -4
  340. package/types/src/extensions/SideMenu/sideMenuHover.d.ts +58 -0
  341. package/types/src/extensions/SideMenu/sideMenuHover.test.d.ts +1 -0
  342. package/types/src/extensions/Versioning/Versioning.browser.test.d.ts +1 -0
  343. package/types/src/extensions/Versioning/Versioning.d.ts +34 -311
  344. package/types/src/extensions/Versioning/Versioning.node.test.d.ts +1 -0
  345. package/types/src/extensions/Versioning/__test__/result.d.ts +3 -0
  346. package/types/src/extensions/Versioning/comparison.test.d.ts +1 -0
  347. package/types/src/extensions/Versioning/createVersioning.d.ts +32 -0
  348. package/types/src/extensions/Versioning/createVersioning.test.d.ts +1 -0
  349. package/types/src/extensions/Versioning/formatVersionDate.d.ts +7 -0
  350. package/types/src/extensions/Versioning/inMemoryVersioning.d.ts +64 -36
  351. package/types/src/extensions/Versioning/index.d.ts +4 -0
  352. package/types/src/extensions/Versioning/scrollScheduling.test.d.ts +1 -0
  353. package/types/src/extensions/Versioning/scrollToFirstChange.d.ts +18 -0
  354. package/types/src/extensions/Versioning/scrollToFirstChange.test.d.ts +1 -0
  355. package/types/src/extensions/Versioning/types.d.ts +239 -0
  356. package/types/src/extensions/Versioning/versioningState.d.ts +43 -0
  357. package/types/src/extensions/blockDOM.browser.test.d.ts +1 -0
  358. package/types/src/extensions/blockDOM.d.ts +37 -0
  359. package/types/src/extensions/blockDOM.test.d.ts +1 -0
  360. package/types/src/extensions/index.d.ts +2 -0
  361. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.d.ts +1 -0
  362. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.d.ts +3 -0
  363. package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.d.ts +1 -0
  364. package/types/src/fonts/inter.browser.test.d.ts +2 -0
  365. package/types/src/i18n/locales/en.d.ts +32 -0
  366. package/types/src/i18n/locales/fa.d.ts +32 -0
  367. package/types/src/i18n/locales/sk.d.ts +32 -0
  368. package/types/src/index.d.ts +6 -3
  369. package/types/src/pm-nodes/BlockContainer.d.ts +6 -0
  370. package/types/src/pm-nodes/BlockContainer.test.d.ts +1 -0
  371. package/types/src/schema/blocks/children.d.ts +39 -0
  372. package/types/src/schema/blocks/children.test.d.ts +1 -0
  373. package/types/src/schema/blocks/createSpec.browser.test.d.ts +1 -0
  374. package/types/src/schema/blocks/createSpec.d.ts +13 -0
  375. package/types/src/schema/blocks/frame.d.ts +109 -0
  376. package/types/src/schema/blocks/frame.test.d.ts +1 -0
  377. package/types/src/schema/blocks/internal.d.ts +6 -0
  378. package/types/src/schema/blocks/keyboard.d.ts +111 -0
  379. package/types/src/schema/blocks/layoutBlockAttributes.d.ts +9 -0
  380. package/types/src/schema/blocks/meta.d.ts +14 -0
  381. package/types/src/schema/blocks/meta.test.d.ts +1 -0
  382. package/types/src/schema/blocks/renderFrame.test.d.ts +1 -0
  383. package/types/src/schema/blocks/types.d.ts +228 -15
  384. package/types/src/schema/blocks/validateChildren.d.ts +5 -0
  385. package/types/src/schema/dataAttributes.d.ts +19 -0
  386. package/types/src/schema/dataAttributes.test.d.ts +1 -0
  387. package/types/src/schema/index.d.ts +3 -0
  388. package/types/src/schema/markGroups.d.ts +8 -0
  389. package/types/src/user/userColors.d.ts +24 -3
  390. package/types/src/user/userColors.test.d.ts +1 -0
  391. package/types/src/y/comments/RESTYjsThreadStore.d.ts +1 -1
  392. package/types/src/y/comments/YjsThreadStore.d.ts +1 -1
  393. package/types/src/y/comments/YjsThreadStoreBase.d.ts +2 -2
  394. package/types/src/y/comments/yjsHelpers.d.ts +5 -5
  395. package/types/src/y/extensions/AttributionExtension.d.ts +19 -21
  396. package/types/src/y/extensions/DiffVersioningExtension.d.ts +9 -4
  397. package/types/src/y/extensions/EmptyDocBinding.test.d.ts +1 -0
  398. package/types/src/y/extensions/ForkYDoc.d.ts +3 -1
  399. package/types/src/y/extensions/ForkYDoc.node.test.d.ts +1 -0
  400. package/types/src/y/extensions/History.test.d.ts +1 -0
  401. package/types/src/y/extensions/Versioning.d.ts +4 -15
  402. package/types/src/y/extensions/Versioning.node.test.d.ts +1 -0
  403. package/types/src/y/extensions/YAttributionMarks.d.ts +13 -2
  404. package/types/src/y/extensions/YCursorPlugin.d.ts +1 -0
  405. package/types/src/y/extensions/YSync.d.ts +4 -18
  406. package/types/src/y/extensions/YSync.node.test.d.ts +1 -0
  407. package/types/src/y/extensions/YSyncRemount.test.d.ts +1 -0
  408. package/types/src/y/extensions/blockMatchNodes.d.ts +0 -22
  409. package/types/src/y/extensions/index.d.ts +27 -44
  410. package/types/src/y/extensions/legacyYjsDocBinding.test.d.ts +1 -0
  411. package/types/src/y/extensions/nestingChanges.test.d.ts +1 -0
  412. package/types/src/y/extensions/persistentBlockGroups.d.ts +189 -0
  413. package/types/src/y/extensions/persistentBlockGroups.test.d.ts +1 -0
  414. package/types/src/y/extensions/snapshotCodec.d.ts +13 -0
  415. package/types/src/y/extensions/snapshotCodec.test.d.ts +1 -0
  416. package/types/src/y/extensions/snapshotPreview.d.ts +21 -0
  417. package/types/src/y/extensions/snapshotPreview.test.d.ts +1 -0
  418. package/types/src/y/extensions/tableReshape.test.d.ts +1 -0
  419. package/types/src/y/extensions/v1BindingSnapshotDiff.test.d.ts +1 -0
  420. package/types/src/y/extensions/versionDiffAttribution.test.d.ts +1 -0
  421. package/types/src/y/extensions/versionDiffPerformance.test.d.ts +1 -0
  422. package/types/src/y/index.d.ts +1 -0
  423. package/types/src/y/utils.d.ts +39 -19
  424. package/types/src/y/versioning/index.d.ts +1 -1
  425. package/types/src/y/versioning/yhub.d.ts +69 -86
  426. package/types/src/y/versioning/yhubClient.d.ts +67 -0
  427. package/types/src/yjs/extensions/ForkYDoc.browser.test.d.ts +1 -0
  428. package/types/src/yjs/extensions/ForkYDoc.d.ts +2 -0
  429. package/types/src/yjs/extensions/ForkYDoc.node.test.d.ts +1 -0
  430. package/types/src/yjs/extensions/Versioning.d.ts +36 -22
  431. package/types/src/yjs/extensions/index.d.ts +2 -1
  432. package/types/src/yjs/index.d.ts +1 -0
  433. package/dist/BlockNoteExtension-BJCLnwrE.cjs +0 -2
  434. package/dist/BlockNoteExtension-BJCLnwrE.cjs.map +0 -1
  435. package/dist/BlockNoteExtension-CbvDA0F7.js.map +0 -1
  436. package/dist/blocks-DLgTreVu.cjs +0 -12
  437. package/dist/blocks-DLgTreVu.cjs.map +0 -1
  438. package/dist/blocks-DaEUT0O1.js.map +0 -1
  439. package/dist/en-BAn9gxr-.js.map +0 -1
  440. package/dist/en-CHnrV5l8.cjs +0 -2
  441. package/dist/en-CHnrV5l8.cjs.map +0 -1
  442. package/dist/extensions-B1JQURVF.js +0 -2138
  443. package/dist/extensions-B1JQURVF.js.map +0 -1
  444. package/dist/extensions-CZkqKzJO.cjs +0 -58
  445. package/dist/extensions-CZkqKzJO.cjs.map +0 -1
  446. package/dist/src-D5w0XAHX.js.map +0 -1
  447. package/dist/src-th5uZEvx.cjs +0 -23
  448. package/dist/src-th5uZEvx.cjs.map +0 -1
  449. package/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.ts +0 -173
  450. package/src/blocks/ListItem/ListItemKeyboardShortcuts.ts +0 -63
  451. package/src/blocks/ToggleWrapper/createToggleWrapper.ts +0 -197
  452. package/src/blocks/utils/listItemEnterHandler.ts +0 -43
  453. package/src/extensions/Versioning/Versioning.test.ts +0 -435
  454. package/src/extensions/getDraggableBlockFromElement.ts +0 -19
  455. package/types/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.d.ts +0 -32
  456. package/types/src/blocks/ListItem/ListItemKeyboardShortcuts.d.ts +0 -2
  457. package/types/src/blocks/ToggleWrapper/createToggleWrapper.d.ts +0 -15
  458. package/types/src/blocks/utils/listItemEnterHandler.d.ts +0 -2
  459. package/types/src/extensions/getDraggableBlockFromElement.d.ts +0 -5
  460. /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":"extensions-D_WkAfSt.cjs","names":[],"sources":["../src/api/nodeUtil.ts","../src/extensions/blockDOM.ts","../src/api/exporters/html/util/serializeBlocksExternalHTML.ts","../src/api/exporters/html/externalHTMLExporter.ts","../src/api/getChangedRangeWithAttrs.ts","../src/api/getBlocksChangedByTransaction.ts","../src/extensions/BlockChange/BlockChange.ts","../src/extensions/DropCursor/utils.ts","../src/api/nodeConversions/fragmentToBlocks.ts","../src/extensions/DropCursor/dropIntoChildren.ts","../src/extensions/DropCursor/DropCursor.ts","../src/extensions/History/History.ts","../src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.ts","../src/extensions/LinkToolbar/LinkToolbar.ts","../src/extensions/LinkToolbar/protocols.ts","../src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.ts","../src/extensions/Placeholder/Placeholder.ts","../src/extensions/PositionMapping/PositionMapping.ts","../src/extensions/PreviousBlockType/PreviousBlockType.ts","../src/extensions/ReadOnly/ReadOnly.ts","../src/extensions/SideMenu/blockGeometry.ts","../src/extensions/SideMenu/sideMenuHover.ts","../src/extensions/SideMenu/blockDropHandling.ts","../src/extensions/tiptap-extensions/Link/helpers/tlds.ts","../src/extensions/tiptap-extensions/Link/helpers/linkDetector.ts","../src/api/parsers/markdown/autolink.ts","../src/api/exporters/markdown/htmlToMarkdown.ts","../src/api/exporters/markdown/markdownExporter.ts","../src/extensions/SideMenu/MultipleNodeSelection.ts","../src/extensions/SideMenu/dragging.ts","../src/extensions/SideMenu/SideMenu.ts","../src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts","../src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.ts","../src/extensions/SyntaxHighlighting/shiki.ts","../src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts","../src/extensions/SuggestionMenu/getDefaultEmojiPickerItems.ts","../src/extensions/TableHandles/TableHandles.ts","../src/extensions/TrailingNode/TrailingNode.ts","../src/extensions/Versioning/versioningState.ts","../src/extensions/Versioning/createVersioning.ts","../src/extensions/Versioning/scrollToFirstChange.ts","../src/extensions/Versioning/Versioning.ts","../src/extensions/Versioning/inMemoryVersioning.ts","../src/extensions/Versioning/formatVersionDate.ts"],"sourcesContent":["import type { Node } from \"prosemirror-model\";\nimport { getNodeId } from \"./getBlockInfoFromPos.js\";\n\n/**\n * Get a TipTap node by id\n */\nexport function getNodeById(\n id: string,\n doc: Node,\n): { node: Node; posBeforeNode: number } | undefined {\n let targetNode: Node | undefined = undefined;\n let posBeforeNode: number | undefined = undefined;\n\n doc.firstChild!.descendants((node, pos) => {\n // Skips traversing nodes after node with target ID has been found.\n if (targetNode) {\n return false;\n }\n\n // Keeps traversing nodes if block with target ID has not been found. Some\n // block nodes we merely pass over (e.g. `column`/`columnList`) may not\n // carry an id — skip them without calling the throwing `getNodeId`, which\n // errors on id-less nodes. Only nodes that actually have an id are compared.\n if (!isNodeBlock(node) || !node.attrs.id || getNodeId(node, doc) !== id) {\n return true;\n }\n\n targetNode = node;\n posBeforeNode = pos + 1;\n\n return false;\n });\n\n if (targetNode === undefined || posBeforeNode === undefined) {\n return undefined;\n }\n\n return {\n node: targetNode,\n posBeforeNode: posBeforeNode,\n };\n}\n\nexport function isNodeBlock(node: Node): boolean {\n return node.type.isInGroup(\"bnBlock\");\n}\n","import type { EditorView } from \"prosemirror-view\";\n\n// FIXME: this file finds blocks through their rendered DOM (selectors,\n// `closest`). Resolving through ProseMirror instead would drop the selectors:\n// `view.posAtDOM` for the block an element is in, the document for a block's\n// children, and `view.nodeDOM` for their boxes. Check `posAtDOM` inside node\n// views and nested editors first.\n\n// UniqueID and the block renderers put data-id on every block root.\n// Ordinary blocks also copy it to blockOuter, which is only rendering chrome.\nexport const BLOCK_SELECTOR =\n '[data-node-type][data-id]:not([data-node-type=\"blockOuter\"])';\n\n/**\n * Returns the root element of the block of this editor that the element is\n * in, if there is one.\n */\nexport function getBlockElement(\n element: Element,\n view: Pick<EditorView, \"dom\">,\n): Element | undefined {\n if (!view.dom.contains(element)) {\n return undefined;\n }\n // Embedded editors own their blocks, even though their DOM is inside ours.\n const owner = element.closest(\".bn-editor\");\n if (owner && owner !== view.dom) {\n return undefined;\n }\n const block = element.closest(BLOCK_SELECTOR);\n return block && block !== view.dom && view.dom.contains(block)\n ? block\n : undefined;\n}\n\n/**\n * Returns the element of the block with `id`, whose node starts at `pos`: the\n * same element as `getBlockElement` finds from inside the block. ProseMirror's\n * DOM for the node can be that element (a layout block's frame), or wrap it: a\n * regular block's `.bn-block-outer`, or a framework's wrappers that don't\n * carry the block's id (React's `display: contents` wrappers).\n *\n * Caution: a React layout block's frame exists only after React renders its\n * node view, which can be after the editor's own render. Until then, this\n * returns `undefined` for it, never another element.\n */\nexport function getBlockElementForNode(\n view: Pick<EditorView, \"nodeDOM\">,\n pos: number,\n id: string,\n): Element | undefined {\n const dom = view.nodeDOM(pos);\n if (!(dom instanceof Element)) {\n return undefined;\n }\n // The block's element comes before its child blocks, so it is the first\n // block element: the node's DOM, or else the first one inside it (inside\n // `.bn-block-outer`, or inside a framework's wrappers).\n const element = dom.matches(BLOCK_SELECTOR)\n ? dom\n : dom.querySelector(BLOCK_SELECTOR);\n return element?.getAttribute(\"data-id\") === id ? element : undefined;\n}\n\n/** Resolves block identity independently of whether it gets a drag handle. */\nexport function getBlockFromElement(\n element: Element,\n view: Pick<EditorView, \"dom\">,\n): { node: HTMLElement; id: string; type: string } | undefined {\n const node = getBlockElement(element, view);\n if (!node) {\n return undefined;\n }\n\n const id = node.getAttribute(\"data-id\");\n const nodeType = node.getAttribute(\"data-node-type\");\n // The regular block's own content precedes its nested blockGroup, even\n // when a renderFrame adds chrome around it.\n const type =\n nodeType === \"blockContainer\"\n ? node\n .querySelector(\"[data-content-type]\")\n ?.getAttribute(\"data-content-type\")\n : nodeType;\n // A matched block root must expose its own identity. Validate this at the\n // DOM boundary so callers never need casts or non-null assertions.\n const HTMLElementClass = node.ownerDocument.defaultView?.HTMLElement;\n if (\n !HTMLElementClass ||\n !(node instanceof HTMLElementClass) ||\n !id ||\n !type\n ) {\n throw new Error(\n \"Block root is missing its HTML element, ID, or block type.\",\n );\n }\n return { node, id, type };\n}\n\n/** A block that opts out hands its drag handle to the nearest eligible ancestor. */\nexport function getDraggableBlockFromElement(\n element: Element,\n view: Pick<EditorView, \"dom\">,\n isDraggable: (type: string) => boolean,\n) {\n let block = getBlockFromElement(element, view);\n while (block) {\n if (isDraggable(block.type)) {\n return block;\n }\n const parent = block.node.parentElement;\n block = parent ? getBlockFromElement(parent, view) : undefined;\n }\n return undefined;\n}\n\n/**\n * Returns the child blocks of a block element: its nested blocks, or the\n * children of a layout block. The blocks of an editor nested in the block are\n * not its children: they belong to that editor.\n */\nexport function getDirectChildBlocks(blockElement: Element): Element[] {\n const editor = blockElement.closest(\".bn-editor\");\n const children: Element[] = [];\n for (const child of blockElement.querySelectorAll(BLOCK_SELECTOR)) {\n if (\n child.parentElement?.closest(BLOCK_SELECTOR) === blockElement &&\n child.closest(\".bn-editor\") === editor\n ) {\n children.push(child);\n }\n }\n return children;\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 BlockImplementation,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../../schema/index.js\";\nimport { isLayoutNode } from \"../../../../schema/blocks/children.js\";\nimport {\n FRAME_SLOT_ATTRIBUTE,\n renderFrameDOM,\n} from \"../../../../schema/blocks/frame.js\";\nimport { isDocumentFragment } from \"../../../../schema/blocks/internal.js\";\nimport { UnreachableCaseError } from \"../../../../util/typescript.js\";\nimport {\n inlineContentToNodes,\n tableContentToNodes,\n} from \"../../../nodeConversions/blockToNode.js\";\nimport { nodeToCustomInlineContent } from \"../../../nodeConversions/nodeToBlock.js\";\n\n/**\n * Placeholder character inserted into empty inline-content blocks when\n * exporting to external HTML. An empty block serializes to an element with no\n * children (e.g. `<p></p>`), which is dropped when the HTML is parsed back into\n * blocks. Filling it with this character keeps the block alive through the\n * round trip, and the parser strips the character again so the block ends up\n * empty (see `HTMLToBlocks`).\n *\n * The Unicode object replacement character (U+FFFC) is used because it's a\n * reserved placeholder that users don't type, so it can be safely removed on\n * import without discarding legitimate content (unlike a non-breaking space).\n */\nexport const EMPTY_BLOCK_PLACEHOLDER = \"\";\n\nfunction addAttributesAndRemoveClasses(element: HTMLElement) {\n // Removes all BlockNote specific class names.\n const className =\n Array.from(element.classList).filter(\n (className) => !className.startsWith(\"bn-\"),\n ) || [];\n\n if (className.length > 0) {\n element.className = className.join(\" \");\n } else {\n element.removeAttribute(\"class\");\n }\n}\n\nexport function serializeInlineContentExternalHTML<\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 options?: { document?: Document; blockType?: string },\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(\n [blockContent],\n editor.pmSchema,\n options?.blockType,\n );\n } else if (Array.isArray(blockContent)) {\n nodes = inlineContentToNodes(\n blockContent,\n editor.pmSchema,\n options?.blockType,\n );\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 or fallback to `render`\n const output = inlineContentImplementation.toExternalHTML\n ? inlineContentImplementation.toExternalHTML(\n inlineContent as any,\n editor as any,\n )\n : 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 = (\n editor.schema.styleSpecs[mark.type.name].implementation\n .toExternalHTML ??\n editor.schema.styleSpecs[mark.type.name].implementation.render\n )(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 if (\n fragment.childNodes.length === 1 &&\n fragment.firstChild?.nodeType === 1 /* Node.ELEMENT_NODE */\n ) {\n addAttributesAndRemoveClasses(fragment.firstChild as HTMLElement);\n }\n\n return fragment;\n}\n\n/** A block's external HTML, before the serializer post-processes it. */\ntype BlockOutput = {\n dom: HTMLElement | DocumentFragment;\n contentDOM?: HTMLElement;\n childrenDOM?: HTMLElement;\n};\n\n/**\n * The block's output for external HTML, and the frame to put it into. The\n * block's own `toExternalHTML` replaces the default export, frame included.\n * By default, a layout block is its frame, with the children in the slot, and\n * any other block is `render`'s output, which the caller puts into the\n * block's frame (if it draws one).\n */\nfunction renderBlockOutput(\n blockImplementation: BlockImplementation,\n block: any,\n editor: BlockNoteEditor<any, any, any>,\n isLayoutBlock: boolean,\n nestingLevel: number,\n): { output: BlockOutput; frame?: { dom: HTMLElement; slot: HTMLElement } } {\n const external = blockImplementation.toExternalHTML?.call({}, block, editor, {\n nestingLevel,\n });\n if (external) {\n return { output: external };\n }\n\n const frame = renderFrameDOM(editor, block);\n if (isLayoutBlock) {\n if (!frame) {\n throw new Error(\n `Layout block \"${block.type}\" drew no frame. This is a bug in BlockNote.`,\n );\n }\n return { output: { dom: frame.dom, childrenDOM: frame.slot } };\n }\n\n if (!blockImplementation.render) {\n throw new Error(\n `Block \"${block.type}\" has no \\`render\\`. This is a bug in BlockNote.`,\n );\n }\n return { output: blockImplementation.render.call({}, block, editor), frame };\n}\n\n/**\n * TODO: there's still quite some logic that handles getting and filtering properties,\n * we should make sure the `toExternalHTML` methods of default blocks actually handle this,\n * instead of the serializer.\n */\nfunction serializeBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n fragment: DocumentFragment,\n editor: BlockNoteEditor<BSchema, I, S>,\n block: PartialBlock<BSchema, I, S>,\n serializer: DOMSerializer,\n orderedListItemBlockTypes: Set<string>,\n unorderedListItemBlockTypes: Set<string>,\n nestingLevel: number,\n options?: { document?: Document },\n) {\n const doc = options?.document ?? document;\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\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\n // the container node is just used as a workaround to get some block-level attributes.\n // we should change toExternalHTML so that this is not necessary\n const attrs = Array.from(bc.dom.attributes);\n\n const blockImplementation = editor.blockImplementations[block.type as any]\n .implementation as BlockImplementation;\n const blockWithDefaults = { ...block, props, children: block.children ?? [] };\n const isLayoutBlock = isLayoutNode(editor.pmSchema.nodes[block.type as any]);\n const { output: ret, frame } = renderBlockOutput(\n blockImplementation,\n blockWithDefaults,\n editor,\n isLayoutBlock,\n nestingLevel,\n );\n\n const elementFragment = doc.createDocumentFragment();\n\n let rootElement: HTMLElement | undefined;\n if (!isDocumentFragment(ret.dom)) {\n rootElement = ret.dom;\n }\n\n if (rootElement?.classList.contains(\"bn-block-content\")) {\n const blockContentDataAttributes = [\n ...attrs,\n ...Array.from(rootElement.attributes),\n ].filter(\n (attr) =>\n attr.name.startsWith(\"data\") &&\n attr.name !== \"data-content-type\" &&\n attr.name !== \"data-file-block\" &&\n attr.name !== \"data-node-view-wrapper\" &&\n attr.name !== \"data-node-type\" &&\n attr.name !== \"data-id\" &&\n attr.name !== \"data-editable\",\n );\n\n for (const attr of blockContentDataAttributes) {\n (rootElement.firstChild! as HTMLElement).setAttribute(\n attr.name,\n attr.value,\n );\n }\n\n addAttributesAndRemoveClasses(rootElement.firstChild! as HTMLElement);\n if (nestingLevel > 0) {\n (rootElement.firstChild! as HTMLElement).setAttribute(\n \"data-nesting-level\",\n nestingLevel.toString(),\n );\n }\n elementFragment.append(...Array.from(rootElement.childNodes));\n } else {\n elementFragment.append(ret.dom);\n if (isLayoutBlock) {\n // Like a regular block's type marker (`data-content-type`), a\n // layout block's markers stay out of external HTML: it parses back only\n // through the block's `parse`, like any other block. Its props stay as\n // `data-*` attributes. This mirrors the unwrapping of a regular block's\n // `.bn-block-content` above: the spec's hooks produce the editor's\n // structure with its markers, and this serializer strips them.\n // TODO: consider not adding the markers in the first place (only the\n // node view and the internal serializer need them), instead of adding\n // and then stripping them. If so, change it for regular blocks too\n // (`wrapInBlockStructure`), so both kinds of block keep one rule.\n rootElement?.removeAttribute(\"data-node-type\");\n rootElement?.removeAttribute(\"data-id\");\n ret.childrenDOM?.removeAttribute(FRAME_SLOT_ATTRIBUTE);\n }\n if (nestingLevel > 0) {\n rootElement?.setAttribute(\"data-nesting-level\", nestingLevel.toString());\n }\n }\n\n if (ret.contentDOM) {\n if (block.content) {\n const ic = serializeInlineContentExternalHTML(\n editor,\n block.content as any, // TODO\n serializer,\n { ...options, blockType: block.type },\n );\n\n ret.contentDOM.appendChild(ic);\n }\n\n // Blocks with empty inline content (e.g. an empty paragraph) serialize to\n // an element with no children (e.g. `<p></p>`), which is ignored when the\n // HTML is parsed back into blocks. To make these blocks survive such a\n // round trip, we fill their content with a placeholder character that the\n // parser strips out again (see `EMPTY_BLOCK_PLACEHOLDER`).\n //\n // Only applies to blocks that hold inline content: containers (columns,\n // tables) fill their `contentDOM` with child blocks later on, and code\n // blocks would turn the placeholder into literal content.\n const blockNodeType = editor.pmSchema.nodes[block.type as any];\n const needsPlaceholder =\n !!blockNodeType?.inlineContent && !blockNodeType.spec.code;\n if (needsPlaceholder && ret.contentDOM.childNodes.length === 0) {\n ret.contentDOM.appendChild(doc.createTextNode(EMPTY_BLOCK_PLACEHOLDER));\n }\n }\n\n // Where the block's children go: where the block placed them, else in the\n // slot of the frame around its content.\n let childrenDOM = ret.childrenDOM;\n if (frame) {\n frame.slot.append(elementFragment);\n elementFragment.append(frame.dom);\n childrenDOM = frame.slot;\n }\n\n let listType = undefined;\n if (orderedListItemBlockTypes.has(block.type!)) {\n listType = \"OL\";\n } else if (unorderedListItemBlockTypes.has(block.type!)) {\n listType = \"UL\";\n }\n\n if (listType) {\n if (fragment.lastChild?.nodeName !== listType) {\n const list = doc.createElement(listType);\n\n if (\n listType === \"OL\" &&\n \"start\" in props &&\n props.start &&\n props?.start !== 1\n ) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n list.setAttribute(\"start\", String(props.start));\n }\n fragment.append(list);\n }\n fragment.lastChild!.appendChild(elementFragment);\n } else {\n fragment.append(elementFragment);\n }\n\n if (block.children && block.children.length > 0) {\n const childFragment = doc.createDocumentFragment();\n serializeBlocksToFragment(\n childFragment,\n editor,\n block.children,\n serializer,\n orderedListItemBlockTypes,\n unorderedListItemBlockTypes,\n nestingLevel + 1,\n options,\n );\n if (\n fragment.lastChild?.nodeName === \"UL\" ||\n fragment.lastChild?.nodeName === \"OL\"\n ) {\n // add nested lists to the last list item\n while (\n childFragment.firstChild?.nodeName === \"UL\" ||\n childFragment.firstChild?.nodeName === \"OL\"\n ) {\n fragment.lastChild!.lastChild!.appendChild(childFragment.firstChild!);\n }\n }\n\n if (childrenDOM) {\n // block specifies where children should go (e.g. toggle blocks\n // place children inside <details>, or a frame's slot)\n childrenDOM.append(childFragment);\n } else if (\n editor.pmSchema.nodes[block.type as any].isInGroup(\"blockContent\") ||\n !ret.contentDOM\n ) {\n // default \"blockContainer\" style blocks are flattened (no \"nested block\" support) for externalHTML, so append the child fragment to the outer fragment.\n // So does a layout block whose own export places its children nowhere.\n fragment.append(childFragment);\n } else {\n // for columns / column lists, do use nesting\n ret.contentDOM.append(childFragment);\n }\n }\n}\n\nconst serializeBlocksToFragment = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n fragment: DocumentFragment,\n editor: BlockNoteEditor<BSchema, I, S>,\n blocks: PartialBlock<BSchema, I, S>[],\n serializer: DOMSerializer,\n orderedListItemBlockTypes: Set<string>,\n unorderedListItemBlockTypes: Set<string>,\n nestingLevel = 0,\n options?: { document?: Document },\n) => {\n for (const block of blocks) {\n serializeBlock(\n fragment,\n editor,\n block,\n serializer,\n orderedListItemBlockTypes,\n unorderedListItemBlockTypes,\n nestingLevel,\n options,\n );\n }\n};\n\nexport const serializeBlocksExternalHTML = <\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 orderedListItemBlockTypes: Set<string>,\n unorderedListItemBlockTypes: Set<string>,\n options?: { document?: Document },\n) => {\n const doc = options?.document ?? document;\n const fragment = doc.createDocumentFragment();\n\n serializeBlocksToFragment(\n fragment,\n editor,\n blocks,\n serializer,\n orderedListItemBlockTypes,\n unorderedListItemBlockTypes,\n 0,\n options,\n );\n return fragment;\n};\n","import { DOMSerializer, Schema } from \"prosemirror-model\";\n\nimport { PartialBlock } from \"../../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContent,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport {\n serializeBlocksExternalHTML,\n serializeInlineContentExternalHTML,\n} from \"./util/serializeBlocksExternalHTML.js\";\n\n// Used to export BlockNote blocks and ProseMirror nodes to HTML for use outside\n// the editor. Blocks are exported using the `toExternalHTML` method in their\n// `blockSpec`, or `toInternalHTML` if `toExternalHTML` is not defined.\n//\n// The HTML created by this serializer is different to what's rendered by the\n// editor to the DOM. This also means that data is likely to be lost when\n// converting back to original blocks. The differences in the output HTML are:\n// 1. It doesn't include the `blockGroup` and `blockContainer` wrappers meaning\n// that nesting is not preserved for non-list-item blocks.\n// 2. `li` items in the output HTML are wrapped in `ul` or `ol` elements.\n// 3. While nesting for list items is preserved, other types of blocks nested\n// inside a list are un-nested and a new list is created after them.\n// 4. The HTML is wrapped in a single `div` element.\n\n// Needs to be sync because it's used in drag handler event (SideMenuExtension)\nexport const createExternalHTMLExporter = <\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 return {\n exportBlocks: (\n blocks: PartialBlock<BSchema, I, S>[],\n options: { document?: Document },\n ) => {\n const html = serializeBlocksExternalHTML(\n editor,\n blocks,\n serializer,\n new Set<string>([\"numberedListItem\"]),\n new Set<string>([\"bulletListItem\", \"checkListItem\", \"toggleListItem\"]),\n options,\n );\n const div = document.createElement(\"div\");\n div.append(html);\n return div.innerHTML;\n },\n\n exportInlineContent: (\n inlineContent: InlineContent<I, S>[],\n options: { document?: Document },\n ) => {\n const domFragment = serializeInlineContentExternalHTML(\n editor,\n inlineContent as any,\n serializer,\n options,\n );\n\n const parent = document.createElement(\"div\");\n parent.append(domFragment.cloneNode(true));\n\n return parent.innerHTML;\n },\n };\n};\n","import type { Transform } from \"prosemirror-transform\";\n\n/**\n * Like ProseMirror's `Transform.changedRange()`, but also accounts for\n * position-preserving steps whose `StepMap` is empty — `AttrStep` (prop-only\n * updates like a heading's `level`) and mark steps. `changedRange()` and tiptap's\n * `getChangedRanges` both miss `AttrStep`, so anything that scopes work to the\n * changed range would silently ignore prop-only updates.\n *\n * O(steps), like `changedRange()`. Returns null when nothing changed.\n */\nexport function getChangedRangeWithAttrs(\n transform: Pick<Transform, \"mapping\" | \"steps\">,\n): { from: number; to: number } | null {\n const { mapping, steps } = transform;\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n\n for (let i = 0; i < mapping.maps.length; i++) {\n const map = mapping.maps[i];\n // Advance the accumulated range into this step's coordinate space.\n if (i) {\n from = map.map(from, 1);\n to = map.map(to, -1);\n }\n\n let hadRange = false;\n map.forEach((_oldFrom, _oldTo, newFrom, newTo) => {\n hadRange = true;\n from = Math.min(from, newFrom);\n to = Math.max(to, newTo);\n });\n\n if (!hadRange) {\n // Position-preserving step: recover the affected position from the step,\n // since its map has no ranges. (DocAttrStep has none and affects no nodes.)\n const step = steps[i] as { pos?: number; from?: number; to?: number };\n if (typeof step.pos === \"number\") {\n // AttrStep\n from = Math.min(from, step.pos);\n to = Math.max(to, step.pos + 1);\n } else if (typeof step.from === \"number\" && typeof step.to === \"number\") {\n // AddMarkStep / RemoveMarkStep\n from = Math.min(from, step.from);\n to = Math.max(to, step.to);\n }\n }\n }\n\n if (from === Number.POSITIVE_INFINITY) {\n return null;\n }\n return { from, to };\n}\n","import { combineTransactionSteps } from \"./combineTransactionSteps.js\";\nimport deepEqual from \"fast-deep-equal\";\nimport type { Node } from \"prosemirror-model\";\nimport type { Transaction } from \"prosemirror-state\";\nimport {\n Block,\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n} from \"../blocks/defaultBlocks.js\";\nimport type { BlockSchema } from \"../schema/index.js\";\nimport type { InlineContentSchema } from \"../schema/inlineContent/types.js\";\nimport type { StyleSchema } from \"../schema/styles/types.js\";\nimport { getChangedRangeWithAttrs } from \"./getChangedRangeWithAttrs.js\";\nimport { getNodeId } from \"./getBlockInfoFromPos.js\";\nimport { nodeToBlock } from \"./nodeConversions/nodeToBlock.js\";\nimport { isNodeBlock } from \"./nodeUtil.js\";\n\n/**\n * Change detection utilities for BlockNote.\n *\n * High-level algorithm used by getBlocksChangedByTransaction:\n * 1) Merge appended transactions into one document change.\n * 2) Compute the single range the transaction touched (in both the old and new\n * doc) and only snapshot blocks within it, rather than walking the whole\n * document. getChanges() runs per transaction, so a full-document snapshot\n * made typing in large documents slow: every keystroke re-converted every block.\n * 3) Snapshot blocks before and after within that range (flat map by id, and\n * per-parent child order).\n * 4) Emit inserts/deletes by diffing ids; for shared ids, emit a move (parent\n * changed) or update (block changed, ignoring children).\n * 5) Detect same-parent sibling reorders via an O(n log n) LIS in\n * detectReorderedChildren, marking only items outside the longest ordered\n * subsequence as moved.\n *\n * The range suffices because `changedRange()` spans from the first to the last\n * changed position: any inserted/deleted/moved/updated/reordered block has its\n * relevant positions inside it, and blocks outside are byte-for-byte identical in\n * the same relative order. A moved block's parent contains it, so the parent\n * overlaps the range too (and nodeToBlock converts its full subtree regardless).\n */\n/**\n * Gets the parent block of a node, if it has one.\n */\nfunction getParentBlockId(doc: Node, pos: number): string | undefined {\n if (pos === 0) {\n return undefined;\n }\n const resolvedPos = doc.resolve(pos);\n for (let i = resolvedPos.depth; i > 0; i--) {\n const parent = resolvedPos.node(i);\n if (isNodeBlock(parent)) {\n return getNodeId(parent, doc);\n }\n }\n return undefined;\n}\n\n/**\n * This attributes the changes to a specific source.\n */\nexport type BlockChangeSource =\n | { type: \"local\" }\n | { type: \"paste\" }\n | { type: \"drop\" }\n | { type: \"undo\" | \"redo\" | \"undo-redo\" }\n | { type: \"yjs-remote\" };\n\nexport type BlocksChanged<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> = Array<\n {\n /**\n * The affected block.\n */\n block: Block<BSchema, ISchema, SSchema>;\n /**\n * The source of the change.\n */\n source: BlockChangeSource;\n } & (\n | {\n type: \"insert\" | \"delete\";\n /**\n * Insert and delete changes don't have a previous block.\n */\n prevBlock: undefined;\n }\n | {\n type: \"update\";\n /**\n * The previous block.\n */\n prevBlock: Block<BSchema, ISchema, SSchema>;\n }\n | {\n type: \"move\";\n /**\n * The affected block.\n */\n block: Block<BSchema, ISchema, SSchema>;\n /**\n * The block before the move.\n */\n prevBlock: Block<BSchema, ISchema, SSchema>;\n /**\n * The previous parent block (if it existed).\n */\n prevParent?: Block<BSchema, ISchema, SSchema>;\n /**\n * The current parent block (if it exists).\n */\n currentParent?: Block<BSchema, ISchema, SSchema>;\n }\n )\n>;\n\nfunction determineChangeSource(transaction: Transaction): BlockChangeSource {\n if (transaction.getMeta(\"paste\")) {\n return { type: \"paste\" };\n }\n if (transaction.getMeta(\"uiEvent\") === \"drop\") {\n return { type: \"drop\" };\n }\n if (transaction.getMeta(\"history$\")) {\n return {\n type: transaction.getMeta(\"history$\").redo ? \"redo\" : \"undo\",\n };\n }\n if (transaction.getMeta(\"y-sync$\")) {\n if (transaction.getMeta(\"y-sync$\").isUndoRedoOperation) {\n return { type: \"undo-redo\" };\n }\n return { type: \"yjs-remote\" };\n }\n return { type: \"local\" };\n}\n\ntype BlockSnapshot<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n> = {\n byId: Record<\n string,\n {\n block: Block<BSchema, ISchema, SSchema>;\n parentId: string | undefined;\n }\n >;\n childrenByParent: Record<string, string[]>;\n};\n\n/**\n * Snapshots blocks and per-parent child order for the block nodes overlapping the\n * given range (uses \"__root__\" for the root level). Traversing only the range is\n * what keeps this cheap per keystroke: nodeToBlock runs only for blocks that could\n * have changed.\n */\nfunction collectSnapshot<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n doc: Node,\n range: { from: number; to: number },\n): BlockSnapshot<BSchema, ISchema, SSchema> {\n const ROOT_KEY = \"__root__\";\n const byId: Record<\n string,\n {\n block: Block<BSchema, ISchema, SSchema>;\n parentId: string | undefined;\n }\n > = {};\n const childrenByParent: Record<string, string[]> = {};\n // Clamp to valid positions; nodesBetween throws on out-of-range ones.\n const from = Math.max(0, Math.min(range.from, doc.content.size));\n const to = Math.max(from, Math.min(range.to, doc.content.size));\n // nodesBetween visits every node overlapping [from, to] in document order,\n // including ancestor blocks that contain the range.\n doc.nodesBetween(from, to, (node, pos) => {\n if (!isNodeBlock(node)) {\n return true;\n }\n const parentId = getParentBlockId(doc, pos);\n const key = parentId ?? ROOT_KEY;\n if (!childrenByParent[key]) {\n childrenByParent[key] = [];\n }\n const block = nodeToBlock(node, doc);\n const nodeId = getNodeId(node, doc);\n byId[nodeId] = { block, parentId };\n childrenByParent[key].push(nodeId);\n return true;\n });\n return { byId, childrenByParent };\n}\n\n/**\n * Determines which child ids have been reordered (moved) within the same parent.\n * Uses LIS to keep the longest ordered subsequence and marks the rest as moved.\n */\nfunction detectReorderedChildren(\n prevOrder: string[] | undefined,\n nextOrder: string[] | undefined,\n): Set<string> {\n const moved = new Set<string>();\n if (!prevOrder || !nextOrder) {\n return moved;\n }\n // Consider only ids present in both orders (ignore inserts/deletes handled elsewhere)\n const prevIds = new Set(prevOrder);\n const commonNext: string[] = nextOrder.filter((id) => prevIds.has(id));\n const commonPrev: string[] = prevOrder.filter((id) =>\n commonNext.includes(id),\n );\n\n if (commonPrev.length <= 1 || commonNext.length <= 1) {\n return moved;\n }\n\n // Map ids to their index in previous order\n const indexInPrev: Record<string, number> = {};\n for (let i = 0; i < commonPrev.length; i++) {\n indexInPrev[commonPrev[i]] = i;\n }\n\n // Build sequence of indices representing next order in terms of previous indices\n const sequence: number[] = commonNext.map((id) => indexInPrev[id]);\n\n // Inline O(n log n) LIS with reconstruction.\n // Why LIS? We want the smallest set of siblings to label as \"moved\".\n // Keeping the longest subsequence that is already in order achieves this,\n // so only items outside the LIS are reported as moves.\n const n = sequence.length;\n const tailsValues: number[] = [];\n const tailsEndsAtIndex: number[] = [];\n const previousIndexInLis: number[] = new Array(n).fill(-1);\n\n const lowerBound = (arr: number[], target: number): number => {\n let lo = 0;\n let hi = arr.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (arr[mid] < target) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n return lo;\n };\n\n for (let i = 0; i < n; i++) {\n const value = sequence[i];\n const pos = lowerBound(tailsValues, value);\n if (pos > 0) {\n previousIndexInLis[i] = tailsEndsAtIndex[pos - 1];\n }\n if (pos === tailsValues.length) {\n tailsValues.push(value);\n tailsEndsAtIndex.push(i);\n } else {\n tailsValues[pos] = value;\n tailsEndsAtIndex[pos] = i;\n }\n }\n\n const lisIndexSet = new Set<number>();\n let k = tailsEndsAtIndex[tailsEndsAtIndex.length - 1] ?? -1;\n while (k !== -1) {\n lisIndexSet.add(k);\n k = previousIndexInLis[k];\n }\n\n // Items not part of LIS are considered moved\n for (let i = 0; i < commonNext.length; i++) {\n if (!lisIndexSet.has(i)) {\n moved.add(commonNext[i]);\n }\n }\n return moved;\n}\n\n/**\n * Get the blocks that were changed by a transaction.\n */\nexport function getBlocksChangedByTransaction<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n>(\n transaction: Transaction,\n appendedTransactions: Transaction[] = [],\n): BlocksChanged<BSchema, ISchema, SSchema> {\n const source = determineChangeSource(transaction);\n const combinedTransaction = combineTransactionSteps(transaction.before, [\n transaction,\n ...appendedTransactions,\n ]);\n\n // Changed range in the new doc; null means nothing changed.\n const newRange = getChangedRangeWithAttrs(combinedTransaction);\n if (!newRange) {\n return [];\n }\n // Map it back to old-doc coordinates. The -1/+1 biases expand outwards so that\n // for pure inserts/deletes (collapsed new range) the old range still covers the\n // affected span.\n const invertedMapping = combinedTransaction.mapping.invert();\n const oldRange = {\n from: invertedMapping.map(newRange.from, -1),\n to: invertedMapping.map(newRange.to, 1),\n };\n\n const prevSnap = collectSnapshot<BSchema, ISchema, SSchema>(\n combinedTransaction.before,\n oldRange,\n );\n const nextSnap = collectSnapshot<BSchema, ISchema, SSchema>(\n combinedTransaction.doc,\n newRange,\n );\n\n const changes: BlocksChanged<BSchema, ISchema, SSchema> = [];\n const changedIds = new Set<string>();\n\n // Handle inserted blocks\n Object.keys(nextSnap.byId)\n .filter((id) => !(id in prevSnap.byId))\n .forEach((id) => {\n changes.push({\n type: \"insert\",\n block: nextSnap.byId[id].block,\n source,\n prevBlock: undefined,\n });\n changedIds.add(id);\n });\n\n // Handle deleted blocks\n Object.keys(prevSnap.byId)\n .filter((id) => !(id in nextSnap.byId))\n .forEach((id) => {\n changes.push({\n type: \"delete\",\n block: prevSnap.byId[id].block,\n source,\n prevBlock: undefined,\n });\n changedIds.add(id);\n });\n\n // Handle updated, moved to different parent, indented, outdented blocks\n Object.keys(nextSnap.byId)\n .filter((id) => id in prevSnap.byId)\n .forEach((id) => {\n const prev = prevSnap.byId[id];\n const next = nextSnap.byId[id];\n const isParentDifferent = prev.parentId !== next.parentId;\n\n if (isParentDifferent) {\n changes.push({\n type: \"move\",\n block: next.block,\n prevBlock: prev.block,\n source,\n prevParent: prev.parentId\n ? prevSnap.byId[prev.parentId]?.block\n : undefined,\n currentParent: next.parentId\n ? nextSnap.byId[next.parentId]?.block\n : undefined,\n });\n changedIds.add(id);\n } else if (\n // Compare blocks while ignoring children to avoid reporting a parent\n // update when only descendants changed.\n !deepEqual(\n { ...prev.block, children: undefined } as any,\n { ...next.block, children: undefined } as any,\n )\n ) {\n changes.push({\n type: \"update\",\n block: next.block,\n prevBlock: prev.block,\n source,\n });\n changedIds.add(id);\n }\n });\n\n // Handle sibling reorders (parent unchanged but relative order changed)\n const prevOrderByParent = prevSnap.childrenByParent;\n const nextOrderByParent = nextSnap.childrenByParent;\n\n // Use a special key for root-level siblings\n const ROOT_KEY = \"__root__\";\n const parents = new Set<string>([\n ...Object.keys(prevOrderByParent),\n ...Object.keys(nextOrderByParent),\n ]);\n\n const addedMoveForId = new Set<string>();\n\n parents.forEach((parentKey) => {\n const movedWithinParent = detectReorderedChildren(\n prevOrderByParent[parentKey],\n nextOrderByParent[parentKey],\n );\n if (movedWithinParent.size === 0) {\n return;\n }\n movedWithinParent.forEach((id) => {\n // Only consider ids that exist in both snapshots and whose parent truly did not change\n const prev = prevSnap.byId[id];\n const next = nextSnap.byId[id];\n if (!prev || !next) {\n return;\n }\n if (prev.parentId !== next.parentId) {\n return;\n }\n // Skip if already accounted for by insert/delete/update/parent move\n if (changedIds.has(id)) {\n return;\n }\n // Verify we're addressing the right parent bucket\n const bucketKey = prev.parentId ?? ROOT_KEY;\n if (bucketKey !== parentKey) {\n return;\n }\n if (addedMoveForId.has(id)) {\n return;\n }\n addedMoveForId.add(id);\n changes.push({\n type: \"move\",\n block: next.block,\n prevBlock: prev.block,\n source,\n prevParent: prev.parentId\n ? prevSnap.byId[prev.parentId]?.block\n : undefined,\n currentParent: next.parentId\n ? nextSnap.byId[next.parentId]?.block\n : undefined,\n });\n changedIds.add(id);\n });\n });\n\n return changes;\n}\n","import { Plugin, PluginKey, Transaction } from \"prosemirror-state\";\nimport {\n BlocksChanged,\n getBlocksChangedByTransaction,\n} from \"../../api/getBlocksChangedByTransaction.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\n/**\n * This plugin can filter transactions before they are applied to the editor, but with a higher-level API than `filterTransaction` from prosemirror.\n */\nexport const BlockChangeExtension = createExtension(() => {\n const beforeChangeCallbacks: ((context: {\n getChanges: () => BlocksChanged<any, any, any>;\n tr: Transaction;\n }) => boolean | void)[] = [];\n return {\n key: \"blockChange\",\n prosemirrorPlugins: [\n new Plugin({\n key: new PluginKey(\"blockChange\"),\n filterTransaction: (tr) => {\n let changes:\n | ReturnType<typeof getBlocksChangedByTransaction<any, any, any>>\n | undefined = undefined;\n\n return beforeChangeCallbacks.reduce((acc, cb) => {\n if (acc === false) {\n // We only care that we hit a `false` result, so we can stop iterating.\n return acc;\n }\n return (\n cb({\n getChanges() {\n if (changes) {\n return changes;\n }\n changes = getBlocksChangedByTransaction<any, any, any>(tr);\n return changes;\n },\n tr,\n }) !== false\n );\n }, true);\n },\n }),\n ],\n\n /**\n * Subscribe to the block change events.\n */\n subscribe(\n callback: (context: {\n getChanges: () => BlocksChanged<any, any, any>;\n tr: Transaction;\n }) => boolean | void,\n ) {\n beforeChangeCallbacks.push(callback);\n\n return () => {\n beforeChangeCallbacks.splice(\n beforeChangeCallbacks.indexOf(callback),\n 1,\n );\n };\n },\n } as const;\n});\n","import type { EditorView } from \"prosemirror-view\";\n\n/**\n * The orientation of the drop cursor.\n */\nexport type DropCursorOrientation =\n | \"inline\" // Vertical line within text\n | \"block-horizontal\" // Horizontal line between blocks\n | \"block-vertical-left\" // Vertical line on left edge of block\n | \"block-vertical-right\"; // Vertical line on right edge of block\n\n/**\n * The position and orientation of the drop cursor.\n */\nexport type DropCursorPosition = {\n pos: number; // Document position\n orientation: DropCursorOrientation;\n};\n/**\n * Bounding rectangle in viewport coordinates (e.g. from getBoundingClientRect).\n */\nexport type Rect = {\n left: number;\n right: number;\n top: number;\n bottom: number;\n};\n\n/**\n * Returns true if the element or any ancestor has the given CSS class.\n * Used to skip drop cursor for elements marked with the exclusion class (e.g. drag handles).\n */\nexport function hasExclusionClassname(\n element: Element | null,\n exclude: string,\n): boolean {\n if (!element || !exclude) {\n return false;\n }\n return !!element.closest(`.${exclude}`);\n}\n\n/**\n * Computes the viewport rect for a block-level drop cursor (horizontal line between blocks\n * or vertical line on left/right edge). Returns null for inline positions or when no DOM node exists.\n */\nexport function getBlockDropRect(\n view: EditorView,\n cursorPos: DropCursorPosition,\n width: number,\n scaleX: number,\n scaleY: number,\n): Rect | null {\n const $pos = view.state.doc.resolve(cursorPos.pos);\n const isBlock = !$pos.parent.inlineContent;\n\n if (!isBlock || cursorPos.orientation === \"inline\") {\n return null;\n }\n\n const before = $pos.nodeBefore;\n\n const after = $pos.nodeAfter;\n\n if (!before && !after) {\n return null;\n }\n\n const isVertical =\n cursorPos.orientation === \"block-vertical-left\" ||\n cursorPos.orientation === \"block-vertical-right\";\n // For vertical cursors, position is at the node position, for horizontal cursors, position is at the node before position\n const nodePos = isVertical\n ? cursorPos.pos\n : cursorPos.pos - (before ? before.nodeSize : 0);\n\n const node = view.nodeDOM(nodePos) as HTMLElement | null;\n if (!node) {\n return null;\n }\n\n const nodeRect = node.getBoundingClientRect();\n\n if (isVertical) {\n const halfWidth = (width / 2) * scaleX;\n const left =\n cursorPos.orientation === \"block-vertical-left\"\n ? nodeRect.left\n : nodeRect.right;\n\n return {\n left: left - halfWidth,\n right: left + halfWidth,\n top: nodeRect.top,\n bottom: nodeRect.bottom,\n };\n }\n\n let top = before ? nodeRect.bottom : nodeRect.top;\n if (before && after) {\n top =\n (top +\n (view.nodeDOM(cursorPos.pos) as HTMLElement).getBoundingClientRect()\n .top) /\n 2;\n }\n const halfHeight = (width / 2) * scaleY;\n\n return {\n left: nodeRect.left,\n right: nodeRect.right,\n top: top - halfHeight,\n bottom: top + halfHeight,\n };\n}\n\n/**\n * Computes the viewport rect for an inline drop cursor (vertical line within text).\n */\nexport function getInlineDropRect(\n view: EditorView,\n cursorPos: DropCursorPosition,\n width: number,\n scaleX: number,\n): Rect {\n const coords = view.coordsAtPos(cursorPos.pos);\n const halfWidth = (width / 2) * scaleX;\n\n return {\n left: coords.left - halfWidth,\n right: coords.left + halfWidth,\n top: coords.top,\n bottom: coords.bottom,\n };\n}\n\n/**\n * Applies orientation-specific CSS classes to the drop cursor element so it can be\n * styled correctly (e.g. horizontal vs vertical line, inline vs block).\n */\nexport function applyOrientationClasses(\n el: HTMLElement,\n orientation: DropCursorOrientation,\n) {\n el.classList.toggle(\n \"prosemirror-dropcursor-inline\",\n orientation === \"inline\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block-horizontal\",\n orientation === \"block-horizontal\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block-vertical-left\",\n orientation === \"block-vertical-left\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block-vertical-right\",\n orientation === \"block-vertical-right\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block\",\n orientation === \"block-horizontal\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-vertical\",\n orientation === \"block-vertical-left\" ||\n orientation === \"block-vertical-right\",\n );\n}\n\n/**\n * Returns the offset of the parent element for converting viewport coordinates to\n * parent-relative coordinates. Handles document.body and static positioning.\n */\nexport function getParentOffsets(parent: HTMLElement | null) {\n if (\n !parent ||\n (parent === document.body && getComputedStyle(parent).position === \"static\")\n ) {\n return {\n parentLeft: -window.pageXOffset,\n parentTop: -window.pageYOffset,\n };\n }\n\n const parentRect = parent.getBoundingClientRect();\n const parentScaleX = parentRect.width / parent.offsetWidth;\n const parentScaleY = parentRect.height / parent.offsetHeight;\n\n return {\n parentLeft: parentRect.left - parent.scrollLeft * parentScaleX,\n parentTop: parentRect.top - parent.scrollTop * parentScaleY,\n };\n}\n","import { Fragment, Node } from \"@tiptap/pm/model\";\nimport {\n BlockNoDefaults,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport {\n isLayoutNode,\n isNamedOnly,\n minChildren,\n} from \"../../schema/blocks/children.js\";\nimport { nodeToBlock } from \"./nodeToBlock.js\";\n\nexport function fragmentToBlocks<\n B extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(fragment: Fragment) {\n const blocks: BlockNoDefaults<B, I, S>[] = [];\n\n function visit(node: Node, root: Node) {\n const childrenConfig = node.type.spec.blockConfig?.children;\n const incompleteBlock =\n node.type.name === \"blockContainer\" &&\n node.firstChild?.type.name === \"blockGroup\";\n const flattenLayoutBlock =\n isLayoutNode(node.type) &&\n (!childrenConfig ||\n isNamedOnly(node.type) ||\n node.childCount < minChildren(childrenConfig));\n\n // Open selections and layout blocks that cannot stand alone contribute\n // their children. Complete blocks already include their descendants.\n if (\n incompleteBlock ||\n flattenLayoutBlock ||\n !node.type.isInGroup(\"bnBlock\")\n ) {\n node.forEach((child) => visit(child, flattenLayoutBlock ? root : child));\n } else {\n blocks.push(nodeToBlock(node, root));\n }\n }\n\n fragment.forEach((node) => visit(node, node));\n return blocks;\n}\n","import type { EditorView } from \"prosemirror-view\";\n\nimport { fragmentToBlocks } from \"../../api/nodeConversions/fragmentToBlocks.js\";\nimport { nodeToBlock } from \"../../api/nodeConversions/nodeToBlock.js\";\nimport { getBlockInfoFromNode } from \"../../api/getBlockInfoFromPos.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\n\n/**\n * Where a block drag at `coords` drops, when it is over the content or frame\n * chrome of a block with `meta.dropsIntoChildren`: the start of that block's\n * children, or its end when it has no children yet.\n *\n * @returns `undefined` when the drop goes before or after a block, as usual:\n * for a text drag, over a block's children, over a block without the\n * setting, or over one of the dragged blocks.\n */\nexport function getDropIntoChildren(\n editor: BlockNoteEditor<any, any, any>,\n view: EditorView,\n coords: { left: number; top: number },\n) {\n const slice = view.dragging?.slice;\n // A block drag holds complete blocks (see `SideMenu.onDragStart`).\n if (!slice || slice.openStart > 0) {\n return undefined;\n }\n const draggedBlocks = fragmentToBlocks<any, any, any>(slice.content);\n const pos = view.posAtCoords(coords);\n if (draggedBlocks.length === 0 || !pos || pos.inside < 0) {\n return undefined;\n }\n\n // The innermost block around the pointer. Over its children group (e.g. a\n // gap between two children), the drop goes between them.\n const $inside = view.state.doc.resolve(pos.inside + 1);\n let depth = $inside.depth;\n while (depth > 0 && !$inside.node(depth).type.isInGroup(\"bnBlock\")) {\n if ($inside.node(depth).type.name === \"blockGroup\") {\n return undefined;\n }\n depth--;\n }\n if (depth === 0) {\n return undefined;\n }\n const blockInfo = getBlockInfoFromNode(\n $inside.node(depth),\n $inside.before(depth),\n );\n if (!blockInfo.hasContent) {\n return undefined;\n }\n\n const dropsIntoChildren = editor.schema.blockSpecs[\n blockInfo.blockNoteType\n ]?.implementation.meta.dropsIntoChildren?.(\n nodeToBlock(blockInfo.block.node, view.state.doc),\n );\n if (!dropsIntoChildren) {\n return undefined;\n }\n\n // A block can't be dropped into itself or into one of its descendants.\n const targetId = blockInfo.block.node.attrs.id;\n const containsTarget = (block: {\n id: string;\n children: { id: string; children: any[] }[];\n }): boolean => block.id === targetId || block.children.some(containsTarget);\n if (draggedBlocks.some(containsTarget)) {\n return undefined;\n }\n\n return {\n blockInfo,\n draggedBlocks,\n pos: blockInfo.children\n ? blockInfo.children.childrenStart\n : blockInfo.block.afterPos - 1,\n };\n}\n","import { Plugin, PluginKey } from \"prosemirror-state\";\nimport { dropPoint } from \"prosemirror-transform\";\nimport { Decoration, DecorationSet, type EditorView } from \"prosemirror-view\";\nimport {\n applyOrientationClasses,\n getBlockDropRect,\n getInlineDropRect,\n getParentOffsets,\n hasExclusionClassname,\n type DropCursorPosition,\n} from \"./utils.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\nimport { getDropIntoChildren } from \"./dropIntoChildren.js\";\n\nexport const DRAG_EXCLUSION_CLASSNAME = \"bn-drag-exclude\";\n\n/** The block a drop goes into, as the drop cursor shows it. */\ntype DropInto = { blockId: string; draggedBlocks: any[]; pos: number };\n\n// The state of `dropIntoChildrenPlugin`: the block the drop goes into, if any.\nconst dropIntoKey = new PluginKey<DropInto | undefined>(\"dropInto\");\n\n/**\n * Context passed to the computeDropPosition hook.\n */\nexport interface ComputeDropPositionContext {\n editor: BlockNoteEditor<any, any, any>;\n event: DragEvent;\n view: EditorView;\n defaultPosition: DropCursorPosition | null;\n}\n\n/**\n * Hooks for customizing drop cursor behavior.\n */\nexport interface DropCursorHooks {\n /**\n * Compute cursor position and orientation.\n * Return null to prevent dropping (no cursor shown).\n */\n computeDropPosition?: (\n context: ComputeDropPositionContext,\n ) => DropCursorPosition | null;\n}\n\n/**\n * Options for the DropCursor extension.\n */\nexport interface DropCursorOptions {\n width?: number; // Cursor width in pixels (default: 5)\n color?: string | false; // Cursor color (default: \"#ddeeff\")\n exclude?: string; // CSS class for exclusion (default: \"bn-drag-exclude\")\n hooks?: DropCursorHooks; // Optional behavior hooks\n}\n\n/**\n * Drop cursor visualization based on prosemirror-dropcursor:\n * https://github.com/ProseMirror/prosemirror-dropcursor/blob/master/src/dropcursor.ts\n *\n * Refactored to use BlockNote extension pattern with mount callback and AbortSignal\n * for lifecycle management instead of ProseMirror PluginView.\n */\nexport const DropCursorExtension = createExtension<\n any,\n {\n dropCursor?: DropCursorOptions;\n }\n>(({ editor, options }) => {\n // State\n let cursorPos: DropCursorPosition | null = null;\n let element: HTMLElement | null = null;\n let timeout = -1;\n let dragSourceElement: Element | null = null;\n\n const config = {\n width: options.dropCursor?.width ?? 5,\n color: options.dropCursor?.color ?? \"#ddeeff\",\n exclude: options.dropCursor?.exclude ?? DRAG_EXCLUSION_CLASSNAME,\n hooks: options.dropCursor?.hooks,\n } as const;\n\n // Helper functions\n const setDropInto = (into: DropInto | undefined) => {\n const view = editor.prosemirrorView;\n const current = dropIntoKey.getState(view.state);\n if (current?.blockId === into?.blockId && current?.pos === into?.pos) {\n return;\n }\n view.dispatch(view.state.tr.setMeta(dropIntoKey, { into }));\n };\n\n const setCursor = (pos: DropCursorPosition | null) => {\n if (\n pos?.pos === cursorPos?.pos &&\n pos?.orientation === cursorPos?.orientation\n ) {\n return;\n }\n cursorPos = pos;\n\n if (pos == null) {\n setDropInto(undefined);\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n element = null;\n } else {\n updateOverlay();\n }\n };\n\n const updateOverlay = () => {\n if (!cursorPos) {\n return;\n }\n\n const view = editor.prosemirrorView;\n const editorDOM = view.dom;\n const editorRect = editorDOM.getBoundingClientRect();\n const scaleX = editorRect.width / editorDOM.offsetWidth;\n const scaleY = editorRect.height / editorDOM.offsetHeight;\n\n const blockRect = getBlockDropRect(\n view,\n cursorPos,\n config.width,\n scaleX,\n scaleY,\n );\n const rect =\n blockRect ?? getInlineDropRect(view, cursorPos, config.width, scaleX);\n\n const parent = view.dom.offsetParent as HTMLElement;\n if (!element) {\n element = parent.appendChild(document.createElement(\"div\"));\n element.style.cssText =\n \"position: absolute; z-index: 50; pointer-events: none;\";\n if (config.color) {\n element.style.backgroundColor = config.color;\n }\n }\n\n applyOrientationClasses(element, cursorPos.orientation);\n\n const { parentLeft, parentTop } = getParentOffsets(parent);\n\n element.style.left = (rect.left - parentLeft) / scaleX + \"px\";\n element.style.top = (rect.top - parentTop) / scaleY + \"px\";\n element.style.width = (rect.right - rect.left) / scaleX + \"px\";\n element.style.height = (rect.bottom - rect.top) / scaleY + \"px\";\n };\n\n const scheduleRemoval = (ms: number) => {\n clearTimeout(timeout);\n timeout = window.setTimeout(() => setCursor(null), ms);\n };\n\n // Event handlers\n const onDragStart = (event: Event) => {\n const e = event as DragEvent;\n dragSourceElement = e.target instanceof Element ? e.target : null;\n };\n\n const onDragOver = (event: Event) => {\n const e = event as DragEvent;\n\n // Check if drag source has exclusion classname\n if (\n dragSourceElement &&\n hasExclusionClassname(dragSourceElement, config.exclude)\n ) {\n return;\n }\n\n // Check if drop target has exclusion classname\n if (\n e.target instanceof Element &&\n hasExclusionClassname(e.target, config.exclude)\n ) {\n return;\n }\n\n const view = editor.prosemirrorView;\n if (!view.editable) {\n return;\n }\n\n const pos = view.posAtCoords({\n left: e.clientX,\n top: e.clientY,\n });\n\n const node = pos && pos.inside >= 0 && view.state.doc.nodeAt(pos.inside);\n const disableDropCursor = node && (node.type.spec as any).disableDropCursor;\n const disabled =\n typeof disableDropCursor === \"function\"\n ? disableDropCursor(view, pos, e)\n : disableDropCursor;\n\n if (pos && !disabled) {\n let target = pos.pos;\n if (view.dragging && view.dragging.slice) {\n const point = dropPoint(view.state.doc, target, view.dragging.slice);\n if (point != null) {\n target = point;\n }\n }\n\n // Compute default position. A block dragged onto a block with\n // `meta.dropsIntoChildren` goes to the start of its children.\n const $pos = view.state.doc.resolve(target);\n const isBlock = !$pos.parent.inlineContent;\n const intoChildren = getDropIntoChildren(editor, view, {\n left: e.clientX,\n top: e.clientY,\n });\n const defaultPosition: DropCursorPosition = intoChildren\n ? { pos: intoChildren.pos, orientation: \"block-horizontal\" }\n : { pos: target, orientation: isBlock ? \"block-horizontal\" : \"inline\" };\n\n // Allow hook to override position\n let finalPosition = defaultPosition;\n if (config.hooks?.computeDropPosition) {\n const hookResult = config.hooks.computeDropPosition({\n editor,\n event: e,\n view,\n defaultPosition,\n });\n if (hookResult === null) {\n // Hook returned null - don't show cursor\n setCursor(null);\n return;\n }\n finalPosition = hookResult;\n }\n\n setCursor(finalPosition);\n // The drop goes into the block while the cursor shows the place of its\n // children. A hook may show another place instead (e.g. a new column).\n if (\n intoChildren &&\n finalPosition.pos === intoChildren.pos &&\n finalPosition.orientation === \"block-horizontal\"\n ) {\n const { block } = intoChildren.blockInfo;\n setDropInto({\n blockId: block.node.attrs.id,\n draggedBlocks: intoChildren.draggedBlocks,\n pos: block.beforePos,\n });\n } else {\n setDropInto(undefined);\n }\n scheduleRemoval(5000);\n }\n };\n\n const onDragLeave = (event: Event) => {\n const e = event as DragEvent;\n if (\n !(e.relatedTarget instanceof Node) ||\n !editor.prosemirrorView.dom.contains(e.relatedTarget)\n ) {\n setCursor(null);\n }\n };\n\n const onDrop = () => {\n scheduleRemoval(20);\n };\n\n const onDragEnd = () => {\n scheduleRemoval(20);\n dragSourceElement = null;\n };\n\n // Drops the blocks where the cursor shows them: as the first children of\n // the block it goes into. Other drops are ProseMirror's.\n const dropIntoChildrenPlugin = new Plugin<DropInto | undefined>({\n key: dropIntoKey,\n state: {\n init: () => undefined,\n apply(tr, into) {\n const meta: { into: DropInto | undefined } | undefined =\n tr.getMeta(dropIntoKey);\n if (meta) {\n return meta.into;\n }\n if (!into) {\n return undefined;\n }\n // The block moves with edits made during the drag, e.g. by a\n // collaborator, and the drop no longer goes into it once it's gone.\n const { pos, deletedAfter } = tr.mapping.mapResult(into.pos, 1);\n return deletedAfter ? undefined : { ...into, pos };\n },\n },\n props: {\n // Highlights the block like a selected block. A decoration, as setting\n // the attribute on the block's element directly is a DOM change\n // ProseMirror reads back: it draws the block again, and the browser then\n // drops the drag without a `drop` event.\n decorations(state) {\n const into = dropIntoKey.getState(state);\n const node = into && state.doc.nodeAt(into.pos);\n if (!into || !node) {\n return DecorationSet.empty;\n }\n return DecorationSet.create(state.doc, [\n Decoration.node(into.pos, into.pos + node.nodeSize, {\n \"data-drop-target\": \"true\",\n }),\n ]);\n },\n handleDrop(view, _event, _slice, moved) {\n const into = dropIntoKey.getState(view.state);\n // The drop ends the drag, and with it the highlight.\n setDropInto(undefined);\n // The block may be gone since the last `dragover`, e.g. removed by a\n // collaborator. ProseMirror then drops the blocks as usual.\n if (!into || !editor.getBlock(into.blockId)) {\n return false;\n }\n const { blockId, draggedBlocks } = into;\n editor.transact(() => {\n if (moved) {\n // A drag from another editor leaves its blocks there.\n editor.removeBlocks(\n draggedBlocks.filter((block) => editor.getBlock(block.id)),\n );\n }\n // The dragged blocks never contain the target (see\n // `getDropIntoChildren`), so removing them keeps it.\n const target = editor.getBlock(blockId);\n if (!target) {\n throw new Error(\n \"The drop target was removed with the dragged blocks\",\n );\n }\n if (target.children.length > 0) {\n editor.insertBlocks(draggedBlocks, target.children[0], \"before\");\n } else {\n editor.updateBlock(target, { children: draggedBlocks });\n }\n });\n return true;\n },\n },\n });\n\n return {\n key: \"dropCursor\",\n prosemirrorPlugins: [dropIntoChildrenPlugin],\n mount({ signal, dom, root }) {\n // Track drag source at document level\n root.addEventListener(\"dragstart\", onDragStart, {\n capture: true,\n signal,\n });\n\n // Handle drag events on the editor\n dom.addEventListener(\"dragover\", onDragOver, { signal });\n dom.addEventListener(\"dragleave\", onDragLeave, { signal });\n dom.addEventListener(\"drop\", onDrop, { signal });\n dom.addEventListener(\"dragend\", onDragEnd, { signal });\n\n // Clean up on unmount\n signal.addEventListener(\"abort\", () => {\n clearTimeout(timeout);\n setCursor(null);\n });\n },\n } as const;\n});\n","import { history, redo, undo } from \"@tiptap/pm/history\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const HistoryExtension = createExtension(() => {\n return {\n key: \"history\",\n prosemirrorPlugins: [history()],\n undoCommand: undo,\n redoCommand: redo,\n } as const;\n});\n","import { Plugin, PluginKey, Selection, TextSelection } from \"prosemirror-state\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey(\"inline-content-boundary-edit\");\n\n// Whether a Backspace/Delete at `selection` would remove the entire content\n// range `[content.from, content.to)` of an inline content node.\nfunction emptiesInlineContent(\n selection: Selection,\n key: string,\n content: { from: number; to: number },\n) {\n if (!selection.empty) {\n return selection.from <= content.from && selection.to >= content.to;\n }\n\n const isSingleChar = content.to - content.from === 1;\n\n return key === \"Backspace\"\n ? isSingleChar && selection.from === content.to\n : isSingleChar && selection.from === content.from;\n}\n\n// Fixes editing at the boundary of an empty custom inline content node (i.e. an\n// inline node with editable content, like a mention or inline math).\n//\n// An empty inline node can't hold a text cursor, so ProseMirror can't reconcile\n// edits across the empty boundary from the DOM: typing into an empty node\n// inserts text next to it rather than inside, and deleting the last character\n// leaves an un-reconcilable empty node that corrupts/freezes the editor. Both\n// boundary edits are handled here via transactions so the caret stays inside\n// the node, which is kept alive and editable in its empty state.\n//\n// The cursor is inside such a node exactly when its directly-enclosing node is\n// inline (`inline: true` in the spec) - regular text blocks aren't inline, and\n// atomic inline content can't hold a cursor - so the handling applies to any\n// inline content type without needing to know it by name.\nexport const InlineContentBoundaryEditExtension = createExtension(\n () =>\n ({\n key: \"inlineContentBoundaryEdit\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n props: {\n handleKeyDown: (view, event) => {\n if (!view.editable) {\n return false;\n }\n\n const isTypedChar =\n event.key.length === 1 && !event.ctrlKey && !event.metaKey;\n\n if (\n !isTypedChar &&\n event.key !== \"Backspace\" &&\n event.key !== \"Delete\"\n ) {\n return false;\n }\n\n const { selection } = view.state;\n const node = selection.$from.node();\n if (!node.type.spec.inline) {\n return false;\n }\n\n const pos = selection.$from.before();\n const contentFrom = pos + 1;\n const contentTo = pos + 1 + node.content.size;\n\n // Empty content: redirect the typed character into the node.\n if (isTypedChar && node.content.size === 0) {\n const tr = view.state.tr.insert(\n contentFrom,\n view.state.schema.text(event.key),\n );\n tr.setSelection(\n TextSelection.create(tr.doc, contentFrom + event.key.length),\n );\n view.dispatch(tr);\n\n return true;\n }\n\n // Backspace/Delete that would empty the content: delete it all in\n // one transaction, keeping the now-empty node (and the caret\n // inside it) so it stays editable.\n if (\n node.content.size > 0 &&\n emptiesInlineContent(selection, event.key, {\n from: contentFrom,\n to: contentTo,\n })\n ) {\n const tr = view.state.tr.delete(contentFrom, contentTo);\n tr.setSelection(TextSelection.create(tr.doc, contentFrom));\n view.dispatch(tr);\n\n return true;\n }\n\n return false;\n },\n },\n }),\n ],\n }) as const,\n);\n","import { posToDOMRect } from \"@tiptap/core\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const LinkToolbarExtension = createExtension(({ editor }) => {\n function getLinkElementAtPos(pos: number) {\n let currentNode = editor.prosemirrorView.nodeDOM(pos);\n while (currentNode && currentNode.parentElement) {\n if (currentNode.nodeName === \"A\") {\n return currentNode as HTMLAnchorElement;\n }\n currentNode = currentNode.parentElement;\n }\n return null;\n }\n\n function getLinkAtPos(pos: number) {\n const linkData = editor.getLinkMarkAtPos(pos);\n if (!linkData) {\n return undefined;\n }\n\n return {\n range: { from: linkData.from, to: linkData.to },\n // Expose mark-like attrs for backward compat with React LinkToolbarController\n mark: { attrs: { href: linkData.href } },\n get text() {\n return linkData.text;\n },\n get position() {\n return posToDOMRect(\n editor.prosemirrorView,\n linkData.from,\n linkData.to,\n ).toJSON() as DOMRect;\n },\n };\n }\n\n function getLinkAtSelection() {\n return editor.transact((tr) => {\n if (!tr.selection.empty) {\n return undefined;\n }\n return getLinkAtPos(tr.selection.anchor);\n });\n }\n\n return {\n key: \"linkToolbar\",\n\n getLinkAtSelection,\n getLinkElementAtPos,\n getMarkAtPos(pos: number, _markType: string) {\n return getLinkAtPos(pos);\n },\n\n getLinkAtElement(element: HTMLElement) {\n return editor.transact(() => {\n const posAtElement = editor.prosemirrorView.posAtDOM(element, 0) + 1;\n return getLinkAtPos(posAtElement);\n });\n },\n\n editLink(\n url: string,\n text: string,\n position = editor.transact((tr) => tr.selection.anchor),\n ) {\n editor.editLink(url, text, position);\n },\n\n deleteLink(position = editor.transact((tr) => tr.selection.anchor)) {\n editor.deleteLink(position);\n },\n } as const;\n});\n","export const VALID_LINK_PROTOCOLS = [\n \"http\",\n \"https\",\n \"ftp\",\n \"ftps\",\n \"mailto\",\n \"tel\",\n \"callto\",\n \"sms\",\n \"cid\",\n \"xmpp\",\n];\nexport const DEFAULT_LINK_PROTOCOL = \"https\";\n","import {\n NodeSelection,\n Plugin,\n PluginKey,\n Selection,\n TextSelection,\n} from \"prosemirror-state\";\nimport {\n createExtension,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey(\"node-selection-keyboard\");\n// By default, typing with a node selection active will cause ProseMirror to\n// replace the node with one that contains editable content. This plugin blocks\n// this behaviour without also blocking things like keyboard shortcuts:\n//\n// - Lets through key presses that do not include alphanumeric characters. This\n// includes things like backspace/delete/home/end/etc.\n// - Lets through any key presses that include ctrl/meta keys. These will be\n// shortcuts of some kind like ctrl+C/mod+C.\n// - Special case for Enter key which creates a new paragraph block below and\n// sets the selection to it. This is just to bring the UX closer to Notion\n//\n// While a more elegant solution would probably process transactions instead of\n// keystrokes, this brings us most of the way to Notion's UX without much added\n// complexity.\nexport const NodeSelectionKeyboardExtension = createExtension(\n ({ editor }: ExtensionOptions) =>\n ({\n key: \"nodeSelectionKeyboard\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n props: {\n handleKeyDown: (view, event) => {\n // Checks for node selection\n const { selection } = view.state;\n if (selection instanceof NodeSelection) {\n // Checks if key press uses ctrl/meta modifier\n if (event.ctrlKey || event.metaKey) {\n return false;\n }\n // Make room to type below a contentless block at the document\n // end, while preserving gap cursors everywhere else.\n if (\n event.key === \"ArrowDown\" &&\n !event.shiftKey &&\n !event.altKey &&\n !event.isComposing &&\n !selection.node.isInline &&\n selection.eq(Selection.atEnd(view.state.doc))\n ) {\n const { block } = editor.getTextCursorPosition();\n if (\n editor.schema.blockSchema[block.type].content === \"none\"\n ) {\n editor.transact((tr) => {\n const [paragraph] = editor.insertBlocks(\n [{ type: \"paragraph\" }],\n block,\n \"after\",\n );\n editor.setTextCursorPosition(paragraph, \"start\");\n tr.scrollIntoView();\n });\n event.preventDefault();\n return true;\n }\n }\n // Checks if key press is alphanumeric\n if (event.key.length === 1) {\n event.preventDefault();\n\n return true;\n }\n // Checks if key press is Enter\n if (\n event.key === \"Enter\" &&\n !event.isComposing &&\n !event.shiftKey &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey\n ) {\n const tr = view.state.tr;\n view.dispatch(\n tr\n .insert(\n view.state.tr.selection.$to.after(),\n view.state.schema.nodes[\"paragraph\"].createChecked(),\n )\n .setSelection(\n new TextSelection(\n tr.doc.resolve(\n view.state.tr.selection.$to.after() + 1,\n ),\n ),\n ),\n );\n\n return true;\n }\n }\n\n return false;\n },\n },\n }),\n ],\n }) as const,\n);\n","import { Plugin, PluginKey } from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport { uuidv4 } from \"lib0/random\";\n\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { BlockNoteEditorOptions } from \"../../editor/BlockNoteEditor.js\";\n\nconst PLUGIN_KEY = new PluginKey(`blocknote-placeholder`);\n\nexport const PlaceholderExtension = createExtension(\n ({\n editor,\n options,\n }: ExtensionOptions<\n Pick<BlockNoteEditorOptions<any, any, any>, \"placeholders\">\n >) => {\n const placeholders = options.placeholders;\n const uniqueEditorSelector = `placeholder-selector-${uuidv4()}`;\n return {\n key: \"placeholder\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n view: (view) => {\n const styleEl = document.createElement(\"style\");\n\n const nonce = editor._tiptapEditor.options.injectNonce;\n if (nonce) {\n styleEl.setAttribute(\"nonce\", nonce);\n }\n\n if (view.root instanceof window.ShadowRoot) {\n view.root.append(styleEl);\n } else {\n view.root.head.appendChild(styleEl);\n }\n\n const styleSheet = styleEl.sheet!;\n\n const getSelector = (additionalSelectors = \"\") =>\n `.${uniqueEditorSelector} .bn-block-content${additionalSelectors}:has(.ProseMirror-trailingBreak:only-child):after`;\n\n try {\n // FIXME: the names \"default\" and \"emptyDocument\" are hardcoded\n const {\n default: defaultPlaceholder,\n emptyDocument: emptyPlaceholder,\n ...rest\n } = placeholders || {};\n\n // add block specific placeholders\n for (const [blockType, placeholder] of Object.entries(rest)) {\n const blockTypeSelector = `[data-content-type=\"${blockType}\"]`;\n\n styleSheet.insertRule(\n `${getSelector(blockTypeSelector)} { content: ${JSON.stringify(\n placeholder,\n )}; }`,\n );\n }\n\n const onlyBlockSelector = `[data-is-only-empty-block]`;\n const mustBeFocusedSelector = `[data-is-empty-and-focused]`;\n\n // placeholder for when there's only one empty block\n styleSheet.insertRule(\n `${getSelector(onlyBlockSelector)} { content: ${JSON.stringify(\n emptyPlaceholder,\n )}; }`,\n );\n\n // placeholder for default blocks, only when the cursor is in the block (mustBeFocused)\n styleSheet.insertRule(\n `${getSelector(mustBeFocusedSelector)} { content: ${JSON.stringify(\n defaultPlaceholder,\n )}; }`,\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n `Failed to insert placeholder CSS rule - this is likely due to the browser not supporting certain CSS pseudo-element selectors (:has, :only-child:, or :before)`,\n e,\n );\n }\n\n return {\n destroy: () => {\n // `remove()` is a no-op if something else (e.g. a router\n // merging `<head>`) already detached the element.\n styleEl.remove();\n },\n };\n },\n props: {\n // Set through ProseMirror, not on `view.dom` directly: ProseMirror\n // observes the editor element, and flushes a change made outside\n // it later, which can outlive the editor.\n attributes: { class: uniqueEditorSelector },\n decorations: (state) => {\n const { doc, selection } = state;\n\n if (!editor.isEditable) {\n return;\n }\n\n if (!selection.empty) {\n return;\n }\n\n // Don't show placeholder when the cursor is inside a code block\n if (selection.$from.parent.type.spec.code) {\n return;\n }\n\n const decs = [];\n\n // decoration for when there's only one empty block\n // positions are hardcoded for now\n if (state.doc.content.size === 6) {\n decs.push(\n Decoration.node(2, 4, {\n \"data-is-only-empty-block\": \"true\",\n }),\n );\n }\n\n const $pos = selection.$anchor;\n const node = $pos.parent;\n\n if (node.content.size === 0) {\n const before = $pos.before();\n\n decs.push(\n Decoration.node(before, before + node.nodeSize, {\n \"data-is-empty-and-focused\": \"true\",\n }),\n );\n }\n\n return DecorationSet.create(doc, decs);\n },\n },\n }),\n ],\n } as const;\n },\n);\n","import { Mapping } from \"prosemirror-transform\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const PositionMappingExtension = createExtension(({ editor }) => {\n /**\n * The mapping object which holds the position mapping across changes.\n */\n let mapping = new Mapping();\n /**\n * The number of live `mapPosition` closures.\n */\n let numInstances = 0;\n\n function reset() {\n mapping = new Mapping();\n numInstances = 0;\n }\n\n // FinalizationRegistry is kept as a non-deterministic fallback for\n // individual closure cleanup during the editor's lifetime.\n const registry =\n typeof FinalizationRegistry !== \"undefined\"\n ? new FinalizationRegistry(() => {\n numInstances--;\n if (numInstances === 0) {\n reset();\n }\n })\n : null;\n\n editor.on(\"create\", () => {\n editor._tiptapEditor.on(\"transaction\", ({ transaction }) => {\n if (numInstances === 0) {\n return;\n }\n mapping.appendMapping(transaction.mapping);\n });\n\n // Deterministic cleanup: when the editor is destroyed, reset state so\n // mapping.maps does not grow unbounded across editor lifecycles.\n editor._tiptapEditor.on(\"destroy\", () => {\n reset();\n });\n });\n\n return {\n key: \"positionMapping\",\n mapPosition: (position: number, side: \"left\" | \"right\" = \"left\") => {\n numInstances++;\n const trackedMapLength = mapping.maps.length;\n\n const getMappedPosition = () => {\n return (\n mapping\n // Only read the history of the mapping that we care about\n .slice(trackedMapLength)\n .map(position, side === \"left\" ? -1 : 1)\n );\n };\n\n if (registry) {\n registry.register(getMappedPosition, undefined);\n }\n\n return getMappedPosition;\n },\n } as const;\n});\n","import { findChildrenInRange } from \"@tiptap/core\";\nimport { Plugin, PluginKey } from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport { getNodeId } from \"../../api/getBlockInfoFromPos.js\";\nimport { getChangedRangeWithAttrs } from \"../../api/getChangedRangeWithAttrs.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey(`previous-blocks`);\n\nconst nodeAttributes: Record<string, string> = {\n // Numbered List Items\n index: \"index\",\n // Headings\n level: \"level\",\n // All Blocks\n type: \"type\",\n depth: \"depth\",\n \"depth-change\": \"depth-change\",\n};\n\n/**\n * This plugin tracks transformation of Block node attributes, so we can support CSS transitions.\n *\n * Problem it solves: ProseMirror recreates the DOM when transactions happen. So when a transaction changes a Node attribute,\n * it results in a completely new DOM element. This means CSS transitions don't work.\n *\n * Solution: When attributes change on a node, this plugin sets a data-* attribute with the \"previous\" value. This way we can still use CSS transitions. (See block.module.css)\n */\nexport const PreviousBlockTypeExtension = createExtension(() => {\n let timeout: ReturnType<typeof setTimeout>;\n // Until the view exists, nothing is on screen to animate from.\n let hasView = false;\n return {\n key: \"previousBlockType\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n view(_editorView) {\n hasView = true;\n return {\n update: async (view, _prevState) => {\n if (this.key?.getState(view.state).updatedBlocks.size > 0) {\n // use setTimeout 0 to clear the decorations so that at least\n // for one DOM-render the decorations have been applied\n timeout = setTimeout(() => {\n view.dispatch(\n view.state.tr.setMeta(PLUGIN_KEY, { clearUpdate: true }),\n );\n }, 0);\n }\n },\n destroy: () => {\n hasView = false;\n if (timeout) {\n clearTimeout(timeout);\n }\n },\n };\n },\n state: {\n init() {\n return {\n // Block attributes, by block ID, from just before the previous transaction.\n prevTransactionOldBlockAttrs: {} as any,\n // Block attributes, by block ID, from just before the current transaction.\n currentTransactionOldBlockAttrs: {} as any,\n // Set of IDs of blocks whose attributes changed from the current transaction.\n updatedBlocks: new Set<string>(),\n };\n },\n\n apply(transaction, prev, oldState, newState) {\n prev.currentTransactionOldBlockAttrs = {};\n prev.updatedBlocks.clear();\n\n if (!transaction.docChanged || !hasView) {\n return prev;\n }\n\n // Only check nodes in the changed range, not the whole document.\n // getChangedRangeWithAttrs() also covers attribute-only steps (AttrStep), so a\n // block whose `level`/`index` changes with no content edit is caught.\n const newRange = getChangedRangeWithAttrs(transaction);\n if (!newRange) {\n return prev;\n }\n\n // Map the new-doc range back to old-doc coordinates\n const invertedMapping = transaction.mapping.invert();\n const oldRange = {\n from: invertedMapping.map(newRange.from, -1),\n to: invertedMapping.map(newRange.to, 1),\n };\n\n const currentTransactionOriginalOldBlockAttrs = {} as any;\n\n const oldNodes = findChildrenInRange(\n oldState.doc,\n oldRange,\n (node) => node.attrs.id,\n );\n const oldNodesById = new Map(\n oldNodes.map((node) => [\n getNodeId(node.node, oldState.doc),\n node,\n ]),\n );\n const newNodes = findChildrenInRange(\n newState.doc,\n newRange,\n (node) => node.attrs.id,\n );\n\n for (const node of newNodes) {\n const nodeId = getNodeId(node.node, newState.doc);\n const oldNode = oldNodesById.get(nodeId);\n\n const oldContentNode = oldNode?.node.firstChild;\n const newContentNode = node.node.firstChild;\n\n if (oldNode && oldContentNode && newContentNode) {\n const newAttrs = {\n index: newContentNode.attrs.index,\n level: newContentNode.attrs.level,\n type: newContentNode.type.name,\n depth: newState.doc.resolve(node.pos).depth,\n };\n\n const oldAttrs = {\n index: oldContentNode.attrs.index,\n level: oldContentNode.attrs.level,\n type: oldContentNode.type.name,\n depth: oldState.doc.resolve(oldNode.pos).depth,\n };\n\n currentTransactionOriginalOldBlockAttrs[nodeId] = oldAttrs;\n\n prev.currentTransactionOldBlockAttrs[nodeId] = oldAttrs;\n\n if (\n oldAttrs.index !== newAttrs.index ||\n oldAttrs.level !== newAttrs.level ||\n oldAttrs.type !== newAttrs.type ||\n oldAttrs.depth !== newAttrs.depth\n ) {\n (oldAttrs as any)[\"depth-change\"] =\n oldAttrs.depth - newAttrs.depth;\n\n prev.updatedBlocks.add(nodeId);\n }\n }\n }\n\n prev.prevTransactionOldBlockAttrs =\n currentTransactionOriginalOldBlockAttrs;\n\n return prev;\n },\n },\n props: {\n decorations(state) {\n const pluginState = (this as Plugin).getState(state);\n if (pluginState.updatedBlocks.size === 0) {\n return undefined;\n }\n\n const decorations: Decoration[] = [];\n\n state.doc.descendants((node, pos) => {\n if (!node.attrs.id) {\n return;\n }\n\n const id = getNodeId(node, state.doc);\n\n if (!pluginState.updatedBlocks.has(id)) {\n return;\n }\n\n const prevAttrs = pluginState.currentTransactionOldBlockAttrs[id];\n const decorationAttrs: any = {};\n\n for (const [nodeAttr, val] of Object.entries(prevAttrs)) {\n decorationAttrs[\"data-prev-\" + nodeAttributes[nodeAttr]] =\n val || \"none\";\n }\n\n decorations.push(\n Decoration.node(pos, pos + node.nodeSize, {\n ...decorationAttrs,\n }),\n );\n });\n\n return DecorationSet.create(state.doc, decorations);\n },\n },\n }),\n ],\n } as const;\n});\n","import { Plugin, PluginKey } from \"prosemirror-state\";\nimport {\n createExtension,\n createStore,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey(\"bn-read-only\");\n\n/** Owns application editability and independent feature restrictions. */\nexport const ReadOnlyExtension = createExtension(\n ({\n editor,\n options,\n }: ExtensionOptions<{ editable?: boolean } | undefined>) => {\n const store = createStore(\n {\n isEditable: options?.editable ?? true,\n enabledSet: new Set<string>(),\n },\n {\n onUpdate(state, prevState) {\n if (\n (state.isEditable && state.enabledSet.size === 0) ===\n (prevState.isEditable && prevState.enabledSet.size === 0)\n ) {\n return;\n }\n if (!editor.headless) {\n // Recompute plugin editability and notify UI subscribers without a\n // document change. Reuse any transaction already in progress.\n editor.transact((tr) => tr.setMeta(\"editable\", true));\n }\n },\n },\n );\n\n return {\n key: \"readOnly\",\n store,\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n props: {\n editable: () =>\n store.state.isEditable && store.state.enabledSet.size === 0,\n },\n }),\n ],\n /** Set the application's preference without releasing feature restrictions. */\n setEditable(editable: boolean) {\n if (store.state.isEditable === editable) {\n return;\n }\n store.setState({ ...store.state, isEditable: editable });\n },\n /**\n * Enable or disable read-only mode for a feature identified by key.\n * Passing false releases only that feature's restriction; other features\n * and the application's editor.isEditable setting still apply.\n * Repeated calls with the same key are idempotent.\n */\n setReadOnly(readOnly: boolean, key: string) {\n store.setState({\n ...store.state,\n enabledSet: readOnly\n ? new Set([...store.state.enabledSet, key])\n : new Set([...store.state.enabledSet].filter((k) => k !== key)),\n });\n },\n } as const;\n },\n);\n","import { BLOCK_SELECTOR, getDirectChildBlocks } from \"../blockDOM.js\";\n\nexport type BlockRect = {\n top: number;\n bottom: number;\n left: number;\n right: number;\n};\n\n// X-match wins over y-only match (disambiguates side-by-side children).\nexport function rectIndexAtCursor(\n rects: BlockRect[],\n mousePos: { x: number; y: number },\n): number | undefined {\n let verticalMatch: number | undefined = undefined;\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i];\n if (mousePos.y < rect.top || mousePos.y > rect.bottom) {\n continue;\n }\n if (mousePos.x >= rect.left && mousePos.x <= rect.right) {\n return i;\n }\n verticalMatch = verticalMatch ?? i;\n }\n return verticalMatch;\n}\n\n/**\n * Returns the deepest block at the height of the pointer, from a block that\n * contains it: the block itself, or one of its descendants at that height.\n * The children of a block are below its own content (nested blocks) or fill\n * it (a container), so the pointer on the block's own content stays on the\n * block. The pointer in the indentation of nested blocks, or in the padding\n * of a container beside a child, goes to the child at that height.\n */\nexport function getNestedBlockAtCursor(\n element: Element,\n mousePos: { x: number; y: number },\n): Element {\n while (element.matches(BLOCK_SELECTOR)) {\n const children = getDirectChildBlocks(element);\n const index = rectIndexAtCursor(\n children.map((child) => child.getBoundingClientRect()),\n mousePos,\n );\n if (index === undefined) {\n break;\n }\n element = children[index];\n }\n return element;\n}\n","import { EditorView } from \"@tiptap/pm/view\";\n\nimport { getBlockElement, getDraggableBlockFromElement } from \"../blockDOM.js\";\nimport { getNestedBlockAtCursor } from \"./blockGeometry.js\";\n\nexport type Point = { x: number; y: number };\n\nexport type Rect = { left: number; top: number; right: number; bottom: number };\n\nexport type HoveredBlock = { node: HTMLElement; id: string };\n\n/**\n * How far inside the edge of the blocks the probe point goes. A probe exactly\n * on an edge can hit the element next to it.\n */\nconst PROBE_INSET = 10;\n\nfunction clamp(value: number, min: number, max: number) {\n return Math.min(Math.max(value, min), max);\n}\n\n/** Returns the block of this editor at a visible point, if there is one. */\nfunction getBlockAtPoint(view: EditorView, point: Point) {\n for (const element of view.root.elementsFromPoint(point.x, point.y)) {\n // Skips UI painted over the blocks (e.g. a toolbar), and the blocks of an\n // editor nested in one of ours: looks below them.\n const block = getBlockElement(element, view);\n if (block) {\n return block;\n }\n }\n return undefined;\n}\n\n/**\n * Finds the block at the height of the pointer, when the pointer is not on\n * the content of a block (it is in padding, in an indentation or in the\n * gutter).\n *\n * The function probes once: it finds the element at a point on the same line\n * as the pointer, just inside the edge of the blocks, with\n * `elementsFromPoint`. This point is next to the pointer, so it is visible\n * when the pointer is. The probe can find a parent instead of the block on\n * the line (e.g. left of a nested block, the element is the parent). Thus the\n * function then goes down into the children of the found block, by their\n * boxes, to the deepest block at the pointer's height.\n */\nfunction probeBlockAtHeight(\n view: EditorView,\n pointer: Point,\n): Element | undefined {\n const blocks = view.dom.firstElementChild?.getBoundingClientRect();\n if (!blocks || pointer.y < blocks.top || pointer.y > blocks.bottom) {\n return undefined;\n }\n const inset = Math.min(PROBE_INSET, blocks.width / 2);\n const reference = getBlockAtPoint(view, {\n x: clamp(pointer.x, blocks.left + inset, blocks.right - inset),\n y: pointer.y,\n });\n return reference ? getNestedBlockAtCursor(reference, pointer) : undefined;\n}\n\nexport type HoverResolution =\n /** The pointer is over this block (directly, or at its height). */\n | { kind: \"block\"; block: HoveredBlock }\n /** The pointer is over UI that belongs to this editor; keep the menu as is. */\n | { kind: \"editorUI\" }\n /** The pointer is not over this editor's blocks. */\n | { kind: \"none\" };\n\n/**\n * Which of this editor's blocks the pointer is about, from the topmost element\n * under the pointer (the event target).\n */\nexport function resolveHoveredBlock(\n view: EditorView,\n target: Element | null,\n pointer: Point,\n /** Whether blocks of this type get a drag handle. */\n isDraggable: (type: string) => boolean,\n /** Whether the element is UI that belongs to this editor (a toolbar, a menu). */\n isWithinEditorUI: (element: Element) => boolean,\n /** How far left or right of the editor element the pointer still counts (px). */\n hoverMargin: number,\n): HoverResolution {\n // Resolve layout before applying drag policy: columns have no handle, but\n // their children do, and their gutter still needs to resolve those children.\n function draggable(block: Element | undefined): HoverResolution {\n const resolved = block\n ? getDraggableBlockFromElement(block, view, isDraggable)\n : undefined;\n return resolved ? { kind: \"block\", block: resolved } : { kind: \"none\" };\n }\n\n if (target && view.dom.contains(target)) {\n // Embedded editors own their blocks, even though their DOM is inside ours.\n if (target.closest(\".bn-editor\") !== view.dom) {\n return { kind: \"none\" };\n }\n // Over a block (its content, its indentation, a container's padding):\n // the deepest block at the pointer's height. Over the editor's own\n // padding: no block is known yet, so probe for the one on the line.\n const block = getBlockElement(target, view);\n return draggable(\n block\n ? getNestedBlockAtCursor(block, pointer)\n : probeBlockAtHeight(view, pointer),\n );\n }\n\n if (target && isWithinEditorUI(target)) {\n // A toolbar, a menu, the side menu itself, or the editor's wrapper: the\n // block under that UI is not what the pointer is about.\n return { kind: \"editorUI\" };\n }\n\n const editorRect = view.dom.getBoundingClientRect();\n\n // Something else is painted over the editor (e.g. another editor in an\n // overlay).\n if (\n pointer.x >= editorRect.left &&\n pointer.x <= editorRect.right &&\n pointer.y >= editorRect.top &&\n pointer.y <= editorRect.bottom\n ) {\n return { kind: \"none\" };\n }\n\n // Beside the editor element (left or right of it, level with its blocks):\n // only within `hoverMargin`, and not over another editor. Above or below\n // it, no block is at the pointer's height. The gutter where the menu sits\n // is the editor's own padding, handled above.\n const besideEditor =\n pointer.y >= editorRect.top &&\n pointer.y <= editorRect.bottom &&\n Math.max(editorRect.left - pointer.x, pointer.x - editorRect.right) <=\n hoverMargin;\n if (besideEditor && !target?.closest(\".bn-editor\")) {\n return draggable(probeBlockAtHeight(view, pointer));\n }\n return { kind: \"none\" };\n}\n\n/**\n * How far (in px) outside the intent hull the pointer may stray. A steep exit\n * from a block's corner towards its menu otherwise starts just outside the\n * hull's thin tip.\n */\nconst INTENT_BUFFER = 3;\n\n/** The z component of (a - o) × (b - o): its sign says which side of o→a b is. */\nfunction cross(o: Point, a: Point, b: Point) {\n return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n\n/** Whether a point is inside the convex polygon (vertices in either order). */\nfunction isInConvexPolygon(point: Point, polygon: Point[]): boolean {\n let sign = 0;\n for (let i = 0; i < polygon.length; i++) {\n const side = Math.sign(\n cross(polygon[i], polygon[(i + 1) % polygon.length], point),\n );\n if (side === 0) {\n continue;\n }\n if (sign === 0) {\n sign = side;\n } else if (side !== sign) {\n return false;\n }\n }\n return true;\n}\n\nfunction distanceToSegment(point: Point, a: Point, b: Point): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lengthSquared = dx * dx + dy * dy;\n const t =\n lengthSquared === 0\n ? 0\n : clamp(\n ((point.x - a.x) * dx + (point.y - a.y) * dy) / lengthSquared,\n 0,\n 1,\n );\n return Math.hypot(point.x - (a.x + t * dx), point.y - (a.y + t * dy));\n}\n\n/** The distance from the point to the rect (0 when it is inside). */\nexport function distanceToRect(point: Point, rect: Rect): number {\n return Math.hypot(\n point.x - clamp(point.x, rect.left, rect.right),\n point.y - clamp(point.y, rect.top, rect.bottom),\n );\n}\n\n/**\n * Convex hull of a small point set, with Andrew's monotone chain algorithm\n * (https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain).\n */\nfunction convexHull(points: Point[]): Point[] {\n const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n const lower: Point[] = [];\n for (const p of sorted) {\n while (\n lower.length >= 2 &&\n cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0\n ) {\n lower.pop();\n }\n lower.push(p);\n }\n const upper: Point[] = [];\n for (const p of [...sorted].reverse()) {\n while (\n upper.length >= 2 &&\n cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0\n ) {\n upper.pop();\n }\n upper.push(p);\n }\n lower.pop();\n upper.pop();\n return lower.concat(upper);\n}\n\n/**\n * Whether the pointer is on its way from the exit point to the menu: inside\n * the \"triangle\" spanned by the exit point and the menu's rect (the convex\n * hull of the point and the rect's corners), or within {@link INTENT_BUFFER}\n * of it, and closer to the menu than the exit point. The latter keeps the\n * buffer around the exit point from holding on to a block the pointer leaves\n * in another direction, e.g. down onto the next block.\n *\n * Similar to Floating UI's `safePolygon`\n * (https://floating-ui.com/docs/useHover#safepolygon), with two differences:\n * the hull covers the way to the menu whatever side the menu is on, and the\n * intent ends when the pointer rests (`INTENT_TIMEOUT` in `SideMenu.ts`)\n * rather than when it slows down, as people slow down when aiming at the\n * menu's small buttons.\n */\nexport function isHeadingToMenu(\n pointer: Point,\n exit: Point,\n menu: Rect,\n): boolean {\n if (distanceToRect(pointer, menu) >= distanceToRect(exit, menu)) {\n return false;\n }\n const hull = convexHull([\n exit,\n { x: menu.left, y: menu.top },\n { x: menu.right, y: menu.top },\n { x: menu.right, y: menu.bottom },\n { x: menu.left, y: menu.bottom },\n ]);\n if (hull.length >= 3 && isInConvexPolygon(pointer, hull)) {\n return true;\n }\n // Also covers a degenerate hull (a zero-size menu).\n return hull.some(\n (vertex, i) =>\n distanceToSegment(pointer, vertex, hull[(i + 1) % hull.length]) <=\n INTENT_BUFFER,\n );\n}\n","import { DOMParser, Slice } from \"@tiptap/pm/model\";\nimport { TextSelection } from \"@tiptap/pm/state\";\nimport { EditorView } from \"@tiptap/pm/view\";\n\nimport { distanceToRect } from \"./sideMenuHover.js\";\n\n/** Marks events we dispatch ourselves, so the handlers ignore them. */\ntype SyntheticEvent = Event & { synthetic?: boolean };\n\nfunction isSynthetic(event: Event): boolean {\n return (event as SyntheticEvent).synthetic === true;\n}\n\n/**\n * Finds the editor that a drag event is about, and the distance from the\n * event to the blocks of that editor. If the event target is in an editor,\n * that editor is the only candidate: where editors overlap, it is the editor\n * on top. Otherwise, the candidates are the editors within `dropMargin` of the\n * event, and it is the one closest to the event.\n *\n * `dropMargin` counts from the editor element, like `hoverMargin`. The\n * distance that picks the closest editor counts to its blocks: the drop lands\n * at the nearest block position, so with uneven editor padding, the editor\n * whose blocks are nearest is the right pick. A drop outside the blocks, even\n * in the editor's padding, is moved onto them.\n */\nfunction findDropEditor(\n view: EditorView,\n event: DragEvent,\n dropMargin: number,\n) {\n const point = { x: event.clientX, y: event.clientY };\n const target =\n event.target instanceof Element ? event.target.closest(\".bn-editor\") : null;\n const editors = target\n ? [target]\n : Array.from(view.root.querySelectorAll(\".bn-editor\")).filter(\n (editor) =>\n distanceToRect(point, editor.getBoundingClientRect()) <= dropMargin,\n );\n const coords = event;\n\n if (editors.length === 0) {\n return null;\n }\n\n let closestEditor = editors[0];\n let minDistance = Number.MAX_VALUE;\n\n for (const editor of editors) {\n const rect = editor\n .querySelector(\".bn-block-group\")!\n .getBoundingClientRect();\n\n const distanceX =\n coords.clientX < rect.left\n ? rect.left - coords.clientX\n : coords.clientX > rect.right\n ? coords.clientX - rect.right\n : 0;\n\n const distanceY =\n coords.clientY < rect.top\n ? rect.top - coords.clientY\n : coords.clientY > rect.bottom\n ? coords.clientY - rect.bottom\n : 0;\n\n const distance = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));\n\n if (distance < minDistance) {\n minDistance = distance;\n closestEditor = editor;\n }\n }\n\n return { element: closestEditor, distance: minDistance };\n}\n\n/**\n * Drag & drop between blocks and between editors. Moved from the\n * former `SideMenuView` class into listeners bound to the extension's mount\n * signal. It changes two things: where\n * editors overlap, the editor under the drag event wins (see\n * `findDropEditor`), and the drag data is parsed in an inert document. `isDragOrigin` reports whether a side menu drag started in this\n * editor. A drop outside every editor but within `dropMargin` (px) of this\n * one goes into this editor.\n */\nexport function registerBlockDropHandlers(\n view: EditorView,\n isDragOrigin: () => boolean,\n dropMargin: number,\n signal: AbortSignal,\n) {\n function isBlockNoteDrag(event: DragEvent) {\n return (\n view.dragging !== null ||\n isDragOrigin() ||\n event.dataTransfer?.types.includes(\"blocknote/html\") ||\n (event.target instanceof Node && view.dom.contains(event.target))\n );\n }\n\n /**\n * Closes the drop-cursor for the current editor\n */\n function closeDropCursor() {\n const evt: SyntheticEvent = new Event(\"dragleave\", { bubbles: false });\n // It needs to be synthetic, so we don't accidentally think it is a real dragend event\n evt.synthetic = true;\n // We dispatch the event to the current editor, so that the drop-cursor is removed for it\n view.dom.dispatchEvent(evt);\n }\n\n /**\n * Re-dispatches a drag event on this editor, with its coordinates clamped\n * into the editor's blocks. A plain `Event` with the drag event's fields\n * copied on, as a `DragEvent`'s coordinates can't be set.\n */\n function dispatchSyntheticEvent(event: DragEvent) {\n const dropPointBoundingBox = (\n view.dom.firstChild as HTMLElement\n ).getBoundingClientRect();\n const evt = Object.assign(new Event(event.type, event), {\n clientX: Math.min(\n Math.max(event.clientX, dropPointBoundingBox.left),\n dropPointBoundingBox.left + dropPointBoundingBox.width,\n ),\n clientY: Math.min(\n Math.max(event.clientY, dropPointBoundingBox.top),\n dropPointBoundingBox.top + dropPointBoundingBox.height,\n ),\n dataTransfer: event.dataTransfer,\n preventDefault: () => event.preventDefault(),\n synthetic: true, // prevent recursion\n });\n view.dom.dispatchEvent(evt);\n }\n\n /**\n * It is surprisingly difficult to determine the information we need to know about a drag event\n *\n * This function is trying to determine the following:\n * - Whether the current editor instance is the drop point\n * - Whether the current editor instance is the drag origin\n * - Whether the drop event is within the bounds of the current editor instance\n */\n function getDragEventContext(event: DragEvent) {\n if (!isBlockNoteDrag(event)) {\n return undefined;\n }\n\n // We need to check if there is text content that is being dragged (select some text & just drag it)\n const textContentIsBeingDragged =\n !event.dataTransfer?.types.includes(\"blocknote/html\") && !!view.dragging;\n // This is the side menu drag from this plugin\n const sideMenuIsBeingDragged = isDragOrigin();\n // Tells us that the current editor instance has a drag ongoing (either text or side menu)\n const isOrigin = textContentIsBeingDragged || sideMenuIsBeingDragged;\n\n // The editor the drag event is about, if any is within `dropMargin`\n const closestEditor = findDropEditor(view, event, dropMargin);\n if (!closestEditor) {\n return undefined;\n }\n\n // We check if the closest editor is the same as the current editor instance (which is the drop point)\n const isDropPoint = closestEditor.element === view.dom;\n // We check if the current editor instance is the same as the editor instance that the drag event is happening within\n const isDropWithinEditorBounds =\n isDropPoint && closestEditor.distance === 0;\n\n // We never want to handle drop events that are not related to us\n if (!isDropPoint && !isOrigin) {\n return undefined;\n }\n\n return {\n isDropPoint,\n isDropWithinEditorBounds,\n isDragOrigin: isOrigin,\n };\n }\n\n /**\n * If a block is being dragged, ProseMirror usually gets the context of what's\n * being dragged from `view.dragging`, which is automatically set when a\n * `dragstart` event fires in the editor. However, if the user tries to drag\n * and drop blocks between multiple editors, only the one in which the drag\n * began has that context, so we need to set it on the others manually. This\n * ensures that PM always drops the blocks in between other blocks, and not\n * inside them.\n *\n * After the `dragstart` event fires on the drag handle, it sets\n * `blocknote/html` data on the clipboard. This handler fires right after,\n * parsing the `blocknote/html` data into nodes and setting them on\n * `view.dragging`.\n *\n * Note: Setting `view.dragging` on `dragover` would be better as the user\n * could then drag between editors in different windows, but you can only\n * access `dataTransfer` contents on `dragstart` and `drop` events.\n */\n function onDragStart(event: DragEvent) {\n const html = event.dataTransfer?.getData(\"blocknote/html\");\n if (!html) {\n return;\n }\n\n if (view.dragging) {\n // already dragging, so no-op\n return;\n }\n\n // Parsed in an inert document: unlike an element of the page, it does not\n // load resources or run event handlers in the HTML.\n const window = view.dom.ownerDocument.defaultView ?? globalThis.window;\n const element = new window.DOMParser().parseFromString(\n html,\n \"text/html\",\n ).body;\n\n // Into the type of the blocks' parent, when this editor has it (see\n // `dragStart`): a block that only this parent can hold, e.g. a column or\n // the step of a stepper, would otherwise be wrapped in a new copy of it.\n const { nodes } = view.state.schema;\n const parentType =\n nodes[event.dataTransfer!.getData(\"blocknote/parent\")] ??\n nodes[\"blockGroup\"];\n const parser = DOMParser.fromSchema(view.state.schema);\n const node = parser.parse(element, { topNode: parentType.create() });\n\n view.dragging = {\n slice: new Slice(node.content, 0, 0),\n move: true,\n };\n }\n\n /**\n * This dragover event handler listens at the document level,\n * and is trying to handle dragover events for all editors.\n *\n * It specifically is trying to handle the following cases:\n * - If the dragover event is within the bounds of any editor, then it does nothing\n * - If the dragover event is outside the bounds of any editor, but close enough (within `dropMargin`) to the closest editor,\n * then it dispatches a synthetic dragover event to the closest editor (which will trigger the drop-cursor to be shown on that editor)\n * - If the dragover event is outside the bounds of the current editor, then it will dispatch a synthetic dragleave event to the current editor\n * (which will trigger the drop-cursor to be removed from the current editor)\n *\n * The synthetic event is a necessary evil because we do not control prosemirror-dropcursor to be able to show the drop-cursor within the range we want\n */\n function onDragOver(event: DragEvent) {\n if (isSynthetic(event)) {\n return;\n }\n\n // Relevance gate: Only handle drags that belong to BlockNote\n // This prevents interference with external drag-and-drop libraries\n // by avoiding calls to closeDropCursor() for non-BlockNote drags\n if (!isBlockNoteDrag(event)) {\n return;\n }\n\n const dragEventContext = getDragEventContext(event);\n\n if (!dragEventContext || !dragEventContext.isDropPoint) {\n // This is not a drag event that we are interested in\n // so, we close the drop-cursor\n closeDropCursor();\n return;\n }\n\n if (!dragEventContext.isDropWithinEditorBounds) {\n // we are the drop point, but the drag over event is not within the bounds of this editor instance\n // so, we need to dispatch an event that is in the bounds of this editor instance\n dispatchSyntheticEvent(event);\n }\n }\n\n /**\n * The drop event handler listens at the document level,\n * and handles drop events for all editors.\n *\n * It specifically handles the following cases:\n * - If we are both the drag origin and drop point:\n * - Let normal drop handling take over\n * - If we are the drop point but not the drag origin:\n * - Collapse selection to prevent PM from deleting unrelated content\n * - If drop event is outside our editor bounds, dispatch synthetic drop event to our editor\n * - If we are the drag origin but not the drop point:\n * - Delete the dragged content from our editor after a delay\n */\n function onDrop(event: DragEvent) {\n if (isSynthetic(event)) {\n return;\n }\n\n if (!isBlockNoteDrag(event)) {\n return;\n }\n\n const context = getDragEventContext(event);\n if (!context) {\n closeDropCursor();\n // This is not a drag event that we are interested in\n return;\n }\n const { isDropPoint, isDropWithinEditorBounds, isDragOrigin } = context;\n\n if (!isDropWithinEditorBounds && isDropPoint) {\n // Any time that the drop event is outside of the editor bounds (but still close to an editor instance)\n // We dispatch a synthetic event that is in the bounds of the editor instance, to have the correct drop point\n dispatchSyntheticEvent(event);\n }\n\n if (isDropPoint) {\n // The current instance is the drop point\n\n if (view.dragging) {\n // Do not collapse selection when text content is being dragged\n return;\n }\n // Because the editor selection is unrelated to the dragged content, we\n // don't want PM to delete its content. Therefore, we collapse the\n // selection.\n view.dispatch(\n view.state.tr.setSelection(\n TextSelection.create(\n view.state.tr.doc,\n view.state.tr.selection.anchor,\n ),\n ),\n );\n return;\n } else if (isDragOrigin) {\n // The current instance is the drag origin, but not the drop point\n // our content got dropped somewhere else\n\n // Because the editor from which the block originates doesn't get a drop\n // event on it, PM doesn't delete its selected content. Therefore, we\n // need to do so manually.\n //\n // Note: Deleting the selected content from the editor from which the\n // block originates, may change its height. This can cause the position of\n // the editor in which the block is being dropping to shift, before it\n // can handle the drop event. That in turn can cause the drop to happen\n // somewhere other than the user intended. To get around this, we delay\n // deleting the selected content until all editors have had the chance to\n // handle the event.\n setTimeout(() => view.dispatch(view.state.tr.deleteSelection()), 0);\n return;\n }\n }\n\n function onDragEnd(event: DragEvent) {\n if (isSynthetic(event)) {\n return;\n }\n // When the user starts dragging a block, `view.dragging` is set on all\n // BlockNote editors. However, when the drag ends, only the editor that the\n // drag originated in automatically clears `view.dragging`. Therefore, we\n // have to manually clear it on all editors.\n view.dragging = null;\n }\n\n // The DOM lib types `root` as `Document | ShadowRoot`, whose listener maps\n // don't share the drag event types, so the handlers are typed by hand.\n const root = view.root as Document;\n root.addEventListener(\"dragstart\", onDragStart, { signal });\n root.addEventListener(\"dragover\", onDragOver, { signal });\n root.addEventListener(\"drop\", onDrop, { signal, capture: true });\n root.addEventListener(\"dragend\", onDragEnd, { signal, capture: true });\n}\n","// THIS FILE IS AUTO-GENERATED. DO NOT EDIT DIRECTLY.\n// Source: https://data.iana.org/TLD/tlds-alpha-by-domain.txt\n// Regenerate with: pnpm --filter @blocknote/core update-tlds\n// Encoding format ported from linkifyjs (MIT) — trie collapsed into ASCII.\n\nexport const ENCODED_TLDS =\n \"aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2\";\n","/**\n * Lightweight URL detection module replacing linkifyjs.\n *\n * Provides two functions:\n * - findLinks(): find all URLs/emails in arbitrary text (replaces linkifyjs find())\n * - tokenizeLink(): tokenize a single word for autolink validation (replaces linkifyjs tokenize())\n */\n\nimport { ENCODED_TLDS } from \"./tlds.js\";\n\nexport interface LinkMatch {\n type: string;\n value: string;\n isLink: boolean;\n href: string;\n start: number;\n end: number;\n}\n\n// ---------------------------------------------------------------------------\n// TLD set – used only for schemeless URL validation.\n// Protocol URLs (http://, https://, etc.) skip TLD checks.\n// Decoded once at module load from the trie-encoded IANA list in tlds.ts.\n// ---------------------------------------------------------------------------\n\nfunction decodeTlds(encoded: string): string[] {\n const words: string[] = [];\n const stack: string[] = [];\n let i = 0;\n while (i < encoded.length) {\n let popDigitCount = 0;\n while (\n i + popDigitCount < encoded.length &&\n encoded.charCodeAt(i + popDigitCount) >= 48 &&\n encoded.charCodeAt(i + popDigitCount) <= 57\n ) {\n popDigitCount++;\n }\n if (popDigitCount > 0) {\n words.push(stack.join(\"\"));\n let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10);\n while (popCount-- > 0) {\n stack.pop();\n }\n i += popDigitCount;\n } else {\n stack.push(encoded[i]);\n i++;\n }\n }\n return words;\n}\n\nconst TLD_SET = new Set(decodeTlds(ENCODED_TLDS));\n\n// Special hostnames recognized without a TLD\nconst SPECIAL_HOSTS = new Set([\"localhost\"]);\n\n// ---------------------------------------------------------------------------\n// Regex building blocks\n// ---------------------------------------------------------------------------\n\n// Characters that are unlikely to be part of a URL when they appear at the end\nconst TRAILING_PUNCT = /[.,;:!?\"']+$/;\n\n// Protocol URLs: http:// https:// ftp:// ftps://\nconst PROTOCOL_RE = /(?:https?|ftp|ftps):\\/\\/[^\\s]+/g;\n\n// Mailto URLs: mailto:...\nconst MAILTO_RE = /mailto:[^\\s]+/g;\n\n// Bare email addresses: user@domain.tld\nconst EMAIL_RE =\n /[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}/g;\n\n// Schemeless URLs: domain.tld with optional port and path\n// Hostname: one or more labels separated by dots, TLD is alpha-only 2+ chars\nconst SCHEMELESS_RE =\n /(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}(?::\\d{1,5})?(?:[/?#][^\\s]*)?/g;\n\n// ---------------------------------------------------------------------------\n// Post-processing helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Trim trailing punctuation and unbalanced closing brackets from a URL match.\n */\nfunction trimTrailing(value: string): string {\n let v = value;\n\n // Iteratively trim trailing punctuation and unbalanced brackets\n let changed = true;\n while (changed) {\n changed = false;\n\n // Trim trailing punctuation chars\n const before = v;\n v = v.replace(TRAILING_PUNCT, \"\");\n if (v !== before) {\n changed = true;\n }\n\n // Trim unbalanced closing brackets from the end\n for (const [open, close] of [\n [\"(\", \")\"],\n [\"[\", \"]\"],\n ] as const) {\n while (v.endsWith(close)) {\n const openCount = countChar(v, open);\n const closeCount = countChar(v, close);\n if (closeCount > openCount) {\n v = v.slice(0, -1);\n changed = true;\n } else {\n break;\n }\n }\n }\n }\n\n return v;\n}\n\nfunction countChar(str: string, ch: string): number {\n let count = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === ch) {\n count++;\n }\n }\n return count;\n}\n\n/**\n * Extract the TLD from a hostname string.\n * Returns the last dot-separated segment.\n */\nfunction extractTld(hostname: string): string {\n const parts = hostname.split(\".\");\n return parts[parts.length - 1].toLowerCase();\n}\n\nfunction isValidTld(hostname: string): boolean {\n const tld = extractTld(hostname);\n return TLD_SET.has(tld);\n}\n\n/**\n * Build the href for a URL value, prepending the default protocol if needed.\n */\nfunction buildHref(\n value: string,\n type: string,\n defaultProtocol: string,\n): string {\n if (type === \"email\") {\n return \"mailto:\" + value;\n }\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(value) || /^mailto:/i.test(value)) {\n // Already has a protocol\n return value;\n }\n return defaultProtocol + \"://\" + value;\n}\n\n// ---------------------------------------------------------------------------\n// findLinks()\n// ---------------------------------------------------------------------------\n\nexport interface FindOptions {\n defaultProtocol?: string;\n}\n\ninterface RawMatch {\n type: string;\n value: string;\n start: number;\n end: number;\n}\n\n/**\n * Find all URLs and email addresses in the given text.\n * Drop-in replacement for linkifyjs find().\n */\nexport function findLinks(text: string, options?: FindOptions): LinkMatch[] {\n if (!text) {\n return [];\n }\n\n const defaultProtocol = options?.defaultProtocol || \"http\";\n const rawMatches: RawMatch[] = [];\n\n // 1. Protocol URLs\n for (const m of text.matchAll(PROTOCOL_RE)) {\n rawMatches.push({\n type: \"url\",\n value: m[0],\n start: m.index!,\n end: m.index! + m[0].length,\n });\n }\n\n // 2. Mailto URLs\n for (const m of text.matchAll(MAILTO_RE)) {\n rawMatches.push({\n type: \"url\",\n value: m[0],\n start: m.index!,\n end: m.index! + m[0].length,\n });\n }\n\n // 3. Bare email addresses\n for (const m of text.matchAll(EMAIL_RE)) {\n rawMatches.push({\n type: \"email\",\n value: m[0],\n start: m.index!,\n end: m.index! + m[0].length,\n });\n }\n\n // 4. Schemeless URLs\n for (const m of text.matchAll(SCHEMELESS_RE)) {\n rawMatches.push({\n type: \"url\",\n value: m[0],\n start: m.index!,\n end: m.index! + m[0].length,\n });\n }\n\n // Sort by start position\n rawMatches.sort((a, b) => a.start - b.start || b.end - a.end);\n\n // Deduplicate overlapping matches (prefer earlier & longer)\n const deduped: RawMatch[] = [];\n let lastEnd = -1;\n for (const match of rawMatches) {\n if (match.start >= lastEnd) {\n deduped.push(match);\n lastEnd = match.end;\n }\n }\n\n // Post-process each match\n const results: LinkMatch[] = [];\n for (const raw of deduped) {\n const value = trimTrailing(raw.value);\n if (!value) {\n continue;\n }\n\n const start = raw.start;\n const end = start + value.length;\n\n // For schemeless URLs, validate TLD\n if (raw.type === \"url\" && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value)) {\n const hostname = new URL(\"http://\" + value).hostname;\n if (!isValidTld(hostname)) {\n continue;\n }\n }\n\n // For emails, validate TLD\n if (raw.type === \"email\") {\n const hostname = value.split(\"@\")[1];\n if (!isValidTld(hostname)) {\n continue;\n }\n }\n\n const href = buildHref(value, raw.type, defaultProtocol);\n\n results.push({\n type: raw.type,\n value,\n isLink: true,\n href,\n start,\n end,\n });\n }\n\n return results;\n}\n\n// ---------------------------------------------------------------------------\n// tokenizeLink()\n// ---------------------------------------------------------------------------\n\n/**\n * Tokenize a single word for autolink validation.\n * Drop-in replacement for: tokenize(word).map(t => t.toObject(defaultProtocol))\n *\n * Returns an array of LinkMatch tokens. The autolink code checks:\n * - 1 token with isLink=true → valid single link\n * - 3 tokens with middle isLink=true and outer brackets → valid wrapped link\n */\nexport function tokenizeLink(\n text: string,\n defaultProtocol = \"http\",\n): LinkMatch[] {\n if (!text) {\n return [nonLinkToken(text, 0, 0)];\n }\n\n // Check for bracket wrapping: (url), [url], {url}\n const brackets: Array<[string, string]> = [\n [\"(\", \")\"],\n [\"[\", \"]\"],\n [\"{\", \"}\"],\n ];\n for (const [open, close] of brackets) {\n if (text.startsWith(open) && text.endsWith(close) && text.length > 2) {\n const inner = text.slice(1, -1);\n if (isSingleUrl(inner)) {\n return [\n nonLinkToken(open, 0, 1),\n linkToken(inner, 1, 1 + inner.length, defaultProtocol),\n nonLinkToken(close, 1 + inner.length, text.length),\n ];\n }\n }\n }\n\n // Check for trailing punctuation (e.g., \"example.com.\" → link + dot)\n if (text.endsWith(\".\") && text.length > 1) {\n const withoutDot = text.slice(0, -1);\n if (isSingleUrl(withoutDot)) {\n return [\n linkToken(withoutDot, 0, withoutDot.length, defaultProtocol),\n nonLinkToken(\".\", withoutDot.length, text.length),\n ];\n }\n }\n\n // Check if the whole text is a single URL\n if (isSingleUrl(text)) {\n return [linkToken(text, 0, text.length, defaultProtocol)];\n }\n\n // Not a link\n return [nonLinkToken(text, 0, text.length)];\n}\n\n/**\n * Check if a string is a single complete URL (no extra chars).\n */\nfunction isSingleUrl(text: string): boolean {\n // Protocol URLs\n if (/^(?:https?|ftp|ftps):\\/\\/[^\\s]+$/.test(text)) {\n return true;\n }\n\n // Mailto URLs\n if (/^mailto:[^\\s]+$/.test(text)) {\n return true;\n }\n\n // Special hosts (e.g., localhost)\n if (SPECIAL_HOSTS.has(text.toLowerCase())) {\n return true;\n }\n\n // Schemeless URLs: hostname.tld with optional port and path\n const schemelessFull =\n /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+([a-zA-Z]{2,})(?::\\d{1,5})?(?:[/?#][^\\s]*)?$/;\n const match = text.match(schemelessFull);\n if (match) {\n const tld = match[1].toLowerCase();\n // TLD must be a-z only (no numbers) and recognized\n if (TLD_SET.has(tld)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction linkToken(\n value: string,\n start: number,\n end: number,\n defaultProtocol: string,\n): LinkMatch {\n const type =\n value.includes(\"@\") &&\n !value.includes(\"://\") &&\n !value.startsWith(\"mailto:\")\n ? \"email\"\n : \"url\";\n return {\n type,\n value,\n isLink: true,\n href: buildHref(value, type, defaultProtocol),\n start,\n end,\n };\n}\n\nfunction nonLinkToken(value: string, start: number, end: number): LinkMatch {\n return {\n type: \"text\",\n value,\n isLink: false,\n href: value,\n start,\n end,\n };\n}\n","import { findLinks } from \"../../../extensions/tiptap-extensions/Link/helpers/linkDetector.js\";\n\nexport type AutolinkLiteral = {\n value: string;\n href: string;\n};\n\nexport function parseAutolinkLiteral(\n candidate: string,\n): AutolinkLiteral | undefined {\n if (!/^(https?:\\/\\/|www\\.)/i.test(candidate)) {\n return undefined;\n }\n\n // Markdown leaves entity-like suffixes outside an autolink.\n const value = candidate.replace(/&[a-zA-Z0-9]+;$/, \"\");\n const match = findLinks(value, { defaultProtocol: \"http\" })[0];\n if (!match || match.start !== 0) {\n return undefined;\n }\n\n return { value: match.value, href: match.href };\n}\n","import { parseAutolinkLiteral } from \"../../parsers/markdown/autolink.js\";\n\n/**\n * Custom HTML-to-Markdown serializer for BlockNote.\n * Replaces the unified/rehype-remark pipeline with a direct DOM-based implementation.\n *\n * Input: HTML string from createExternalHTMLExporter\n * Output: GFM-compatible markdown string\n */\n\n/**\n * Convert an HTML string (from BlockNote's external HTML exporter) to markdown.\n */\nexport function htmlToMarkdown(html: string): string {\n // Use a temporary element to parse HTML. This works in both browser and\n // server (JSDOM) environments, unlike `new DOMParser()` which may not be\n // globally available in Node.js.\n const container = document.createElement(\"div\");\n container.innerHTML = html;\n const result = serializeChildren(container, {\n indent: \"\",\n inListItem: false,\n });\n return result.trim() + \"\\n\";\n}\n\ninterface SerializeContext {\n indent: string; // current indentation prefix for list nesting\n // True when the current node is being serialized as continuation content\n // of a parent list item. Used to suppress trailing blank lines that would\n // otherwise turn the parent list into a \"loose\" list.\n inListItem: boolean;\n}\n\n// ─── Main Serializer ─────────────────────────────────────────────────────────\n\nfunction serializeChildren(node: Node, ctx: SerializeContext): string {\n let result = \"\";\n const children = Array.from(node.childNodes);\n\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n result += serializeNode(child, ctx);\n }\n\n return result;\n}\n\nfunction serializeNode(node: Node, ctx: SerializeContext): string {\n if (node.nodeType === 3 /* Node.TEXT_NODE */) {\n return node.textContent || \"\";\n }\n\n if (node.nodeType !== 1 /* Node.ELEMENT_NODE */) {\n return \"\";\n }\n\n const el = node as HTMLElement;\n const tag = el.tagName.toLowerCase();\n\n switch (tag) {\n case \"p\":\n return serializeParagraph(el, ctx);\n case \"h1\":\n case \"h2\":\n case \"h3\":\n case \"h4\":\n case \"h5\":\n case \"h6\":\n return serializeHeading(el, ctx);\n case \"blockquote\":\n return serializeBlockquote(el, ctx);\n case \"pre\":\n return serializeCodeBlock(el, ctx);\n case \"ul\":\n return serializeUnorderedList(el, ctx);\n case \"ol\":\n return serializeOrderedList(el, ctx);\n case \"table\":\n return serializeTable(el, ctx);\n case \"hr\":\n return ctx.indent + \"***\\n\\n\";\n case \"math\":\n return serializeMathBlock(el, ctx);\n case \"img\":\n return serializeImage(el, ctx);\n case \"video\":\n return serializeVideo(el, ctx);\n case \"audio\":\n return serializeAudio(el, ctx);\n case \"embed\":\n return serializeEmbed(el, ctx);\n case \"figure\":\n return serializeFigure(el, ctx);\n case \"a\":\n // Block-level link (file block)\n return serializeBlockLink(el, ctx);\n case \"details\":\n return serializeDetails(el, ctx);\n case \"div\":\n // Page break or generic container — serialize children\n return serializeChildren(el, ctx);\n case \"br\":\n return \"\";\n default:\n return serializeChildren(el, ctx);\n }\n}\n\n// ─── Block Serializers ───────────────────────────────────────────────────────\n\nfunction serializeParagraph(el: HTMLElement, ctx: SerializeContext): string {\n const content = serializeInlineContent(el);\n // Trim leading/trailing hard breaks (matching remark behavior)\n const trimmed = trimHardBreaks(content);\n if (ctx.inListItem) {\n return trimmed;\n }\n return ctx.indent + trimmed + \"\\n\\n\";\n}\n\nfunction serializeHeading(el: HTMLElement, ctx: SerializeContext): string {\n const level = parseInt(el.tagName[1], 10);\n const prefix = \"#\".repeat(level) + \" \";\n const content = serializeInlineContent(el);\n return ctx.indent + prefix + content + \"\\n\\n\";\n}\n\nfunction serializeBlockquote(el: HTMLElement, ctx: SerializeContext): string {\n // Check if blockquote contains block-level elements (like <p>)\n const blockChildren = Array.from(el.children).filter((child) => {\n const tag = child.tagName.toLowerCase();\n return [\"p\", \"ul\", \"ol\", \"pre\", \"blockquote\", \"table\", \"hr\"].includes(tag);\n });\n\n let content: string;\n if (blockChildren.length > 0) {\n // Has block-level children — serialize each\n const parts: string[] = [];\n for (const child of blockChildren) {\n const tag = child.tagName.toLowerCase();\n if (tag === \"p\") {\n parts.push(serializeInlineContent(child as HTMLElement));\n } else {\n const innerCtx: SerializeContext = { indent: \"\", inListItem: false };\n parts.push(serializeNode(child, innerCtx).trim());\n }\n }\n content = parts.join(\"\\n\\n\");\n } else {\n // No block-level children — treat entire content as inline\n content = serializeInlineContent(el);\n }\n\n const lines = content.split(\"\\n\");\n return lines.map((line) => ctx.indent + \"> \" + line).join(\"\\n\") + \"\\n\\n\";\n}\n\nfunction serializeCodeBlock(el: HTMLElement, ctx: SerializeContext): string {\n const codeEl = el.querySelector(\"code\");\n if (!codeEl) {\n return \"\";\n }\n\n const language =\n codeEl.getAttribute(\"data-language\") ||\n extractLanguageFromClass(codeEl.className) ||\n \"\";\n\n // Extract code content, handling <br> elements as newlines\n const code = extractCodeContent(codeEl);\n\n // Use a fence longer than the longest backtick run in the code\n const longestRun = Math.max(\n 0,\n ...(code.match(/`+/g) ?? []).map((run) => run.length),\n );\n const fence = \"`\".repeat(Math.max(3, longestRun + 1));\n\n // For empty code blocks, don't add a newline between the fences\n if (!code) {\n return ctx.indent + fence + language + \"\\n\" + ctx.indent + fence + \"\\n\\n\";\n }\n\n // Every (non-blank) line carries the indent - inside a list item or\n // blockquote, an unindented line would end the parent container. Blank\n // lines stay blank: they don't terminate an indented fence, and indenting\n // them would add trailing whitespace.\n const lines = [\n fence + language,\n ...(code.endsWith(\"\\n\") ? code.slice(0, -1) : code).split(\"\\n\"),\n fence,\n ];\n return (\n lines.map((line) => (line ? ctx.indent + line : line)).join(\"\\n\") + \"\\n\\n\"\n );\n}\n\n// The LaTeX source of a MathML element, taken from the annotation KaTeX\n// embeds in its output (also what external HTML parsing reads). Falls back to\n// the element's text content for MathML from other sources.\nfunction extractMathLatexSource(el: Element): string {\n const annotation = el.querySelector(\n 'annotation[encoding=\"application/x-tex\"]',\n );\n return (annotation?.textContent ?? el.textContent ?? \"\").trim();\n}\n\nfunction serializeMathBlock(el: HTMLElement, ctx: SerializeContext): string {\n const latex = extractMathLatexSource(el);\n // Every (non-blank) line carries the indent - inside a list item or\n // blockquote, an unindented line would end the parent container.\n return (\n [\"$$\", ...latex.split(\"\\n\"), \"$$\"]\n .map((line) => (line ? ctx.indent + line : line))\n .join(\"\\n\") + \"\\n\\n\"\n );\n}\n\nfunction extractCodeContent(el: Element): string {\n let result = \"\";\n for (const child of Array.from(el.childNodes)) {\n if (child.nodeType === 3 /* Node.TEXT_NODE */) {\n result += child.textContent || \"\";\n } else if (child.nodeType === 1 /* Node.ELEMENT_NODE */) {\n const tag = (child as HTMLElement).tagName.toLowerCase();\n if (tag === \"br\") {\n result += \"\\n\";\n } else {\n result += extractCodeContent(child as Element);\n }\n }\n }\n return result;\n}\n\nfunction extractLanguageFromClass(className: string): string {\n const match = className.match(/language-(\\S+)/);\n return match ? match[1] : \"\";\n}\n\nfunction serializeUnorderedList(\n el: HTMLElement,\n ctx: SerializeContext,\n): string {\n let result = \"\";\n const items = Array.from(el.children).filter(\n (child) => child.tagName.toLowerCase() === \"li\",\n );\n\n for (const item of items) {\n result += serializeListItem(item as HTMLElement, \"bullet\", ctx);\n }\n\n // Trailing blank line separates the list from the next block. Skip when\n // this list is nested inside another list item — adding it would convert\n // the parent list into a \"loose\" list (or break tightness).\n if (!ctx.inListItem) {\n result += \"\\n\";\n }\n return result;\n}\n\nfunction serializeOrderedList(el: HTMLElement, ctx: SerializeContext): string {\n let result = \"\";\n const items = Array.from(el.children).filter(\n (child) => child.tagName.toLowerCase() === \"li\",\n );\n const startNum = parseInt(el.getAttribute(\"start\") || \"1\", 10);\n\n for (let i = 0; i < items.length; i++) {\n const num = startNum + i;\n result += serializeListItem(items[i] as HTMLElement, \"ordered\", ctx, num);\n }\n\n if (!ctx.inListItem) {\n result += \"\\n\";\n }\n return result;\n}\n\nfunction serializeListItem(\n el: HTMLElement,\n listType: \"bullet\" | \"ordered\",\n ctx: SerializeContext,\n num?: number,\n): string {\n // Check for checkbox (task list) - direct children only\n let checkbox: HTMLInputElement | null = null;\n let details: HTMLElement | null = null;\n\n for (const child of Array.from(el.children)) {\n const tag = child.tagName.toLowerCase();\n if (tag === \"input\" && (child as HTMLInputElement).type === \"checkbox\") {\n checkbox = child as HTMLInputElement;\n }\n if (tag === \"details\") {\n details = child as HTMLElement;\n }\n }\n\n let marker: string;\n let markerWidth: number;\n\n if (checkbox) {\n const state = checkbox.checked ? \"[x]\" : \"[ ]\";\n marker = `* ${state} `;\n // For child indentation, use bullet width (2), not full checkbox marker width\n markerWidth = 2;\n } else if (listType === \"ordered\") {\n marker = `${num}. `;\n markerWidth = marker.length;\n } else {\n marker = \"* \";\n markerWidth = 2;\n }\n\n // Collect the item's inline content\n let inlineContent: string;\n let firstContentEl: Element | null;\n\n if (details) {\n // Toggle item: get content from summary\n const summary = details.querySelector(\"summary\");\n const summaryP = summary?.querySelector(\"p\");\n firstContentEl = details;\n inlineContent = summaryP ? serializeInlineContent(summaryP) : \"\";\n } else {\n firstContentEl = getFirstContentElement(el, checkbox);\n inlineContent = firstContentEl\n ? serializeInlineContent(firstContentEl)\n : \"\";\n }\n\n // The marker line ends with a single `\\n` so that consecutive list items\n // produce a \"tight\" list (no blank line between markers). Continuation\n // content within the item (nested lists, continuation paragraphs, other\n // blocks) injects its own spacing as needed.\n let result = ctx.indent + marker + inlineContent + \"\\n\";\n\n // Serialize child content (nested lists, continuation paragraphs, etc.)\n const childIndent = ctx.indent + \" \".repeat(markerWidth);\n const childCtx: SerializeContext = { indent: childIndent, inListItem: true };\n\n // For toggle items, also serialize children inside the details element\n if (details) {\n const summary = details.querySelector(\"summary\");\n for (const child of Array.from(details.children)) {\n if (child === summary) {\n continue;\n }\n const childTag = child.tagName.toLowerCase();\n if (childTag === \"p\") {\n const content = serializeInlineContent(child as HTMLElement);\n // Continuation paragraph needs a blank line to separate it from the\n // previous content; CommonMark would otherwise treat it as a soft\n // wrap of that content.\n result += \"\\n\" + childIndent + content + \"\\n\";\n } else {\n result += serializeNode(child, childCtx);\n }\n }\n }\n\n const children = Array.from(el.children);\n for (const child of children) {\n const childTag = child.tagName.toLowerCase();\n\n // Skip the first content element and checkbox\n if (child === firstContentEl || (child as HTMLElement) === checkbox) {\n continue;\n }\n if (childTag === \"input\") {\n continue;\n }\n\n // Nested lists and other block content\n if (childTag === \"ul\" || childTag === \"ol\") {\n // Nested list flows directly under the parent marker — no blank line.\n result += serializeNode(child, childCtx);\n } else if (childTag === \"p\") {\n // Continuation paragraph within list item — requires blank line before\n // so it isn't read as part of the marker line's text.\n const content = serializeInlineContent(child as HTMLElement);\n result += \"\\n\" + childIndent + content + \"\\n\";\n } else {\n // Other block-level children (code blocks, blockquotes, etc.) already\n // emit their own separating newlines; prefix with a blank line so they\n // are recognized as separate blocks.\n result += \"\\n\" + serializeNode(child, childCtx);\n }\n }\n\n return result;\n}\n\nfunction getFirstContentElement(\n li: HTMLElement,\n checkbox: HTMLInputElement | null,\n): HTMLElement | null {\n for (const child of Array.from(li.children)) {\n if (child === checkbox) {\n continue;\n }\n if (child.tagName.toLowerCase() === \"input\") {\n continue;\n }\n const tag = child.tagName.toLowerCase();\n if (tag === \"p\" || tag === \"span\") {\n return child as HTMLElement;\n }\n }\n return null;\n}\n\n// ─── Table Serializer ────────────────────────────────────────────────────────\n\nfunction serializeTable(el: HTMLElement, ctx: SerializeContext): string {\n // First, determine column count from colgroup or first row\n const colgroup = el.querySelector(\"colgroup\");\n let colCount = 0;\n\n if (colgroup) {\n colCount = colgroup.querySelectorAll(\"col\").length;\n }\n\n const rows: string[][] = [];\n let hasHeader = false;\n\n // Collect all rows, handling colspan/rowspan\n const trElements = el.querySelectorAll(\"tr\");\n // Build a grid to handle colspan/rowspan\n const grid: (string | null)[][] = [];\n\n trElements.forEach((tr, rowIdx) => {\n if (!grid[rowIdx]) {\n grid[rowIdx] = [];\n }\n const cellElements = tr.querySelectorAll(\"th, td\");\n let gridCol = 0;\n\n cellElements.forEach((cell) => {\n // Find next empty column in this row\n while (grid[rowIdx][gridCol] !== undefined) {\n gridCol++;\n }\n\n if (rowIdx === 0 && cell.tagName.toLowerCase() === \"th\") {\n hasHeader = true;\n }\n\n const content = escapeTableCell(\n serializeInlineContent(cell as HTMLElement).trim(),\n );\n const colspan = parseInt(cell.getAttribute(\"colspan\") || \"1\", 10);\n const rowspan = parseInt(cell.getAttribute(\"rowspan\") || \"1\", 10);\n\n // Fill the grid\n for (let r = 0; r < rowspan; r++) {\n for (let c = 0; c < colspan; c++) {\n const ri = rowIdx + r;\n if (!grid[ri]) {\n grid[ri] = [];\n }\n grid[ri][gridCol + c] = r === 0 && c === 0 ? content : \"\";\n }\n }\n\n gridCol += colspan;\n });\n\n // Update colCount\n if (grid[rowIdx]) {\n colCount = Math.max(colCount, grid[rowIdx].length);\n }\n });\n\n // Convert grid to rows\n for (const gridRow of grid) {\n const row: string[] = [];\n for (let c = 0; c < colCount; c++) {\n row.push(gridRow && gridRow[c] !== undefined ? (gridRow[c] ?? \"\") : \"\");\n }\n rows.push(row);\n }\n\n if (rows.length === 0) {\n return \"\";\n }\n\n // Determine column widths\n const colWidths: number[] = [];\n for (let c = 0; c < colCount; c++) {\n let maxWidth = 3; // minimum width for separator \"---\"\n for (const row of rows) {\n const cellWidth = c < row.length ? row[c].length : 0;\n maxWidth = Math.max(maxWidth, cellWidth);\n }\n // Use minimum of 10 to match remark output\n colWidths.push(Math.max(maxWidth, 10));\n }\n\n let result = \"\";\n\n if (hasHeader) {\n result += ctx.indent + formatTableRow(rows[0], colWidths, colCount) + \"\\n\";\n result += ctx.indent + formatSeparatorRow(colWidths, colCount) + \"\\n\";\n for (let r = 1; r < rows.length; r++) {\n result +=\n ctx.indent + formatTableRow(rows[r], colWidths, colCount) + \"\\n\";\n }\n } else {\n // No header — emit empty header + separator\n const emptyRow = new Array(colCount).fill(\"\");\n result += ctx.indent + formatTableRow(emptyRow, colWidths, colCount) + \"\\n\";\n result += ctx.indent + formatSeparatorRow(colWidths, colCount) + \"\\n\";\n for (const row of rows) {\n result += ctx.indent + formatTableRow(row, colWidths, colCount) + \"\\n\";\n }\n }\n\n result += \"\\n\";\n return result;\n}\n\nfunction escapeTableCell(text: string): string {\n return text.replace(/\\|/g, \"\\\\|\");\n}\n\nfunction formatTableRow(\n cells: string[],\n colWidths: number[],\n colCount: number,\n): string {\n const parts: string[] = [];\n for (let c = 0; c < colCount; c++) {\n const cell = c < cells.length ? cells[c] : \"\";\n parts.push(\" \" + cell.padEnd(colWidths[c]) + \" \");\n }\n return \"|\" + parts.join(\"|\") + \"|\";\n}\n\nfunction formatSeparatorRow(colWidths: number[], colCount: number): string {\n const parts: string[] = [];\n for (let c = 0; c < colCount; c++) {\n parts.push(\" \" + \"-\".repeat(colWidths[c]) + \" \");\n }\n return \"|\" + parts.join(\"|\") + \"|\";\n}\n\n// ─── Media Serializers ───────────────────────────────────────────────────────\n\nfunction serializeImage(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || \"\";\n const alt = el.getAttribute(\"alt\") || \"\";\n // Empty placeholder — preserve the block-level break, matching how\n // serializeParagraph/serializeHeading emit `\\n\\n` for empty content.\n if (!src) {\n return \"\\n\\n\";\n }\n return ctx.indent + `![${alt}](${src})\\n\\n`;\n}\n\nfunction serializeVideo(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || el.getAttribute(\"data-url\") || \"\";\n const name = el.getAttribute(\"data-name\") || el.getAttribute(\"title\") || \"\";\n if (!src) {\n return \"\\n\\n\";\n }\n return ctx.indent + `![${name}](${src})\\n\\n`;\n}\n\nfunction serializeAudio(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || \"\";\n if (!src) {\n return \"\\n\\n\";\n }\n // Audio has no markdown syntax, so emit raw HTML. The markdown parser\n // passes <audio> blocks through verbatim and BlockNote's audio block parser\n // recognizes them, giving a clean round-trip.\n return (\n ctx.indent + `<audio src=\"${escapeHtmlAttr(src)}\" controls></audio>\\n\\n`\n );\n}\n\nfunction serializeEmbed(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || \"\";\n if (!src) {\n return \"\\n\\n\";\n }\n return ctx.indent + `[](${src})\\n\\n`;\n}\n\nfunction serializeFigure(el: HTMLElement, ctx: SerializeContext): string {\n const img = el.querySelector(\"img\");\n const video = el.querySelector(\"video\");\n const audio = el.querySelector(\"audio\");\n const link = el.querySelector(\"a\");\n\n const figcaption = el.querySelector(\"figcaption\");\n const captionText = figcaption?.textContent?.trim() || \"\";\n\n if (img) {\n return serializeMediaFigure(\n \"img\",\n img.getAttribute(\"src\") || \"\",\n img.getAttribute(\"alt\") || \"\",\n captionText,\n ctx,\n );\n }\n if (video) {\n const src =\n video.getAttribute(\"src\") || video.getAttribute(\"data-url\") || \"\";\n const name =\n video.getAttribute(\"data-name\") || video.getAttribute(\"title\") || \"\";\n return serializeMediaFigure(\"video\", src, name, captionText, ctx);\n }\n if (audio) {\n return serializeMediaFigure(\n \"audio\",\n audio.getAttribute(\"src\") || \"\",\n \"\",\n captionText,\n ctx,\n );\n }\n if (link) {\n return serializeBlockLink(link as HTMLElement, ctx);\n }\n return \"\";\n}\n\nfunction serializeMediaFigure(\n kind: \"img\" | \"video\" | \"audio\",\n src: string,\n descriptor: string,\n captionText: string,\n ctx: SerializeContext,\n): string {\n if (!src) {\n return \"\";\n }\n\n // No caption + has a markdown shorthand → use it.\n if (!captionText && kind !== \"audio\") {\n return ctx.indent + `![${descriptor}](${src})\\n\\n`;\n }\n\n // The descriptor (alt / data-name) is dropped when it duplicates the\n // caption text; otherwise on round-trip both `name` and `caption` would\n // get set to the same string (BlockNote's HTML exporter writes alt =\n // name || caption, so a caption-only image has alt === figcaption text).\n const showDescriptor = descriptor && descriptor !== captionText;\n const descAttr = !showDescriptor\n ? \"\"\n : kind === \"img\"\n ? ` alt=\"${escapeHtmlAttr(descriptor)}\"`\n : kind === \"video\"\n ? ` data-name=\"${escapeHtmlAttr(descriptor)}\"`\n : \"\";\n\n const tag =\n kind === \"img\"\n ? `<img${descAttr} src=\"${escapeHtmlAttr(src)}\">`\n : `<${kind} src=\"${escapeHtmlAttr(src)}\"${descAttr} controls></${kind}>`;\n\n const captionPart = captionText\n ? `<figcaption>${escapeHtmlText(captionText)}</figcaption>`\n : \"\";\n return ctx.indent + `<figure>${tag}${captionPart}</figure>\\n\\n`;\n}\n\nfunction escapeHtmlAttr(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction escapeHtmlText(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction serializeBlockLink(el: HTMLElement, ctx: SerializeContext): string {\n const href = el.getAttribute(\"href\") || \"\";\n const text = el.textContent?.trim() || \"\";\n if (!href) {\n return ctx.indent + text + \"\\n\\n\";\n }\n return ctx.indent + formatLink(text, href) + \"\\n\\n\";\n}\n\n/**\n * Render a link, mirroring the remark-stringify behavior from\n * TypeCellOS/BlockNote#2661: when the link label equals the URL (or is\n * empty), emit the bare URL so that pasting the link into another input\n * produces a valid href instead of `<url>`-autolink brackets or redundant\n * `[url](url)` markup. Otherwise emit `[text](url)` with the URL escaped so\n * a `)` inside the URL does not prematurely close the destination.\n */\nfunction formatLink(text: string, href: string): string {\n if (!text) {\n return href;\n }\n if (text === href) {\n const autolink = parseAutolinkLiteral(href);\n if (\n !/^(https?:\\/\\/|www\\.)/i.test(href) ||\n (autolink?.href === href && autolink.value === href)\n ) {\n return href;\n }\n }\n return `[${text}](${escapeLinkDestination(href)})`;\n}\n\nfunction escapeLinkDestination(url: string): string {\n return url.replace(/[\\\\()]/g, \"\\\\$&\");\n}\n\nfunction serializeDetails(el: HTMLElement, ctx: SerializeContext): string {\n // Toggle heading or toggle list item\n const summary = el.querySelector(\"summary\");\n if (!summary) {\n return serializeChildren(el, ctx);\n }\n\n // Check if summary contains a heading\n const heading = summary.querySelector(\"h1, h2, h3, h4, h5, h6\");\n if (heading) {\n let result = serializeHeading(heading as HTMLElement, ctx);\n // Also serialize non-summary children of details\n for (const child of Array.from(el.children)) {\n if (child !== summary) {\n result += serializeNode(child, ctx);\n }\n }\n return result;\n }\n\n // Otherwise serialize the summary content\n return serializeChildren(summary, ctx);\n}\n\n// ─── Inline Content Serializer ───────────────────────────────────────────────\n\nfunction serializeInlineContent(el: Element): string {\n let result = \"\";\n\n for (const child of Array.from(el.childNodes)) {\n if (child.nodeType === 3 /* Node.TEXT_NODE */) {\n result += child.textContent || \"\";\n } else if (child.nodeType === 1 /* Node.ELEMENT_NODE */) {\n const childEl = child as HTMLElement;\n const tag = childEl.tagName.toLowerCase();\n\n switch (tag) {\n case \"strong\":\n case \"b\": {\n const inner = serializeInlineContent(childEl);\n const { content, trailing } = extractTrailingWhitespace(inner);\n if (content) {\n result += `**${content}**${trailing}`;\n } else {\n // All whitespace — just output it without emphasis\n result += trailing;\n }\n break;\n }\n case \"em\":\n case \"i\": {\n const inner = serializeInlineContent(childEl);\n const { content, trailing } = extractTrailingWhitespace(inner);\n if (content) {\n result += `*${content}*${trailing}`;\n } else {\n result += trailing;\n }\n break;\n }\n case \"s\":\n case \"del\":\n result += `~~${serializeInlineContent(childEl)}~~`;\n break;\n case \"code\": {\n const text = childEl.textContent || \"\";\n const longestRun = Math.max(\n 0,\n ...(text.match(/`+/g) ?? []).map((run) => run.length),\n );\n const fence = \"`\".repeat(longestRun + 1);\n const needsPadding = text.startsWith(\"`\") || text.endsWith(\"`\");\n result += fence + (needsPadding ? ` ${text} ` : text) + fence;\n break;\n }\n case \"u\":\n // No markdown equivalent — strip the tag, keep content\n result += serializeInlineContent(childEl);\n break;\n case \"a\": {\n const href = childEl.getAttribute(\"href\") || \"\";\n const text = serializeInlineContent(childEl);\n result += formatLink(text, href);\n break;\n }\n case \"br\":\n result += \"\\\\\\n\";\n break;\n case \"math\": {\n // Inline math — emit its LaTeX source as a math span. Collapsed to\n // a single line, as $...$ spans cannot contain newlines.\n const latex = extractMathLatexSource(childEl)\n .split(\"\\n\")\n .map((line) => line.trim())\n .join(\" \");\n result += `$${latex}$`;\n break;\n }\n case \"span\":\n // Color spans, etc. — strip the tag, keep content\n result += serializeInlineContent(childEl);\n break;\n case \"img\": {\n const src = childEl.getAttribute(\"src\") || \"\";\n const alt = childEl.getAttribute(\"alt\") || \"\";\n result += `![${alt}](${src})`;\n break;\n }\n case \"video\": {\n const src =\n childEl.getAttribute(\"src\") ||\n childEl.getAttribute(\"data-url\") ||\n \"\";\n const name =\n childEl.getAttribute(\"data-name\") ||\n childEl.getAttribute(\"title\") ||\n \"\";\n result += `![${name}](${src})`;\n break;\n }\n case \"p\":\n // Paragraph inside inline context (e.g., table cell)\n result += serializeInlineContent(childEl);\n break;\n case \"input\":\n // Checkbox in task list — handled at block level\n break;\n default:\n result += serializeInlineContent(childEl);\n break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extract trailing whitespace from emphasis content.\n * Moves trailing spaces outside the emphasis delimiters to produce valid markdown.\n * E.g., `<strong>Bold </strong>` → `**Bold** ` instead of `**Bold **`.\n */\nfunction extractTrailingWhitespace(text: string): {\n content: string;\n trailing: string;\n} {\n const match = text.match(/^(.*?)(\\s*)$/);\n if (match) {\n return { content: match[1], trailing: match[2] };\n }\n return { content: text, trailing: \"\" };\n}\n\n/**\n * Escape leading character after emphasis if it could break parsing.\n * For example, \"Heading\" after \"**Bold **\" — the 'H' should be escaped\n * if the trailing space was escaped.\n */\n\n/**\n * Trim leading/trailing hard breaks from inline content.\n * Matches remark behavior where <br> at start/end of paragraph is dropped.\n */\nfunction trimHardBreaks(content: string): string {\n // Remove leading hard breaks\n let result = content.replace(/^(\\\\\\n)+/, \"\");\n // Remove trailing hard breaks produced by `<br>`\n result = result.replace(/(\\\\\\n)+$/, \"\");\n return result;\n}\n","import { Schema } 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 { createExternalHTMLExporter } from \"../html/externalHTMLExporter.js\";\nimport { EMPTY_BLOCK_PLACEHOLDER } from \"../html/util/serializeBlocksExternalHTML.js\";\nimport { htmlToMarkdown } from \"./htmlToMarkdown.js\";\n\n// Needs to be sync because it's used in drag handler event (SideMenuExtension)\nexport function cleanHTMLToMarkdown(cleanHTMLString: string) {\n // The external HTML exporter fills empty inline-content blocks with a\n // placeholder character so they survive an HTML round trip (see\n // `EMPTY_BLOCK_PLACEHOLDER`). Markdown has no need for that placeholder, so we\n // remove it to avoid it showing up as a stray character in the output.\n const withoutPlaceholder = cleanHTMLString\n .split(EMPTY_BLOCK_PLACEHOLDER)\n .join(\"\");\n\n return htmlToMarkdown(withoutPlaceholder);\n}\n\nexport function blocksToMarkdown<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n blocks: PartialBlock<BSchema, I, S>[],\n schema: Schema,\n editor: BlockNoteEditor<BSchema, I, S>,\n options: { document?: Document },\n): string {\n const exporter = createExternalHTMLExporter(schema, editor);\n const externalHTML = exporter.exportBlocks(blocks, options);\n\n return cleanHTMLToMarkdown(externalHTML);\n}\n","import { Fragment, Node, ResolvedPos, Slice } from \"prosemirror-model\";\nimport { Selection } from \"prosemirror-state\";\nimport { Mappable } from \"prosemirror-transform\";\n\n/**\n * This class represents an editor selection which spans multiple nodes/blocks. It's currently only used to allow users\n * to drag multiple blocks at the same time. Expects the selection anchor and head to be between nodes, i.e. just before\n * the first target node and just after the last, and that anchor and head are at the same nesting level.\n *\n * Partially based on ProseMirror's NodeSelection implementation:\n * (https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.ts)\n * MultipleNodeSelection differs from NodeSelection in the following ways:\n * 1. Stores which nodes are included in the selection instead of just a single node.\n * 2. Already expects the selection to start just before the first target node and ends just after the last, while a\n * NodeSelection automatically sets both anchor and head to just before the single target node.\n */\nexport class MultipleNodeSelection extends Selection {\n nodes: Array<Node>;\n\n constructor($anchor: ResolvedPos, $head: ResolvedPos) {\n super($anchor, $head);\n\n // Parent is at the same nesting level as anchor/head since they are just before/ just after target nodes.\n const parentNode = $anchor.node();\n\n this.nodes = [];\n $anchor.doc.nodesBetween($anchor.pos, $head.pos, (node, _pos, parent) => {\n if (parent !== null && parent.eq(parentNode)) {\n this.nodes.push(node);\n return false;\n }\n return;\n });\n }\n\n static create(doc: Node, from: number, to = from): MultipleNodeSelection {\n return new MultipleNodeSelection(doc.resolve(from), doc.resolve(to));\n }\n\n content(): Slice {\n return new Slice(Fragment.from(this.nodes), 0, 0);\n }\n\n eq(selection: Selection): boolean {\n if (!(selection instanceof MultipleNodeSelection)) {\n return false;\n }\n\n if (this.nodes.length !== selection.nodes.length) {\n return false;\n }\n\n if (this.from !== selection.from || this.to !== selection.to) {\n return false;\n }\n\n for (let i = 0; i < this.nodes.length; i++) {\n if (!this.nodes[i].eq(selection.nodes[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n map(doc: Node, mapping: Mappable): Selection {\n const fromResult = mapping.mapResult(this.from);\n const toResult = mapping.mapResult(this.to);\n\n if (toResult.deleted) {\n return Selection.near(doc.resolve(fromResult.pos));\n }\n\n if (fromResult.deleted) {\n return Selection.near(doc.resolve(toResult.pos));\n }\n\n return new MultipleNodeSelection(\n doc.resolve(fromResult.pos),\n doc.resolve(toResult.pos),\n );\n }\n\n toJSON(): any {\n return { type: \"multiple-node\", anchor: this.anchor, head: this.head };\n }\n}\n\nSelection.jsonID(\"multiple-node\", MultipleNodeSelection);\n","import { Node } from \"prosemirror-model\";\nimport { NodeSelection, Selection } from \"prosemirror-state\";\nimport { EditorView } from \"prosemirror-view\";\n\nimport { createExternalHTMLExporter } from \"../../api/exporters/html/externalHTMLExporter.js\";\nimport { cleanHTMLToMarkdown } from \"../../api/exporters/markdown/markdownExporter.js\";\nimport { fragmentToBlocks } from \"../../api/nodeConversions/fragmentToBlocks.js\";\nimport { getNodeById } from \"../../api/nodeUtil.js\";\nimport { Block } from \"../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { MultipleNodeSelection } from \"./MultipleNodeSelection.js\";\n\nlet dragImageElement: Element | undefined;\n\nfunction blockPositionsFromSelection(selection: Selection, doc: Node) {\n // Absolute positions just before the first block spanned by the selection, and just after the last block. Having the\n // selection start and end just before and just after the target blocks ensures no whitespace/line breaks are left\n // behind after dragging & dropping them.\n let beforeFirstBlockPos: number;\n let afterLastBlockPos: number;\n\n // Even the user starts dragging blocks but drops them in the same place, the selection will still be moved just\n // before & just after the blocks spanned by the selection, and therefore doesn't need to change if they try to drag\n // the same blocks again. If this happens, the anchor & head move out of the block content node they were originally\n // in. If the anchor should update but the head shouldn't and vice versa, it means the user selection is outside a\n // block content node, which should never happen.\n const selectionStartInBlockContent =\n doc.resolve(selection.from).node().type.spec.group === \"blockContent\";\n const selectionEndInBlockContent =\n doc.resolve(selection.to).node().type.spec.group === \"blockContent\";\n\n // Ensures that entire outermost nodes are selected if the selection spans multiple nesting levels.\n const minDepth = Math.min(selection.$anchor.depth, selection.$head.depth);\n\n if (selectionStartInBlockContent && selectionEndInBlockContent) {\n // Absolute positions at the start of the first block in the selection and at the end of the last block. User\n // selections will always start and end in block content nodes, but we want the start and end positions of their\n // parent block nodes, which is why minDepth - 1 is used.\n const startFirstBlockPos = selection.$from.start(minDepth - 1);\n const endLastBlockPos = selection.$to.end(minDepth - 1);\n\n // Shifting start and end positions by one moves them just outside the first and last selected blocks.\n beforeFirstBlockPos = doc.resolve(startFirstBlockPos - 1).pos;\n afterLastBlockPos = doc.resolve(endLastBlockPos + 1).pos;\n } else {\n beforeFirstBlockPos = selection.from;\n afterLastBlockPos = selection.to;\n }\n\n return { from: beforeFirstBlockPos, to: afterLastBlockPos };\n}\n\nfunction setDragImage(view: EditorView, from: number, to = from) {\n if (from === to) {\n // Moves to position to be just after the first (and only) selected block.\n to += view.state.doc.resolve(from + 1).node().nodeSize;\n }\n\n // The preview is a copy of the element that holds the dragged blocks,\n // without its other children: a copy of each dragged block's element. The\n // holding element can have no box of its own (`display: contents`, e.g. the\n // slot of a React layout block), but the preview needs one.\n const preview = view.domAtPos(from).node.cloneNode(false) as HTMLElement;\n preview.style.removeProperty(\"display\");\n for (let pos = from; pos < to; pos += view.state.doc.nodeAt(pos)!.nodeSize) {\n const blockDOM = view.nodeDOM(pos);\n if (!blockDOM) {\n throw new Error(`The dragged block at ${pos} has no DOM.`);\n }\n preview.appendChild(blockDOM.cloneNode(true));\n }\n\n // dataTransfer.setDragImage(element) only works if element is attached to the DOM.\n unsetDragImage(view.root);\n dragImageElement = preview;\n\n // Browsers may have CORS policies which prevents iframes from being\n // manipulated, so better to stay on the safe side and remove them from the\n // drag preview. The drag preview doesn't work with embedded documents\n // (iframe/embed/object) anyway, and including an <embed> (e.g. a PDF)\n // can prevent the drag from initiating at all.\n const embeddedDocs = dragImageElement.querySelectorAll(\n \"iframe, embed, object\",\n );\n embeddedDocs.forEach((el) => el.parentElement?.removeChild(el));\n\n // TODO: This is hacky, need a better way of assigning classes to the editor so that they can also be applied to the\n // drag preview.\n const classes = view.dom.className.split(\" \");\n const inheritedClasses = classes\n .filter(\n (className) =>\n className !== \"ProseMirror\" &&\n className !== \"bn-root\" &&\n className !== \"bn-editor\",\n )\n .join(\" \");\n\n dragImageElement.className =\n dragImageElement.className + \" bn-drag-preview \" + inheritedClasses;\n\n if (view.root instanceof ShadowRoot) {\n view.root.appendChild(dragImageElement);\n } else {\n view.root.body.appendChild(dragImageElement);\n }\n}\n\nexport function unsetDragImage(rootEl: Document | ShadowRoot) {\n if (dragImageElement !== undefined) {\n if (rootEl instanceof ShadowRoot) {\n rootEl.removeChild(dragImageElement);\n } else {\n rootEl.body.removeChild(dragImageElement);\n }\n\n dragImageElement = undefined;\n }\n}\n\nexport function dragStart<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n e: { dataTransfer: DataTransfer | null; clientY: number },\n block: Block<BSchema, I, S>,\n editor: BlockNoteEditor<BSchema, I, S>,\n) {\n if (!e.dataTransfer) {\n return;\n }\n\n if (editor.headless) {\n return;\n }\n const view = editor.prosemirrorView;\n\n const posInfo = getNodeById(block.id, view.state.doc);\n if (!posInfo) {\n throw new Error(`Block with ID ${block.id} not found`);\n }\n const pos = posInfo.posBeforeNode;\n\n if (pos != null) {\n const selection = view.state.selection;\n const doc = view.state.doc;\n\n const { from, to } = blockPositionsFromSelection(selection, doc);\n\n const draggedBlockInSelection = from <= pos && pos < to;\n const multipleBlocksSelected =\n selection.$anchor.node() !== selection.$head.node() ||\n selection instanceof MultipleNodeSelection;\n\n if (draggedBlockInSelection && multipleBlocksSelected) {\n view.dispatch(\n view.state.tr.setSelection(MultipleNodeSelection.create(doc, from, to)),\n );\n setDragImage(view, from, to);\n } else {\n view.dispatch(\n view.state.tr.setSelection(NodeSelection.create(view.state.doc, pos)),\n );\n setDragImage(view, pos);\n }\n\n const selectedSlice = view.state.selection.content();\n const schema = editor.pmSchema;\n\n const clipboardHTML =\n view.serializeForClipboard(selectedSlice).dom.innerHTML;\n\n const externalHTMLExporter = createExternalHTMLExporter(schema, editor);\n\n const blocks = fragmentToBlocks(selectedSlice.content);\n const externalHTML = externalHTMLExporter.exportBlocks(blocks, {});\n\n const plainText = cleanHTMLToMarkdown(externalHTML);\n\n e.dataTransfer.clearData();\n e.dataTransfer.setData(\"blocknote/html\", clipboardHTML);\n // The type of the dragged blocks' parent. The editors parse the blocks\n // into it (see `blockDropHandling.ts`), so that a block that only this\n // parent can hold is not wrapped in a new copy of it.\n e.dataTransfer.setData(\n \"blocknote/parent\",\n view.state.selection.$from.parent.type.name,\n );\n e.dataTransfer.setData(\"text/html\", externalHTML);\n e.dataTransfer.setData(\"text/plain\", plainText);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setDragImage(dragImageElement!, 0, 0);\n }\n}\n","import { Plugin, PluginKey } from \"@tiptap/pm/state\";\n\nimport { Block } from \"../../blocks/defaultBlocks.js\";\nimport {\n createExtension,\n createStore,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { UiElementPosition } from \"../../extensions-shared/UiElementPosition.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { registerBlockDropHandlers } from \"./blockDropHandling.js\";\nimport { dragStart, unsetDragImage } from \"./dragging.js\";\nimport {\n HoveredBlock,\n isHeadingToMenu,\n Point,\n resolveHoveredBlock,\n} from \"./sideMenuHover.js\";\n\nexport type SideMenuState<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = UiElementPosition & {\n /**\n * The block that the side menu is attached to. While the menu is hidden\n * (`show` is `false`), the block it was last attached to, so it can animate\n * out next to it. The store's state is `undefined` until the menu first\n * shows.\n */\n block: Block<BSchema, I, S>;\n};\n\n/**\n * How far the areas around the editor where the side menu responds reach, in\n * px from the editor element's box. The editor element itself (including its\n * padding, where the menu sits) always counts.\n */\nexport type SideMenuOptions = {\n /**\n * How far left or right of the editor element the pointer still shows the\n * side menu, for the block at the pointer's height. Above or below the\n * editor, no block is at that height.\n * @default 0\n */\n hoverMargin?: number;\n /**\n * How far outside the editor element, on any side, a dragged block can still\n * be dropped into it (the drop goes to the nearest position in the editor).\n * @default 250\n */\n dropMargin?: number;\n};\n\n/**\n * How long the pointer may rest on its way to the menu (inside the triangle\n * from where it left the block to the menu) before the menu follows it to the\n * block it is over.\n */\nconst INTENT_TIMEOUT = 350;\n\n/** The event's target as an element (text nodes resolve to their parent). */\nfunction targetElement(target: EventTarget | null): Element | null {\n if (!target || !(\"nodeType\" in target)) {\n return null;\n }\n const node = target as Node;\n return node.nodeType === Node.ELEMENT_NODE\n ? (node as Element)\n : node.parentElement;\n}\n\nexport const sideMenuPluginKey = new PluginKey(\"SideMenuPlugin\");\n\n/**\n * Shows a menu next to the block the pointer is about. This\n * extension owns that decision: it listens to the pointer in `mount` and\n * writes the store; the UI only reads the store, positions the menu, and\n * registers the menu's element with `setMenuElement`.\n *\n * The block comes from the topmost element under the pointer (so an editor\n * covered by another element or editor gets no menu), falling back to probing\n * at the pointer's height when that element is padding or the gutter beside\n * the blocks. When the pointer leaves the block towards the menu, the menu\n * stays with the block while the pointer is inside the triangle from its exit\n * point to the menu, until it rests there for {@link INTENT_TIMEOUT}. Once on\n * the menu, leaving it anywhere but onto its block follows the pointer at\n * once. The menu hides when the pointer leaves the window.\n */\nexport const SideMenuExtension = createExtension(\n ({\n editor,\n options,\n }: ExtensionOptions<{ sideMenu?: SideMenuOptions } | undefined>) => {\n const store = createStore<SideMenuState<any, any, any> | undefined>(\n undefined,\n );\n\n const hoverMargin = options?.sideMenu?.hoverMargin ?? 0;\n\n let menuFrozen = false;\n let isDragOrigin = false;\n // The side menu's DOM element, registered by the UI that renders it.\n let menuElement: HTMLElement | undefined;\n // The last pointer position over this document.\n let pointer: Point | undefined;\n // The last pointer position over the active block (or the menu).\n let lastOnActive: Point | undefined;\n // Set while the pointer is heading from the active block to the menu.\n let intent:\n | { exit: Point; timer: ReturnType<typeof setTimeout> }\n | undefined;\n\n function isDraggable(type: string) {\n return editor.schema.blockSpecs[type].implementation.meta.draggable;\n }\n\n function clearIntent() {\n if (intent) {\n clearTimeout(intent.timer);\n intent = undefined;\n }\n }\n\n function hideMenu() {\n const state = store.state;\n if (state?.show) {\n store.setState({ ...state, show: false });\n }\n }\n\n function showMenu(hovered: HoveredBlock) {\n const block = editor.getBlock(hovered.id);\n if (!block) {\n hideMenu();\n return;\n }\n store.setState({\n show: true,\n // The hovered block's box: the menu goes next to the block itself, as\n // the React UI anchors it to the block's element.\n referencePos: hovered.node.getBoundingClientRect(),\n block,\n });\n }\n\n /**\n * Updates the menu for the pointer at `point` over `target`. With\n * `allowIntent`, a pointer heading to the menu keeps the active block.\n */\n function update(\n point: Point,\n target: Element | null,\n allowIntent: boolean,\n ) {\n // While a block is dragged by its handle, the menu must stay as it is:\n // the handle is the drag source, and if the menu hid or moved, React would\n // remove it from the DOM, so its `dragend` (and `blockDragEnd`, which\n // removes the drag image) would never fire. The drop's document change\n // otherwise re-resolves the block at the pointer's pre-drag position.\n if (menuFrozen || isDragOrigin) {\n // Frozen or dragging: keep the menu as it is.\n return;\n }\n if (target && menuElement?.contains(target)) {\n // On the menu: the pointer got where it was heading. Recording the\n // point here makes it the exit point if the pointer leaves the menu,\n // and as nothing is closer to the menu than the menu, leaving it\n // anywhere but onto its block follows the pointer at once.\n clearIntent();\n lastOnActive = point;\n // On the menu: keep the menu as it is.\n return;\n }\n\n if (!editor.isEditable) {\n clearIntent();\n hideMenu();\n // Read-only editor: hide the menu.\n return;\n }\n\n const resolution = resolveHoveredBlock(\n editor.prosemirrorView,\n target,\n point,\n isDraggable,\n editor.isWithinEditor,\n hoverMargin,\n );\n if (resolution.kind === \"editorUI\") {\n // On other UI of the editor (e.g. a toolbar): keep the menu as it is.\n return;\n }\n\n const state = store.state;\n const active = state?.show ? state.block.id : undefined;\n if (resolution.kind === \"block\" && resolution.block.id === active) {\n clearIntent();\n lastOnActive = point;\n // On the block of the menu: keep the menu as it is.\n return;\n }\n\n if (allowIntent && active !== undefined && menuElement?.isConnected) {\n const exit = intent?.exit ?? lastOnActive ?? point;\n if (isHeadingToMenu(point, exit, menuElement.getBoundingClientRect())) {\n // Restarts the timeout, so it measures how long the pointer rests.\n clearIntent();\n intent = { exit, timer: setTimeout(releaseIntent, INTENT_TIMEOUT) };\n // On the way to the menu: keep the menu on its block for now.\n return;\n }\n }\n\n // Not on the way to the menu: show the menu for the block under the\n // pointer, or hide it if there is no block.\n clearIntent();\n if (resolution.kind === \"block\") {\n lastOnActive = point;\n showMenu(resolution.block);\n } else {\n hideMenu();\n }\n }\n\n function endBlockDrag() {\n unsetDragImage(editor.prosemirrorView.root);\n isDragOrigin = false;\n }\n\n /** The pointer rested on its way to the menu: follow it after all. */\n function releaseIntent() {\n intent = undefined;\n refresh();\n }\n\n /**\n * Re-resolves the block for the last pointer position, without intent,\n * e.g. after a document change. If the pointer is on the menu (e.g. it\n * clicked a menu button), this resolves just right of the menu instead:\n * the menu is next to its block, so that point is on the line of the block,\n * in its column. The pointer itself can be over another block, e.g. the\n * \"+\" of a block in a column is over the column to its left. If the block\n * was removed, the block that moved up into its place takes over.\n */\n function refresh() {\n if (!pointer) {\n return;\n }\n const view = editor.prosemirrorView;\n const menu = menuElement?.isConnected\n ? menuElement.getBoundingClientRect()\n : undefined;\n const onMenu =\n menu !== undefined &&\n pointer.x >= menu.left &&\n pointer.x <= menu.right &&\n pointer.y >= menu.top &&\n pointer.y <= menu.bottom;\n const point = onMenu ? { x: menu.right + 1, y: pointer.y } : pointer;\n // Looks past other UI of the editor at what is underneath.\n const target =\n view.root\n .elementsFromPoint(point.x, point.y)\n .find(\n (element) =>\n view.dom.contains(element) || !editor.isWithinEditor(element),\n ) ?? null;\n update(point, target, false);\n }\n\n return {\n key: \"sideMenu\",\n store,\n prosemirrorPlugins: [\n new Plugin({\n key: sideMenuPluginKey,\n appendTransaction: (transactions, _oldState, newState) => {\n if (transactions.some((tr) => tr.getMeta(\"uiEvent\") === \"drop\")) {\n // Forces a `scrollIntoView` immediately after a drop. Fixes WebKit\n // specific behavior where focusing scrolls the selection into\n // view. This happens on drop before ProseMirror updates the\n // document/selection, which is incorrect.\n return newState.tr.scrollIntoView();\n }\n return null;\n },\n }),\n ],\n mount({\n root,\n signal,\n }: {\n root: Document | ShadowRoot;\n signal: AbortSignal;\n }) {\n registerBlockDropHandlers(\n editor.prosemirrorView,\n () => isDragOrigin,\n options?.sideMenu?.dropMargin ?? 250,\n signal,\n );\n\n // Shows or updates the menu whenever the pointer moves, unless frozen.\n root.addEventListener(\n // `mousemove`, not `pointermove`: iOS Safari delivers a tap as a hover\n // (one compatibility `mousemove` to the tap point, then the click),\n // which is how the side menu shows on phones.\n \"mousemove\",\n (event) => {\n // Synthetic events created via `new Event(\"mousemove\")` (e.g.\n // dispatched by browser extensions) have no `clientX`/`clientY`,\n // which would make `elementsFromPoint` throw on the resulting\n // non-finite coordinates.\n const { clientX, clientY, buttons } = event as Partial<MouseEvent>;\n if (\n menuFrozen ||\n typeof clientX !== \"number\" ||\n typeof clientY !== \"number\" ||\n !Number.isFinite(clientX) ||\n !Number.isFinite(clientY)\n ) {\n return;\n }\n if (isDragOrigin && buttons === 0) {\n // The drag ended without `dragend` reaching the handle (e.g. the\n // menu was unmounted by its controller): clean up now.\n endBlockDrag();\n }\n const point = { x: clientX, y: clientY };\n pointer = point;\n update(point, targetElement(event.target), true);\n },\n { signal, capture: true },\n );\n\n // The pointer left the window: no block is hovered any more. Only\n // `mouseout` reports this (with no `relatedTarget`), as `mouseleave`\n // doesn't reach a document or shadow root.\n root.addEventListener(\n \"mouseout\",\n (event) => {\n if (\n (event as MouseEvent).relatedTarget === null &&\n !menuFrozen &&\n !isDragOrigin\n ) {\n pointer = undefined;\n clearIntent();\n hideMenu();\n }\n },\n { signal, capture: true },\n );\n\n // Hides the menu whenever the user types.\n root.addEventListener(\n \"keydown\",\n () => {\n if (store.state?.show && editor.isFocused()) {\n clearIntent();\n hideMenu();\n }\n },\n { signal, capture: true },\n );\n\n // Needed in cases where the document changes without the pointer\n // moving: blocks move under it when blocks above it change. For\n // example, a side menu button which removes the block can cause the\n // block below to jump up into the place of the removed block when\n // clicked, allowing the user to click the button again without moving\n // the pointer. This would otherwise not update the side menu, and so\n // clicking the button again would attempt to remove the same block\n // again, causing an error.\n const unsubscribeOnChange = editor.onChange(() => {\n if (store.state?.show) {\n clearIntent();\n refresh();\n }\n });\n\n signal.addEventListener(\"abort\", () => {\n unsubscribeOnChange();\n clearIntent();\n hideMenu();\n });\n },\n\n /**\n * Registers the element that renders the side menu. Moving the pointer\n * from a block towards this element keeps the menu on that block, and\n * hovering it never changes the block.\n */\n setMenuElement(element: HTMLElement | undefined) {\n menuElement = element;\n },\n\n /**\n * Handles drag & drop events for blocks.\n */\n blockDragStart(\n event: { dataTransfer: DataTransfer | null; clientY: number },\n block: Block<any, any, any>,\n ) {\n isDragOrigin = true;\n dragStart(event, block, editor);\n },\n\n /**\n * Handles drag & drop events for blocks.\n */\n blockDragEnd() {\n endBlockDrag();\n editor.blur();\n },\n\n /**\n * Whether the side menu is currently frozen (e.g. because the drag handle\n * menu is open).\n */\n get menuFrozen() {\n return menuFrozen;\n },\n\n /**\n * Freezes the side menu. When frozen, the side menu will stay\n * attached to the same block regardless of which block is hovered by the\n * mouse cursor.\n */\n freezeMenu() {\n menuFrozen = true;\n clearIntent();\n const state = store.state;\n if (state) {\n store.setState({ ...state, show: true });\n }\n },\n\n /**\n * Unfreezes the side menu. When frozen, the side menu will stay\n * attached to the same block regardless of which block is hovered by the\n * mouse cursor.\n */\n unfreezeMenu() {\n menuFrozen = false;\n hideMenu();\n },\n\n /**\n * Hides the side menu unless it is currently frozen (e.g. the drag\n * handle menu is open). Used to dismiss the menu on scroll without\n * interfering with open submenus.\n */\n hideMenuIfNotFrozen() {\n // A drag can scroll the page, but hiding the menu would remove the drag\n // source (see `update`).\n if (!menuFrozen && !isDragOrigin) {\n clearIntent();\n hideMenu();\n }\n },\n } as const;\n },\n);\n","import { TextSelection } from \"prosemirror-state\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor\";\nimport {\n createExtension,\n createStore,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { Block } from \"../../blocks/index.js\";\n\n/**\n * A single editor-wide extension that drives the source popup for blocks that\n * render a preview. Which blocks it activates on is decided by each spec's\n * `meta.hasPreview` flag, so individual blocks opt in rather than the extension\n * being configured with a block type.\n *\n * The extension is registered once (it's a default extension) and is a no-op\n * when no block declares `meta.hasPreview`.\n */\nexport const SourceBlockWithPreviewExtension = createExtension(\n ({ editor }: { editor: BlockNoteEditor<any> }) => {\n const store = createStore<{\n popupOpen: string | undefined;\n selected: string | undefined;\n }>({\n popupOpen: undefined,\n selected: undefined,\n });\n\n // A block has a preview iff its spec's implementation declares\n // `meta.hasPreview` (read from the spec, like the syntax-highlighting\n // extension reads `meta.highlight`).\n const blockHasPreview = (block: Block<any, any, any>) =>\n !!editor.schema.blockSpecs[block.type]?.implementation.meta.hasPreview;\n\n const handleArrow =\n (direction: \"prev\" | \"next\") =>\n ({ editor }: { editor: BlockNoteEditor<any> }) => {\n const { block, prevBlock, nextBlock } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen === block.id) {\n return false;\n }\n\n const targetBlock = direction === \"prev\" ? prevBlock : nextBlock;\n if (!targetBlock) {\n return false;\n }\n\n editor.setTextCursorPosition(\n targetBlock.id,\n direction === \"prev\" ? \"end\" : \"start\",\n );\n\n return true;\n };\n\n return {\n key: \"sourceBlockWithPreview\",\n store,\n keyboardShortcuts: {\n // Toggles the popup, unless Enter inserts line breaks in the block\n // (`keyboard.enter: \"line-break\"`).\n Enter: ({ editor }) => {\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block)) {\n return false;\n }\n\n if (\n store.state.popupOpen === block.id &&\n editor.schema.blockSpecs[block.type].implementation.keyboard(block)\n .enter === \"line-break\"\n ) {\n const view = editor.prosemirrorView!;\n view.dispatch(view.state.tr.insertText(\"\\n\"));\n\n return true;\n }\n\n editor.setTextCursorPosition(block.id, \"end\");\n store.setState((state) => ({\n ...state,\n popupOpen:\n store.state.popupOpen === block.id ? undefined : block.id,\n }));\n\n return true;\n },\n // Closes the popup.\n Escape: ({ editor }) => {\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen !== block.id) {\n return false;\n }\n\n editor.setTextCursorPosition(block.id, \"end\");\n\n store.setState((state) => ({ ...state, popupOpen: undefined }));\n\n return true;\n },\n // While the popup is open, selects the whole source instead of the\n // whole document.\n \"Mod-a\": ({ editor }) => {\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen !== block.id) {\n return false;\n }\n\n const view = editor.prosemirrorView!;\n const { $from } = view.state.selection;\n if ($from.parent.type.name !== block.type) {\n return false;\n }\n\n view.dispatch(\n view.state.tr.setSelection(\n TextSelection.create(view.state.doc, $from.start(), $from.end()),\n ),\n );\n\n return true;\n },\n // While the popup is closed, moves the selection straight to the previous/next block\n // instead of into the (hidden) source.\n ArrowUp: handleArrow(\"prev\"),\n ArrowLeft: handleArrow(\"prev\"),\n ArrowDown: handleArrow(\"next\"),\n ArrowRight: handleArrow(\"next\"),\n },\n mount: ({ dom, signal }) => {\n // Closes the popup when the selection leaves the block that owns it and tracks which block\n // the selection is in.\n const unsubscribeSelectionChange = editor.onSelectionChange(() => {\n const { block } = editor.getTextCursorPosition();\n\n const selected = blockHasPreview(block) ? block.id : undefined;\n const popupOpen =\n store.state.popupOpen && store.state.popupOpen !== block.id\n ? undefined\n : store.state.popupOpen;\n\n if (\n selected === store.state.selected &&\n popupOpen === store.state.popupOpen\n ) {\n return;\n }\n\n store.setState((state) => ({ ...state, selected, popupOpen }));\n });\n signal.addEventListener(\"abort\", unsubscribeSelectionChange);\n\n // While the popup is closed, prevents editing of the (hidden) source. Handled here rather\n // than in `keyboardShortcuts` as it needs to match any text-input key, which a keymap\n // can't express.\n const handleKeyDown = (event: KeyboardEvent) => {\n if (!editor.isEditable) {\n return;\n }\n\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen === block.id) {\n return;\n }\n\n if (event.key === \"Backspace\" || event.key === \"Delete\") {\n event.preventDefault();\n event.stopImmediatePropagation();\n editor.removeBlocks([block.id]);\n\n return;\n }\n\n if (\n (event.key.length === 1 && !event.ctrlKey && !event.metaKey) ||\n event.key === \"Tab\"\n ) {\n event.preventDefault();\n event.stopImmediatePropagation();\n }\n };\n dom.addEventListener(\"keydown\", handleKeyDown, {\n capture: true,\n signal,\n });\n\n const handleBlur = () =>\n store.setState((state) => ({ ...state, popupOpen: undefined }));\n dom.addEventListener(\"blur\", handleBlur, { capture: true, signal });\n },\n };\n },\n);\n","import { Selection, TextSelection } from \"prosemirror-state\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor\";\nimport {\n createExtension,\n createStore,\n} from \"../../editor/BlockNoteExtension.js\";\n\n/**\n * Inline-content counterpart of {@link SourceBlockWithPreviewExtension}. A\n * single editor-wide extension that drives the source popup for inline content\n * that renders a preview. Which inline content it activates on is decided by\n * each spec's `meta.hasPreview` flag, so individual inline content opts in\n * rather than the extension being configured with a type.\n *\n * Unlike the block version, the popup isn't toggled with a separate state flag:\n * it's open exactly when the selection is inside the inline content's source.\n * The store therefore only tracks which inline content (by its position) holds\n * the selection - moving the selection in opens its popup, moving it out closes\n * it. Since the source popup is always laid out (just hidden via opacity), the\n * cursor can navigate into and out of it with the arrow keys as usual.\n *\n * The extension is registered once (it's a default extension) and is a no-op\n * when no inline content declares `meta.hasPreview`.\n */\nexport const SourceInlineContentWithPreviewExtension = createExtension(\n ({ editor }: { editor: BlockNoteEditor<any, any, any> }) => {\n const store = createStore<{\n selected: number | undefined;\n }>({\n selected: undefined,\n });\n\n // Inline content has a preview iff its spec's implementation declares\n // `meta.hasPreview`.\n const nodeHasPreview = (nodeName: string) =>\n !!editor.schema.inlineContentSpecs[nodeName]?.implementation?.meta\n ?.hasPreview;\n\n // Moves the selection out of the inline content, to just `\"before\"` or\n // `\"after\"` it, which closes the popup via the selection-change handler\n // below. Lets the keyboard commit-and-exit the source the same way arrowing\n // past its edge does, keeps Enter from splitting the block while editing the\n // source, and lets the up/down arrows step out of the source rather than\n // staying trapped inside it.\n const moveSelectionOut =\n (direction: \"before\" | \"after\") =>\n ({ editor }: { editor: BlockNoteEditor<any, any, any> }) => {\n const { $from } = editor.prosemirrorState.selection;\n const node = $from.node();\n if (!nodeHasPreview(node.type.name)) {\n return false;\n }\n\n const view = editor.prosemirrorView!;\n const selection = Selection.near(\n view.state.doc.resolve(\n direction === \"before\" ? $from.before() : $from.after(),\n ),\n direction === \"before\" ? -1 : 1,\n );\n view.dispatch(view.state.tr.setSelection(selection));\n\n return true;\n };\n\n return {\n key: \"sourceInlineContentWithPreview\",\n store,\n keyboardShortcuts: {\n Enter: moveSelectionOut(\"after\"),\n \"Shift-Enter\": moveSelectionOut(\"after\"),\n Escape: moveSelectionOut(\"after\"),\n ArrowUp: moveSelectionOut(\"before\"),\n ArrowDown: moveSelectionOut(\"after\"),\n // While editing the source, selects the whole source instead of the\n // whole document.\n \"Mod-a\": ({ editor }) => {\n const { $from } = editor.prosemirrorState.selection;\n if (!nodeHasPreview($from.node().type.name)) {\n return false;\n }\n\n const view = editor.prosemirrorView!;\n view.dispatch(\n view.state.tr.setSelection(\n TextSelection.create(view.state.doc, $from.start(), $from.end()),\n ),\n );\n\n return true;\n },\n },\n mount: ({ dom, signal }) => {\n // The popup is open exactly when the selection is inside the inline\n // content, so we just track which inline content (if any) holds it.\n const unsubscribeSelectionChange = editor.onSelectionChange(() => {\n const { $from } = editor.prosemirrorState.selection;\n const node = $from.node();\n\n store.setState({\n selected: nodeHasPreview(node.type.name)\n ? $from.before()\n : undefined,\n });\n });\n signal.addEventListener(\"abort\", unsubscribeSelectionChange);\n\n // Sets `visibility: hidden` on the popup for a single frame when pressing up/down arrow\n // keys. The popup is normally hidden through `opacity: 0`, which means it's still visible\n // to the browser for navigation. Therefore, the up/down arrows can sometimes move the\n // selection into the popup from unexpected positions, such as on the same line. Setting\n // `visibility: hidden` makes the browser ignore it when determining the new selection.\n // TODO: This is hacky, we should find a cleaner solution.\n const handleVerticalArrow = (event: KeyboardEvent) => {\n if (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\") {\n return;\n }\n\n // When the selection is already inside a source, leave navigation\n // (moving within or out of it) to the browser as usual.\n const { $from } = editor.prosemirrorState.selection;\n if (nodeHasPreview($from.node().type.name)) {\n return;\n }\n\n dom.classList.add(\"bn-suppress-source-popup-caret\");\n requestAnimationFrame(() =>\n dom.classList.remove(\"bn-suppress-source-popup-caret\"),\n );\n };\n dom.addEventListener(\"keydown\", handleVerticalArrow, {\n capture: true,\n signal,\n });\n\n const handleBlur = () => store.setState({ selected: undefined });\n dom.addEventListener(\"blur\", handleBlur, { capture: true, signal });\n },\n };\n },\n);\n","import type { HighlighterGeneric } from \"@shikijs/types\";\nimport { Parser, createHighlightPlugin } from \"prosemirror-highlight\";\nimport { createParser } from \"prosemirror-highlight/shiki\";\nimport type { SyntaxHighlightingOptions } from \"./SyntaxHighlighting.js\";\nimport { CustomBlockNoteSchema } from \"../../schema/schema.js\";\n\nexport const shikiParserSymbol = Symbol.for(\"blocknote.shikiParser\");\nexport const shikiHighlighterPromiseSymbol = Symbol.for(\n \"blocknote.shikiHighlighterPromise\",\n);\n\n// Languages that represent \"no highlighting\" - skipped without asking Shiki to\n// load a grammar for them.\nconst PLAIN_TEXT_LANGUAGES = [\"text\", \"none\", \"plaintext\", \"txt\"];\n\n/**\n * Creates the syntax highlighting plugin for the given block types, lazily\n * loading the highlighter on first use.\n *\n * Each spec's `meta.highlight` callback resolves a node to a language, which is\n * passed straight to Shiki - it resolves aliases and loads the grammar from its\n * bundle, so any language the provided highlighter bundles can be highlighted.\n */\nexport function lazyShikiPlugin(\n options: SyntaxHighlightingOptions,\n nodeTypes: string[],\n schema: CustomBlockNoteSchema<any, any, any>,\n) {\n const globalThisForShiki = globalThis as {\n [shikiHighlighterPromiseSymbol]?: Promise<HighlighterGeneric<any, any>>;\n [shikiParserSymbol]?: Parser;\n };\n\n let highlighter: HighlighterGeneric<any, any> | undefined;\n let parser: Parser | undefined;\n // Languages the highlighter failed to load (e.g. not in its bundle). Tracked\n // so we don't keep retrying - and re-triggering re-highlights - forever.\n const unsupportedLanguages = new Set<string>();\n const lazyParser: Parser = (parserOptions) => {\n if (!options.createHighlighter) {\n return [];\n }\n if (!highlighter) {\n globalThisForShiki[shikiHighlighterPromiseSymbol] =\n globalThisForShiki[shikiHighlighterPromiseSymbol] ||\n options.createHighlighter();\n\n return globalThisForShiki[shikiHighlighterPromiseSymbol].then(\n (createdHighlighter) => {\n highlighter = createdHighlighter;\n },\n );\n }\n const language = parserOptions.language;\n\n if (\n !language ||\n PLAIN_TEXT_LANGUAGES.includes(language) ||\n unsupportedLanguages.has(language)\n ) {\n return [];\n }\n\n if (!highlighter.getLoadedLanguages().includes(language)) {\n return highlighter.loadLanguage(language as any).catch(() => {\n // The highlighter doesn't bundle this language - give up on it so we\n // don't loop trying to load it on every re-highlight.\n unsupportedLanguages.add(language);\n });\n }\n\n if (!parser) {\n parser =\n globalThisForShiki[shikiParserSymbol] ||\n createParser(highlighter as any, pickThemeOptions(highlighter));\n globalThisForShiki[shikiParserSymbol] = parser;\n }\n\n return parser(parserOptions);\n };\n\n return createHighlightPlugin({\n parser: lazyParser,\n // The highlight plugin only gives us the block content node, so we can only\n // reconstruct the block's `type` and `props` (which is all a spec's\n // `meta.highlight` needs to pick a language).\n languageExtractor: (node) => {\n const nodeShape = {\n type: node.type.name,\n props: node.attrs,\n };\n // search for the node in the blockSpec or inlineContentSpecs\n const spec =\n schema.blockSpecs[nodeShape.type] ||\n schema.inlineContentSpecs[nodeShape.type];\n\n return spec?.implementation.meta.highlight?.(nodeShape) ?? undefined;\n },\n nodeTypes,\n });\n}\n\n// If a light and dark theme is added to the highlighter, this function specifies them in\n// `createParser`. This lets us use `--shiki-light` and `--shiki-dark` CSS variables for correct\n// styling for both light & dark editor themes.\nfunction pickThemeOptions(highlighter: HighlighterGeneric<any, any>) {\n const themes = highlighter.getLoadedThemes();\n const light = themes.find((t) => /light/i.test(t));\n const dark = themes.find((t) => /dark/i.test(t));\n\n if (light && dark) {\n return { themes: { light, dark }, defaultColor: false as const };\n }\n\n return undefined;\n}\n","import type { HighlighterGeneric } from \"@shikijs/types\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { lazyShikiPlugin } from \"./shiki.js\";\nimport {\n CustomInlineContentConfig,\n InlineContentSpec,\n LooseBlockSpec,\n} from \"../../schema/index.js\";\n\nexport type SyntaxHighlightingOptions = {\n /**\n * Creates the Shiki highlighter used for syntax highlighting. Can be\n * asynchronous, so the highlighter is only loaded once it's first needed.\n *\n * When omitted, content renders without syntax highlighting.\n */\n createHighlighter: () => Promise<HighlighterGeneric<any, any>>;\n};\n\n/**\n * Collects the node type names that should be syntax-highlighted from a schema's\n * block and inline-content specs.\n *\n * A spec is a candidate when it has a `meta.highlight` callback (which decides\n * the language) AND the node actually holds editable text. Block and\n * inline-content specs use different `content` value spaces, so \"editable text\"\n * means `content === \"plain\"` for both blocks (code/math blocks) and inline\n * content (inline math) - both hold plain text - hence the two are filtered\n * separately.\n *\n * Inline content (e.g. inline math) is highlighted too: `prosemirror-highlight`\n * collects nodes by `node.inlineContent` since v0.15.3\n * (https://github.com/ocavue/prosemirror-highlight/pull/137), so inline nodes\n * holding inline content are visited alongside text blocks.\n */\nexport function collectHighlightNodeTypes(schema: {\n blockSpecs: Record<string, unknown>;\n inlineContentSpecs: Record<string, unknown>;\n}): string[] {\n const blockNodeTypes = Object.values(schema.blockSpecs)\n .filter(\n (blockSpec): blockSpec is LooseBlockSpec =>\n typeof (blockSpec as LooseBlockSpec)?.config === \"object\" &&\n (blockSpec as LooseBlockSpec).config.content === \"plain\" &&\n !!(blockSpec as LooseBlockSpec).implementation.meta.highlight,\n )\n .map((blockSpec) => blockSpec.config.type);\n\n const inlineContentNodeTypes = Object.values(schema.inlineContentSpecs)\n .filter(\n (\n inlineContentSpec,\n ): inlineContentSpec is InlineContentSpec<CustomInlineContentConfig> =>\n typeof (\n inlineContentSpec as InlineContentSpec<CustomInlineContentConfig>\n )?.config === \"object\" &&\n (inlineContentSpec as InlineContentSpec<CustomInlineContentConfig>)\n .config.content === \"plain\" &&\n !!(inlineContentSpec as InlineContentSpec<CustomInlineContentConfig>)\n .implementation?.meta?.highlight,\n )\n .map((inlineContentSpec) => inlineContentSpec.config.type);\n\n return [...blockNodeTypes, ...inlineContentNodeTypes];\n}\n\n/**\n * A single editor-wide extension that syntax-highlights block and inline-content\n * content. Which nodes get highlighted (and as which language) is decided by\n * each spec's `meta.highlight` callback, so individual specs declare their own\n * language rather than the extension configuring them.\n *\n * Highlighting is opt-in: the user adds this extension to the editor's\n * `extensions` (configured with a `createHighlighter`) to enable it. When it's\n * absent, content renders as plain text.\n */\nexport const SyntaxHighlightingExtension = createExtension(\n ({ editor, options }: ExtensionOptions<SyntaxHighlightingOptions>) => {\n const nodeTypes = collectHighlightNodeTypes(editor.schema);\n\n return {\n key: \"syntaxHighlighting\",\n prosemirrorPlugins: [lazyShikiPlugin(options, nodeTypes, editor.schema)],\n };\n },\n);\n","import type { Emoji, EmojiMartData } from \"@emoji-mart/data\";\n\nimport { defaultInlineContentSchema } from \"../../blocks/defaultBlocks.js\";\nimport { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { DefaultGridSuggestionItem } from \"./DefaultGridSuggestionItem.js\";\n\n// Temporary fix for https://github.com/missive/emoji-mart/pull/929\nlet emojiLoadingPromise:\n | Promise<{\n emojiMart: typeof import(\"emoji-mart\");\n emojiData: EmojiMartData;\n }>\n | undefined;\n\nasync function loadEmojiMart() {\n if (emojiLoadingPromise) {\n return emojiLoadingPromise;\n }\n\n emojiLoadingPromise = (async () => {\n // load dynamically because emoji-mart doesn't specify type: module and breaks in nodejs\n const [emojiMartModule, emojiDataModule] = await Promise.all([\n import(\"emoji-mart\"),\n // use a dynamic import to encourage bundle-splitting\n // and a smaller initial client bundle size\n import(\"@emoji-mart/data\"),\n ]);\n\n const emojiMart =\n \"default\" in emojiMartModule ? emojiMartModule.default : emojiMartModule;\n const emojiData =\n \"default\" in emojiDataModule\n ? (emojiDataModule.default as EmojiMartData)\n : (emojiDataModule as EmojiMartData);\n\n await emojiMart.init({ data: emojiData });\n\n return { emojiMart, emojiData };\n })();\n\n return emojiLoadingPromise;\n}\n\nexport async function getDefaultEmojiPickerItems<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n query: string,\n): Promise<DefaultGridSuggestionItem[]> {\n if (\n !(\"text\" in editor.schema.inlineContentSchema) ||\n editor.schema.inlineContentSchema[\"text\"] !==\n defaultInlineContentSchema[\"text\"]\n ) {\n return [];\n }\n\n const { emojiData, emojiMart } = await loadEmojiMart();\n\n const emojisToShow =\n query.trim() === \"\"\n ? Object.values(emojiData.emojis)\n : ((await emojiMart!.SearchIndex.search(query)) as Emoji[]);\n\n return emojisToShow.map((emoji) => ({\n id: emoji.skins[0].native,\n onItemClick: () => editor.insertInlineContent(emoji.skins[0].native + \" \"),\n }));\n}\n","import type { Node } from \"prosemirror-model\";\nimport { EditorState, Plugin, PluginKey, PluginView } from \"prosemirror-state\";\nimport {\n CellSelection,\n addColumnAfter,\n addColumnBefore,\n addRowAfter,\n addRowBefore,\n deleteColumn,\n deleteRow,\n mergeCells,\n splitCell,\n} from \"prosemirror-tables\";\nimport { Decoration, DecorationSet, EditorView } from \"prosemirror-view\";\nimport {\n RelativeCellIndices,\n addRowsOrColumns,\n areInSameColumn,\n canColumnBeDraggedInto,\n canRowBeDraggedInto,\n cropEmptyRowsOrColumns,\n getCellsAtColumnHandle,\n getCellsAtRowHandle,\n getDimensionsOfTable,\n moveColumn,\n moveRow,\n} from \"../../api/blockManipulation/tables/tables.js\";\nimport { nodeToBlock } from \"../../api/nodeConversions/nodeToBlock.js\";\nimport { getNodeById } from \"../../api/nodeUtil.js\";\nimport {\n blockHasType,\n isTableCellNode,\n isTableCellSelection,\n} from \"../../blocks/defaultBlockTypeGuards.js\";\nimport { DefaultBlockSchema } from \"../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n createExtension,\n createStore,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n BlockFromConfigNoChildren,\n BlockSchemaWithBlock,\n} from \"../../schema/index.js\";\nimport { getBlockFromElement } from \"../blockDOM.js\";\n\nlet dragImageElement: HTMLElement | undefined;\n\n// TODO consider switching this to jotai, it is a bit messy and noisy\nexport type TableHandlesState = {\n show: boolean;\n showAddOrRemoveRowsButton: boolean;\n showAddOrRemoveColumnsButton: boolean;\n referencePosCell: DOMRect | undefined;\n referencePosTable: DOMRect;\n\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>;\n colIndex: number | undefined;\n rowIndex: number | undefined;\n\n draggingState:\n | {\n draggedCellOrientation: \"row\" | \"col\";\n originalIndex: number;\n mousePos: number;\n }\n | undefined;\n\n widgetContainer: HTMLElement | undefined;\n};\n\nfunction setHiddenDragImage(rootEl: Document | ShadowRoot) {\n if (dragImageElement) {\n return;\n }\n\n dragImageElement = document.createElement(\"div\");\n dragImageElement.innerHTML = \"_\";\n dragImageElement.style.opacity = \"0\";\n dragImageElement.style.height = \"1px\";\n dragImageElement.style.width = \"1px\";\n if (rootEl instanceof Document) {\n rootEl.body.appendChild(dragImageElement);\n } else {\n rootEl.appendChild(dragImageElement);\n }\n}\n\nfunction unsetHiddenDragImage(rootEl: Document | ShadowRoot) {\n if (dragImageElement) {\n if (rootEl instanceof Document) {\n rootEl.body.removeChild(dragImageElement);\n } else {\n rootEl.removeChild(dragImageElement);\n }\n dragImageElement = undefined;\n }\n}\n\nfunction getChildIndex(node: Element) {\n return Array.prototype.indexOf.call(node.parentElement!.childNodes, node);\n}\n\n// Finds the DOM element corresponding to the table cell that the target element\n// is currently in. If the target element is not in a table cell, returns null.\nfunction domCellAround(target: Element) {\n let currentTarget: Element | undefined = target;\n while (\n currentTarget &&\n currentTarget.nodeName !== \"TD\" &&\n currentTarget.nodeName !== \"TH\" &&\n !currentTarget.classList.contains(\"tableWrapper\")\n ) {\n if (currentTarget.classList.contains(\"ProseMirror\")) {\n return undefined;\n }\n const parent: ParentNode | null = currentTarget.parentNode;\n\n if (!parent || !(parent instanceof Element)) {\n return undefined;\n }\n currentTarget = parent;\n }\n\n return currentTarget.nodeName === \"TD\" || currentTarget.nodeName === \"TH\"\n ? {\n type: \"cell\",\n domNode: currentTarget,\n tbodyNode: currentTarget.closest(\"tbody\"),\n }\n : {\n type: \"wrapper\",\n domNode: currentTarget,\n tbodyNode: currentTarget.querySelector(\"tbody\"),\n };\n}\n\n// Hides elements in the DOMwith the provided class names.\nfunction hideElements(selector: string, rootEl: Document | ShadowRoot) {\n const elementsToHide = rootEl.querySelectorAll(selector);\n\n for (let i = 0; i < elementsToHide.length; i++) {\n (elementsToHide[i] as HTMLElement).style.visibility = \"hidden\";\n }\n}\n\nexport class TableHandlesView implements PluginView {\n public state?: TableHandlesState;\n public emitUpdate: () => void;\n\n public tableId: string | undefined;\n public tablePos: number | undefined;\n public tableElement: HTMLElement | undefined;\n\n public menuFrozen = false;\n\n public mouseState: \"up\" | \"down\" | \"selecting\" = \"up\";\n\n public prevWasEditable: boolean | null = null;\n\n constructor(\n private readonly editor: BlockNoteEditor<\n BlockSchemaWithBlock<\"table\", DefaultBlockSchema[\"table\"]>,\n any,\n any\n >,\n private readonly pmView: EditorView,\n emitUpdate: (state: TableHandlesState | undefined) => void,\n ) {\n this.emitUpdate = () => {\n emitUpdate(this.state);\n };\n\n pmView.dom.addEventListener(\"mousemove\", this.mouseMoveHandler);\n pmView.dom.addEventListener(\"mousedown\", this.viewMousedownHandler);\n window.addEventListener(\"mouseup\", this.mouseUpHandler);\n\n pmView.root.addEventListener(\n \"dragover\",\n this.dragOverHandler as EventListener,\n );\n pmView.root.addEventListener(\n \"drop\",\n this.dropHandler as unknown as EventListener,\n );\n }\n\n viewMousedownHandler = () => {\n this.mouseState = \"down\";\n };\n\n // Hides the handles if they're currently shown. Used whenever the mouse moves\n // somewhere that shouldn't have table handles attached to it.\n hideHandles = () => {\n if (this.state?.show) {\n this.state.show = false;\n this.state.showAddOrRemoveRowsButton = false;\n this.state.showAddOrRemoveColumnsButton = false;\n this.emitUpdate();\n }\n };\n\n mouseUpHandler = (event: MouseEvent) => {\n this.mouseState = \"up\";\n this.mouseMoveHandler(event);\n };\n\n mouseMoveHandler = (event: MouseEvent) => {\n if (this.menuFrozen) {\n return;\n }\n\n if (this.mouseState === \"selecting\") {\n return;\n }\n\n if (\n !(event.target instanceof Element) ||\n !this.pmView.dom.contains(event.target)\n ) {\n return;\n }\n\n const target = domCellAround(event.target);\n\n if (\n target?.type === \"cell\" &&\n this.mouseState === \"down\" &&\n !this.state?.draggingState\n ) {\n // hide draghandles when selecting text as they could be in the way of the user\n this.mouseState = \"selecting\";\n\n this.hideHandles();\n return;\n }\n\n if (!target || !this.editor.isEditable) {\n this.hideHandles();\n return;\n }\n\n if (!target.tbodyNode) {\n return;\n }\n\n const tableRect = target.tbodyNode.getBoundingClientRect();\n\n const blockEl = getBlockFromElement(target.domNode, this.pmView);\n if (!blockEl) {\n this.hideHandles();\n return;\n }\n\n const { pmNodeInfo, doc } = this.editor.transact((tr) => ({\n pmNodeInfo: getNodeById(blockEl.id, tr.doc),\n doc: tr.doc,\n }));\n\n // The DOM target must still correspond to a block in this document.\n if (!pmNodeInfo) {\n this.hideHandles();\n return;\n }\n\n const block = nodeToBlock(pmNodeInfo.node, doc);\n\n // `domCellAround` matches any `TD`/`TH` in the DOM, so the hovered block may\n // just as well be a custom block that renders a table of its own. Checking\n // the block itself (rather than only whether the schema has a table block)\n // keeps the handles off blocks that have no table content to work with.\n if (!blockHasType(block, this.editor, \"table\")) {\n this.hideHandles();\n return;\n }\n\n const tableBlock = block as unknown as BlockFromConfigNoChildren<\n DefaultBlockSchema[\"table\"],\n any,\n any\n >;\n\n this.tablePos = pmNodeInfo.posBeforeNode + 1;\n this.tableElement = blockEl.node;\n this.tableId = blockEl.id;\n const widgetContainer = target.domNode\n .closest(\".tableWrapper\")\n ?.querySelector(\".table-widgets-container\") as HTMLElement;\n\n if (target?.type === \"wrapper\") {\n // if we're just to the right or below the table, show the extend buttons\n // (this is a bit hacky. It would probably be cleaner to render the extend buttons in the Table NodeView instead)\n const belowTable =\n event.clientY >= tableRect.bottom - 1 && // -1 to account for fractions of pixels in \"bottom\"\n event.clientY < tableRect.bottom + 20;\n const toRightOfTable =\n event.clientX >= tableRect.right - 1 &&\n event.clientX < tableRect.right + 20;\n\n const hideHandles =\n // always hide handles when the actively hovered table changed\n this.state?.block?.id !== tableBlock.id ||\n // make sure we don't hide existing handles (keep col / row index) when\n // we're hovering just above or to the right of a table\n event.clientX > tableRect.right ||\n event.clientY > tableRect.bottom;\n\n this.state = {\n ...this.state!,\n show: true,\n showAddOrRemoveRowsButton: belowTable,\n showAddOrRemoveColumnsButton: toRightOfTable,\n referencePosTable: tableRect,\n block: tableBlock,\n widgetContainer,\n colIndex: hideHandles ? undefined : this.state?.colIndex,\n rowIndex: hideHandles ? undefined : this.state?.rowIndex,\n referencePosCell: hideHandles\n ? undefined\n : this.state?.referencePosCell,\n };\n } else {\n const colIndex = getChildIndex(target.domNode);\n const rowIndex = getChildIndex(target.domNode.parentElement!);\n const cellRect = target.domNode.getBoundingClientRect();\n\n if (\n this.state !== undefined &&\n this.state.show &&\n this.tableId === blockEl.id &&\n this.state.rowIndex === rowIndex &&\n this.state.colIndex === colIndex\n ) {\n // no update needed\n return;\n }\n\n this.state = {\n show: true,\n showAddOrRemoveColumnsButton:\n colIndex === tableBlock.content.rows[0].cells.length - 1,\n showAddOrRemoveRowsButton:\n rowIndex === tableBlock.content.rows.length - 1,\n referencePosTable: tableRect,\n\n block: tableBlock,\n draggingState: undefined,\n referencePosCell: cellRect,\n colIndex: colIndex,\n rowIndex: rowIndex,\n\n widgetContainer,\n };\n }\n this.emitUpdate();\n\n return false;\n };\n\n dragOverHandler = (event: DragEvent) => {\n if (this.state?.draggingState === undefined) {\n return;\n }\n\n event.preventDefault();\n event.dataTransfer!.dropEffect = \"move\";\n\n hideElements(\n \".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline\",\n this.pmView.root,\n );\n\n // The mouse cursor coordinates, bounded to the table's bounding box. The\n // bounding box is shrunk by 1px on each side to ensure that the bounded\n // coordinates are always inside a table cell.\n const boundedMouseCoords = {\n left: Math.min(\n Math.max(event.clientX, this.state.referencePosTable.left + 1),\n this.state.referencePosTable.right - 1,\n ),\n top: Math.min(\n Math.max(event.clientY, this.state.referencePosTable.top + 1),\n this.state.referencePosTable.bottom - 1,\n ),\n };\n\n // Gets the table cell element that the bounded mouse cursor coordinates lie\n // in.\n const tableCellElements = this.pmView.root\n .elementsFromPoint(boundedMouseCoords.left, boundedMouseCoords.top)\n .filter(\n (element) => element.tagName === \"TD\" || element.tagName === \"TH\",\n );\n if (tableCellElements.length === 0) {\n return;\n }\n const tableCellElement = tableCellElements[0];\n\n let emitStateUpdate = false;\n\n // Gets current row and column index.\n const rowIndex = getChildIndex(tableCellElement.parentElement!);\n const colIndex = getChildIndex(tableCellElement);\n\n // Checks if the drop cursor needs to be updated. This affects decorations\n // only so it doesn't trigger a state update.\n const oldIndex =\n this.state.draggingState.draggedCellOrientation === \"row\"\n ? this.state.rowIndex\n : this.state.colIndex;\n const newIndex =\n this.state.draggingState.draggedCellOrientation === \"row\"\n ? rowIndex\n : colIndex;\n const dispatchDecorationsTransaction = newIndex !== oldIndex;\n\n // Checks if either the hovered cell has changed and updates the row and\n // column index. Also updates the reference DOMRect.\n if (this.state.rowIndex !== rowIndex || this.state.colIndex !== colIndex) {\n this.state.rowIndex = rowIndex;\n this.state.colIndex = colIndex;\n\n this.state.referencePosCell = tableCellElement.getBoundingClientRect();\n\n emitStateUpdate = true;\n }\n\n // Checks if the mouse cursor position along the axis that the user is\n // dragging on has changed and updates it.\n const mousePos =\n this.state.draggingState.draggedCellOrientation === \"row\"\n ? boundedMouseCoords.top\n : boundedMouseCoords.left;\n if (this.state.draggingState.mousePos !== mousePos) {\n this.state.draggingState.mousePos = mousePos;\n\n emitStateUpdate = true;\n }\n\n // Emits a state update if any of the fields have changed.\n if (emitStateUpdate) {\n this.emitUpdate();\n }\n\n // Dispatches a dummy transaction to force a decorations update if\n // necessary.\n if (dispatchDecorationsTransaction) {\n this.editor.transact((tr) => tr.setMeta(tableHandlesPluginKey, true));\n }\n };\n\n dropHandler = (event: DragEvent) => {\n this.mouseState = \"up\";\n if (this.state === undefined || this.state.draggingState === undefined) {\n return false;\n }\n\n if (\n this.state.rowIndex === undefined ||\n this.state.colIndex === undefined\n ) {\n throw new Error(\n \"Attempted to drop table row or column, but no table block was hovered prior.\",\n );\n }\n\n event.preventDefault();\n\n const { draggingState, colIndex, rowIndex } = this.state;\n // Clear so a re-dispatched drop short-circuits above (issue #2691).\n this.state.draggingState = undefined;\n\n const columnWidths = this.state.block.content.columnWidths;\n\n if (draggingState.draggedCellOrientation === \"row\") {\n if (\n !canRowBeDraggedInto(\n this.state.block,\n draggingState.originalIndex,\n rowIndex,\n )\n ) {\n // If the target row is invalid, don't move the row\n return false;\n }\n const newTable = moveRow(\n this.state.block,\n draggingState.originalIndex,\n rowIndex,\n );\n this.editor.updateBlock(this.state.block, {\n type: \"table\",\n content: {\n ...this.state.block.content,\n rows: newTable as any,\n },\n });\n } else {\n if (\n !canColumnBeDraggedInto(\n this.state.block,\n draggingState.originalIndex,\n colIndex,\n )\n ) {\n // If the target column is invalid, don't move the column\n return false;\n }\n const newTable = moveColumn(\n this.state.block,\n draggingState.originalIndex,\n colIndex,\n );\n const [columnWidth] = columnWidths.splice(draggingState.originalIndex, 1);\n columnWidths.splice(colIndex, 0, columnWidth);\n this.editor.updateBlock(this.state.block, {\n type: \"table\",\n content: {\n ...this.state.block.content,\n columnWidths,\n rows: newTable as any,\n },\n });\n }\n\n // Have to reset text cursor position to the block as `updateBlock` moves\n // the existing selection out of the block.\n this.editor.setTextCursorPosition(this.state.block.id);\n\n return true;\n };\n\n // Resolves the position just inside the hovered table, within `doc`. The\n // position is looked up by ID on each use rather than read from a cached one,\n // as anything changing before the table (a collaborator inserting a block\n // above it, say) shifts it: a stale position resolves into the wrong node, or\n // past the end of the document entirely.\n getTablePos(doc: Node): number | undefined {\n if (this.tableId === undefined) {\n return undefined;\n }\n\n const pmNodeInfo = getNodeById(this.tableId, doc);\n\n return pmNodeInfo && pmNodeInfo.posBeforeNode + 1;\n }\n\n // Updates drag handles when the table is modified or removed.\n update() {\n if (!this.state || !this.state.show) {\n return;\n }\n\n // Hide handles if the table block has been removed.\n const refreshedBlock = this.editor.getBlock(this.state.block.id);\n if (\n !refreshedBlock ||\n refreshedBlock.type !== \"table\" ||\n // when collaborating, the table element might be replaced and out of date\n // because yjs replaces the element when for example you change the color via the side menu\n !this.tableElement?.isConnected\n ) {\n this.state = undefined;\n this.tableId = undefined;\n this.tablePos = undefined;\n this.tableElement = undefined;\n this.emitUpdate();\n\n return;\n }\n this.state.block = refreshedBlock as typeof this.state.block;\n\n // The table may have shifted in this update, so re-resolve its position.\n this.tablePos = this.getTablePos(this.pmView.state.doc);\n\n const { height: rowCount, width: colCount } = getDimensionsOfTable(\n this.state.block,\n );\n\n if (\n this.state.rowIndex !== undefined &&\n this.state.colIndex !== undefined\n ) {\n // If rows or columns are deleted in the update, the hovered indices for\n // those may now be out of bounds. If this is the case, they are moved to\n // the new last row or column.\n if (this.state.rowIndex >= rowCount) {\n this.state.rowIndex = rowCount - 1;\n }\n if (this.state.colIndex >= colCount) {\n this.state.colIndex = colCount - 1;\n }\n }\n\n // Update bounding boxes.\n const tableBody = this.tableElement!.querySelector(\"tbody\");\n\n if (!tableBody) {\n throw new Error(\n \"Table block does not contain a 'tbody' HTML element. This should never happen.\",\n );\n }\n\n if (\n this.state.rowIndex !== undefined &&\n this.state.colIndex !== undefined\n ) {\n const row = tableBody.children[this.state.rowIndex];\n const cell = row.children[this.state.colIndex];\n if (cell) {\n this.state.referencePosCell = cell.getBoundingClientRect();\n } else {\n this.state.rowIndex = undefined;\n this.state.colIndex = undefined;\n }\n }\n this.state.referencePosTable = tableBody.getBoundingClientRect();\n\n this.emitUpdate();\n }\n\n destroy() {\n this.pmView.dom.removeEventListener(\"mousemove\", this.mouseMoveHandler);\n window.removeEventListener(\"mouseup\", this.mouseUpHandler);\n this.pmView.dom.removeEventListener(\"mousedown\", this.viewMousedownHandler);\n this.pmView.root.removeEventListener(\n \"dragover\",\n this.dragOverHandler as EventListener,\n );\n this.pmView.root.removeEventListener(\n \"drop\",\n this.dropHandler as unknown as EventListener,\n );\n }\n}\n\nexport const tableHandlesPluginKey = new PluginKey(\"TableHandlesPlugin\");\n\nexport const TableHandlesExtension = createExtension(({ editor }) => {\n let view: TableHandlesView | undefined = undefined;\n\n const store = createStore<TableHandlesState | undefined>(undefined);\n\n return {\n key: \"tableHandles\",\n store,\n prosemirrorPlugins: [\n new Plugin({\n key: tableHandlesPluginKey,\n view: (editorView) => {\n view = new TableHandlesView(editor as any, editorView, (state) => {\n store.setState(\n state?.block\n ? {\n ...state,\n draggingState: state.draggingState\n ? { ...state.draggingState }\n : undefined,\n }\n : undefined,\n );\n });\n return view;\n },\n // We use decorations to render the drop cursor when dragging a table row\n // or column. The decorations are updated in the `dragOverHandler` method.\n props: {\n decorations: (state) => {\n if (\n view === undefined ||\n view.state === undefined ||\n view.state.draggingState === undefined\n ) {\n return;\n }\n\n // Resolved against the state being rendered rather than read from\n // `view.tablePos`, as ProseMirror computes decorations for a\n // transaction before it calls the plugin view's `update` - so the\n // cached position is still the pre-transaction one here.\n const tablePos = view.getTablePos(state.doc);\n\n if (tablePos === undefined) {\n return;\n }\n\n const newIndex =\n view.state.draggingState.draggedCellOrientation === \"row\"\n ? view.state.rowIndex\n : view.state.colIndex;\n\n if (newIndex === undefined) {\n return;\n }\n\n const decorations: Decoration[] = [];\n const { block, draggingState } = view.state;\n const { originalIndex, draggedCellOrientation } = draggingState;\n\n // Return empty decorations if:\n // - Dragging to same position\n // - No block exists\n // - Row drag not allowed\n // - Column drag not allowed\n if (\n newIndex === originalIndex ||\n !block ||\n (draggedCellOrientation === \"row\" &&\n !canRowBeDraggedInto(block, originalIndex, newIndex)) ||\n (draggedCellOrientation === \"col\" &&\n !canColumnBeDraggedInto(block, originalIndex, newIndex))\n ) {\n return DecorationSet.create(state.doc, decorations);\n }\n\n // Gets the table to show the drop cursor in.\n const tableResolvedPos = state.doc.resolve(tablePos + 1);\n\n if (view.state.draggingState.draggedCellOrientation === \"row\") {\n const cellsInRow = getCellsAtRowHandle(\n view.state.block,\n newIndex,\n );\n\n cellsInRow.forEach(({ row, col }) => {\n // Gets each row in the table.\n const rowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(row) + 1,\n );\n\n // Gets the cell within the row.\n const cellResolvedPos = state.doc.resolve(\n rowResolvedPos.posAtIndex(col) + 1,\n );\n const cellNode = cellResolvedPos.node();\n // Creates a decoration at the start or end of each cell,\n // depending on whether the new index is before or after the\n // original index.\n const decorationPos =\n cellResolvedPos.pos +\n (newIndex > originalIndex ? cellNode.nodeSize - 2 : 0);\n decorations.push(\n // The widget is a small bar which spans the width of the cell.\n Decoration.widget(decorationPos, () => {\n const widget = document.createElement(\"div\");\n widget.className = \"bn-table-drop-cursor\";\n widget.style.left = \"0\";\n widget.style.right = \"0\";\n // This is only necessary because the drop indicator's height\n // is an even number of pixels, whereas the border between\n // table cells is an odd number of pixels. So this makes the\n // positioning slightly more consistent regardless of where\n // the row is being dropped.\n if (newIndex > originalIndex) {\n widget.style.bottom = \"-2px\";\n } else {\n widget.style.top = \"-3px\";\n }\n widget.style.height = \"4px\";\n\n return widget;\n }),\n );\n });\n } else {\n const cellsInColumn = getCellsAtColumnHandle(\n view.state.block,\n newIndex,\n );\n\n cellsInColumn.forEach(({ row, col }) => {\n // Gets each row in the table.\n const rowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(row) + 1,\n );\n\n // Gets the cell within the row.\n const cellResolvedPos = state.doc.resolve(\n rowResolvedPos.posAtIndex(col) + 1,\n );\n const cellNode = cellResolvedPos.node();\n\n // Creates a decoration at the start or end of each cell,\n // depending on whether the new index is before or after the\n // original index.\n const decorationPos =\n cellResolvedPos.pos +\n (newIndex > originalIndex ? cellNode.nodeSize - 2 : 0);\n\n decorations.push(\n // The widget is a small bar which spans the height of the cell.\n Decoration.widget(decorationPos, () => {\n const widget = document.createElement(\"div\");\n widget.className = \"bn-table-drop-cursor\";\n widget.style.top = \"0\";\n widget.style.bottom = \"0\";\n // This is only necessary because the drop indicator's width\n // is an even number of pixels, whereas the border between\n // table cells is an odd number of pixels. So this makes the\n // positioning slightly more consistent regardless of where\n // the column is being dropped.\n if (newIndex > originalIndex) {\n widget.style.right = \"-2px\";\n } else {\n widget.style.left = \"-3px\";\n }\n widget.style.width = \"4px\";\n\n return widget;\n }),\n );\n });\n }\n\n return DecorationSet.create(state.doc, decorations);\n },\n },\n }),\n ],\n\n /**\n * Callback that should be set on the `dragStart` event for whichever element\n * is used as the column drag handle.\n */\n colDragStart(event: {\n dataTransfer: DataTransfer | null;\n clientX: number;\n }) {\n if (\n view === undefined ||\n view.state === undefined ||\n view.state.colIndex === undefined\n ) {\n throw new Error(\n \"Attempted to drag table column, but no table block was hovered prior.\",\n );\n }\n\n view.state.draggingState = {\n draggedCellOrientation: \"col\",\n originalIndex: view.state.colIndex,\n mousePos: event.clientX,\n };\n view.emitUpdate();\n\n editor.transact((tr) =>\n tr.setMeta(tableHandlesPluginKey, {\n draggedCellOrientation:\n view!.state!.draggingState!.draggedCellOrientation,\n originalIndex: view!.state!.colIndex,\n newIndex: view!.state!.colIndex,\n tablePos: view!.tablePos,\n }),\n );\n\n if (editor.headless) {\n return;\n }\n\n setHiddenDragImage(editor.prosemirrorView.root);\n event.dataTransfer!.setDragImage(dragImageElement!, 0, 0);\n event.dataTransfer!.effectAllowed = \"move\";\n },\n\n /**\n * Callback that should be set on the `dragStart` event for whichever element\n * is used as the row drag handle.\n */\n rowDragStart(event: {\n dataTransfer: DataTransfer | null;\n clientY: number;\n }) {\n if (view!.state === undefined || view!.state.rowIndex === undefined) {\n throw new Error(\n \"Attempted to drag table row, but no table block was hovered prior.\",\n );\n }\n\n view!.state.draggingState = {\n draggedCellOrientation: \"row\",\n originalIndex: view!.state.rowIndex,\n mousePos: event.clientY,\n };\n view!.emitUpdate();\n\n editor.transact((tr) =>\n tr.setMeta(tableHandlesPluginKey, {\n draggedCellOrientation:\n view!.state!.draggingState!.draggedCellOrientation,\n originalIndex: view!.state!.rowIndex,\n newIndex: view!.state!.rowIndex,\n tablePos: view!.tablePos,\n }),\n );\n\n if (editor.headless) {\n return;\n }\n\n setHiddenDragImage(editor.prosemirrorView.root);\n event.dataTransfer!.setDragImage(dragImageElement!, 0, 0);\n event.dataTransfer!.effectAllowed = \"copyMove\";\n },\n\n /**\n * Callback that should be set on the `dragEnd` event for both the element\n * used as the row drag handle, and the one used as the column drag handle.\n */\n dragEnd() {\n if (view!.state === undefined) {\n throw new Error(\n \"Attempted to drag table row, but no table block was hovered prior.\",\n );\n }\n\n view!.state.draggingState = undefined;\n view!.emitUpdate();\n\n editor.transact((tr) => tr.setMeta(tableHandlesPluginKey, null));\n\n if (editor.headless) {\n return;\n }\n\n unsetHiddenDragImage(editor.prosemirrorView.root);\n },\n\n /**\n * Freezes the drag handles. When frozen, they will stay attached to the same\n * cell regardless of which cell is hovered by the mouse cursor.\n */\n freezeHandles() {\n view!.menuFrozen = true;\n },\n\n /**\n * Unfreezes the drag handles. When frozen, they will stay attached to the\n * same cell regardless of which cell is hovered by the mouse cursor.\n */\n unfreezeHandles() {\n view!.menuFrozen = false;\n },\n\n /**\n * Hides the table handles unless they are currently frozen (e.g. a\n * handle menu is open). Used to dismiss the handles on scroll without\n * interfering with open submenus.\n */\n hideHandlesIfNotFrozen() {\n if (!view!.menuFrozen) {\n view!.hideHandles();\n }\n },\n\n getCellsAtRowHandle(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n relativeRowIndex: RelativeCellIndices[\"row\"],\n ) {\n return getCellsAtRowHandle(block, relativeRowIndex);\n },\n\n /**\n * Get all the cells in a column of the table block.\n */\n getCellsAtColumnHandle(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n relativeColumnIndex: RelativeCellIndices[\"col\"],\n ) {\n return getCellsAtColumnHandle(block, relativeColumnIndex);\n },\n\n /**\n * Sets the selection to the given cell or a range of cells.\n * @returns The new state after the selection has been set.\n */\n setCellSelection(\n state: EditorState,\n relativeStartCell: RelativeCellIndices,\n relativeEndCell: RelativeCellIndices = relativeStartCell,\n ) {\n if (!view) {\n throw new Error(\"Table handles view not initialized\");\n }\n\n // Resolved against `state`, which may be several transactions ahead of\n // the mouse move that attached the handles (a menu can stay open across\n // edits from elsewhere, e.g. a collaborator).\n const tablePos = view.getTablePos(state.doc);\n\n if (tablePos === undefined) {\n throw new Error(\n \"Attempted to select table cells, but the hovered table is no longer in the document.\",\n );\n }\n\n const tableResolvedPos = state.doc.resolve(tablePos + 1);\n const startRowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(relativeStartCell.row) + 1,\n );\n const startCellResolvedPos = state.doc.resolve(\n // No need for +1, since CellSelection expects the position before the cell\n startRowResolvedPos.posAtIndex(relativeStartCell.col),\n );\n const endRowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(relativeEndCell.row) + 1,\n );\n const endCellResolvedPos = state.doc.resolve(\n // No need for +1, since CellSelection expects the position before the cell\n endRowResolvedPos.posAtIndex(relativeEndCell.col),\n );\n\n // Begin a new transaction to set the selection\n const tr = state.tr;\n\n // Set the selection to the given cell or a range of cells\n tr.setSelection(\n new CellSelection(startCellResolvedPos, endCellResolvedPos),\n );\n\n // Quickly apply the transaction to get the new state to update the selection before splitting the cell\n return state.apply(tr);\n },\n\n /**\n * Adds a row or column to the table using prosemirror-table commands\n */\n addRowOrColumn(\n index: RelativeCellIndices[\"row\"],\n direction:\n | { orientation: \"row\"; side: \"above\" | \"below\" }\n | { orientation: \"column\"; side: \"left\" | \"right\" },\n ) {\n editor.exec((beforeState, dispatch) => {\n const state = this.setCellSelection(\n beforeState,\n direction.orientation === \"row\"\n ? { row: index, col: 0 }\n : { row: 0, col: index },\n );\n\n if (direction.orientation === \"row\") {\n if (direction.side === \"above\") {\n return addRowBefore(state, dispatch);\n } else {\n return addRowAfter(state, dispatch);\n }\n } else {\n if (direction.side === \"left\") {\n return addColumnBefore(state, dispatch);\n } else {\n return addColumnAfter(state, dispatch);\n }\n }\n });\n },\n\n /**\n * Removes a row or column from the table using prosemirror-table commands\n */\n removeRowOrColumn(\n index: RelativeCellIndices[\"row\"],\n direction: \"row\" | \"column\",\n ) {\n if (direction === \"row\") {\n return editor.exec((beforeState, dispatch) => {\n const state = this.setCellSelection(beforeState, {\n row: index,\n col: 0,\n });\n return deleteRow(state, dispatch);\n });\n } else {\n return editor.exec((beforeState, dispatch) => {\n const state = this.setCellSelection(beforeState, {\n row: 0,\n col: index,\n });\n return deleteColumn(state, dispatch);\n });\n }\n },\n\n /**\n * Merges the cells in the table block.\n */\n mergeCells(cellsToMerge?: {\n relativeStartCell: RelativeCellIndices;\n relativeEndCell: RelativeCellIndices;\n }) {\n return editor.exec((beforeState, dispatch) => {\n const state = cellsToMerge\n ? this.setCellSelection(\n beforeState,\n cellsToMerge.relativeStartCell,\n cellsToMerge.relativeEndCell,\n )\n : beforeState;\n\n return mergeCells(state, dispatch);\n });\n },\n\n /**\n * Splits the cell in the table block.\n * If no cell is provided, the current cell selected will be split.\n */\n splitCell(relativeCellToSplit?: RelativeCellIndices) {\n return editor.exec((beforeState, dispatch) => {\n const state = relativeCellToSplit\n ? this.setCellSelection(beforeState, relativeCellToSplit)\n : beforeState;\n\n return splitCell(state, dispatch);\n });\n },\n\n /**\n * Gets the start and end cells of the current cell selection.\n * @returns The start and end cells of the current cell selection.\n */\n getCellSelection():\n | undefined\n | {\n from: RelativeCellIndices;\n to: RelativeCellIndices;\n /**\n * All of the cells that are within the selected range.\n */\n cells: RelativeCellIndices[];\n } {\n // Based on the current selection, find the table cells that are within the selected range\n\n return editor.transact((tr) => {\n const selection = tr.selection;\n\n let $fromCell = selection.$from;\n let $toCell = selection.$to;\n if (isTableCellSelection(selection)) {\n // When the selection is a table cell selection, we can find the\n // from and to cells by iterating over the ranges in the selection\n const { ranges } = selection;\n ranges.forEach((range) => {\n $fromCell = range.$from.min($fromCell ?? range.$from);\n $toCell = range.$to.max($toCell ?? range.$to);\n });\n } else {\n // When the selection is a normal text selection\n // Assumes we are within a tableParagraph\n // And find the from and to cells by resolving the positions\n const fromCellPos =\n selection.$from.pos - selection.$from.parentOffset - 1;\n const toCellPos = selection.$to.pos - selection.$to.parentOffset - 1;\n\n // Opt-out when the selection is not pointing into cells. This happens when the selection\n // is at the start of the table's `blockContainer` node and therefore just before the\n // actual `table` node.\n if (fromCellPos < 0 || toCellPos < 0) {\n return undefined;\n }\n\n $fromCell = tr.doc.resolve(fromCellPos);\n $toCell = tr.doc.resolve(toCellPos);\n\n // Opt-out when the selection is not actually pointing into table\n // cells (e.g. a gap cursor next to a nested block).\n if (\n !isTableCellNode($fromCell.parent) ||\n !isTableCellNode($toCell.parent)\n ) {\n return undefined;\n }\n }\n\n // Find the row and table that the from and to cells are in\n const $fromRow = tr.doc.resolve(\n $fromCell.pos - $fromCell.parentOffset - 1,\n );\n const $toRow = tr.doc.resolve($toCell.pos - $toCell.parentOffset - 1);\n\n // Find the table\n const $table = tr.doc.resolve($fromRow.pos - $fromRow.parentOffset - 1);\n\n // Find the column and row indices of the from and to cells\n const fromColIndex = $fromCell.index($fromRow.depth);\n const fromRowIndex = $fromRow.index($table.depth);\n const toColIndex = $toCell.index($toRow.depth);\n const toRowIndex = $toRow.index($table.depth);\n\n const cells: RelativeCellIndices[] = [];\n for (let row = fromRowIndex; row <= toRowIndex; row++) {\n for (let col = fromColIndex; col <= toColIndex; col++) {\n cells.push({ row, col });\n }\n }\n\n return {\n from: {\n row: fromRowIndex,\n col: fromColIndex,\n },\n to: {\n row: toRowIndex,\n col: toColIndex,\n },\n cells,\n };\n });\n },\n\n /**\n * Gets the direction of the merge based on the current cell selection.\n *\n * Returns undefined when there is no cell selection, or the selection is not within a table.\n */\n getMergeDirection(\n block:\n | BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>\n | undefined,\n ) {\n return editor.transact((tr) => {\n const isSelectingTableCells = isTableCellSelection(tr.selection)\n ? tr.selection\n : undefined;\n\n if (\n !isSelectingTableCells ||\n !block ||\n // Only offer the merge button if there is more than one cell selected.\n isSelectingTableCells.ranges.length <= 1\n ) {\n return undefined;\n }\n\n const cellSelection = this.getCellSelection();\n\n if (!cellSelection) {\n return undefined;\n }\n\n if (areInSameColumn(cellSelection.from, cellSelection.to, block)) {\n return \"vertical\";\n }\n\n return \"horizontal\";\n });\n },\n\n cropEmptyRowsOrColumns(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n removeEmpty: \"columns\" | \"rows\",\n ) {\n return cropEmptyRowsOrColumns(block, removeEmpty);\n },\n\n addRowsOrColumns(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n addType: \"columns\" | \"rows\",\n numToAdd: number,\n ) {\n return addRowsOrColumns(block, addType, numToAdd);\n },\n } as const;\n});\n","import type { Node as PMNode } from \"prosemirror-model\";\nimport {\n Plugin,\n PluginKey,\n Selection,\n type Transaction,\n} from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey<DecorationSet>(\"trailingNode\");\n\n// Skip the widget when the container already ends with an empty paragraph\n// block (since the user can just type into it).\nfunction containerNeedsTrailingWidget(container: PMNode): boolean {\n const lastBlock = container.lastChild;\n const lastContent = lastBlock?.firstChild;\n\n return !(\n lastBlock?.type.name === \"blockContainer\" &&\n lastContent?.type.name === \"paragraph\" &&\n lastContent.content.size === 0\n );\n}\n\n// Returns the position at the end of each container that should render a\n// trailing widget: the root blockGroup, and columns from the multi-column\n// package. Nested blockGroups (a block's children) are excluded, as they have\n// no empty space below them for a widget to occupy.\nfunction getTrailingWidgetPositions(doc: PMNode): number[] {\n // When the schema has no columns, the root blockGroup is the only possible\n // container, so traversing the doc to find others can be skipped.\n if (!doc.type.schema.nodes[\"column\"]) {\n const rootGroup = doc.lastChild;\n return rootGroup && containerNeedsTrailingWidget(rootGroup)\n ? [doc.content.size - 1]\n : [];\n }\n\n const positions: number[] = [];\n\n doc.descendants((node, pos, parent) => {\n if (node.isTextblock) {\n return false;\n }\n\n const isContainer =\n node.type.name === \"column\" ||\n (node.type.name === \"blockGroup\" && parent?.type.name === \"doc\");\n\n if (isContainer && containerNeedsTrailingWidget(node)) {\n positions.push(pos + node.nodeSize - 1);\n }\n\n return true;\n });\n\n return positions;\n}\n\n/**\n * Renders a fake trailing block as a widget decoration after the last block of\n * the document, as well as of any other container that blocks can be appended\n * to (e.g. columns). Clicking it inserts a real trailing block in the\n * container and moves the selection into it. This way the trailing block is\n * not part of the document content, so it doesn't appear when the editor is\n * read-only or when the content is exported.\n */\nexport const TrailingNodeExtension = createExtension(\n ({ editor }: ExtensionOptions) => {\n function createTrailingWidget(pos: number): Decoration {\n return Decoration.widget(\n pos,\n () => {\n const el = document.createElement(\"div\");\n el.className = \"bn-trailing-block\";\n el.contentEditable = \"false\";\n el.addEventListener(\"mousedown\", (event) => {\n // Stop ProseMirror from trying to place the selection somewhere\n // based on this click.\n event.preventDefault();\n\n const view = editor.prosemirrorView;\n if (!view) {\n return;\n }\n\n // The widget may have been remapped since it was created, so its\n // container is resolved from its current DOM position instead of\n // captured up front.\n const container = view.state.doc.resolve(\n view.posAtDOM(el, 0),\n ).parent;\n const lastBlockId = container.lastChild?.attrs[\"id\"];\n if (!lastBlockId) {\n return;\n }\n\n editor.transact((tr) => {\n const [insertedBlock] = editor.insertBlocks(\n [{ type: \"paragraph\" }],\n lastBlockId,\n \"after\",\n );\n editor.setTextCursorPosition(insertedBlock, \"start\");\n tr.scrollIntoView();\n });\n\n view.focus();\n });\n return el;\n },\n { side: 1 },\n );\n }\n\n // Maps the existing DecorationSet through the transaction, then diffs it\n // against the containers that should currently show a widget, only adding\n // and removing where the two differ. Decorations (and their rendered DOM)\n // stay reference-stable across transactions for unchanged containers.\n function nextDecorationSet(\n tr: Transaction,\n oldSet: DecorationSet,\n isEditable: boolean,\n ): DecorationSet {\n const mapped = oldSet.map(tr.mapping, tr.doc);\n const desiredPositions = new Set(\n isEditable ? getTrailingWidgetPositions(tr.doc) : [],\n );\n\n const keptPositions = new Set<number>();\n const stale: Decoration[] = [];\n for (const decoration of mapped.find()) {\n if (\n desiredPositions.has(decoration.from) &&\n !keptPositions.has(decoration.from)\n ) {\n keptPositions.add(decoration.from);\n } else {\n stale.push(decoration);\n }\n }\n const missing = [...desiredPositions].filter(\n (pos) => !keptPositions.has(pos),\n );\n\n let next = mapped;\n if (stale.length > 0) {\n next = next.remove(stale);\n }\n if (missing.length > 0) {\n next = next.add(tr.doc, missing.map(createTrailingWidget));\n }\n return next;\n }\n\n return {\n key: \"trailingNode\",\n prosemirrorPlugins: [\n new Plugin<DecorationSet>({\n key: PLUGIN_KEY,\n state: {\n init: (_, state) =>\n nextDecorationSet(\n state.tr,\n DecorationSet.empty,\n editor.isEditable,\n ),\n apply: (tr, oldSet) => {\n if (!tr.docChanged && !tr.getMeta(PLUGIN_KEY)) {\n return oldSet;\n }\n return nextDecorationSet(tr, oldSet, editor.isEditable);\n },\n },\n // Editable changes don't dispatch a transaction on their own, so the\n // plugin state can't re-evaluate on its own. Watch for the change\n // and dispatch a no-op transaction tagged with this plugin's key so\n // `apply` re-runs and adds or removes the widget.\n view(view) {\n let lastEditable = view.editable;\n return {\n update(view) {\n if (view.editable === lastEditable) {\n return;\n }\n lastEditable = view.editable;\n view.dispatch(view.state.tr.setMeta(PLUGIN_KEY, true));\n },\n };\n },\n props: {\n decorations: (state) => PLUGIN_KEY.getState(state),\n // Prevents ProseMirror from trying to move the selection into the\n // trailing block at the end of the document, which causes the text\n // caret to flicker in it before returning to its previous\n // position.\n handleKeyDown: (view, event) => {\n if (event.key !== \"ArrowRight\" && event.key !== \"ArrowDown\") {\n return false;\n }\n\n const { selection } = view.state;\n if (!selection.empty) {\n return false;\n }\n\n const docEnd = Selection.atEnd(view.state.doc);\n if (selection.$head.pos !== docEnd.$head.pos) {\n return false;\n }\n\n const rootGroup = view.state.doc.lastChild;\n if (\n !editor.isEditable ||\n !rootGroup ||\n !containerNeedsTrailingWidget(rootGroup)\n ) {\n return false;\n }\n\n event.preventDefault();\n return true;\n },\n },\n }),\n ],\n } as const;\n },\n);\n","import type {\n VersionError,\n VersioningState,\n VersionSelection,\n VersionSnapshot,\n} from \"./types.js\";\n\nexport type VersioningEvent =\n | {\n type: \"opened\";\n capturedAt: number;\n showCurrentVersion: boolean;\n restoring: boolean;\n }\n | { type: \"closed\"; restoring?: boolean }\n | { type: \"historyStarted\"; operation: \"refresh\" | \"loadMore\" }\n | {\n type: \"historyFailed\";\n operation: \"refresh\" | \"loadMore\";\n error: VersionError;\n }\n | {\n type: \"historyLoaded\";\n operation: \"refresh\" | \"loadMore\";\n snapshots: VersionSnapshot[];\n nextCursor?: string;\n }\n | { type: \"selectionStarted\"; target: VersionSelection }\n | { type: \"selectionFailed\" }\n | { type: \"selectionShown\"; target: VersionSelection; compareTo?: string }\n | { type: \"restoreChanged\"; restoring: boolean }\n | { type: \"snapshotRenamed\"; id: string; name?: string }\n | { type: \"snapshotCreated\"; snapshot: VersionSnapshot };\n\nfunction mergeSnapshots(snapshots: VersionSnapshot[]) {\n return [\n ...new Map(snapshots.map((snapshot) => [snapshot.id, snapshot])).values(),\n ].sort((a, b) => b.createdAt - a.createdAt);\n}\n\n/** Pure published-state transitions. Request ownership and editor effects stay in the controller. */\nexport function reduceVersioningState(\n state: VersioningState,\n event: VersioningEvent,\n): VersioningState {\n if (event.type === \"opened\") {\n return {\n mode: \"versions\",\n capturedAt: event.capturedAt,\n showCurrentVersion: event.showCurrentVersion,\n restoring: event.restoring,\n displayed: { type: \"current\" },\n history: { status: \"pending\" },\n };\n }\n if (event.type === \"closed\") {\n return event.restoring\n ? { mode: \"live\", restoring: true }\n : { mode: \"live\" };\n }\n if (state.mode === \"live\") {\n if (event.type === \"restoreChanged\") {\n return event.restoring\n ? { mode: \"live\", restoring: true }\n : { mode: \"live\" };\n }\n return state;\n }\n switch (event.type) {\n case \"historyStarted\":\n return {\n ...state,\n mode: \"versions\",\n history: {\n status: \"pending\",\n operation: event.operation,\n data: state.history.data,\n },\n };\n case \"historyFailed\":\n return {\n ...state,\n mode: \"versions\",\n history: {\n status: \"error\",\n operation: event.operation,\n error: event.error,\n data: state.history.data,\n },\n };\n case \"historyLoaded\":\n return {\n ...state,\n mode: \"versions\",\n nextCursor: event.nextCursor,\n history: {\n status: \"success\",\n data: mergeSnapshots(\n event.operation === \"refresh\"\n ? event.snapshots\n : [...(state.history.data ?? []), ...event.snapshots],\n ),\n },\n };\n case \"selectionStarted\":\n return { ...state, pending: event.target };\n case \"selectionFailed\":\n return { ...state, pending: undefined };\n case \"selectionShown\":\n return {\n ...state,\n displayed: event.target,\n compareTo: event.compareTo,\n pending: undefined,\n };\n case \"restoreChanged\":\n return {\n ...state,\n restoring: event.restoring,\n pending: event.restoring ? undefined : state.pending,\n };\n case \"snapshotRenamed\":\n return {\n ...state,\n mode: \"versions\",\n history: {\n status: \"success\",\n data: (state.history.data ?? []).map((snapshot) =>\n snapshot.id === event.id\n ? { ...snapshot, name: event.name }\n : snapshot,\n ),\n },\n };\n case \"snapshotCreated\":\n return {\n ...state,\n mode: \"versions\",\n history: {\n status: \"success\",\n data: mergeSnapshots([\n event.snapshot,\n ...(state.history.data ?? []).filter(\n (snapshot) => snapshot.id !== event.snapshot.id,\n ),\n ]),\n },\n };\n default: {\n const exhaustive: never = event;\n return exhaustive;\n }\n }\n}\n","import { Store } from \"../../util/Store.js\";\nimport {\n reduceVersioningState,\n type VersioningEvent,\n} from \"./versioningState.js\";\nimport type {\n VersioningState,\n VersionDisplay,\n VersionResult,\n VersionOperationResult,\n VersionSelection,\n VersionStorage,\n VersionView,\n VersionViewAdapter,\n} from \"./types.js\";\n\n/** One replaceable read per slot. The session lifetime cancels both slots. */\nfunction createRequestSlot(lifetime: AbortSignal) {\n let current: AbortController | undefined;\n function cancel() {\n current?.abort();\n }\n function start() {\n const previous = current;\n const controller = new AbortController();\n current = controller;\n const signal = AbortSignal.any([lifetime, controller.signal]);\n // Install the replacement before notifying the cancelled request.\n previous?.abort();\n return {\n signal,\n cancel() {\n controller.abort();\n },\n };\n }\n return { start, cancel };\n}\n\n/**\n * One isolated view per opening. Every read belongs to that opening.\n * Adapter/provider callbacks and store subscribers must defer controller commands;\n * synchronous reentry and recovery after unexpected callback failures are unsupported.\n */\nexport function createVersioning<Content, Attributions>(options: {\n adapter: VersionViewAdapter<Content, Attributions>;\n storage: VersionStorage<Content, Attributions>;\n setReadOnly: (enabled: boolean) => void;\n}) {\n const { adapter, setReadOnly } = options;\n const store = new Store<VersioningState>({ mode: \"live\" });\n type Session = {\n view: VersionView<Content, Attributions>;\n lifetime: AbortController;\n selection: ReturnType<typeof createRequestSlot>;\n selectionBaseline?: string;\n history: ReturnType<typeof createRequestSlot>;\n loadingMore?: Promise<VersionOperationResult>;\n };\n let session: Session | undefined;\n let disposed = false;\n let restoring = false;\n\n function dispatch(event: VersioningEvent) {\n const previous = store.state;\n const next = reduceVersioningState(previous, event);\n if (next !== previous) {\n store.setState(next);\n }\n return next;\n }\n\n function publish(signal: AbortSignal, event: VersioningEvent) {\n if (!signal.aborted) {\n return dispatch(event);\n }\n return undefined;\n }\n\n function open() {\n if (disposed) {\n throw new Error(\"Versioning has been disposed\");\n }\n if (restoring) {\n return false;\n }\n if (session) {\n return true;\n }\n try {\n setReadOnly(true);\n const view = adapter.open();\n const lifetime = new AbortController();\n session = {\n view,\n lifetime,\n selection: createRequestSlot(lifetime.signal),\n history: createRequestSlot(lifetime.signal),\n };\n dispatch({\n type: \"opened\",\n capturedAt: session.view.current.capturedAt,\n showCurrentVersion: options.storage.showCurrentVersion ?? true,\n restoring,\n });\n } catch (error) {\n if (!session) {\n setReadOnly(restoring);\n }\n throw error;\n }\n return true;\n }\n\n function close() {\n if (!session) {\n return;\n }\n const closing = session;\n session = undefined;\n closing.lifetime.abort();\n closing.view.close();\n dispatch({ type: \"closed\", restoring });\n setReadOnly(restoring);\n }\n\n /** Reset history to the first page without changing the displayed preview. */\n function list(): Promise<VersionOperationResult> {\n const active = session;\n if (!active || restoring) {\n return Promise.resolve({ status: \"unavailable\" });\n }\n active.loadingMore = undefined;\n return readHistory(active, { operation: \"refresh\" });\n }\n\n /** Append one page. Concurrent callers share the same request. */\n function loadMore(): Promise<VersionOperationResult> {\n const active = session;\n const state = store.state;\n if (!active || restoring || state.mode !== \"versions\") {\n return Promise.resolve({ status: \"unavailable\" });\n }\n if (active.loadingMore) {\n return active.loadingMore;\n }\n if (\n state.history.status === \"error\" &&\n state.history.operation === \"refresh\"\n ) {\n return list();\n }\n if (state.nextCursor === undefined || state.history.status === \"pending\") {\n return Promise.resolve({ status: \"unavailable\" });\n }\n return readHistory(active, {\n operation: \"loadMore\",\n cursor: state.nextCursor,\n });\n }\n\n function readHistory(\n active: Session,\n read: { operation: \"refresh\" } | { operation: \"loadMore\"; cursor: string },\n ): Promise<VersionOperationResult> {\n const { signal } = active.history.start();\n publish(signal, { type: \"historyStarted\", operation: read.operation });\n const pending = (async (): Promise<VersionOperationResult> => {\n try {\n const result = await options.storage.list(\n signal,\n read.operation === \"refresh\" ? undefined : read.cursor,\n );\n if (signal.aborted) {\n return { status: \"cancelled\" };\n }\n if (!result.ok) {\n publish(signal, {\n type: \"historyFailed\",\n operation: read.operation,\n error: result.error,\n });\n return { status: \"error\", error: result.error };\n }\n if (\n read.operation === \"loadMore\" &&\n result.value.nextCursor === read.cursor\n ) {\n throw new Error(\"Version history cursor did not advance\");\n }\n const loaded = publish(signal, {\n type: \"historyLoaded\",\n operation: read.operation,\n ...result.value,\n });\n if (signal.aborted) {\n return { status: \"cancelled\" };\n }\n if (\n loaded?.mode === \"versions\" &&\n loaded.showCurrentVersion === false &&\n loaded.displayed.type === \"current\" &&\n !loaded.pending &&\n loaded.history.data?.[0]\n ) {\n return select({ type: \"snapshot\", id: loaded.history.data[0].id });\n }\n return { status: \"done\" };\n } catch (error) {\n if (signal.aborted) {\n return { status: \"cancelled\" };\n }\n throw error;\n } finally {\n if (!signal.aborted) {\n active.loadingMore = undefined;\n }\n }\n })();\n if (read.operation === \"loadMore\" && !signal.aborted) {\n active.loadingMore = pending;\n }\n return pending;\n }\n\n async function loadDisplay(\n active: Session,\n target: VersionSelection,\n baselineId: string | undefined,\n signal: AbortSignal,\n ): Promise<VersionResult<VersionDisplay<Content, Attributions>>> {\n const storage = options.storage;\n const [content, comparison] = await Promise.all([\n target.type === \"current\"\n ? { ok: true as const, value: active.view.current.content }\n : storage.getContent(target.id, signal),\n baselineId === undefined\n ? undefined\n : Promise.all([\n storage.getContent(baselineId, signal),\n storage.getAttributions?.(\n target,\n baselineId,\n active.view.current.capturedAt,\n signal,\n ),\n ]),\n ]);\n if (!content.ok) {\n return content;\n }\n if (!comparison) {\n return { ok: true, value: { content: content.value, target } };\n }\n const [baseline, attributions] = comparison;\n if (!baseline.ok) {\n return baseline;\n }\n if (attributions && !attributions.ok) {\n return attributions;\n }\n return {\n ok: true,\n value: {\n content: content.value,\n target,\n comparison: {\n content: baseline.value,\n attributions: attributions?.value,\n },\n },\n };\n }\n\n async function select(\n target: VersionSelection,\n selectionOptions?: { compareTo?: string },\n ): Promise<VersionOperationResult> {\n const active = session;\n if (!active || restoring) {\n return { status: \"unavailable\" };\n }\n if (\n target.type === \"current\" &&\n options.storage.showCurrentVersion === false\n ) {\n const state = store.state;\n const latest =\n state.mode === \"versions\" ? state.history.data?.[0] : undefined;\n if (!latest) {\n return { status: \"unavailable\" };\n }\n target = { type: \"snapshot\", id: latest.id };\n }\n if (\n selectionOptions?.compareTo !== undefined &&\n !adapter.supportsComparison\n ) {\n return { status: \"unavailable\" };\n }\n const request = active.selection.start();\n const { signal } = request;\n active.selectionBaseline = selectionOptions?.compareTo;\n publish(signal, { type: \"selectionStarted\", target });\n const baselineId = selectionOptions?.compareTo;\n try {\n const result = await loadDisplay(active, target, baselineId, signal);\n if (signal.aborted) {\n return { status: \"cancelled\" };\n }\n if (!result.ok) {\n publish(signal, { type: \"selectionFailed\" });\n return { status: \"error\", error: result.error };\n }\n active.view.show(result.value);\n publish(signal, {\n type: \"selectionShown\",\n target,\n compareTo: baselineId,\n });\n return { status: \"done\" };\n } catch (error) {\n if (signal.aborted) {\n return { status: \"cancelled\" };\n }\n publish(signal, { type: \"selectionFailed\" });\n request.cancel();\n throw error;\n }\n }\n\n async function restore(id: string): Promise<VersionOperationResult> {\n const active = session;\n if (!active || restoring) {\n return { status: \"unavailable\" };\n }\n const storage = options.storage;\n if (!storage.restore) {\n return { status: \"unavailable\" };\n }\n restoring = true;\n try {\n active.selection.cancel();\n publish(active.lifetime.signal, {\n type: \"restoreChanged\",\n restoring: true,\n });\n const result = await storage.restore(id);\n if (!result.ok) {\n return { status: \"error\", error: result.error };\n }\n close();\n return { status: \"done\" };\n } finally {\n restoring = false;\n dispatch({ type: \"restoreChanged\", restoring: false });\n if (!session) {\n setReadOnly(false);\n }\n }\n }\n\n async function refreshAfterNaming(\n active: Session,\n event: Extract<\n VersioningEvent,\n { type: \"snapshotRenamed\" | \"snapshotCreated\" }\n >,\n ) {\n publish(active.lifetime.signal, event);\n if (!active.lifetime.signal.aborted) {\n await list();\n }\n }\n\n async function rename(\n id: string,\n name?: string,\n ): Promise<VersionOperationResult> {\n const active = session;\n const storage = options.storage;\n if (restoring || !storage.rename) {\n return { status: \"unavailable\" };\n }\n const result = await storage.rename(id, name);\n if (!result.ok) {\n return { status: \"error\", error: result.error };\n }\n if (active) {\n await refreshAfterNaming(active, { type: \"snapshotRenamed\", id, name });\n }\n return { status: \"done\" };\n }\n\n function references(\n active: Session,\n state: Extract<VersioningState, { mode: \"versions\" }>,\n id: string,\n ) {\n return (\n (state.displayed.type === \"snapshot\" && state.displayed.id === id) ||\n (state.pending?.type === \"snapshot\" && state.pending.id === id) ||\n (state.pending !== undefined && active.selectionBaseline === id) ||\n state.compareTo === id\n );\n }\n\n return {\n store,\n open,\n close,\n list,\n loadMore,\n select,\n restore,\n rename,\n get canCompare() {\n return adapter.supportsComparison;\n },\n get historyIncludesBeginning() {\n return options.storage.historyIncludesBeginning === true;\n },\n get canCreate() {\n return options.storage.create !== undefined;\n },\n get canRename() {\n return options.storage.rename !== undefined;\n },\n get canRestore() {\n return options.storage.restore !== undefined;\n },\n get canRemove() {\n return options.storage.remove !== undefined;\n },\n async create(this: void, name?: string): Promise<VersionOperationResult> {\n const active = session;\n const storage = options.storage;\n if (!active || restoring || !storage.create) {\n return { status: \"unavailable\" };\n }\n const current = active.view.current;\n const result = await storage.create(\n current.content,\n name,\n current.capturedAt,\n );\n if (!result.ok) {\n return { status: \"error\", error: result.error };\n }\n await refreshAfterNaming(active, {\n type: \"snapshotCreated\",\n snapshot: result.value,\n });\n return { status: \"done\" };\n },\n async remove(this: void, id: string): Promise<VersionOperationResult> {\n const active = session;\n const storage = options.storage;\n if (!active || restoring || !storage.remove) {\n return { status: \"unavailable\" };\n }\n const removed = await storage.remove(id);\n if (!removed.ok) {\n return { status: \"error\", error: removed.error };\n }\n if (!active.lifetime.signal.aborted) {\n await list();\n // Missing page metadata does not prove deletion. Continuous-history\n // providers may only clear a name, leaving its content available.\n const state = store.state;\n if (state.mode === \"versions\" && references(active, state, id)) {\n const content = await storage.getContent(id, active.lifetime.signal);\n const current = store.state;\n if (\n !active.lifetime.signal.aborted &&\n !content.ok &&\n content.error.type === \"not-found\" &&\n current.mode === \"versions\" &&\n references(active, current, id)\n ) {\n await select(\n (current.displayed.type === \"snapshot\" &&\n current.displayed.id === id) ||\n (current.pending?.type === \"snapshot\" &&\n current.pending.id === id)\n ? { type: \"current\" }\n : current.displayed,\n );\n }\n }\n }\n return { status: \"done\" };\n },\n dispose() {\n disposed = true;\n close();\n },\n };\n}\n","// Attribution wrappers carry `data-user-ids` but may be `display: contents`.\n// Resolve their layout boxes locally without importing the `@y/*` stack.\n\n/** Duration of the transient block highlight. */\nconst HIGHLIGHT_MS = 1500;\n\n/** Allow the preview layout to settle; animation frames pause in background tabs. */\nexport const SCROLL_TO_FIRST_CHANGE_DELAY_MS = 200;\n\nfunction hasBox(element: Element): boolean {\n const { width, height } = element.getBoundingClientRect();\n return width !== 0 || height !== 0;\n}\n\n/** Descend through `display: contents` wrappers to the first laid-out node. */\nfunction findVisibleTarget(mark: Element): Element | undefined {\n for (\n let element: Element | null = mark;\n element;\n element = element.firstElementChild\n ) {\n if (hasBox(element)) {\n return element;\n }\n }\n return undefined;\n}\n\n/**\n * Nearest ancestor of `mark` (below `root`) with a layout box: for a change\n * hidden inside a collapsed toggle, that's the toggle block itself.\n */\nfunction findVisibleAncestor(\n mark: Element,\n root: Element,\n): Element | undefined {\n for (\n let element = mark.parentElement;\n element && element !== root && root.contains(element);\n element = element.parentElement\n ) {\n if (hasBox(element)) {\n return element;\n }\n }\n return undefined;\n}\n\n/** Cancel the previous highlight when another change is revealed. */\nlet activeHighlight: Animation | undefined;\n\nfunction highlight(block: Element) {\n activeHighlight?.cancel();\n // Fire-and-forget pulse: no DOM mutations for ProseMirror to observe. A\n // finished animation stays referenced until the next scroll cancels it,\n // which is a harmless no-op. Scrolling still works without WAAPI.\n activeHighlight = block.animate?.(\n [\n {\n backgroundColor: \"color-mix(in srgb, #3e5de7 14%, transparent)\",\n boxShadow: \"0 0 0 1px color-mix(in srgb, #3e5de7 45%, transparent)\",\n borderRadius: \"4px\",\n easing: \"ease-out\",\n },\n {\n backgroundColor: \"transparent\",\n boxShadow: \"0 0 0 1px transparent\",\n borderRadius: \"4px\",\n },\n ],\n { duration: HIGHLIGHT_MS, fill: \"none\" },\n );\n}\n\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window !== \"undefined\" &&\n (window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false)\n );\n}\n\n/**\n * Scroll to the first change after preview layout settles. No-ops when\n * disabled or when `isCurrent` reports the preview as superseded.\n * Returns a cancellation callback when a timer is scheduled.\n */\nexport function scheduleScrollToFirstChange(\n getRoot: () => Element | undefined,\n options?: { enabled?: boolean; isCurrent?: () => boolean },\n): (() => void) | undefined {\n if (options?.enabled === false) {\n return;\n }\n // Let preview layout settle; timers also run in background tabs.\n const timeout = setTimeout(() => {\n if (options?.isCurrent && !options.isCurrent()) {\n return;\n }\n scrollToFirstChange(getRoot());\n }, SCROLL_TO_FIRST_CHANGE_DELAY_MS);\n return () => clearTimeout(timeout);\n}\n\n/**\n * Centre the first change in document order and highlight its block,\n * respecting reduced motion. Changes hidden inside collapsed content fall\n * back to their toggle block.\n * @returns Whether a change was found and scrolled to.\n */\nexport function scrollToFirstChange(root: Element | undefined): boolean {\n if (!root) {\n return false;\n }\n\n let firstMark: Element | undefined;\n let target: Element | undefined;\n for (const mark of root.querySelectorAll(\"[data-user-ids]\")) {\n firstMark ??= mark;\n target = findVisibleTarget(mark);\n if (target) {\n break;\n }\n }\n target ??= firstMark ? findVisibleAncestor(firstMark, root) : undefined;\n if (!target) {\n return false;\n }\n // A block-level mark wraps the block; point at its content instead so the\n // highlight doesn't span nested children.\n target = target.querySelector(\".bn-block-content\") ?? target;\n\n target.scrollIntoView({\n block: \"center\",\n behavior: prefersReducedMotion() ? \"auto\" : \"smooth\",\n });\n highlight(target.closest(\".bn-block-content\") ?? target);\n\n return true;\n}\n","import { createExtension } from \"../../editor/BlockNoteExtension.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport type {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { ReadOnlyExtension } from \"../ReadOnly/ReadOnly.js\";\nimport { createVersioning } from \"./createVersioning.js\";\nimport type { VersionStorage, VersionViewAdapter } from \"./types.js\";\nimport { scheduleScrollToFirstChange } from \"./scrollToFirstChange.js\";\nimport {\n normalizeToUserStore,\n type UserStoreOrResolver,\n} from \"../../user/index.js\";\n\n/** Configure storage and a view once; the sidebar only opens, selects, and closes. */\nexport function createVersioningExtension<\n Content,\n Attributions = never,\n BSchema extends BlockSchema = BlockSchema,\n ISchema extends InlineContentSchema = InlineContentSchema,\n SSchema extends StyleSchema = StyleSchema,\n>(\n configure: (editor: BlockNoteEditor<BSchema, ISchema, SSchema>) => {\n adapter: VersionViewAdapter<Content, Attributions>;\n storage: VersionStorage<Content, Attributions>;\n resolveUsers?: UserStoreOrResolver;\n scrollToFirstChange?: boolean;\n },\n) {\n type Editor = BlockNoteEditor<BSchema, ISchema, SSchema>;\n return createExtension(({ editor }: { editor: Editor }) => {\n let configuration:\n | (ReturnType<typeof configure> & {\n userStore: ReturnType<typeof normalizeToUserStore>;\n })\n | undefined;\n\n editor.on(\"create\", () => {\n const configured = configure(editor);\n configuration = {\n ...configured,\n userStore: normalizeToUserStore(configured.resolveUsers),\n };\n });\n\n function getConfiguration() {\n if (!configuration) {\n throw new Error(\n \"Versioning must be installed during editor construction\",\n );\n }\n return configuration;\n }\n\n const mode = createVersioning({\n get storage() {\n return getConfiguration().storage;\n },\n adapter: {\n get supportsComparison() {\n return getConfiguration().adapter.supportsComparison;\n },\n open() {\n const configured = getConfiguration();\n // Preview adapters replace the document. Keep undo detached through\n // opening, switching and live restoration, then start fresh history.\n const undoExtensions = editor.unregisterExtension([\n \"history\",\n \"yUndo\",\n ]);\n let view: ReturnType<typeof configured.adapter.open>;\n try {\n view = configured.adapter.open();\n } catch (error) {\n editor.registerExtension(undoExtensions);\n throw error;\n }\n let cancelScroll: (() => void) | undefined;\n let closed = false;\n return {\n current: view.current,\n show(display) {\n cancelScroll?.();\n cancelScroll = undefined;\n view.show(display);\n if (display.comparison && !closed) {\n cancelScroll = scheduleScrollToFirstChange(\n () => editor.domElement,\n {\n enabled: configured.scrollToFirstChange,\n isCurrent: () =>\n mode.store.state.mode === \"versions\" &&\n mode.store.state.pending === undefined &&\n !mode.store.state.restoring,\n },\n );\n }\n },\n close() {\n if (closed) {\n return;\n }\n closed = true;\n cancelScroll?.();\n cancelScroll = undefined;\n view.close();\n editor.registerExtension(undoExtensions);\n },\n };\n },\n },\n setReadOnly(enabled) {\n const readOnly = editor.getExtension(ReadOnlyExtension);\n if (!readOnly) {\n throw new Error(\"Versioning requires the ReadOnly extension\");\n }\n readOnly.setReadOnly(enabled, \"versioning\");\n },\n });\n const key = \"versioning\";\n return assignWithDescriptors(mode, {\n key,\n get userStore() {\n return getConfiguration().userStore;\n },\n mount() {\n const unsubscribe = mode.store.subscribe(({ currentVal }) => {\n editor.domElement?.classList.toggle(\n \"bn-loading\",\n currentVal.mode === \"versions\" && currentVal.pending !== undefined,\n );\n });\n\n return () => {\n mode.close();\n unsubscribe();\n editor.domElement?.classList.remove(\"bn-loading\");\n };\n },\n });\n });\n}\n\n/** Attach extension properties without evaluating their getters. */\nfunction assignWithDescriptors<T extends object, const U extends object>(\n target: T,\n source: U,\n): T & U;\nfunction assignWithDescriptors(target: object, source: object) {\n return Object.defineProperties(\n target,\n Object.getOwnPropertyDescriptors(source),\n );\n}\n\n/** Content-independent controls shared by every versioning integration. */\nexport type VersioningController = ReturnType<\n typeof createVersioning<unknown, unknown>\n> & { key: \"versioning\"; userStore: ReturnType<typeof normalizeToUserStore> };\n","import type { Node } from \"prosemirror-model\";\nimport { EditorState } from \"prosemirror-state\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { originalFactorySymbol } from \"../../editor/managers/ExtensionManager/symbol.js\";\nimport type {\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n PartialBlock,\n} from \"../../blocks/defaultBlocks.js\";\nimport type {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { blockToNode } from \"../../api/nodeConversions/blockToNode.js\";\nimport { docToBlocks } from \"../../api/nodeConversions/nodeToBlock.js\";\nimport type { DiffVersioningExtension } from \"../../y/extensions/DiffVersioningExtension.js\";\nimport type {\n VersionSnapshot,\n VersionStorage,\n VersionViewAdapter,\n} from \"./types.js\";\nimport { createVersioningExtension } from \"./Versioning.js\";\nimport type { UserStoreOrResolver } from \"../../user/index.js\";\n\n/** ProseMirror JSON uses schema-defined node/mark names and attribute values. */\nexport type ProseMirrorNodeJSON = {\n type: string;\n attrs?: Record<string, unknown>;\n content?: ProseMirrorNodeJSON[];\n marks?: Array<{ type: string; attrs?: Record<string, unknown> }>;\n text?: string;\n};\n\nexport type ProseMirrorDocumentJSON = ProseMirrorNodeJSON & { type: \"doc\" };\n\nexport type LocalVersioningSeedOptions<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> = {\n initialVersions?: Array<{\n /** A partial-block array or ProseMirror document JSON, valid in this editor's schema. */\n content:\n | PartialBlock<BSchema, ISchema, SSchema>[]\n | ProseMirrorDocumentJSON;\n name?: string;\n createdAt: number;\n }>;\n};\n\nexport type LocalVersioningOptions<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> = LocalVersioningSeedOptions<BSchema, ISchema, SSchema> & {\n resolveUsers?: UserStoreOrResolver;\n scrollToFirstChange?: boolean;\n};\n\n/** Install an independent in-memory history for this editor. */\nexport function InMemoryVersioningExtension<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n>(options?: LocalVersioningOptions<BSchema, ISchema, SSchema>) {\n return function createLocalVersioningExtension({\n editor,\n }: {\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>;\n }) {\n const extension = createVersioningExtension(() => ({\n ...createLocalVersioning(editor, options),\n resolveUsers: options?.resolveUsers,\n scrollToFirstChange: options?.scrollToFirstChange,\n }))()({ editor });\n // Register the public factory for editor.getExtension(factory).\n Object.assign(extension, {\n [originalFactorySymbol]: InMemoryVersioningExtension,\n });\n return extension;\n };\n}\n\n/** A separate editor state preserves live selection and undo without preview mappings. */\nexport function createLocalVersioning<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n options?: LocalVersioningSeedOptions<BSchema, ISchema, SSchema>,\n): {\n adapter: VersionViewAdapter<Node>;\n storage: VersionStorage<Node>;\n} {\n let live: EditorState | undefined;\n let nextId = 0;\n const snapshots = new Map<\n string,\n { version: VersionSnapshot; content: Node }\n >();\n for (const entry of options?.initialVersions ?? []) {\n const version = {\n id: String(++nextId),\n name: entry.name,\n createdAt: entry.createdAt,\n };\n const content = entry.content;\n const document = Array.isArray(content)\n ? editor.pmSchema.topNodeType.createChecked(\n null,\n editor.pmSchema.nodes.blockGroup.createChecked(\n null,\n content.map((block) =>\n blockToNode(block, editor.pmSchema, editor.schema.styleSchema),\n ),\n ),\n )\n : editor.pmSchema.nodeFromJSON(content);\n // Invalid seeds are configuration errors, not recoverable editor input.\n // nodeFromJSON does not check the whole content tree; container block\n // conversion is also intentionally lenient, so validate both paths here.\n if (document.type !== editor.pmSchema.topNodeType) {\n throw new Error(\"Version content must be a ProseMirror document\");\n }\n document.check();\n snapshots.set(version.id, { version, content: document });\n }\n\n function inEditorSchema(content: Node): Node {\n // ProseMirror matches node types by identity, not name. Seeded or loaded\n // documents can come from another editor with a different schema instance.\n return content.type.schema === editor.pmSchema\n ? content\n : editor.pmSchema.nodeFromJSON(content.toJSON());\n }\n\n return {\n adapter: {\n get supportsComparison() {\n return (\n editor.getExtension<typeof DiffVersioningExtension>(\n \"diffVersioning\",\n ) !== undefined\n );\n },\n open() {\n if (live || editor.getExtension(\"ySync\")) {\n throw new Error(\n \"Local version views require an unbound local editor\",\n );\n }\n live = editor.prosemirrorState;\n const current = { content: live.doc, capturedAt: Date.now() };\n let closed = false;\n try {\n editor.prosemirrorView.updateState(\n EditorState.create({\n doc: live.doc,\n selection: live.selection,\n plugins: live.plugins,\n }),\n );\n } catch (error) {\n editor.prosemirrorView.updateState(live);\n live = undefined;\n throw error;\n }\n return {\n current,\n show({ content, comparison }) {\n if (closed) {\n throw new Error(\"Version view is closed\");\n }\n const diff =\n editor.getExtension<typeof DiffVersioningExtension>(\n \"diffVersioning\",\n );\n if (comparison && diff) {\n diff.renderDiff(\n docToBlocks(content),\n docToBlocks(comparison.content),\n );\n return;\n }\n const document = inEditorSchema(content);\n editor.transact((tr) => {\n tr.replaceWith(0, tr.doc.content.size, document.content);\n tr.setMeta(\"addToHistory\", false);\n });\n },\n close() {\n if (closed) {\n return;\n }\n if (!live) {\n throw new Error(\"Missing live editor state\");\n }\n editor.prosemirrorView.updateState(\n live.reconfigure({\n plugins: editor.prosemirrorState.plugins,\n }),\n );\n closed = true;\n live = undefined;\n },\n };\n },\n },\n storage: {\n historyIncludesBeginning: true,\n async list(signal) {\n signal.throwIfAborted();\n return {\n ok: true,\n value: {\n snapshots: Array.from(snapshots.values(), ({ version }) => ({\n ...version,\n })).sort((a, b) => b.createdAt - a.createdAt),\n },\n };\n },\n async getContent(id, signal) {\n signal.throwIfAborted();\n const stored = snapshots.get(id);\n return stored\n ? { ok: true, value: stored.content }\n : { ok: false, error: { type: \"not-found\" } };\n },\n async create(content, name) {\n const version = { id: String(++nextId), createdAt: Date.now(), name };\n snapshots.set(version.id, { version, content });\n return { ok: true, value: { ...version } };\n },\n async restore(id) {\n const stored = snapshots.get(id);\n if (!stored) {\n return { ok: false, error: { type: \"not-found\" } };\n }\n const content = inEditorSchema(stored.content);\n if (live) {\n live = live.apply(\n live.tr.replaceWith(0, live.doc.content.size, content.content),\n );\n } else {\n editor.transact((tr) =>\n tr.replaceWith(0, tr.doc.content.size, content.content),\n );\n }\n return { ok: true, value: undefined };\n },\n async rename(id, name) {\n const stored = snapshots.get(id);\n if (!stored) {\n return { ok: false, error: { type: \"not-found\" } };\n }\n stored.version.name = name;\n return { ok: true, value: undefined };\n },\n async remove(id) {\n snapshots.delete(id);\n return { ok: true, value: undefined };\n },\n },\n };\n}\n","// One formatter per locale: building an `Intl.DateTimeFormat` is the costly\n// part, and history lists format a date per row on every render.\nconst formatters = new Map<string | undefined, Intl.DateTimeFormat>();\n\n/**\n * A version's date and time as one string. A single formatter lets the locale\n * order and join the parts itself (e.g. \"3 January 2024 at 9:44\",\n * \"3. Januar 2024 um 9:44\"), rather than a hardcoded \"date, time\".\n * @param locale - Defaults to the browser's locale.\n */\nexport function formatVersionDate(timestamp: number, locale?: string): string {\n let formatter = formatters.get(locale);\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(locale, {\n day: \"numeric\",\n month: \"long\",\n year: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n formatters.set(locale, formatter);\n }\n return formatter.format(timestamp);\n}\n"],"mappings":"yiBAMA,SAAgB,EACd,EACA,EACmD,CACnD,IAAI,EACA,EAEJ,KAAI,WAAY,aAAa,EAAM,IAE7B,EACK,GAOL,CAAC,EAAY,CAAI,GAAK,CAAC,EAAK,MAAM,IAAM,EAAA,GAAU,EAAM,CAAG,IAAM,IAIrE,EAAa,EACb,EAAgB,EAAM,EAEf,GACR,EAEG,IAAe,IAAA,IAAa,IAAkB,IAAA,GAIlD,MAAO,CACL,KAAM,EACS,eACjB,CACF,CAEA,SAAgB,EAAY,EAAqB,CAC/C,OAAO,EAAK,KAAK,UAAU,SAAS,CACtC,CCnCA,IAAa,EACX,+DAMF,SAAgB,EACd,EACA,EACqB,CACrB,GAAI,CAAC,EAAK,IAAI,SAAS,CAAO,EAC5B,OAGF,IAAM,EAAQ,EAAQ,QAAQ,YAAY,EAC1C,GAAI,GAAS,IAAU,EAAK,IAC1B,OAEF,IAAM,EAAQ,EAAQ,QAAQ,CAAc,EAC5C,OAAO,GAAS,IAAU,EAAK,KAAO,EAAK,IAAI,SAAS,CAAK,EACzD,EACA,IAAA,EACN,CAaA,SAAgB,EACd,EACA,EACA,EACqB,CACrB,IAAM,EAAM,EAAK,QAAQ,CAAG,EAC5B,GAAI,EAAE,aAAe,SACnB,OAKF,IAAM,EAAU,EAAI,QAAA,8DAAsB,EACtC,EACA,EAAI,cAAc,CAAc,EACpC,OAAO,GAAS,aAAa,SAAS,IAAM,EAAK,EAAU,IAAA,EAC7D,CAGA,SAAgB,EACd,EACA,EAC6D,CAC7D,IAAM,EAAO,EAAgB,EAAS,CAAI,EAC1C,GAAI,CAAC,EACH,OAGF,IAAM,EAAK,EAAK,aAAa,SAAS,EAChC,EAAW,EAAK,aAAa,gBAAgB,EAG7C,EACJ,IAAa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