@blocknote/core 0.53.0 → 0.54.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 (197) 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-BEJW9OM_.js → blocks-CzQLehlc.js} +571 -568
  12. package/dist/blocks-CzQLehlc.js.map +1 -0
  13. package/dist/blocks-CzkqclGj.cjs +12 -0
  14. package/dist/blocks-CzkqclGj.cjs.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-CSB9ZvuL.cjs +58 -0
  26. package/dist/extensions-CSB9ZvuL.cjs.map +1 -0
  27. package/dist/{extensions-BR5hkAio.js → extensions-DGuhtOgB.js} +662 -427
  28. package/dist/extensions-DGuhtOgB.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-BkfZVfaO.js} +967 -899
  36. package/dist/src-BkfZVfaO.js.map +1 -0
  37. package/dist/src-DM3syMdf.cjs +23 -0
  38. package/dist/src-DM3syMdf.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 +59 -56
  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 +88 -76
  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/nodeConversions/blockToNode.ts +5 -1
  55. package/src/api/nodeConversions/nodeToBlock.ts +3 -0
  56. package/src/api/pmUtil.ts +16 -8
  57. package/src/blocks/Code/CodeBlockOptions.ts +83 -0
  58. package/src/blocks/Code/block.test.ts +1 -1
  59. package/src/blocks/Code/block.ts +29 -281
  60. package/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.ts +120 -0
  61. package/src/blocks/Code/helpers/parse/parsePreCode.ts +45 -0
  62. package/src/blocks/Code/helpers/render/createCodeBlock.ts +98 -0
  63. package/src/blocks/Code/helpers/toExternalHTML/createPreCode.ts +14 -0
  64. package/src/blocks/index.ts +3 -0
  65. package/src/comments/extension.ts +2 -4
  66. package/src/editor/Block.css +273 -2
  67. package/src/editor/BlockNoteEditor.ts +25 -4
  68. package/src/editor/BlockNoteExtension.ts +1 -1
  69. package/src/editor/managers/ExtensionManager/extensions.ts +6 -0
  70. package/src/exporter/ExportImage.ts +50 -0
  71. package/src/exporter/Exporter.test.ts +48 -0
  72. package/src/exporter/Exporter.ts +46 -12
  73. package/src/exporter/index.ts +1 -0
  74. package/src/exporter/mapping.ts +4 -1
  75. package/src/extensions/FormattingToolbar/FormattingToolbar.ts +10 -8
  76. package/src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.ts +109 -0
  77. package/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts +192 -0
  78. package/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.ts +142 -0
  79. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.ts +120 -0
  80. package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts +89 -0
  81. package/src/extensions/SyntaxHighlighting/inlineHighlight.test.ts +135 -0
  82. package/src/extensions/SyntaxHighlighting/shiki.ts +116 -0
  83. package/src/extensions/Versioning/inMemoryVersioning.ts +13 -3
  84. package/src/extensions/index.ts +4 -0
  85. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.ts +51 -2
  86. package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +22 -2
  87. package/src/i18n/locales/ar.ts +9 -0
  88. package/src/i18n/locales/de.ts +9 -0
  89. package/src/i18n/locales/en.ts +9 -0
  90. package/src/i18n/locales/es.ts +9 -0
  91. package/src/i18n/locales/fa.ts +9 -0
  92. package/src/i18n/locales/fr.ts +9 -0
  93. package/src/i18n/locales/he.ts +9 -0
  94. package/src/i18n/locales/hr.ts +9 -0
  95. package/src/i18n/locales/is.ts +9 -0
  96. package/src/i18n/locales/it.ts +9 -0
  97. package/src/i18n/locales/ja.ts +9 -0
  98. package/src/i18n/locales/ko.ts +9 -0
  99. package/src/i18n/locales/nl.ts +9 -0
  100. package/src/i18n/locales/no.ts +9 -0
  101. package/src/i18n/locales/pl.ts +9 -0
  102. package/src/i18n/locales/pt.ts +9 -0
  103. package/src/i18n/locales/ru.ts +9 -0
  104. package/src/i18n/locales/sk.ts +9 -0
  105. package/src/i18n/locales/uk.ts +9 -0
  106. package/src/i18n/locales/uz.ts +9 -0
  107. package/src/i18n/locales/vi.ts +9 -0
  108. package/src/i18n/locales/zh-tw.ts +9 -0
  109. package/src/i18n/locales/zh.ts +9 -0
  110. package/src/index.ts +5 -1
  111. package/src/schema/blocks/createSpec.ts +2 -3
  112. package/src/schema/blocks/types.ts +53 -3
  113. package/src/schema/contentTypePropagation.test.ts +1 -1
  114. package/src/schema/inlineContent/createSpec.test.ts +161 -0
  115. package/src/schema/inlineContent/createSpec.ts +171 -12
  116. package/src/schema/inlineContent/internal.ts +21 -2
  117. package/src/schema/inlineContent/types.ts +35 -5
  118. package/src/user/UserStore.ts +1 -1
  119. package/src/util/Store.test.ts +132 -0
  120. package/src/util/Store.ts +135 -0
  121. package/src/y/extensions/AttributionExtension.test.ts +10 -0
  122. package/src/y/extensions/Versioning.test.ts +20 -7
  123. package/src/yjs/comments/RESTYjsThreadStore.test.ts +85 -0
  124. package/src/yjs/comments/RESTYjsThreadStore.ts +7 -1
  125. package/src/yjs/extensions/ForkYDoc.test.ts +37 -0
  126. package/src/yjs/extensions/ForkYDoc.ts +26 -1
  127. package/src/yjs/extensions/RelativePositionMapping.ts +8 -2
  128. package/src/yjs/extensions/Versioning.test.ts +17 -5
  129. package/types/src/api/pmUtil.d.ts +7 -7
  130. package/types/src/blocks/Code/CodeBlockOptions.d.ts +61 -0
  131. package/types/src/blocks/Code/block.d.ts +3 -53
  132. package/types/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.d.ts +35 -0
  133. package/types/src/blocks/Code/helpers/parse/parsePreCode.d.ts +8 -0
  134. package/types/src/blocks/Code/helpers/render/createCodeBlock.d.ts +18 -0
  135. package/types/src/blocks/Code/helpers/toExternalHTML/createPreCode.d.ts +5 -0
  136. package/types/src/blocks/index.d.ts +3 -0
  137. package/types/src/comments/extension.d.ts +1 -15
  138. package/types/src/editor/BlockNoteEditor.d.ts +3 -3
  139. package/types/src/editor/BlockNoteExtension.d.ts +1 -1
  140. package/types/src/exporter/ExportImage.d.ts +36 -0
  141. package/types/src/exporter/Exporter.d.ts +21 -0
  142. package/types/src/exporter/Exporter.test.d.ts +1 -0
  143. package/types/src/exporter/index.d.ts +1 -0
  144. package/types/src/exporter/mapping.d.ts +1 -1
  145. package/types/src/extensions/FilePanel/FilePanel.d.ts +1 -1
  146. package/types/src/extensions/FormattingToolbar/FormattingToolbar.d.ts +1 -1
  147. package/types/src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.d.ts +5 -0
  148. package/types/src/extensions/ShowSelection/ShowSelection.d.ts +1 -5
  149. package/types/src/extensions/SideMenu/SideMenu.d.ts +1 -1
  150. package/types/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.d.ts +45 -0
  151. package/types/src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.d.ts +49 -0
  152. package/types/src/extensions/SuggestionMenu/SuggestionMenu.d.ts +1 -11
  153. package/types/src/extensions/SyntaxHighlighting/SyntaxHighlighting.d.ts +44 -0
  154. package/types/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.d.ts +1 -0
  155. package/types/src/extensions/SyntaxHighlighting/inlineHighlight.test.d.ts +1 -0
  156. package/types/src/extensions/SyntaxHighlighting/shiki.d.ts +13 -0
  157. package/types/src/extensions/TableHandles/TableHandles.d.ts +1 -1
  158. package/types/src/extensions/Versioning/Versioning.d.ts +1 -35
  159. package/types/src/extensions/index.d.ts +4 -0
  160. package/types/src/i18n/locales/en.d.ts +9 -0
  161. package/types/src/i18n/locales/fa.d.ts +9 -0
  162. package/types/src/i18n/locales/sk.d.ts +9 -0
  163. package/types/src/index.d.ts +2 -1
  164. package/types/src/schema/blocks/types.d.ts +36 -3
  165. package/types/src/schema/inlineContent/createSpec.d.ts +35 -3
  166. package/types/src/schema/inlineContent/createSpec.test.d.ts +1 -0
  167. package/types/src/schema/inlineContent/internal.d.ts +3 -2
  168. package/types/src/schema/inlineContent/types.d.ts +22 -3
  169. package/types/src/user/UserStore.d.ts +1 -1
  170. package/types/src/util/Store.d.ts +45 -0
  171. package/types/src/util/Store.test.d.ts +1 -0
  172. package/types/src/y/extensions/AttributionExtension.d.ts +1 -1
  173. package/types/src/y/extensions/DiffVersioningExtension.d.ts +1 -1
  174. package/types/src/y/extensions/ForkYDoc.d.ts +1 -5
  175. package/types/src/y/extensions/index.d.ts +2 -10
  176. package/types/src/yjs/comments/RESTYjsThreadStore.test.d.ts +1 -0
  177. package/types/src/yjs/extensions/ForkYDoc.d.ts +1 -5
  178. package/types/src/yjs/extensions/index.d.ts +1 -5
  179. package/dist/BlockNoteExtension-B_IEJHS8.js +0 -38
  180. package/dist/BlockNoteExtension-B_IEJHS8.js.map +0 -1
  181. package/dist/BlockNoteExtension-M0znTzxP.cjs +0 -2
  182. package/dist/BlockNoteExtension-M0znTzxP.cjs.map +0 -1
  183. package/dist/UserStore-QbbPFj0z.js.map +0 -1
  184. package/dist/blocks-BEJW9OM_.js.map +0 -1
  185. package/dist/blocks-BPmJglFo.cjs +0 -12
  186. package/dist/blocks-BPmJglFo.cjs.map +0 -1
  187. package/dist/en-C5Z4Ag9_.cjs +0 -2
  188. package/dist/en-C5Z4Ag9_.cjs.map +0 -1
  189. package/dist/en-CGKXfWma.js.map +0 -1
  190. package/dist/extensions-AitWbYdJ.cjs +0 -52
  191. package/dist/extensions-AitWbYdJ.cjs.map +0 -1
  192. package/dist/extensions-BR5hkAio.js.map +0 -1
  193. package/dist/src-BHPuOo7W.cjs +0 -21
  194. package/dist/src-BHPuOo7W.cjs.map +0 -1
  195. package/dist/src-BUXut68d.js.map +0 -1
  196. package/src/blocks/Code/shiki.ts +0 -73
  197. package/types/src/blocks/Code/shiki.d.ts +0 -4
