@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
@@ -1,5 +1,7 @@
1
1
  import { BlockNoteSchema } from "../blocks/BlockNoteSchema.js";
2
2
  import { COLORS_DEFAULT } from "../editor/defaultColors.js";
3
+ import type { Dictionary } from "../i18n/dictionary.js";
4
+ import { en } from "../i18n/locales/index.js";
3
5
  import {
4
6
  BlockFromConfig,
5
7
  BlockSchema,
@@ -34,6 +36,20 @@ export type ExporterOptions = {
34
36
  * Colors to use for background of blocks, font colors, and highlight colors
35
37
  */
36
38
  colors: typeof COLORS_DEFAULT;
39
+ /**
40
+ * The strings an exporter renders into the produced document (file link
41
+ * texts, error placeholders). Accepts a locale from
42
+ * `@blocknote/core/locales` or an editor dictionary; block packages that
43
+ * ship their own exporter strings (e.g. math, diagram) read their sections
44
+ * from this same object, exactly as they do from an editor dictionary.
45
+ *
46
+ * @default the English strings
47
+ */
48
+ dictionary?: { exporter: Dictionary["exporter"] } & {
49
+ // Block packages read their own sections (e.g. `math`, `diagram`) from
50
+ // the same object; their types live with those packages.
51
+ [blockDictionary: string]: unknown;
52
+ };
37
53
  };
38
54
  export abstract class Exporter<
39
55
  B extends BlockSchema,
@@ -54,30 +70,66 @@ export abstract class Exporter<
54
70
  public readonly options: ExporterOptions,
55
71
  ) {}
56
72
 
73
+ /**
74
+ * The strings this exporter renders into the produced document - the
75
+ * `exporter` section of the configured dictionary (the `dictionary`
76
+ * option of {@link ExporterOptions}), or the English defaults.
77
+ */
78
+ public get dictionary(): Dictionary["exporter"] {
79
+ return this.options.dictionary?.exporter ?? en.exporter;
80
+ }
81
+
57
82
  public async resolveFile(url: string) {
58
83
  if (!this.options?.resolveFileUrl) {
59
- return (await fetch(url)).blob();
84
+ return this.fetchBlob(url);
60
85
  }
61
86
  const ret = await this.options.resolveFileUrl(url);
62
87
  if (ret instanceof Blob) {
63
88
  return ret;
64
89
  }
65
- return (await fetch(ret)).blob();
90
+ return this.fetchBlob(ret);
91
+ }
92
+
93
+ /**
94
+ * Fetch a URL as a Blob, throwing a clear error on a non-OK response. Without
95
+ * this an error page (404 / rate-limit / proxy failure) would be returned as
96
+ * the file's bytes and silently embedded as a corrupt image. An unreachable
97
+ * file is an environment failure, not expected input, so it fails the export
98
+ * loudly (see the error-handling conventions in AGENTS.md) rather than
99
+ * degrading the document silently.
100
+ */
101
+ private async fetchBlob(url: string): Promise<Blob> {
102
+ const res = await fetch(url);
103
+ if (!res.ok) {
104
+ throw new Error(
105
+ `Failed to fetch file "${url}": ${res.status} ${res.statusText}`,
106
+ );
107
+ }
108
+ return res.blob();
66
109
  }
67
110
 
68
111
  public mapStyles(styles: Styles<S>) {
69
112
  const stylesArray = Object.entries(styles).map(([key, value]) => {
70
- const mappedStyle = this.mappings.styleMapping[key](value, this);
113
+ const mapping = this.mappings.styleMapping[key];
114
+ if (!mapping) {
115
+ throw new Error(
116
+ `Exporter is missing a style mapping for style "${key}". If this style comes from a separate package, spread that package's exporter mappings into your styleMapping.`,
117
+ );
118
+ }
119
+ const mappedStyle = mapping(value, this);
71
120
  return mappedStyle;
72
121
  });
73
122
  return stylesArray;
74
123
  }
75
124
 
