@blocknote/core 0.53.0 → 0.54.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/dist/BlockNoteExtension-BJCLnwrE.cjs +2 -0
  2. package/dist/BlockNoteExtension-BJCLnwrE.cjs.map +1 -0
  3. package/dist/BlockNoteExtension-CbvDA0F7.js +80 -0
  4. package/dist/BlockNoteExtension-CbvDA0F7.js.map +1 -0
  5. package/dist/{UserStore-QbbPFj0z.js → UserStore-C4TzkGEn.js} +3 -3
  6. package/dist/{UserStore-DCG6lsla.cjs.map → UserStore-C4TzkGEn.js.map} +1 -1
  7. package/dist/{UserStore-DCG6lsla.cjs → UserStore-mj3fXW4D.cjs} +2 -2
  8. package/dist/UserStore-mj3fXW4D.cjs.map +1 -0
  9. package/dist/blocknote.cjs +1 -1
  10. package/dist/blocknote.js +6 -6
  11. package/dist/blocks-CTB_5Vyj.cjs +12 -0
  12. package/dist/blocks-CTB_5Vyj.cjs.map +1 -0
  13. package/dist/{blocks-BEJW9OM_.js → blocks-Dol85hpH.js} +680 -670
  14. package/dist/blocks-Dol85hpH.js.map +1 -0
  15. package/dist/blocks.cjs +1 -1
  16. package/dist/blocks.js +2 -2
  17. package/dist/comments.cjs +1 -1
  18. package/dist/comments.cjs.map +1 -1
  19. package/dist/comments.js +7 -7
  20. package/dist/comments.js.map +1 -1
  21. package/dist/en-BuzSuuTq.cjs +2 -0
  22. package/dist/en-BuzSuuTq.cjs.map +1 -0
  23. package/dist/{en-CGKXfWma.js → en-uzHzj6eH.js} +10 -1
  24. package/dist/en-uzHzj6eH.js.map +1 -0
  25. package/dist/extensions-B7Rsp_Ft.cjs +58 -0
  26. package/dist/extensions-B7Rsp_Ft.cjs.map +1 -0
  27. package/dist/{extensions-BR5hkAio.js → extensions-D6JcJCwd.js} +735 -457
  28. package/dist/extensions-D6JcJCwd.js.map +1 -0
  29. package/dist/extensions.cjs +1 -1
  30. package/dist/extensions.js +4 -4
  31. package/dist/locales.cjs +1 -1
  32. package/dist/locales.cjs.map +1 -1
  33. package/dist/locales.js +199 -1
  34. package/dist/locales.js.map +1 -1
  35. package/dist/{src-BUXut68d.js → src-Buuo5l7X.js} +924 -851
  36. package/dist/src-Buuo5l7X.js.map +1 -0
  37. package/dist/src-C54Ok9E0.cjs +23 -0
  38. package/dist/src-C54Ok9E0.cjs.map +1 -0
  39. package/dist/style.css +1 -1
  40. package/dist/webpack-stats.json +1 -1
  41. package/dist/y.cjs +1 -1
  42. package/dist/y.cjs.map +1 -1
  43. package/dist/y.js +245 -242
  44. package/dist/y.js.map +1 -1
  45. package/dist/yjs.cjs +1 -1
  46. package/dist/yjs.cjs.map +1 -1
  47. package/dist/yjs.js +79 -67
  48. package/dist/yjs.js.map +1 -1
  49. package/package.json +17 -18
  50. package/src/api/blockManipulation/commands/updateBlock/__snapshots__/updateBlock.test.ts.snap +2505 -763
  51. package/src/api/blockManipulation/commands/updateBlock/updateBlock.test.ts +42 -0
  52. package/src/api/blockManipulation/commands/updateBlock/updateBlock.ts +16 -4
  53. package/src/api/exporters/markdown/htmlToMarkdown.ts +45 -10
  54. package/src/api/getBlocksChangedByTransaction.test.ts +211 -0
  55. package/src/api/getBlocksChangedByTransaction.ts +48 -12
  56. package/src/api/getChangedRange.ts +54 -0
  57. package/src/api/nodeConversions/blockToNode.ts +5 -1
  58. package/src/api/nodeConversions/nodeToBlock.ts +3 -0
  59. package/src/api/pmUtil.ts +16 -8
  60. package/src/blocks/Code/CodeBlockOptions.ts +83 -0
  61. package/src/blocks/Code/block.test.ts +1 -1
  62. package/src/blocks/Code/block.ts +29 -281
  63. package/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.ts +120 -0
  64. package/src/blocks/Code/helpers/parse/parsePreCode.ts +45 -0
  65. package/src/blocks/Code/helpers/render/createCodeBlock.ts +98 -0
  66. package/src/blocks/Code/helpers/toExternalHTML/createPreCode.ts +14 -0
  67. package/src/blocks/index.ts +3 -1
  68. package/src/comments/extension.ts +2 -4
  69. package/src/editor/Block.css +273 -2
  70. package/src/editor/BlockNoteEditor.ts +25 -4
  71. package/src/editor/BlockNoteExtension.ts +1 -1
  72. package/src/editor/managers/ExtensionManager/extensions.ts +6 -0
  73. package/src/editor/performance.test.ts +45 -0
  74. package/src/exporter/ExportImage.ts +50 -0
  75. package/src/exporter/Exporter.test.ts +186 -0
  76. package/src/exporter/Exporter.ts +66 -14
  77. package/src/exporter/index.ts +1 -0
  78. package/src/exporter/mapping.ts +4 -1
  79. package/src/extensions/FormattingToolbar/FormattingToolbar.ts +10 -8
  80. package/src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.ts +109 -0
  81. package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +21 -0
  82. package/src/extensions/PreviousBlockType/PreviousBlockType.ts +5 -3
  83. package/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts +192 -0
  84. package/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.ts +142 -0
  85. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.ts +120 -0
  86. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts +89 -0
  87. package/src/extensions/SyntaxHighlighting/inlineHighlight.test.ts +135 -0
  88. package/src/extensions/SyntaxHighlighting/shiki.ts +116 -0
  89. package/src/extensions/TableHandles/TableHandles.browser.test.ts +305 -0
  90. package/src/extensions/TableHandles/TableHandles.ts +82 -41
  91. package/src/extensions/Versioning/inMemoryVersioning.ts +13 -3
  92. package/src/extensions/index.ts +4 -0
  93. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.ts +51 -2
  94. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +22 -2
  95. package/src/fonts/inter.css +9 -9
  96. package/src/i18n/locales/ar.ts +9 -0
  97. package/src/i18n/locales/de.ts +9 -0
  98. package/src/i18n/locales/en.ts +9 -0
  99. package/src/i18n/locales/es.ts +9 -0
  100. package/src/i18n/locales/fa.ts +9 -0
  101. package/src/i18n/locales/fr.ts +9 -0
  102. package/src/i18n/locales/he.ts +9 -0
  103. package/src/i18n/locales/hr.ts +9 -0
  104. package/src/i18n/locales/is.ts +9 -0
  105. package/src/i18n/locales/it.ts +9 -0
  106. package/src/i18n/locales/ja.ts +9 -0
  107. package/src/i18n/locales/ko.ts +9 -0
  108. package/src/i18n/locales/nl.ts +9 -0
  109. package/src/i18n/locales/no.ts +9 -0
  110. package/src/i18n/locales/pl.ts +9 -0
  111. package/src/i18n/locales/pt.ts +9 -0
  112. package/src/i18n/locales/ru.ts +9 -0
  113. package/src/i18n/locales/sk.ts +9 -0
  114. package/src/i18n/locales/uk.ts +9 -0
  115. package/src/i18n/locales/uz.ts +9 -0
  116. package/src/i18n/locales/vi.ts +9 -0
  117. package/src/i18n/locales/zh-tw.ts +9 -0
  118. package/src/i18n/locales/zh.ts +9 -0
  119. package/src/index.ts +5 -1
  120. package/src/schema/blocks/createSpec.ts +5 -7
  121. package/src/schema/blocks/types.ts +53 -3
  122. package/src/schema/contentTypePropagation.test.ts +1 -1
  123. package/src/schema/inlineContent/createSpec.test.ts +161 -0
  124. package/src/schema/inlineContent/createSpec.ts +175 -17
  125. package/src/schema/inlineContent/internal.ts +21 -2
  126. package/src/schema/inlineContent/types.ts +35 -5
  127. package/src/schema/nodeViewMutations.test.ts +81 -56
  128. package/src/schema/nodeViewMutations.ts +30 -27
  129. package/src/schema/schema.test.ts +110 -0
  130. package/src/schema/schema.ts +13 -4
  131. package/src/user/UserStore.ts +1 -1
  132. package/src/util/Store.test.ts +132 -0
  133. package/src/util/Store.ts +135 -0
  134. package/src/y/extensions/AttributionExtension.test.ts +18 -9
  135. package/src/y/extensions/Versioning.test.ts +20 -7
  136. package/src/y/versioning/__test__/yhub.test.ts +92 -59
  137. package/src/y/versioning/yhub.ts +35 -29
  138. package/src/yjs/comments/RESTYjsThreadStore.test.ts +85 -0
  139. package/src/yjs/comments/RESTYjsThreadStore.ts +7 -1
  140. package/src/yjs/extensions/ForkYDoc.test.ts +37 -0
  141. package/src/yjs/extensions/ForkYDoc.ts +26 -1
  142. package/src/yjs/extensions/RelativePositionMapping.ts +8 -2
  143. package/src/yjs/extensions/Versioning.test.ts +17 -5
  144. package/types/src/api/getChangedRange.d.ts +14 -0
  145. package/types/src/api/pmUtil.d.ts +7 -7
  146. package/types/src/blocks/Code/CodeBlockOptions.d.ts +61 -0
  147. package/types/src/blocks/Code/block.d.ts +3 -53
  148. package/types/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.d.ts +35 -0
  149. package/types/src/blocks/Code/helpers/parse/parsePreCode.d.ts +8 -0
  150. package/types/src/blocks/Code/helpers/render/createCodeBlock.d.ts +18 -0
  151. package/types/src/blocks/Code/helpers/toExternalHTML/createPreCode.d.ts +5 -0
  152. package/types/src/blocks/index.d.ts +3 -1
  153. package/types/src/comments/extension.d.ts +1 -15
  154. package/types/src/editor/BlockNoteEditor.d.ts +3 -3
  155. package/types/src/editor/BlockNoteExtension.d.ts +1 -1
  156. package/types/src/exporter/ExportImage.d.ts +36 -0
  157. package/types/src/exporter/Exporter.d.ts +30 -0
  158. package/types/src/exporter/Exporter.test.d.ts +1 -0
  159. package/types/src/exporter/index.d.ts +1 -0
  160. package/types/src/exporter/mapping.d.ts +1 -1
  161. package/types/src/extensions/FilePanel/FilePanel.d.ts +1 -1
  162. package/types/src/extensions/FormattingToolbar/FormattingToolbar.d.ts +1 -1
  163. package/types/src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.d.ts +5 -0
  164. package/types/src/extensions/ShowSelection/ShowSelection.d.ts +1 -5
  165. package/types/src/extensions/SideMenu/SideMenu.d.ts +1 -1
  166. package/types/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.d.ts +45 -0
  167. package/types/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.d.ts +49 -0
  168. package/types/src/extensions/SuggestionMenu/SuggestionMenu.d.ts +1 -11
  169. package/types/src/extensions/SyntaxHighlighting/SyntaxHighlighting.d.ts +44 -0
  170. package/types/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.d.ts +1 -0
  171. package/types/src/extensions/SyntaxHighlighting/inlineHighlight.test.d.ts +1 -0
  172. package/types/src/extensions/SyntaxHighlighting/shiki.d.ts +13 -0
  173. package/types/src/extensions/TableHandles/TableHandles.browser.test.d.ts +1 -0
  174. package/types/src/extensions/TableHandles/TableHandles.d.ts +4 -1
  175. package/types/src/extensions/Versioning/Versioning.d.ts +1 -35
  176. package/types/src/extensions/index.d.ts +4 -0
  177. package/types/src/i18n/locales/en.d.ts +9 -0
  178. package/types/src/i18n/locales/fa.d.ts +9 -0
  179. package/types/src/i18n/locales/sk.d.ts +9 -0
  180. package/types/src/index.d.ts +2 -1
  181. package/types/src/schema/blocks/types.d.ts +36 -3
  182. package/types/src/schema/inlineContent/createSpec.d.ts +35 -3
  183. package/types/src/schema/inlineContent/createSpec.test.d.ts +1 -0
  184. package/types/src/schema/inlineContent/internal.d.ts +3 -2
  185. package/types/src/schema/inlineContent/types.d.ts +22 -3
  186. package/types/src/schema/nodeViewMutations.d.ts +2 -2
  187. package/types/src/schema/schema.test.d.ts +1 -0
  188. package/types/src/user/UserStore.d.ts +1 -1
  189. package/types/src/util/Store.d.ts +45 -0
  190. package/types/src/util/Store.test.d.ts +1 -0
  191. package/types/src/y/extensions/AttributionExtension.d.ts +1 -1
  192. package/types/src/y/extensions/DiffVersioningExtension.d.ts +1 -1
  193. package/types/src/y/extensions/ForkYDoc.d.ts +1 -5
  194. package/types/src/y/extensions/index.d.ts +2 -10
  195. package/types/src/y/versioning/yhub.d.ts +3 -2
  196. package/types/src/yjs/comments/RESTYjsThreadStore.test.d.ts +1 -0
  197. package/types/src/yjs/extensions/ForkYDoc.d.ts +1 -5
  198. package/types/src/yjs/extensions/index.d.ts +1 -5
  199. package/dist/BlockNoteExtension-B_IEJHS8.js +0 -38
  200. package/dist/BlockNoteExtension-B_IEJHS8.js.map +0 -1
  201. package/dist/BlockNoteExtension-M0znTzxP.cjs +0 -2
  202. package/dist/BlockNoteExtension-M0znTzxP.cjs.map +0 -1
  203. package/dist/UserStore-QbbPFj0z.js.map +0 -1
  204. package/dist/blocks-BEJW9OM_.js.map +0 -1
  205. package/dist/blocks-BPmJglFo.cjs +0 -12
  206. package/dist/blocks-BPmJglFo.cjs.map +0 -1
  207. package/dist/en-C5Z4Ag9_.cjs +0 -2
  208. package/dist/en-C5Z4Ag9_.cjs.map +0 -1
  209. package/dist/en-CGKXfWma.js.map +0 -1
  210. package/dist/extensions-AitWbYdJ.cjs +0 -52
  211. package/dist/extensions-AitWbYdJ.cjs.map +0 -1
  212. package/dist/extensions-BR5hkAio.js.map +0 -1
  213. package/dist/src-BHPuOo7W.cjs +0 -21
  214. package/dist/src-BHPuOo7W.cjs.map +0 -1
  215. package/dist/src-BUXut68d.js.map +0 -1
  216. package/src/blocks/Code/shiki.ts +0 -73
  217. package/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.ts +0 -20
  218. package/types/src/blocks/Code/shiki.d.ts +0 -4
  219. package/types/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.d.ts +0 -6