@@ -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);
@@ -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
  }
@@ -0,0 +1,83 @@
1
+ import type { BlockNoteEditor } from "../../editor/BlockNoteEditor.js";
2
+ import type { BlockFromConfig } from "../../schema/index.js";
3
+
4
+ /**
5
+ * Renders a preview of a code block's content (e.g. rendered LaTeX). Takes the
6
+ * same parameters as a block's `render` function and returns the same type,
7
+ * minus `contentDOM` - as a preview never holds the block's editable content.
8
+ *
9
+ * A `renderPreview` function is only responsible for the preview itself. It has
10
+ * no opinion on when, where, or how the preview is displayed - that's up to the
11
+ * code block's `render` function.
12
+ */
13
+ export type CodeBlockPreview = (
14
+ block: BlockFromConfig<any, any, any>,
15
+ editor: BlockNoteEditor<any>,
16
+ ) => {
17
+ dom: HTMLElement | DocumentFragment;
18
+ error?: string | null;
19
+ };
20
+
21
+ export type CodeBlockOptions = {
22
+ /**
23
+ * Whether to indent lines with a tab when the user presses `Tab` in a code block.
24
+ *
25
+ * @default true
26
+ */
27
+ indentLineWithTab?: boolean;
28
+ /**
29
+ * The default language to use for code blocks.
30
+ *
31
+ * @default "text"
32
+ */
33
+ defaultLanguage?: string;
34
+ /**
35
+ * The languages that are supported in the editor.
36
+ *
37
+ * @example
38
+ * {
39
+ * javascript: {
40
+ * name: "JavaScript",
41
+ * aliases: ["js"],
42
+ * },
43
+ * typescript: {
44
+ * name: "TypeScript",
45
+ * aliases: ["ts"],
46
+ * },
47
+ * }
48
+ */
49
+ supportedLanguages?: Record<
50
+ string,
51
+ {
52
+ /**
53
+ * The display name of the language.
54
+ */
55
+ name: string;
56
+ /**
57
+ * Aliases for this language.
58
+ */
59
+ aliases?: string[];
60
+ /**
61
+ * Renders a preview of the result of the code (e.g. rendered LaTeX). When
62
+ * defined, the code block displays this preview instead of the raw source
63
+ * by default, and shows the editable source in a popup when selected.
64
+ */
65
+ createPreview?: CodeBlockPreview;
66
+ }
67
+ >;
68
+ };
69
+
70
+ export function getLanguageId(
71
+ options: CodeBlockOptions,
72
+ languageName: string,
73
+ ): string | undefined {
74
+ const normalizedLanguage = languageName.trim().toLowerCase();
75
+ return Object.entries(options.supportedLanguages ?? {}).find(
76
+ ([id, { aliases }]) => {
77
+ return (
78
+ id.toLowerCase() === normalizedLanguage ||
79
+ aliases?.some((alias) => alias.toLowerCase() === normalizedLanguage)
80
+ );
81
+ },
82
+ )?.[0];
83
+ }
@@ -8,7 +8,7 @@ import {
8
8
  } from "vite-plus/test";