76
125
  public mapInlineContent(inlineContent: InlineContent<I, S>) {
77
- return this.mappings.inlineContentMapping[inlineContent.type](
78
- inlineContent,
79
- this,
80
- );
126
+ const mapping = this.mappings.inlineContentMapping[inlineContent.type];
127
+ if (!mapping) {
128
+ throw new Error(
129
+ `Exporter is missing an inline content mapping for inline content type "${inlineContent.type}". If this inline content comes from a separate package, spread that package's exporter mappings into your inlineContentMapping.`,
130
+ );
131
+ }
132
+ return mapping(inlineContent, this);
81
133
  }
82
134
 
83
135
  public transformInlineContent(inlineContentArray: InlineContent<I, S>[]) {
@@ -92,12 +144,12 @@ export abstract class Exporter<
92
144
  numberedListIndex: number,
93
145
  children?: Array<Awaited<RB>>,
94
146
  ) {
95
- return this.mappings.blockMapping[block.type](
96
- block,
97
- this,
98
- nestingLevel,
99
- numberedListIndex,
100
- children,
101
- );
147
+ const mapping = this.mappings.blockMapping[block.type];
148
+ if (!mapping) {
149
+ throw new Error(
150
+ `Exporter is missing a block mapping for block type "${block.type}". If this block comes from a separate package, spread that package's exporter mappings into your blockMapping.`,
151
+ );
152
+ }
153
+ return mapping(block, this, nestingLevel, numberedListIndex, children);
102
154
  }
103
155
  }
@@ -1,2 +1,3 @@
1
1
  export * from "./Exporter.js";
2
+ export * from "./ExportImage.js";
2
3
  export * from "./mapping.js";
@@ -42,7 +42,10 @@ export type InlineContentMapping<
42
42
  > = {
43
43
  [K in keyof I]: (
44
44
  inlineContent: InlineContentFromConfig<I[K], S>,
45
- exporter: Exporter<any, I, S, any, RI, any, TS>,
45
+ // Deliberately loose on the schema generics, like `BlockMapping` above -
46
+ // otherwise a mapping declared for one schema can't be reused (e.g.
47
+ // spread) in a mapping for a schema with different types.
48
+ exporter: Exporter<any, any, any, any, RI, any, TS>,
46
49
  ) => RI;
47
50
  };
48
51
 