@@ -475,6 +475,48 @@ describe("Test updateBlock", () => {
475
475
  expect(getEditor().document).toMatchSnapshot();
476
476
  });
477
477
 
478
+ it("Update inline content to plain content", () => {
479
+ expect(
480
+ getEditor().transact((tr) =>
481
+ updateBlock(tr, "paragraph-0", {
482
+ type: "codeBlock",
483
+ }),
484
+ ),
485
+ ).toMatchSnapshot();
486
+
487
+ expect(getEditor().document).toMatchSnapshot();
488
+ });
489
+
490
+ it("Update styled inline content to plain content", () => {
491
+ // The plain block can't hold formatting marks, so the styling is dropped
492
+ // but the text is preserved.
493
+ expect(
494
+ getEditor().transact((tr) =>
495
+ updateBlock(tr, "paragraph-with-styled-content", {
496
+ type: "codeBlock",
497
+ }),
498
+ ),
499
+ ).toMatchSnapshot();
500
+
501
+ expect(getEditor().document).toMatchSnapshot();
502
+ });
503
+
504
+ it("Update plain content to inline content", () => {
505
+ getEditor().transact((tr) =>
506
+ updateBlock(tr, "paragraph-0", { type: "codeBlock" }),
507
+ );
508
+
509
+ expect(
510
+ getEditor().transact((tr) =>
511
+ updateBlock(tr, "paragraph-0", {
512
+ type: "paragraph",
513
+ }),
514
+ ),
515
+ ).toMatchSnapshot();
516
+
517
+ expect(getEditor().document).toMatchSnapshot();
518
+ });
519
+
478
520
  it("Update no content to empty inline content", () => {
479
521
  expect(
480
522
  getEditor().transact((tr) =>
@@ -202,14 +202,26 @@ function updateBlockContentNode<
202
202
  // Since some block types contain inline content and others don't,
203
203
  // we either need to call setNodeMarkup to just update type &
204
204
  // attributes, or replaceWith to replace the whole blockContent.
205
+ const oldContent = blockInfo.blockContent.node.content;
205
206
  if (oldNodeType.spec.content === "") {
206
207
  // keep old content, because it's empty anyway and should be compatible with
207
208
  // any newContentType
208
- } else if (newNodeType.spec.content !== oldNodeType.spec.content) {
209
- // the content type changed, replace the previous content
210
- content = [];
211
- } else {
209
+ } else if (newNodeType.spec.content === oldNodeType.spec.content) {
212
210
  // keep old content, because the content type is the same and should be compatible
211
+ } else if (newNodeType.validContent(oldContent)) {
212
+ // The content-type strings differ (e.g. "inline*" vs a plain block's
213
+ // "text*"), but the existing content is still valid for the new type
214
+ // (e.g. plain, unstyled text), so keep it rather than clearing it.
215
+ } else if (newNodeType.inlineContent && oldNodeType.inlineContent) {
216
+ // Both blocks hold text, but the existing content isn't directly valid
217
+ // for the new type (e.g. converting styled/complex inline content into a
218
+ // plain block that disallows formatting marks and inline nodes). Preserve
219
+ // the text, dropping the styling the new type can't represent.
220
+ const text = blockInfo.blockContent.node.textContent;
221
+ content = text.length > 0 ? [pmSchema.text(text)] : [];
222
+ } else {
223
+ // the content type changed and is incompatible, replace the previous content
224
+ content = [];
213
225
  }
214
226
  }
215
227
 
@@ -78,6 +78,8 @@ function serializeNode(node: Node, ctx: SerializeContext): string {
78
78
  return serializeTable(el, ctx);
79
79
  case "hr":
80
80
  return ctx.indent + "***\n\n";
81
+ case "math":
82
+ return serializeMathBlock(el, ctx);
81
83
  case "img":
82
84
  return serializeImage(el, ctx);
83
85
  case "video":
@@ -175,18 +177,41 @@ function serializeCodeBlock(el: HTMLElement, ctx: SerializeContext): string {
175
177
 
176
178
  // For empty code blocks, don't add a newline between the fences
177
179
  if (!code) {
178
- return ctx.indent + fence + language + "\n" + fence + "\n\n";
179
- }
180
+ return ctx.indent + fence + language + "\n" + ctx.indent + fence + "\n\n";
181
+ }
182
+
183
+ // Every (non-blank) line carries the indent - inside a list item or
184
+ // blockquote, an unindented line would end the parent container. Blank
185
+ // lines stay blank: they don't terminate an indented fence, and indenting
186
+ // them would add trailing whitespace.
187
+ const lines = [
188
+ fence + language,
189
+ ...(code.endsWith("\n") ? code.slice(0, -1) : code).split("\n"),
190
+ fence,
191
+ ];
192
+ return (
193
+ lines.map((line) => (line ? ctx.indent + line : line)).join("\n") + "\n\n"
194
+ );
195
+ }
180
196
 
197
+ // The LaTeX source of a MathML element, taken from the annotation KaTeX
198
+ // embeds in its output (also what external HTML parsing reads). Falls back to
199
+ // the element's text content for MathML from other sources.
200
+ function extractMathLatexSource(el: Element): string {
201
+ const annotation = el.querySelector(
202
+ 'annotation[encoding="application/x-tex"]',
203
+ );
204
+ return (annotation?.textContent ?? el.textContent ?? "").trim();
205
+ }
206
+
207
+ function serializeMathBlock(el: HTMLElement, ctx: SerializeContext): string {
208
+ const latex = extractMathLatexSource(el);
209
+ // Every (non-blank) line carries the indent - inside a list item or
210
+ // blockquote, an unindented line would end the parent container.
181
211
  return (
182
- ctx.indent +
183
- fence +
184
- language +
185
- "\n" +
186
- code +
187
- (code.endsWith("\n") ? "" : "\n") +
188
- fence +
189
- "\n\n"
212
+ ["$$", ...latex.split("\n"), "$$"]
213
+ .map((line) => (line ? ctx.indent + line : line))
214
+ .join("\n") + "\n\n"
190
215
  );
191
216
  }
192
217
 
@@ -775,6 +800,16 @@ function serializeInlineContent(el: Element): string {
775
800
  case "br":
776
801
  result += "\\\n";
777
802
  break;
803
+ case "math": {
804
+ // Inline math — emit its LaTeX source as a math span. Collapsed to
805
+ // a single line, as $...$ spans cannot contain newlines.
806
+ const latex = extractMathLatexSource(childEl)
807
+ .split("\n")
808
+ .map((line) => line.trim())
809
+ .join(" ");
810
+ result += `$${latex}$`;
811
+ break;
812
+ }
778
813
  case "span":
779
814
  // Color spans, etc. — strip the tag, keep content
780
815
  result += serializeInlineContent(childEl);
@@ -2,7 +2,10 @@ import { describe, expect, it, beforeEach } from "vite-plus/test";
2
2
 
3
3
  import { setupTestEnv } from "./blockManipulation/setupTestEnv.js";
4
4
  import { getBlocksChangedByTransaction } from "./getBlocksChangedByTransaction.js";
5
+ import { getBlockInfo } from "./getBlockInfoFromPos.js";
6
+ import { getNodeById } from "./nodeUtil.js";
5
7
  import { BlockNoteEditor } from "../editor/BlockNoteEditor.js";
8
+ import { PartialBlock } from "../blocks/defaultBlocks.js";
6
9
 
7
10
  const getEditor = setupTestEnv();
8
11
 
@@ -570,3 +573,211 @@ describe("getBlocksChangedByTransaction", () => {
570
573
  );
571
574
  });
572
575
  });
576
+
577
+ /**
578
+ * These exercise the ranged optimization: getBlocksChangedByTransaction only
579
+ * snapshots the range a transaction touched, not the whole document. In a large
580
+ * document the failure modes are (a) missing a real change and (b) reporting a
581
+ * block that didn't actually change. Each test edits a big document and asserts
582
+ * the exact set of reported changes.
583
+ */
584
+ describe("getBlocksChangedByTransaction - ranged optimization", () => {
585
+ let editor: BlockNoteEditor;
586
+
587
+ const LARGE = 200;
588
+
589
+ function makeParagraphs(count: number): PartialBlock[] {
590
+ return Array.from({ length: count }, (_, i) => ({
591
+ id: `p-${i}`,
592
+ type: "paragraph",
593
+ content: `Paragraph ${i}`,
594
+ }));
595
+ }
596
+
597
+ function summarize(changes: Array<{ type: string; block: { id: string } }>) {
598
+ return changes.map((change) => ({
599
+ type: change.type,
600
+ id: change.block.id,
601
+ }));
602
+ }
603
+
604
+ beforeEach(() => {
605
+ editor = getEditor();
606
+ });
607
+
608
+ it("reports only the changed block for a prop update deep in a large doc", () => {
609
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
610
+
611
+ const changes = editor.transact((tr) => {
612
+ editor.updateBlock("p-120", { props: { backgroundColor: "red" } });
613
+ return getBlocksChangedByTransaction(tr);
614
+ });
615
+
616
+ expect(summarize(changes)).toEqual([{ type: "update", id: "p-120" }]);
617
+ });
618
+
619
+ it("reports only the edited block for a content insertion in a large doc", () => {
620
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
621
+
622
+ const changes = editor.transact((tr) => {
623
+ editor.setTextCursorPosition("p-77", "start");
624
+ editor.insertInlineContent("Hello ");
625
+ return getBlocksChangedByTransaction(tr);
626
+ });
627
+
628
+ expect(summarize(changes)).toEqual([{ type: "update", id: "p-77" }]);
629
+ });
630
+
631
+ it("reports two distant prop updates without reporting the blocks between them", () => {
632
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
633
+
634
+ const changes = editor.transact((tr) => {
635
+ editor.updateBlock("p-10", { props: { backgroundColor: "red" } });
636
+ editor.updateBlock("p-190", { props: { backgroundColor: "blue" } });
637
+ return getBlocksChangedByTransaction(tr);
638
+ });
639
+
640
+ const summary = summarize(changes);
641
+ expect(summary).toContainEqual({ type: "update", id: "p-10" });
642
+ expect(summary).toContainEqual({ type: "update", id: "p-190" });
643
+ expect(summary).toHaveLength(2);
644
+ });
645
+
646
+ it("reports a mark-only change as an update (empty-map AddMarkStep)", () => {
647
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
648
+
649
+ const changes = editor.transact((tr) => {
650
+ const posInfo = getNodeById("p-140", tr.doc);
651
+ if (!posInfo) {
652
+ throw new Error("block not found");
653
+ }
654
+ const info = getBlockInfo(posInfo);
655
+ if (!info.isBlockContainer) {
656
+ throw new Error("expected a block container");
657
+ }
658
+ // Adding a mark produces an AddMarkStep, whose StepMap is empty — the case
659
+ // getChangedRange has to recover from the step's own from/to.
660
+ tr.addMark(
661
+ info.blockContent.beforePos + 1,
662
+ info.blockContent.afterPos - 1,
663
+ editor.pmSchema.marks.bold.create(),
664
+ );
665
+ return getBlocksChangedByTransaction(tr);
666
+ });
667
+
668
+ expect(summarize(changes)).toEqual([{ type: "update", id: "p-140" }]);
669
+ });
670
+
671
+ it("reports mixed insert/update/delete across a large doc in one transaction", () => {
672
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
673
+
674
+ const changes = editor.transact((tr) => {
675
+ editor.updateBlock("p-20", { props: { backgroundColor: "red" } });
676
+ editor.removeBlocks(["p-100"]);
677
+ editor.insertBlocks(
678
+ [{ id: "inserted", type: "paragraph", content: "new" }],
679
+ "p-180",
680
+ "after",
681
+ );
682
+ return getBlocksChangedByTransaction(tr);
683
+ });
684
+
685
+ const summary = summarize(changes);
686
+ expect(summary).toContainEqual({ type: "update", id: "p-20" });
687
+ expect(summary).toContainEqual({ type: "delete", id: "p-100" });
688
+ expect(summary).toContainEqual({ type: "insert", id: "inserted" });
689
+ expect(summary).toHaveLength(3);
690
+ });
691
+
692
+ it("reports an insert at the very start of a large doc", () => {
693
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
694
+
695
+ const changes = editor.transact((tr) => {
696
+ editor.insertBlocks(
697
+ [{ id: "new-first", type: "paragraph", content: "X" }],
698
+ "p-0",
699
+ "before",
700
+ );
701
+ return getBlocksChangedByTransaction(tr);
702
+ });
703
+
704
+ expect(summarize(changes)).toEqual([{ type: "insert", id: "new-first" }]);
705
+ });
706
+
707
+ it("reports an insert at the very end of a large doc", () => {
708
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
709
+
710
+ const changes = editor.transact((tr) => {
711
+ editor.insertBlocks(
712
+ [{ id: "new-last", type: "paragraph", content: "X" }],
713
+ `p-${LARGE - 1}`,
714
+ "after",
715
+ );
716
+ return getBlocksChangedByTransaction(tr);
717
+ });
718
+
719
+ expect(summarize(changes)).toEqual([{ type: "insert", id: "new-last" }]);
720
+ });
721
+
722
+ it("reports a delete in the middle without touching the blocks it shifts", () => {
723
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
724
+
725
+ const changes = editor.transact((tr) => {
726
+ editor.removeBlocks(["p-100"]);
727
+ return getBlocksChangedByTransaction(tr);
728
+ });
729
+
730
+ expect(summarize(changes)).toEqual([{ type: "delete", id: "p-100" }]);
731
+ });
732
+
733
+ it("reports a single move for a block moved across a large span", () => {
734
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
735
+
736
+ const changes = editor.transact((tr) => {
737
+ const block = editor.getBlock("p-5");
738
+ editor.removeBlocks(["p-5"]);
739
+ editor.insertBlocks([{ ...block }], "p-195", "after");
740
+ return getBlocksChangedByTransaction(tr);
741
+ });
742
+
743
+ expect(summarize(changes)).toEqual([{ type: "move", id: "p-5" }]);
744
+ });
745
+
746
+ it("does not report ancestor blocks when a deeply nested block changes", () => {
747
+ const blocks = makeParagraphs(100);
748
+ blocks[50] = {
749
+ id: "parent",
750
+ type: "paragraph",
751
+ content: "Parent",
752
+ children: [
753
+ {
754
+ id: "child",
755
+ type: "paragraph",
756
+ content: "Child",
757
+ children: [
758
+ { id: "grandchild", type: "paragraph", content: "Grandchild" },
759
+ ],
760
+ },
761
+ ],
762
+ };
763
+ editor.replaceBlocks(editor.document, blocks);
764
+
765
+ const changes = editor.transact((tr) => {
766
+ editor.updateBlock("grandchild", { props: { backgroundColor: "red" } });
767
+ return getBlocksChangedByTransaction(tr);
768
+ });
769
+
770
+ expect(summarize(changes)).toEqual([{ type: "update", id: "grandchild" }]);
771
+ });
772
+
773
+ it("returns no changes for a selection-only transaction in a large doc", () => {
774
+ editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
775
+
776
+ const changes = editor.transact((tr) => {
777
+ editor.setTextCursorPosition("p-100", "end");
778
+ return getBlocksChangedByTransaction(tr);
779
+ });
780
+
781
+ expect(changes).toEqual([]);
782
+ });
783
+ });
@@ -11,6 +11,7 @@ import {
11
11
  import type { BlockSchema } from "../schema/index.js";
12
12
  import type { InlineContentSchema } from "../schema/inlineContent/types.js";
13
13
  import type { StyleSchema } from "../schema/styles/types.js";
14
+ import { getChangedRange } from "./getChangedRange.js";
14
15
  import { getNodeId } from "./getBlockInfoFromPos.js";
15
16
  import { nodeToBlock } from "./nodeConversions/nodeToBlock.js";
16
17
  import { isNodeBlock } from "./nodeUtil.js";
@@ -20,14 +21,23 @@ import { isNodeBlock } from "./nodeUtil.js";
20
21
  *
21
22
  * High-level algorithm used by getBlocksChangedByTransaction:
22
23
  * 1) Merge appended transactions into one document change.
23
- * 2) Collect a snapshot of blocks before and after (flat map by id, and per-parent child order).
24
- * 3) Emit inserts and deletes by diffing ids between snapshots.
25
- * 4) For ids present in both snapshots:
26
- * - If parentId changed, emit a move
27
- * - Else if block changed (ignoring children), emit an update
28
- * 5) Finally, detect same-parent sibling reorders by comparing child order per parent.
29
- * We use an inlined O(n log n) LIS inside detectReorderedChildren to keep a
30
- * longest already-ordered subsequence and mark only the remaining items as moved.
24
+ * 2) Compute the single range the transaction touched (in both the old and new
25
+ * doc) and only snapshot blocks within it, rather than walking the whole
26
+ * document. getChanges() runs per transaction, so a full-document snapshot
27
+ * made typing in large documents slow: every keystroke re-converted every block.
28
+ * 3) Snapshot blocks before and after within that range (flat map by id, and
29
+ * per-parent child order).
30
+ * 4) Emit inserts/deletes by diffing ids; for shared ids, emit a move (parent
31
+ * changed) or update (block changed, ignoring children).
32
+ * 5) Detect same-parent sibling reorders via an O(n log n) LIS in
33
+ * detectReorderedChildren, marking only items outside the longest ordered
34
+ * subsequence as moved.
35
+ *
36
+ * The range suffices because `changedRange()` spans from the first to the last
37
+ * changed position: any inserted/deleted/moved/updated/reordered block has its
38
+ * relevant positions inside it, and blocks outside are byte-for-byte identical in
39
+ * the same relative order. A moved block's parent contains it, so the parent
40
+ * overlaps the range too (and nodeToBlock converts its full subtree regardless).
31
41
  */
