@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
@@ -0,0 +1,132 @@
1
+ import { describe, expect, it, vi } from "vite-plus/test";
2
+ import { Store } from "./Store.js";
3
+
4
+ describe("Store", () => {
5
+ it("updates state from a value", () => {
6
+ const store = new Store({ count: 0 });
7
+
8
+ store.setState({ count: 1 });
9
+
10
+ expect(store.state).toEqual({ count: 1 });
11
+ });
12
+
13
+ it("updates state from an updater function", () => {
14
+ const store = new Store({ count: 0 });
15
+
16
+ store.setState((prev) => ({ count: prev.count + 1 }));
17
+
18
+ expect(store.state).toEqual({ count: 1 });
19
+ });
20
+
21
+ it("exposes the previous state after an update", () => {
22
+ const store = new Store({ count: 0 });
23
+
24
+ store.setState({ count: 1 });
25
+ expect(store.prevState).toEqual({ count: 0 });
26
+
27
+ store.setState({ count: 2 });
28
+ expect(store.prevState).toEqual({ count: 1 });
29
+ });
30
+
31
+ it("notifies listeners with the previous and current state", () => {
32
+ const store = new Store({ count: 0 });
33
+ const listener = vi.fn();
34
+ store.subscribe(listener);
35
+
36
+ store.setState({ count: 1 });
37
+
38
+ expect(listener).toHaveBeenCalledTimes(1);
39
+ expect(listener).toHaveBeenCalledWith({
40
+ prevVal: { count: 0 },
41
+ currentVal: { count: 1 },
42
+ });
43
+ });
44
+
45
+ it("stops notifying after unsubscribing", () => {
46
+ const store = new Store({ count: 0 });
47
+ const listener = vi.fn();
48
+ const unsubscribe = store.subscribe(listener);
49
+
50
+ store.setState({ count: 1 });
51
+ unsubscribe();
52
+ store.setState({ count: 2 });
53
+
54
+ expect(listener).toHaveBeenCalledTimes(1);
55
+ expect(store.state).toEqual({ count: 2 });
56
+ });
57
+
58
+ it("calls `onUpdate` after the write but before listeners", () => {
59
+ const calls: string[] = [];
60
+ const store: Store<{ count: number }> = new Store(
61
+ { count: 0 },
62
+ {
63
+ onUpdate() {
64
+ // The new state is already committed by the time `onUpdate` runs, which is
65
+ // what the comments & ShowSelection extensions rely on to dispatch a
66
+ // transaction reflecting it.
67
+ calls.push(`onUpdate:${store.state.count}`);
68
+ },
69
+ },
70
+ );
71
+ store.subscribe(() => calls.push("listener"));
72
+
73
+ store.setState({ count: 1 });
74
+
75
+ expect(calls).toEqual(["onUpdate:1", "listener"]);
76
+ });
77
+
78
+ it("passes the new and previous state to `onUpdate`", () => {
79
+ const onUpdate = vi.fn();
80
+ const store = new Store({ count: 0 }, { onUpdate });
81
+
82
+ store.setState({ count: 1 });
83
+
84
+ expect(onUpdate).toHaveBeenCalledWith({ count: 1 }, { count: 0 });
85
+ });
86
+
87
+ it("notifies once with the settled state when `onUpdate` writes back", () => {
88
+ const seen: Array<{ prev: number; curr: number }> = [];
89
+ let nested = false;
90
+ const store: Store<{ count: number }> = new Store(
91
+ { count: 0 },
92
+ {
93
+ onUpdate(state) {
94
+ // A callback that writes back to its own store — e.g. one dispatching a
95
+ // transaction that settles the state. The nested write must be coalesced
96
+ // into the in-progress flush rather than draining on its own.
97
+ if (!nested && state.count === 1) {
98
+ nested = true;
99
+ store.setState({ count: 2 });
100
+ }
101
+ },
102
+ },
103
+ );
104
+ store.subscribe(({ prevVal, currentVal }) =>
105
+ seen.push({ prev: prevVal.count, curr: currentVal.count }),
106
+ );
107
+
108
+ store.setState({ count: 1 });
109
+
110
+ expect(seen).toEqual([{ prev: 1, curr: 2 }]);
111
+ expect(store.state).toEqual({ count: 2 });
112
+ });
113
+
114
+ it("flattens re-entrant updates instead of recursing", () => {
115
+ const store = new Store({ count: 0 });
116
+ const seen: number[] = [];
117
+
118
+ store.subscribe(({ currentVal }) => {
119
+ seen.push(currentVal.count);
120
+ // A listener writing back to the store — e.g. one that dispatches a transaction
121
+ // which in turn updates state. This must terminate rather than recurse.
122
+ if (currentVal.count < 3) {
123
+ store.setState({ count: currentVal.count + 1 });
124
+ }
125
+ });
126
+
127
+ store.setState({ count: 1 });
128
+
129
+ expect(seen).toEqual([1, 2, 3]);
130
+ expect(store.state).toEqual({ count: 3 });
131
+ });
132
+ });
@@ -0,0 +1,135 @@
1
+ // Vendored from https://github.com/TanStack/store/blob/main/packages/store/src/store.ts (MIT)
2
+ //
3
+ // BlockNote only ever used `Store` — never the `Derived`/`Effect` reactive graph that
4
+ // makes up the rest of `@tanstack/store`, and that graph isn't tree-shakeable because
5
+ // `setState` reaches into the scheduler. Since the `Store` type is part of BlockNote's
6
+ // public API (every extension exposes one), owning these ~40 lines lets us keep that
7
+ // surface stable instead of tracking a 0.x dependency's breaking changes.
8
+ //
9
+ // Behaviour matches `@tanstack/store@0.7.7`, minus the dependency graph and the
10
+ // `updateFn`/`onSubscribe` options, which nothing used. `onUpdate` additionally receives
11
+ // the new and previous state rather than requiring callers to close over the store.
12
+
13
+ /**
14
+ * The value a {@link Listener} is called with when a {@link Store} updates.
15
+ */
16
+ export interface ListenerValue<T> {
17
+ readonly prevVal: T;
18
+ readonly currentVal: T;
19
+ }
20
+
21
+ /**
22
+ * A callback invoked when a {@link Store}'s state changes.
23
+ */
24
+ export type Listener<T> = (value: ListenerValue<T>) => void;
25
+
26
+ /**
27
+ * A new state, or a function deriving it from the previous state.
28
+ */
29
+ export type Updater<T> = T | ((prev: T) => T);
30
+
31
+ export interface StoreOptions<TState> {
32
+ /**
33
+ * Called after the state has been updated, before listeners are notified.
34
+ */
35
+ onUpdate?: (state: TState, prevState: TState) => void;
36
+ }
37
+
38
+ /**
39
+ * A minimal observable state container.
40
+ *
41
+ * Extensions expose one of these as their `store` so that both React (via
42
+ * `useExtensionState`) and vanilla consumers can read and subscribe to their state.
43
+ */
44
+ export class Store<TState> {
45
+ listeners = new Set<Listener<TState>>();
46
+ state: TState;
47
+ prevState: TState;
48
+ options?: StoreOptions<TState>;
49
+
50
+ constructor(initialState: TState, options?: StoreOptions<TState>) {
51
+ this.prevState = initialState;
52
+ this.state = initialState;
53
+ this.options = options;
54
+ }
55
+
56
+ subscribe = (listener: Listener<TState>) => {
57
+ this.listeners.add(listener);
58
+
59
+ return () => {
60
+ this.listeners.delete(listener);
61
+ };
62
+ };
63
+
64
+ /**
65
+ * Update the store state, either with a new state or a function deriving it from the
66
+ * previous one.
67
+ */
68
+ setState(updater: (prevState: TState) => TState): void;
69
+ setState(updater: TState): void;
70
+ setState(updater: Updater<TState>): void {
71
+ this.prevState = this.state;
72
+ this.state = isUpdaterFunction(updater) ? updater(this.prevState) : updater;
73
+
74
+ flush(this);
75
+ }
76
+
77
+ /**
78
+ * @internal Only to be called by {@link flush}.
79
+ */
80
+ _notify() {
81
+ const value: ListenerValue<TState> = {
82
+ prevVal: this.prevState,
83
+ currentVal: this.state,
84
+ };
85
+ for (const listener of this.listeners) {
86
+ listener(value);
87
+ }
88
+ }
89
+ }
90
+
91
+ function isUpdaterFunction<T>(updater: Updater<T>): updater is (prev: T) => T {
92
+ return typeof updater === "function";
93
+ }
94
+
95
+ // Both `onUpdate` and listener notification can synchronously trigger further `setState`
96
+ // calls — a callback that dispatches a ProseMirror transaction, for example. Rather than
97
+ // recursing, re-entrant writes are queued and drained by the outermost flush, so a write
98
+ // made during a callback still reaches every listener but the stack stays flat and
99
+ // subscribers see the settled state once.
100
+ //
101
+ // `onUpdate` therefore runs *inside* the flush transaction: the store is queued and the
102
+ // flush is marked in progress before the callback fires, so a nested write it makes is
103
+ // coalesced into this drain rather than starting its own.
104
+ let isFlushing = false;
105
+ const pendingUpdates = new Set<Store<any>>();
106
+
107
+ function flush(store: Store<any>) {
108
+ pendingUpdates.add(store);
109
+
110
+ const isOutermost = !isFlushing;
111
+ isFlushing = true;
112
+
113
+ try {
114
+ store.options?.onUpdate?.(store.state, store.prevState);
115
+
116
+ if (!isOutermost) {
117
+ return;
118
+ }
119
+
120
+ while (pendingUpdates.size > 0) {
121
+ const stores = Array.from(pendingUpdates);
122
+ pendingUpdates.clear();
123
+ for (const pendingStore of stores) {
124
+ pendingStore._notify();
125
+ }
126
+ }
127
+ } finally {
128
+ if (isOutermost) {
129
+ isFlushing = false;
130
+ // A throwing callback would otherwise strand queued stores, letting them notify
131
+ // during an unrelated store's next flush.
132
+ pendingUpdates.clear();
133
+ }
134
+ }
135
+ }
@@ -7,6 +7,12 @@ import { BlockNoteEditor } from "../../editor/BlockNoteEditor.js";
7
7
  import type { User } from "../../user/index.js";