9
9
  import { BlockNoteEditor } from "../../editor/BlockNoteEditor.js";
10
10
  import type { PartialBlock } from "../defaultBlocks.js";
11
- import { getLanguageId, type CodeBlockOptions } from "./block.js";
11
+ import { getLanguageId, type CodeBlockOptions } from "./CodeBlockOptions.js";
12
12
 
13
13
  /**
14
14
  * @vitest-environment jsdom
@@ -1,57 +1,14 @@
1
- import type { HighlighterGeneric } from "@shikijs/types";
2
- import { DOMParser } from "@tiptap/pm/model";
3
- import { createExtension } from "../../editor/BlockNoteExtension.js";
4
1
  import { createBlockConfig, createBlockSpec } from "../../schema/index.js";
5
- import { lazyShikiPlugin } from "./shiki.js";
2
+ import {
3
+ parsePreCode,
4
+ parsePreCodeContent,
5
+ } from "./helpers/parse/parsePreCode.js";
6
+ import { createPreCode } from "./helpers/toExternalHTML/createPreCode.js";
7
+ import { CodeKeyboardShortcutsExtension } from "./helpers/extensions/CodeKeyboardShortcutsExtension.js";
8
+ import { CodeBlockOptions } from "./CodeBlockOptions.js";
9
+ import { createCodeBlock } from "./helpers/render/createCodeBlock.js";
6
10
 
7
- export type CodeBlockOptions = {
8
- /**
9
- * Whether to indent lines with a tab when the user presses `Tab` in a code block.
10
- *
11
- * @default true
12
- */
13
- indentLineWithTab?: boolean;
14
- /**
15
- * The default language to use for code blocks.
16
- *
17
- * @default "text"
18
- */
19
- defaultLanguage?: string;
20
- /**
21
- * The languages that are supported in the editor.
22
- *
23
- * @example
24
- * {
25
- * javascript: {
26
- * name: "JavaScript",
27
- * aliases: ["js"],
28
- * },
29
- * typescript: {
30
- * name: "TypeScript",
31
- * aliases: ["ts"],
32
- * },
33
- * }
34
- */
35
- supportedLanguages?: Record<
36
- string,
37
- {
38
- /**
39
- * The display name of the language.
40
- */
41
- name: string;
42
- /**
43
- * Aliases for this language.
44
- */
45
- aliases?: string[];
46
- }
47
- >;
48
- /**
49
- * The highlighter to use for code blocks.
50
- */
51
- createHighlighter?: () => Promise<HighlighterGeneric<any, any>>;
52
- };
53
-
54
- export type CodeBlockConfig = ReturnType<typeof createCodeBlockConfig>;
11
+ const CODE_BLOCK_KEYBOARD_SHORTCUTS_KEY = "code-block-keyboard-shortcuts";
55
12
 