32
42
  /**
33
43
  * Gets the parent block of a node, if it has one.
@@ -144,14 +154,19 @@ type BlockSnapshot<
144
154
  };
145
155
 
146
156
  /**
147
- * Collects a snapshot of blocks and per-parent child order in a single traversal.
148
- * Uses "__root__" to represent the root level where parentId is undefined.
157
+ * Snapshots blocks and per-parent child order for the block nodes overlapping the
158
+ * given range (uses "__root__" for the root level). Traversing only the range is
159
+ * what keeps this cheap per keystroke: nodeToBlock runs only for blocks that could
160
+ * have changed.
149
161
  */
150
162
  function collectSnapshot<
151
163
  BSchema extends BlockSchema,
152
164
  ISchema extends InlineContentSchema,
153
165
  SSchema extends StyleSchema,
154
- >(doc: Node): BlockSnapshot<BSchema, ISchema, SSchema> {
166
+ >(
167
+ doc: Node,
168
+ range: { from: number; to: number },
169
+ ): BlockSnapshot<BSchema, ISchema, SSchema> {
155
170
  const ROOT_KEY = "__root__";
156
171
  const byId: Record<
157
172
  string,
@@ -161,7 +176,12 @@ function collectSnapshot<
161
176
  }
162
177
  > = {};
163
178
  const childrenByParent: Record<string, string[]> = {};
164
- doc.descendants((node, pos) => {
179
+ // Clamp to valid positions; nodesBetween throws on out-of-range ones.
180
+ const from = Math.max(0, Math.min(range.from, doc.content.size));
181
+ const to = Math.max(from, Math.min(range.to, doc.content.size));
182
+ // nodesBetween visits every node overlapping [from, to] in document order,
183
+ // including ancestor blocks that contain the range.
184
+ doc.nodesBetween(from, to, (node, pos) => {
165
185
  if (!isNodeBlock(node)) {
166
186
  return true;
167
187
  }
@@ -282,11 +302,27 @@ export function getBlocksChangedByTransaction<
282
302
  ...appendedTransactions,
283
303
  ]);
284
304
 
305
+ // Changed range in the new doc; null means nothing changed.
306
+ const newRange = getChangedRange(combinedTransaction);
307
+ if (!newRange) {
308
+ return [];
309
+ }
310
+ // Map it back to old-doc coordinates. The -1/+1 biases expand outwards so that
311
+ // for pure inserts/deletes (collapsed new range) the old range still covers the
312
+ // affected span.
313
+ const invertedMapping = combinedTransaction.mapping.invert();
314
+ const oldRange = {
315
+ from: invertedMapping.map(newRange.from, -1),
316
+ to: invertedMapping.map(newRange.to, 1),
317
+ };
318
+
285
319
  const prevSnap = collectSnapshot<BSchema, ISchema, SSchema>(
286
320
  combinedTransaction.before,
321
+ oldRange,
287
322
  );
288
323
  const nextSnap = collectSnapshot<BSchema, ISchema, SSchema>(
289
324
  combinedTransaction.doc,
325
+ newRange,
290
326
  );
291
327
 
292
328
  const changes: BlocksChanged<BSchema, ISchema, SSchema> = [];
@@ -0,0 +1,54 @@
1
+ import type { Transform } from "prosemirror-transform";
2
+
3
+ /**
4
+ * Like ProseMirror's `Transform.changedRange()`, but also accounts for
5
+ * position-preserving steps whose `StepMap` is empty — `AttrStep` (prop-only
6
+ * updates like a heading's `level`) and mark steps. `changedRange()` and tiptap's
7
+ * `getChangedRanges` both miss `AttrStep`, so anything that scopes work to the
8
+ * changed range would silently ignore prop-only updates.
9
+ *
10
+ * O(steps), like `changedRange()`. Returns null when nothing changed.
11
+ */
12
+ export function getChangedRange(
13
+ transform: Transform,
14
+ ): { from: number; to: number } | null {
15
+ const { mapping, steps } = transform;
16
+ let from = Number.POSITIVE_INFINITY;
17
+ let to = Number.NEGATIVE_INFINITY;
18
+
19
+ for (let i = 0; i < mapping.maps.length; i++) {
20
+ const map = mapping.maps[i];
21
+ // Advance the accumulated range into this step's coordinate space.
22
+ if (i) {
23
+ from = map.map(from, 1);
24
+ to = map.map(to, -1);
25
+ }
26
+
27
+ let hadRange = false;
28
+ map.forEach((_oldFrom, _oldTo, newFrom, newTo) => {
29
+ hadRange = true;
30
+ from = Math.min(from, newFrom);
31
+ to = Math.max(to, newTo);
32
+ });
33
+
34
+ if (!hadRange) {
35
+ // Position-preserving step: recover the affected position from the step,
36
+ // since its map has no ranges. (DocAttrStep has none and affects no nodes.)
37
+ const step = steps[i] as { pos?: number; from?: number; to?: number };
38
+ if (typeof step.pos === "number") {
39
+ // AttrStep
40
+ from = Math.min(from, step.pos);
41
+ to = Math.max(to, step.pos + 1);
42
+ } else if (typeof step.from === "number" && typeof step.to === "number") {
43
+ // AddMarkStep / RemoveMarkStep
44
+ from = Math.min(from, step.from);
45
+ to = Math.max(to, step.to);
46
+ }
47
+ }
48
+ }
49
+
50
+ if (from === Number.POSITIVE_INFINITY) {
51
+ return null;
52
+ }
53
+ return { from, to };
54
+ }
@@ -64,7 +64,11 @@ function styledTextToNodes<T extends StyleSchema>(
64
64
  ? [...schema.nodes[blockType].allowedMarks(marks)]
65
65
  : marks;
66
66
 
67
- const parseHardBreaks = !blockType || !schema.nodes[blockType].spec.code;
67
+ // Plain content nodes hold raw text — including newlines —
68
+ // rather than inline content, so they can't contain `hardBreak` nodes. Keep
69
+ // newlines as text characters for them instead of splitting into hard breaks.
70
+ const parseHardBreaks =
71
+ !blockType || !isPlainContentNodeType(schema, schema.nodes[blockType]);
68
72
 
69
73
  if (!parseHardBreaks) {
70
74
  return styledText.text.length > 0
@@ -373,6 +373,9 @@ export function nodeToCustomInlineContent<
373
373
  inlineContentSchema,
374
374
  styleSchema,
375
375
  ) as any; // TODO: is this safe? could we have Links here that are undesired?
376
+ } else if (icConfig.content === "plain") {
377
+ // Plain inline content is a single unstyled string.
378
+ content = node.textContent as any;
376
379
  } else {
377
380
  content = undefined;
378
381
  }
package/src/api/pmUtil.ts CHANGED
@@ -54,18 +54,26 @@ export function getBlockCache(schema: Schema) {
54
54
  }
55
55
 
56
56
  /**
57
- * Whether `nodeType` is a BlockNote block whose content type is `"plain"` — i.e.
58
- * it holds unstyled text and only allows the non-formatting (`"annotation"`)
59
- * marks. Resolved semantically from the block schema (the source of truth),
60
- * reachable from `schema.cached.blockNoteEditor`.
57
+ * Whether `nodeType` is a BlockNote block or inline content whose content type
58
+ * is `"plain"` — i.e. it holds unstyled text and only allows the non-formatting
59
+ * (`"annotation"`) marks. Resolved semantically from the block / inline content
60
+ * schema (the source of truth), reachable from `schema.cached.blockNoteEditor`.
61
61
  *
62
- * Returns `false` for every non-block / structural node type (`doc`,
63
- * `blockGroup`, `text`, inline content, table sub-nodes), since those aren't
64
- * keys in the block schema.
62
+ * Returns `false` for every other node type (`doc`, `blockGroup`, `text`, table
63
+ * sub-nodes, and non-plain blocks / inline content), since those aren't plain
64
+ * content keys in either schema.
65
65
  */
66
66
  export function isPlainContentNodeType(
67
67
  schema: Schema,
68
68
  nodeType: NodeType,
69
69
  ): boolean {
70
- return getBlockSchema(schema)[nodeType.name]?.content === "plain";
70
+ if (getBlockSchema(schema)[nodeType.name]?.content === "plain") {
71
+ return true;
72
+ }
73
+
74
+ const inlineContentConfig = getInlineContentSchema(schema)[nodeType.name];
75
+ return (
76
+ typeof inlineContentConfig === "object" &&
77
+ inlineContentConfig.content === "plain"
78
+ );
71
79
  }