8
8
  import { AttributionExtension } from "./AttributionExtension.js";
9
9
 
10
+ // Editors created during a test, destroyed in afterEach: an undestroyed
11
+ // EditorView leaves ProseMirror DOMObserver timers behind, which fire after
12
+ // the jsdom environment is torn down ("document is not defined" as an
13
+ // unhandled error - flaky, timing-dependent, mostly on slow CI).
14
+ const editors: BlockNoteEditor[] = [];
15
+
10
16
  // A `resolveUsers` spy plus an editor with the AttributionExtension registered.
11
17
  // No Yjs/collaboration needed — the extension's load plugin only cares that a
12
18
  // transaction adds a `y-attributed-*` mark, which we do directly below.
@@ -26,6 +32,7 @@ function createEditor() {
26
32
  extensions: [AttributionExtension({ resolveUsers })],
27
33
  });
28
34
  editor.mount(document.createElement("div"));
35
+ editors.push(editor);
29
36
 
30
37
  return { editor, resolveUsers };
31
38
  }
@@ -47,6 +54,9 @@ function addInsertMark(editor: BlockNoteEditor, userIds: string[]) {
47
54
 
48
55
  describe("AttributionExtension user loading", () => {
49
56
  afterEach(() => {
57
+ for (const editor of editors.splice(0)) {
58
+ editor._tiptapEditor.destroy();
59
+ }
50
60
  vi.restoreAllMocks();
51
61
  });
52
62
 
@@ -31,15 +31,26 @@ function createInMemoryYjsEndpoints(): VersioningEndpoints<Y.Type, Uint8Array> {
31
31
  >();
32
32
  const contents = new Map<string, Uint8Array>();
33
33
 
34
+ // `Date.now()` only has millisecond resolution, so snapshots created in quick
35
+ // succession (as they are in these tests) can share a timestamp, which leaves
36
+ // the newest-first ordering of `list()` ambiguous. Hand out strictly
37
+ // increasing timestamps so creation order is always recoverable.
38
+ let lastTimestamp = 0;
39
+ function nextTimestamp() {
40
+ lastTimestamp = Math.max(Date.now(), lastTimestamp + 1);
41
+ return lastTimestamp;
42
+ }
43
+
34
44
  return {
35
45
  list: async () =>
36
46
  [...snapshots.values()].sort((a, b) => b.createdAt - a.createdAt),
37
47
  create: async (fragment, options) => {
48
+ const now = nextTimestamp();
38
49
  const snapshot = {
39
50
  id: crypto.randomUUID(),
40
51
  name: options?.name,
41
- createdAt: Date.now(),
42
- updatedAt: Date.now(),
52
+ createdAt: now,
53
+ updatedAt: now,
43
54
  restoredFromSnapshotId: options?.restoredFromSnapshot?.id
44
55
  ? String(options.restoredFromSnapshot.id)
45
56
  : undefined,
@@ -57,11 +68,12 @@ function createInMemoryYjsEndpoints(): VersioningEndpoints<Y.Type, Uint8Array> {
57
68
  },
58
69
  restore: async (fragment, snapshot) => {
59
70
  // Create backup
71
+ const backupTimestamp = nextTimestamp();
60
72
  const backup = {
61
73
  id: crypto.randomUUID(),
62
74
  name: "Backup",
63
- createdAt: Date.now(),
64
- updatedAt: Date.now(),
75
+ createdAt: backupTimestamp,
76
+ updatedAt: backupTimestamp,
65
77
  };
66
78
  contents.set(backup.id, Y.encodeStateAsUpdateV2(fragment.doc!));
67
79
  snapshots.set(backup.id, backup);
@@ -70,11 +82,12 @@ function createInMemoryYjsEndpoints(): VersioningEndpoints<Y.Type, Uint8Array> {
70
82
  const tempDoc = new Y.Doc();
71
83
  Y.applyUpdateV2(tempDoc, snapshotContent);
72
84
 
85
+ const restoredTimestamp = nextTimestamp();
73
86
  const restored = {
74
87
  id: crypto.randomUUID(),
75
88
  name: "Restored Snapshot",
76
- createdAt: Date.now(),
77
- updatedAt: Date.now(),
89
+ createdAt: restoredTimestamp,
90
+ updatedAt: restoredTimestamp,
78
91
  restoredFromSnapshotId: String(snapshot.id),
79
92
  };
80
93
  contents.set(restored.id, Y.encodeStateAsUpdateV2(tempDoc));
@@ -89,7 +102,7 @@ function createInMemoryYjsEndpoints(): VersioningEndpoints<Y.Type, Uint8Array> {
89
102
  throw new Error(`Snapshot ${String(snapshot.id)} not found`);
90
103
  }
91
104
  s.name = name;
92
- s.updatedAt = Date.now();
105
+ s.updatedAt = nextTimestamp();
93
106
  },
94
107
  };
95
108
  }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * @vitest-environment jsdom
3
+ */
4
+ import {
5
+ relativePositionToAbsolutePosition,
6
+ ySyncPluginKey,
7
+ } from "y-prosemirror";
8
+ import { afterEach, describe, expect, it, vi } from "vite-plus/test";
9
+ import * as Y from "yjs";
10
+ import { BlockNoteEditor } from "../../editor/BlockNoteEditor.js";
11
+ import { DefaultThreadStoreAuth } from "../../comments/threadstore/DefaultThreadStoreAuth.js";
12
+ import { withCollaboration } from "../extensions/index.js";
13
+ import { RESTYjsThreadStore } from "./RESTYjsThreadStore.js";
14
+
15
+ function createCollabEditor() {
16
+ const doc = new Y.Doc();
17
+ const fragment = doc.getXmlFragment("doc");
18
+ const editor = BlockNoteEditor.create(
19
+ withCollaboration({
20
+ collaboration: {
21
+ fragment,
22
+ user: { name: "Test User", color: "#FF0000" },
23
+ provider: undefined,
24
+ },
25
+ trailingBlock: false,
26
+ }),
27
+ );
28
+ editor.mount(document.createElement("div"));
29
+ editor.replaceBlocks(editor.document, [
30
+ { type: "paragraph", content: "Hello World" },
31
+ ]);
32
+ return { editor, doc, fragment };
33
+ }
34
+
35
+ afterEach(() => {
36
+ vi.restoreAllMocks();
37
+ });
38
+
39
+ describe("RESTYjsThreadStore", () => {
40
+ it("sends resolvable yjs positions along with the thread", async () => {
41
+ const { editor, doc, fragment } = createCollabEditor();
42
+
43
+ const requests: any[] = [];
44
+ vi.spyOn(globalThis, "fetch").mockImplementation((async (
45
+ _url: any,
46
+ init: any,
47
+ ) => {
48
+ requests.push(JSON.parse(init.body));
49
+ return new Response("{}", {
50
+ status: 200,
51
+ headers: { "Content-Type": "application/json" },
52
+ });
53
+ }) as any);
54
+
55
+ const store = new RESTYjsThreadStore(
56
+ "https://example.com/threads",
57
+ {},
58
+ doc.getMap("threads"),
59
+ new DefaultThreadStoreAuth("user-1", "editor"),
60
+ );
61
+
62
+ await store.addThreadToDocument({
63
+ threadId: "thread-1",
64
+ selection: { anchor: 3, head: 8 },
65
+ editor,
66
+ });
67
+
68
+ expect(requests).toHaveLength(1);
69
+ const { yjs } = requests[0].selection;
70
+ expect(yjs).toBeDefined();
71
+
72
+ // the relative positions must resolve back to the positions we passed in
73
+ const state = ySyncPluginKey.getState(editor.prosemirrorState) as any;
74
+ const resolve = (relPos: any) =>
75
+ relativePositionToAbsolutePosition(
76
+ fragment.doc!,
77
+ state.binding.type,
78
+ Y.createRelativePositionFromJSON(relPos),
79
+ state.binding.mapping,
80
+ );
81
+
82
+ expect(resolve(yjs.anchor)).toBe(3);
83
+ expect(resolve(yjs.head)).toBe(8);
84
+ });
85
+ });
@@ -59,7 +59,13 @@ export class RESTYjsThreadStore extends YjsThreadStoreBase {
59
59
  }) => {
60
60
  const { threadId, selection } = options;
61
61
 
62
- const binding = ySyncPluginKey.getState(options.editor.prosemirrorState);
62
+ // Note: the positions have to be resolved against the *binding's* type and
63
+ // mapping. The plugin state has a `type` of its own, but no `mapping`, and
64
+ // its `type` can go stale (e.g. while the doc is forked, see
65
+ // `ForkYDocExtension`).
66
+ const binding = ySyncPluginKey.getState(
67
+ options.editor.prosemirrorState,
68
+ )?.binding;
63
69
  const yjsSelection = binding
64
70
  ? {
65
71
  head: absolutePositionToRelativePosition(
@@ -1,4 +1,5 @@
1
1
  import { afterEach, describe, expect, it } from "vite-plus/test";
2
+ import { trackPosition } from "../../api/positionMapping.js";
2
3
  import * as Y from "yjs";
3
4
  import { Awareness } from "y-protocols/awareness";
4
5
  import { BlockNoteEditor } from "../../index.js";
@@ -213,4 +214,40 @@ describe("ForkYDocExtension", () => {
213
214
  forkYDoc.merge({ keepChanges: true });
214
215
  expect(getEditorText(ctx.editor)).toContain("Forked modification");
215
216
  });
217
+
218
+ // https://github.com/TypeCellOS/BlockNote/issues/2946
219
+ it("can track positions while forked", () => {
220
+ ctx = createCollabEditor();
221
+ setEditorText(ctx.editor, "Hello World");
222
+
223
+ const forkYDoc = ctx.editor.getExtension(ForkYDocExtension)!;
224
+ forkYDoc.fork();
225
+
226
+ // Store position at "Hello| World"
227
+ const getCursorPos = trackPosition(ctx.editor, 8);
228
+ expect(getCursorPos()).toBe(8);
229
+
230
+ // Insert text at the beginning of "|Hello World"
231
+ ctx.editor._tiptapEditor.commands.insertContentAt(3, "Test ");
232
+ expect(getCursorPos()).toBe(13);
233
+ });
234
+
235
+ // https://github.com/TypeCellOS/BlockNote/issues/2946
236
+ it("can track positions across fork and merge", () => {
237
+ ctx = createCollabEditor();
238
+ setEditorText(ctx.editor, "Hello World");
239
+
240
+ // Store position at "Hello| World"
241
+ const getCursorPos = trackPosition(ctx.editor, 8);
242
+
243
+ const forkYDoc = ctx.editor.getExtension(ForkYDocExtension)!;
244
+ forkYDoc.fork();
245
+ expect(getCursorPos()).toBe(8);
246
+
247
+ ctx.editor._tiptapEditor.commands.insertContentAt(3, "Test ");
248
+ expect(getCursorPos()).toBe(13);
249
+
250
+ forkYDoc.merge({ keepChanges: true });
251
+ expect(getCursorPos()).toBe(13);
252
+ });
216
253
  });
@@ -1,5 +1,6 @@
1
- import { yUndoPluginKey } from "y-prosemirror";
1
+ import { ySyncPluginKey, yUndoPluginKey } from "y-prosemirror";
2
2
  import * as Y from "yjs";
3
+ import type { BlockNoteEditor } from "../../editor/BlockNoteEditor.js";
3
4
  import {
4
5
  createExtension,
5
6
  createStore,
@@ -11,6 +12,26 @@ import { YSyncExtension } from "./YSync.js";
11
12
  import { YUndoExtension } from "./YUndo.js";
12
13
  import { findTypeInOtherYdoc } from "../utils.js";
13
14
 
15
+ /**
16
+ * Point the `ySync` plugin state at `fragment`.
17
+ *
18
+ * Swapping the `ySync` plugin reconfigures the ProseMirror state, and
19
+ * ProseMirror carries over the state of plugins that share a key instead of
20
+ * re-initializing them. So the new plugin's `binding` (which is set from its
21
+ * view, via a transaction) ends up on the new fragment, while `type` and `doc`
22
+ * still point at the fragment the editor was bound to before. Anything reading
23
+ * those (e.g. `RelativePositionMappingExtension`) would then mix up the two
24
+ * Y.Docs, so we set them explicitly here.
25
+ */
26
+ function bindYSyncPluginStateTo(
27
+ editor: BlockNoteEditor<any, any, any>,
28
+ fragment: Y.XmlFragment,
29
+ ) {
30
+ editor.transact((tr) =>
31
+ tr.setMeta(ySyncPluginKey, { type: fragment, doc: fragment.doc }),
32
+ );
33
+ }
34
+
14
35
  export const ForkYDocExtension = createExtension(
15
36
  ({ editor, options }: ExtensionOptions<CollaborationOptions>) => {
16
37
  let forkedState:
@@ -84,6 +105,8 @@ export const ForkYDocExtension = createExtension(
84
105
  ],
85
106
  );
86
107
 
108
+ bindYSyncPluginStateTo(editor, forkedFragment);
109
+
87
110
  // Tell the store that the editor is now forked
88
111
  store.setState({ isForked: true });
89
112
  },
@@ -110,6 +133,8 @@ export const ForkYDocExtension = createExtension(
110
133
  ],
111
134
  );
112
135
 
136
+ bindYSyncPluginStateTo(editor, originalFragment);
137
+
113
138
  // Reset the undo stack to the original undo stack
114
139
  yUndoPluginKey.getState(
115
140
  editor.prosemirrorState,
@@ -51,9 +51,15 @@ export const RelativePositionMappingExtension = createExtension(
51
51
  const curYSyncPluginState = ySyncPluginKey.getState(
52
52
  editor.prosemirrorState,
53
53
  ) as typeof ySyncPluginState;
54
+ // Resolve against the doc that owns the currently bound type, and not
55
+ // against `curYSyncPluginState.doc`. Those can point at different
56
+ // Y.Docs (e.g. right after forking the doc, see `ForkYDocExtension`),
57
+ // in which case the resolved type wouldn't be part of the bound
58
+ // fragment and the position would be reported as "not found".
59
+ const boundType = curYSyncPluginState.binding.type;
54
60
  const pos = relativePositionToAbsolutePosition(
55
- curYSyncPluginState.doc,
56
- curYSyncPluginState.binding.type,
61
+ boundType.doc,
62
+ boundType,
57
63
  relativePosition,
58
64
  curYSyncPluginState.binding.mapping,
59
65
  );
@@ -304,15 +304,26 @@ function createInMemoryYjsEndpoints(): VersioningEndpoints<
304
304
  >();
305
305
  const contents = new Map<string, Uint8Array>();
306
306
 
307
+ // `Date.now()` only has millisecond resolution, so snapshots created in quick
308
+ // succession (as they are in these tests) can share a timestamp, which leaves
309
+ // the newest-first ordering of `list()` ambiguous. Hand out strictly
310
+ // increasing timestamps so creation order is always recoverable.
311
+ let lastTimestamp = 0;
312
+ function nextTimestamp() {
313
+ lastTimestamp = Math.max(Date.now(), lastTimestamp + 1);
314
+ return lastTimestamp;
315
+ }
316
+
307
317
  return {
308
318
  list: async () =>
309
319
  [...snapshots.values()].sort((a, b) => b.createdAt - a.createdAt),
310
320
  create: async (fragment, options) => {
321
+ const now = nextTimestamp();
311
322
  const snapshot = {
312
323
  id: crypto.randomUUID(),
313
324
  name: options?.name,
314
- createdAt: Date.now(),
315
- updatedAt: Date.now(),
325
+ createdAt: now,
326
+ updatedAt: now,
316
327
  restoredFromSnapshotId: options?.restoredFromSnapshot?.id
317
328
  ? String(options.restoredFromSnapshot.id)
318
329
  : undefined,
@@ -329,11 +340,12 @@ function createInMemoryYjsEndpoints(): VersioningEndpoints<
329
340
  return data;
330
341
  },
331
342
  restore: async (fragment, snapshot) => {
343
+ const backupTimestamp = nextTimestamp();
332
344
  const backup = {
333
345
  id: crypto.randomUUID(),
334
346
  name: "Backup",
335
- createdAt: Date.now(),
336
- updatedAt: Date.now(),
347
+ createdAt: backupTimestamp,
348
+ updatedAt: backupTimestamp,
337
349
  };
338
350
  contents.set(backup.id, Y.encodeStateAsUpdate(fragment.doc!));
339
351
  snapshots.set(backup.id, backup);
@@ -347,7 +359,7 @@ function createInMemoryYjsEndpoints(): VersioningEndpoints<
347
359
  throw new Error(`Snapshot ${String(snapshot.id)} not found`);
348
360
  }
349
361
  s.name = name;
350
- s.updatedAt = Date.now();
362
+ s.updatedAt = nextTimestamp();
351
363
  },
352
364
  };
353
365
  }
@@ -11,13 +11,13 @@ export declare function getInlineContentSchema<I extends InlineContentSchema>(sc
11
11
  export declare function getStyleSchema<S extends StyleSchema>(schema: Schema): S;
12
12
  export declare function getBlockCache(schema: Schema): import("../index.js").BlockCache<any, any, any>;
13
13
  /**
14
- * Whether `nodeType` is a BlockNote block whose content type is `"plain"` — i.e.
15
- * it holds unstyled text and only allows the non-formatting (`"annotation"`)
16
- * marks. Resolved semantically from the block schema (the source of truth),
17
- * reachable from `schema.cached.blockNoteEditor`.
14
+ * Whether `nodeType` is a BlockNote block or inline content whose content type
15
+ * is `"plain"` — i.e. it holds unstyled text and only allows the non-formatting
16
+ * (`"annotation"`) marks. Resolved semantically from the block / inline content
17
+ * schema (the source of truth), reachable from `schema.cached.blockNoteEditor`.
18
18
  *
19
- * Returns `false` for every non-block / structural node type (`doc`,
20
- * `blockGroup`, `text`, inline content, table sub-nodes), since those aren't
21
- * keys in the block schema.
19
+ * Returns `false` for every other node type (`doc`, `blockGroup`, `text`, table
20
+ * sub-nodes, and non-plain blocks / inline content), since those aren't plain
21
+ * content keys in either schema.
22
22
  */
23
23
  export declare function isPlainContentNodeType(schema: Schema, nodeType: NodeType): boolean;