56
13
  export const createCodeBlockConfig = createBlockConfig(
57
14
  ({ defaultLanguage = "text" }: CodeBlockOptions) =>
@@ -66,6 +23,8 @@ export const createCodeBlockConfig = createBlockConfig(
66
23
  }) as const,
67
24
  );
68
25
 
26
+ export type CodeBlockConfig = ReturnType<typeof createCodeBlockConfig>;
27
+
69
28
  export const createCodeBlockSpec = createBlockSpec(
70
29
  createCodeBlockConfig,
71
30
  (options) => ({
@@ -73,236 +32,25 @@ export const createCodeBlockSpec = createBlockSpec(
73
32
  code: true,
74
33
  defining: true,
75
34
  isolating: false,
35
+ highlight: (block) => block.props.language,
76
36
  },
77
- parse: (e) => {
78
- if (e.tagName !== "PRE") {
79
- return undefined;
80
- }
81
-
82
- if (
83
- e.childElementCount !== 1 ||
84
- e.firstElementChild?.tagName !== "CODE"
85
- ) {
86
- return undefined;
87
- }
88
-
89
- const code = e.firstElementChild!;
90
- const language =
91
- code.getAttribute("data-language") ||
92
- code.className
93
- .split(" ")
94
- .find((name) => name.includes("language-"))
95
- ?.replace("language-", "");
96
-
97
- return { language };
98
- },
99
-
100
- parseContent: ({ el, schema }) => {
101
- const parser = DOMParser.fromSchema(schema);
102
- const code = el.firstElementChild!;
103
-
104
- return parser.parse(code, {
105
- preserveWhitespace: "full",
106
- topNode: schema.nodes["codeBlock"].create(),
107
- }).content;
108
- },
109
-
110
- render(block, editor) {
111
- const wrapper = document.createDocumentFragment();
112
- const pre = document.createElement("pre");
113
- const code = document.createElement("code");
114
- pre.appendChild(code);
115
-
116
- let removeSelectChangeListener = undefined;
117
-
118
- if (options.supportedLanguages) {
119
- const select = document.createElement("select");
120
-
121
- Object.entries(options.supportedLanguages ?? {}).forEach(
122
- ([id, { name }]) => {
123
- const option = document.createElement("option");
124
-
125
- option.value = id;
126
- option.text = name;
127
- select.appendChild(option);
128
- },
129
- );
130
- select.value =
131
- block.props.language || options.defaultLanguage || "text";
132
-
133
- if (editor.isEditable) {
134
- const handleLanguageChange = (event: Event) => {
135
- const language = (event.target as HTMLSelectElement).value;
136
-
137
- editor.updateBlock(block.id, { props: { language } });
138
- };
139
- select.addEventListener("change", handleLanguageChange);
140
- removeSelectChangeListener = () =>
141
- select.removeEventListener("change", handleLanguageChange);
142
- } else {
143
- select.disabled = true;
144
- }
145
-
146
- const selectWrapper = document.createElement("div");
147
- selectWrapper.contentEditable = "false";
148
-
149
- selectWrapper.appendChild(select);
150
- wrapper.appendChild(selectWrapper);
151
- }
152
- wrapper.appendChild(pre);
153
-
154
- return {
155
- dom: wrapper,
156
- contentDOM: code,
157
- destroy: () => {
158
- removeSelectChangeListener?.();
37
+ parse: (el) => parsePreCode(el),
38
+ parseContent: (opts) => parsePreCodeContent(opts, "codeBlock"),
39
+ render: (block, editor) =>
40
+ createCodeBlock(
41
+ block,
42
+ editor,
43
+ options.supportedLanguages && {
44
+ selectedLanguage: block.props.language,
45
+ supportedLanguages: options.supportedLanguages,
159
46
  },
160
- };
161
- },
162
- toExternalHTML(block) {
163
- const pre = document.createElement("pre");
164
- const code = document.createElement("code");
165
- code.className = `language-${block.props.language}`;
166
- code.dataset.language = block.props.language;
167
- pre.appendChild(code);
168
- return {
169
- dom: pre,
170
- contentDOM: code,
171
- };
172
- },
47
+ ),
48
+ toExternalHTML: (block) => createPreCode(block),
173
49
  }),
174
- (options) => {
175
- return [
176
- createExtension({
177
- key: "code-block-highlighter",
178
- prosemirrorPlugins: [lazyShikiPlugin(options)],
179
- }),
180
- createExtension({
181
- key: "code-block-keyboard-shortcuts",
182
- keyboardShortcuts: {
183
- Delete: ({ editor }) => {
184
- return editor.transact((tr) => {
185
- const { block } = editor.getTextCursorPosition();
186
- if (block.type !== "codeBlock") {
187
- return false;
188
- }
189
- const { $from } = tr.selection;
190
-
191
- // When inside empty codeblock, on `DELETE` key press, delete the codeblock
192
- if (!$from.parent.textContent) {
193
- editor.removeBlocks([block]);
194
-
195
- return true;
196
- }
197
-
198
- return false;
199
- });
200
- },
201
- Tab: ({ editor }) => {
202
- if (options.indentLineWithTab === false) {
203
- return false;
204
- }
205
-
206
- return editor.transact((tr) => {
207
- const { block } = editor.getTextCursorPosition();
208
- if (block.type === "codeBlock") {
209
- // TODO should probably only tab when at a line start or already tabbed in
210
- tr.insertText(" ");
211
- return true;
212
- }
213
-
214
- return false;
215
- });
216
- },
217
- Enter: ({ editor }) => {
218
- return editor.transact((tr) => {
219
- const { block, nextBlock } = editor.getTextCursorPosition();
220
- if (block.type !== "codeBlock") {
221
- return false;
222
- }
223
- const { $from } = tr.selection;
224
-
225
- const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
226
- const endsWithDoubleNewline =
227
- $from.parent.textContent.endsWith("\n\n");
228
-
229
- // The user is trying to exit the code block by pressing enter at the end of the code block
230
- if (isAtEnd && endsWithDoubleNewline) {
231
- // Remove the double newline
232
- tr.delete($from.pos - 2, $from.pos);
233
-
234
- // If there is a next block, move the cursor to it
235
- if (nextBlock) {
236
- editor.setTextCursorPosition(nextBlock, "start");
237
- return true;
238
- }
239
-
240
- // If there is no next block, insert a new paragraph
241
- const [newBlock] = editor.insertBlocks(
242
- [{ type: "paragraph" }],
243
- block,
244
- "after",
245
- );
246
- // Move the cursor to the new block
247
- editor.setTextCursorPosition(newBlock, "start");
248
-
249
- return true;
250
- }
251
-
252
- tr.insertText("\n");
253
- return true;
254
- });
255
- },
256
- "Shift-Enter": ({ editor }) => {
257
- return editor.transact(() => {
258
- const { block } = editor.getTextCursorPosition();
259
- if (block.type !== "codeBlock") {
260
- return false;
261
- }
262
-
263
- const [newBlock] = editor.insertBlocks(
264
- // insert a new paragraph
265
- [{ type: "paragraph" }],
266
- block,
267
- "after",
268
- );
269
- // move the cursor to the new block
270
- editor.setTextCursorPosition(newBlock, "start");
271
- return true;
272
- });
273
- },
274
- },
275
- inputRules: [
276
- {
277
- find: /^```(.*?)\s$/,
278
- replace: ({ match }) => {
279
- const languageName = match[1].trim();
280
- const attributes = {
281
- language: getLanguageId(options, languageName) ?? languageName,
282
- };
283
-
284
- return {
285
- type: "codeBlock",
286
- props: {
287
- language: attributes.language,
288
- },
289
- content: [],
290
- };
291
- },
292
- },
293
- ],
294
- }),
295
- ];
296
- },
50
+ (options) => [
51
+ CodeKeyboardShortcutsExtension(options)(
52
+ CODE_BLOCK_KEYBOARD_SHORTCUTS_KEY,
53
+ "codeBlock",
54
+ ),
55
+ ],
297
56
  );
298
-
299
- export function getLanguageId(
300
- options: CodeBlockOptions,
301
- languageName: string,
302
- ): string | undefined {
303
- return Object.entries(options.supportedLanguages ?? {}).find(
304
- ([id, { aliases }]) => {
305
- return aliases?.includes(languageName) || id === languageName;
306
- },
307
- )?.[0];
308
- }