@@ -24,18 +24,20 @@ export const FormattingToolbarExtension = createExtension(({ editor }) => {
24
24
  return false;
25
25
  }
26
26
 
27
- // Searches the content of the selection to see if it spans a node with a
28
- // code spec.
29
- let spansCode = false;
27
+ // Searches the content of the selection to see if it spans a node with
28
+ // `"plain"` content (mapped to a `"text*"` node spec), i.e. plain,
29
+ // unformattable text such as a code block. Blocks without inline content
30
+ // but that aren't plain (e.g. images) should still show the toolbar.
31
+ let spansPlainContent = false;
30
32
  tr.selection.content().content.descendants((node) => {
31
- if (node.type.spec.code) {
32
- spansCode = true;
33
+ if (node.type.spec.content === "text*") {
34
+ spansPlainContent = true;
33
35
  }
34
- return !spansCode; // keep descending if we haven't found a code block
36
+ return !spansPlainContent; // keep descending until we find plain content
35
37
  });
36
38
 
37
- // Don't show if the selection spans a code block.
38
- if (spansCode) {
39
+ // Don't show if the selection spans plain content.
40
+ if (spansPlainContent) {
39
41
  return false;
40
42
  }
41
43
 
@@ -0,0 +1,109 @@
1
+ import { Plugin, PluginKey, Selection, TextSelection } from "prosemirror-state";
2
+ import { createExtension } from "../../editor/BlockNoteExtension.js";
3
+
4
+ const PLUGIN_KEY = new PluginKey("inline-content-boundary-edit");
5
+
6
+ // Whether a Backspace/Delete at `selection` would remove the entire content
7
+ // range `[content.from, content.to)` of an inline content node.
8
+ function emptiesInlineContent(
9
+ selection: Selection,
10
+ key: string,
11
+ content: { from: number; to: number },
12
+ ) {
13
+ if (!selection.empty) {
14
+ return selection.from <= content.from && selection.to >= content.to;
15
+ }
16
+
17
+ const isSingleChar = content.to - content.from === 1;
18
+
19
+ return key === "Backspace"
20
+ ? isSingleChar && selection.from === content.to
21
+ : isSingleChar && selection.from === content.from;
22
+ }
23
+
24
+ // Fixes editing at the boundary of an empty custom inline content node (i.e. an
25
+ // inline node with editable content, like a mention or inline math).
26
+ //
27
+ // An empty inline node can't hold a text cursor, so ProseMirror can't reconcile
28
+ // edits across the empty boundary from the DOM: typing into an empty node
29
+ // inserts text next to it rather than inside, and deleting the last character
30
+ // leaves an un-reconcilable empty node that corrupts/freezes the editor. Both
31
+ // boundary edits are handled here via transactions so the caret stays inside
32
+ // the node, which is kept alive and editable in its empty state.
33
+ //
34
+ // The cursor is inside such a node exactly when its directly-enclosing node is
35
+ // inline (`inline: true` in the spec) - regular text blocks aren't inline, and
36
+ // atomic inline content can't hold a cursor - so the handling applies to any
37
+ // inline content type without needing to know it by name.
38
+ export const InlineContentBoundaryEditExtension = createExtension(
39
+ () =>
40
+ ({
41
+ key: "inlineContentBoundaryEdit",
42
+ prosemirrorPlugins: [
43
+ new Plugin({
44
+ key: PLUGIN_KEY,
45
+ props: {
46
+ handleKeyDown: (view, event) => {
47
+ if (!view.editable) {
48
+ return false;
49
+ }
50
+
51
+ const isTypedChar =
52
+ event.key.length === 1 && !event.ctrlKey && !event.metaKey;
53
+
54
+ if (
55
+ !isTypedChar &&
56
+ event.key !== "Backspace" &&
57
+ event.key !== "Delete"
58
+ ) {
59
+ return false;
60
+ }
61
+
62
+ const { selection } = view.state;
63
+ const node = selection.$from.node();
64
+ if (!node.type.spec.inline) {
65
+ return false;
66
+ }
67
+
68
+ const pos = selection.$from.before();
69
+ const contentFrom = pos + 1;
70
+ const contentTo = pos + 1 + node.content.size;
71
+
72
+ // Empty content: redirect the typed character into the node.
73
+ if (isTypedChar && node.content.size === 0) {
74
+ const tr = view.state.tr.insert(
75
+ contentFrom,
76
+ view.state.schema.text(event.key),
77
+ );
78
+ tr.setSelection(
79
+ TextSelection.create(tr.doc, contentFrom + event.key.length),
80
+ );
81
+ view.dispatch(tr);
82
+
83
+ return true;
84
+ }
85
+
86
+ // Backspace/Delete that would empty the content: delete it all in
87
+ // one transaction, keeping the now-empty node (and the caret
88
+ // inside it) so it stays editable.
89
+ if (
90
+ node.content.size > 0 &&
91
+ emptiesInlineContent(selection, event.key, {
92
+ from: contentFrom,
93
+ to: contentTo,
94
+ })
95
+ ) {
96
+ const tr = view.state.tr.delete(contentFrom, contentTo);
97
+ tr.setSelection(TextSelection.create(tr.doc, contentFrom));
98
+ view.dispatch(tr);
99
+
100
+ return true;
101
+ }
102
+
103
+ return false;
104
+ },
105
+ },
106
+ }),
107
+ ],
108
+ }) as const,
109
+ );
@@ -96,4 +96,25 @@ describe("PreviousBlockType: scoped traversal", () => {
96
96
  ).length;
97
97
  expect(trackedBlockCount).toBeLessThan(10);
98
98
  });
99
+
100
+ it("detects attribute-only changes (heading level) that emit an AttrStep", () => {
101
+ const editor = createEditorWithBlocks(100, "heading");
102
+
103
+ // Changing only a heading's level (type stays "heading") emits an AttrStep,
104
+ // whose StepMap is empty — so ProseMirror's changedRange() returns null and
105
+ // the change would be missed unless the scoped range also covers AttrSteps.
106
+ const firstBlock = editor.document[0];
107
+ editor.updateBlock(firstBlock, { props: { level: 2 } } as any);
108
+
109
+ const state = getPreviousBlockTypePluginState(editor);
110
+
111
+ expect(state.updatedBlocks.size).toBe(1);
112
+ expect(state.updatedBlocks.has(firstBlock.id)).toBe(true);
113
+
114
+ // Still scoped to the changed range, not all 100 blocks.
115
+ const trackedBlockCount = Object.keys(
116
+ state.currentTransactionOldBlockAttrs,
117
+ ).length;
118
+ expect(trackedBlockCount).toBeLessThan(10);
119
+ });
99
120
  });
@@ -2,6 +2,7 @@ import { findChildrenInRange } from "@tiptap/core";
2
2
  import { Plugin, PluginKey } from "prosemirror-state";
3
3
  import { Decoration, DecorationSet } from "prosemirror-view";
4
4
  import { getNodeId } from "../../api/getBlockInfoFromPos.js";
5
+ import { getChangedRange } from "../../api/getChangedRange.js";
5
6
  import { createExtension } from "../../editor/BlockNoteExtension.js";
6
7
 
7
8
  const PLUGIN_KEY = new PluginKey(`previous-blocks`);
@@ -72,9 +73,10 @@ export const PreviousBlockTypeExtension = createExtension(() => {
72
73
  return prev;
73
74
  }
74
75
 
75
- // Only check nodes affected by the transaction, not the entire document.
76
- // changedRange() is O(steps) unlike tiptap's getChangedRanges which is O(steps²).
77
- const newRange = transaction.changedRange();
76
+ // Only check nodes in the changed range, not the whole document.
77
+ // getChangedRange() also covers attribute-only steps (AttrStep), so a
78
+ // block whose `level`/`index` changes with no content edit is caught.
79
+ const newRange = getChangedRange(transaction);
78
80
  if (!newRange) {
79
81
  return prev;
80
82
  }
@@ -0,0 +1,192 @@
1
+ import { TextSelection } from "prosemirror-state";
2
+
3
+ import type { BlockNoteEditor } from "../../editor/BlockNoteEditor";
4
+ import {
5
+ createExtension,
6
+ createStore,
7
+ } from "../../editor/BlockNoteExtension.js";
8
+ import { Block } from "../../blocks/index.js";
9
+
10
+ /**
11
+ * A single editor-wide extension that drives the source popup for blocks that
12
+ * render a preview. Which blocks it activates on is decided by each spec's
13
+ * `meta.hasPreview` flag, so individual blocks opt in rather than the extension
14
+ * being configured with a block type.
15
+ *
16
+ * The extension is registered once (it's a default extension) and is a no-op
17
+ * when no block declares `meta.hasPreview`.
18
+ */
19
+ export const SourceBlockWithPreviewExtension = createExtension(
20
+ ({ editor }: { editor: BlockNoteEditor<any> }) => {
21
+ const store = createStore<{
22
+ popupOpen: string | undefined;
23
+ selected: string | undefined;
24
+ }>({
25
+ popupOpen: undefined,
26
+ selected: undefined,
27
+ });
28
+
29
+ // A block has a preview iff its spec's implementation declares
30
+ // `meta.hasPreview` (read from the spec, like the syntax-highlighting
31
+ // extension reads `meta.highlight`).
32
+ const blockHasPreview = (block: Block<any, any, any>) =>
33
+ !!editor.schema.blockSpecs[block.type]?.implementation?.meta?.hasPreview;
34
+
35
+ const handleArrow =
36
+ (direction: "prev" | "next") =>
37
+ ({ editor }: { editor: BlockNoteEditor<any> }) => {
38
+ const { block, prevBlock, nextBlock } = editor.getTextCursorPosition();
39
+ if (!blockHasPreview(block) || store.state.popupOpen === block.id) {
40
+ return false;
41
+ }
42
+
43
+ const targetBlock = direction === "prev" ? prevBlock : nextBlock;
44
+ if (!targetBlock) {
45
+ return false;
46
+ }
47
+
48
+ editor.setTextCursorPosition(
49
+ targetBlock.id,
50
+ direction === "prev" ? "end" : "start",
51
+ );
52
+
53
+ return true;
54
+ };
55
+
56
+ return {
57
+ key: "sourceBlockWithPreview",
58
+ store,
59
+ keyboardShortcuts: {
60
+ // Toggles the popup. This may be overridden by `hardBreakShortcut`.
61
+ Enter: ({ editor }) => {
62
+ const { block } = editor.getTextCursorPosition();
63
+ if (!blockHasPreview(block)) {
64
+ return false;
65
+ }
66
+
67
+ if (
68
+ store.state.popupOpen === block.id &&
69
+ editor.schema.blockSpecs[block.type]?.implementation?.meta
70
+ ?.hardBreakShortcut === "enter"
71
+ ) {
72
+ const view = editor.prosemirrorView!;
73
+ view.dispatch(view.state.tr.insertText("\n"));
74
+
75
+ return true;
76
+ }
77
+
78
+ editor.setTextCursorPosition(block.id, "end");
79
+ store.setState((state) => ({
80
+ ...state,
81
+ popupOpen:
82
+ store.state.popupOpen === block.id ? undefined : block.id,
83
+ }));
84
+
85
+ return true;
86
+ },
87
+ // Closes the popup.
88
+ Escape: ({ editor }) => {
89
+ const { block } = editor.getTextCursorPosition();
90
+ if (!blockHasPreview(block) || store.state.popupOpen !== block.id) {
91
+ return false;
92
+ }
93
+
94
+ editor.setTextCursorPosition(block.id, "end");
95
+
96
+ store.setState((state) => ({ ...state, popupOpen: undefined }));
97
+
98
+ return true;
99
+ },
100
+ // While the popup is open, selects the whole source instead of the
101
+ // whole document.
102
+ "Mod-a": ({ editor }) => {
103
+ const { block } = editor.getTextCursorPosition();
104
+ if (!blockHasPreview(block) || store.state.popupOpen !== block.id) {
105
+ return false;
106
+ }
107
+
108
+ const view = editor.prosemirrorView!;
109
+ const { $from } = view.state.selection;
110
+ if ($from.parent.type.name !== block.type) {
111
+ return false;
112
+ }
113
+
114
+ view.dispatch(
115
+ view.state.tr.setSelection(
116
+ TextSelection.create(view.state.doc, $from.start(), $from.end()),
117
+ ),
118
+ );
119
+
120
+ return true;
121
+ },
122
+ // While the popup is closed, moves the selection straight to the previous/next block
123
+ // instead of into the (hidden) source.
124
+ ArrowUp: handleArrow("prev"),
125
+ ArrowLeft: handleArrow("prev"),
126
+ ArrowDown: handleArrow("next"),
127
+ ArrowRight: handleArrow("next"),
128
+ },
129
+ mount: ({ dom, signal }) => {
130
+ // Closes the popup when the selection leaves the block that owns it and tracks which block
131
+ // the selection is in.
132
+ const unsubscribeSelectionChange = editor.onSelectionChange(() => {
133
+ const { block } = editor.getTextCursorPosition();
134
+
135
+ const selected = blockHasPreview(block) ? block.id : undefined;
136
+ const popupOpen =
137
+ store.state.popupOpen && store.state.popupOpen !== block.id
138
+ ? undefined
139
+ : store.state.popupOpen;
140
+
141
+ if (
142
+ selected === store.state.selected &&
143
+ popupOpen === store.state.popupOpen
144
+ ) {
145
+ return;
146
+ }
147
+
148
+ store.setState((state) => ({ ...state, selected, popupOpen }));
149
+ });
150
+ signal.addEventListener("abort", unsubscribeSelectionChange);
151
+
152
+ // While the popup is closed, prevents editing of the (hidden) source. Handled here rather
153
+ // than in `keyboardShortcuts` as it needs to match any text-input key, which a keymap
154
+ // can't express.
155
+ const handleKeyDown = (event: KeyboardEvent) => {
156
+ if (!editor.isEditable) {
157
+ return;
158
+ }
159
+
160
+ const { block } = editor.getTextCursorPosition();
161
+ if (!blockHasPreview(block) || store.state.popupOpen === block.id) {
162
+ return;
163
+ }
164
+
165
+ if (event.key === "Backspace" || event.key === "Delete") {
166
+ event.preventDefault();
167
+ event.stopImmediatePropagation();
168
+ editor.removeBlocks([block.id]);
169
+
170
+ return;
171
+ }
172
+
173
+ if (
174
+ (event.key.length === 1 && !event.ctrlKey && !event.metaKey) ||
175
+ event.key === "Tab"
176
+ ) {
177
+ event.preventDefault();
178
+ event.stopImmediatePropagation();
179
+ }
180
+ };
181
+ dom.addEventListener("keydown", handleKeyDown, {
182
+ capture: true,
183
+ signal,
184
+ });
185
+
186
+ const handleBlur = () =>
187
+ store.setState((state) => ({ ...state, popupOpen: undefined }));
188
+ dom.addEventListener("blur", handleBlur, { capture: true, signal });
189
+ },
190
+ };
191
+ },
192
+ );
@@ -0,0 +1,142 @@
1
+ import { Selection, TextSelection } from "prosemirror-state";
2
+
3
+ import type { BlockNoteEditor } from "../../editor/BlockNoteEditor";
4
+ import {
5
+ createExtension,
6
+ createStore,
7
+ } from "../../editor/BlockNoteExtension.js";
8
+
9
+ /**
10
+ * Inline-content counterpart of {@link SourceBlockWithPreviewExtension}. A
11
+ * single editor-wide extension that drives the source popup for inline content
12
+ * that renders a preview. Which inline content it activates on is decided by
13
+ * each spec's `meta.hasPreview` flag, so individual inline content opts in
14
+ * rather than the extension being configured with a type.
15
+ *
16
+ * Unlike the block version, the popup isn't toggled with a separate state flag:
17
+ * it's open exactly when the selection is inside the inline content's source.
18
+ * The store therefore only tracks which inline content (by its position) holds
19
+ * the selection - moving the selection in opens its popup, moving it out closes
20
+ * it. Since the source popup is always laid out (just hidden via opacity), the
21
+ * cursor can navigate into and out of it with the arrow keys as usual.
22
+ *
23
+ * The extension is registered once (it's a default extension) and is a no-op
24
+ * when no inline content declares `meta.hasPreview`.
25
+ */
26
+ export const SourceInlineContentWithPreviewExtension = createExtension(
27
+ ({ editor }: { editor: BlockNoteEditor<any, any, any> }) => {
28
+ const store = createStore<{
29
+ selected: number | undefined;
30
+ }>({
31
+ selected: undefined,
32
+ });
33
+
34
+ // Inline content has a preview iff its spec's implementation declares
35
+ // `meta.hasPreview`.
36
+ const nodeHasPreview = (nodeName: string) =>
37
+ !!editor.schema.inlineContentSpecs[nodeName]?.implementation?.meta
38
+ ?.hasPreview;
39
+
40
+ // Moves the selection out of the inline content, to just `"before"` or
41
+ // `"after"` it, which closes the popup via the selection-change handler
42
+ // below. Lets the keyboard commit-and-exit the source the same way arrowing
43
+ // past its edge does, keeps Enter from splitting the block while editing the
44
+ // source, and lets the up/down arrows step out of the source rather than
45
+ // staying trapped inside it.
46
+ const moveSelectionOut =
47
+ (direction: "before" | "after") =>
48
+ ({ editor }: { editor: BlockNoteEditor<any, any, any> }) => {
49
+ const { $from } = editor.prosemirrorState.selection;
50
+ const node = $from.node();
51
+ if (!nodeHasPreview(node.type.name)) {
52
+ return false;
53
+ }
54
+
55
+ const view = editor.prosemirrorView!;
56
+ const selection = Selection.near(
57
+ view.state.doc.resolve(
58
+ direction === "before" ? $from.before() : $from.after(),
59
+ ),
60
+ direction === "before" ? -1 : 1,
61
+ );
62
+ view.dispatch(view.state.tr.setSelection(selection));
63
+
64
+ return true;
65
+ };
66
+
67
+ return {
68
+ key: "sourceInlineContentWithPreview",
69
+ store,
70
+ keyboardShortcuts: {
71
+ Enter: moveSelectionOut("after"),
72
+ "Shift-Enter": moveSelectionOut("after"),
73
+ Escape: moveSelectionOut("after"),
74
+ ArrowUp: moveSelectionOut("before"),
75
+ ArrowDown: moveSelectionOut("after"),
76
+ // While editing the source, selects the whole source instead of the
77
+ // whole document.
78
+ "Mod-a": ({ editor }) => {
79
+ const { $from } = editor.prosemirrorState.selection;
80
+ if (!nodeHasPreview($from.node().type.name)) {
81
+ return false;
82
+ }
83
+
84
+ const view = editor.prosemirrorView!;
85
+ view.dispatch(
86
+ view.state.tr.setSelection(
87
+ TextSelection.create(view.state.doc, $from.start(), $from.end()),
88
+ ),
89
+ );
90
+
91
+ return true;
92
+ },
93
+ },
94
+ mount: ({ dom, signal }) => {
95
+ // The popup is open exactly when the selection is inside the inline
96
+ // content, so we just track which inline content (if any) holds it.
97
+ const unsubscribeSelectionChange = editor.onSelectionChange(() => {
98
+ const { $from } = editor.prosemirrorState.selection;
99
+ const node = $from.node();
100
+
101
+ store.setState({
102
+ selected: nodeHasPreview(node.type.name)
103
+ ? $from.before()
104
+ : undefined,
105
+ });
106
+ });
107
+ signal.addEventListener("abort", unsubscribeSelectionChange);
108
+
109
+ // Sets `visibility: hidden` on the popup for a single frame when pressing up/down arrow
110
+ // keys. The popup is normally hidden through `opacity: 0`, which means it's still visible
111
+ // to the browser for navigation. Therefore, the up/down arrows can sometimes move the
112
+ // selection into the popup from unexpected positions, such as on the same line. Setting
113
+ // `visibility: hidden` makes the browser ignore it when determining the new selection.
114
+ // TODO: This is hacky, we should find a cleaner solution.
115
+ const handleVerticalArrow = (event: KeyboardEvent) => {
116
+ if (event.key !== "ArrowUp" && event.key !== "ArrowDown") {
117
+ return;
118
+ }
119
+
120
+ // When the selection is already inside a source, leave navigation
121
+ // (moving within or out of it) to the browser as usual.
122
+ const { $from } = editor.prosemirrorState.selection;
123
+ if (nodeHasPreview($from.node().type.name)) {
124
+ return;
125
+ }
126
+
127
+ dom.classList.add("bn-suppress-source-popup-caret");
128
+ requestAnimationFrame(() =>
129
+ dom.classList.remove("bn-suppress-source-popup-caret"),
130
+ );
131
+ };
132
+ dom.addEventListener("keydown", handleVerticalArrow, {
133
+ capture: true,
134
+ signal,
135
+ });
136
+
137
+ const handleBlur = () => store.setState({ selected: undefined });
138
+ dom.addEventListener("blur", handleBlur, { capture: true, signal });
139
+ },
140
+ };
141
+ },
142
+ );