forked from TypeCellOS/BlockNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockNoteEditor.ts
More file actions
1330 lines (1206 loc) · 42.2 KB
/
Copy pathBlockNoteEditor.ts
File metadata and controls
1330 lines (1206 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
createDocument,
EditorOptions,
FocusPosition,
getSchema,
Editor as TiptapEditor,
} from "@tiptap/core";
import { type Command, type Plugin, type Transaction } from "@tiptap/pm/state";
import { Node, Schema } from "prosemirror-model";
import type { BlocksChanged } from "../api/getBlocksChangedByTransaction.js";
import { blockToNode } from "../api/nodeConversions/blockToNode.js";
import {
Block,
BlockNoteSchema,
DefaultBlockSchema,
DefaultInlineContentSchema,
DefaultStyleSchema,
PartialBlock,
} from "../blocks/index.js";
import type { CollaborationOptions } from "../extensions/Collaboration/Collaboration.js";
import { BlockChangeExtension } from "../extensions/index.js";
import { UniqueID } from "../extensions/tiptap-extensions/UniqueID/UniqueID.js";
import type { Dictionary } from "../i18n/dictionary.js";
import { en } from "../i18n/locales/index.js";
import type {
BlockIdentifier,
BlockNoteDOMAttributes,
BlockSchema,
BlockSpecs,
CustomBlockNoteSchema,
InlineContentSchema,
InlineContentSpecs,
PartialInlineContent,
Styles,
StyleSchema,
StyleSpecs,
} from "../schema/index.js";
import "../style.css";
import { mergeCSSClasses } from "../util/browser.js";
import { EventEmitter } from "../util/EventEmitter.js";
import type { NoInfer } from "../util/typescript.js";
import { ExtensionFactoryInstance } from "./BlockNoteExtension.js";
import type { TextCursorPosition } from "./cursorPositionTypes.js";
import {
BlockManager,
EventManager,
ExportManager,
ExtensionManager,
SelectionManager,
StateManager,
StyleManager,
} from "./managers/index.js";
import type { Selection } from "./selectionTypes.js";
import { transformPasted } from "./transformPasted.js";
export type BlockCache<
BSchema extends BlockSchema = any,
ISchema extends InlineContentSchema = any,
SSchema extends StyleSchema = any,
> = WeakMap<Node, Block<BSchema, ISchema, SSchema>>;
export interface BlockNoteEditorOptions<
BSchema extends BlockSchema,
ISchema extends InlineContentSchema,
SSchema extends StyleSchema,
> {
/**
* Whether changes to blocks (like indentation, creating lists, changing headings) should be animated or not. Defaults to `true`.
*
* @default true
*/
animations?: boolean;
/**
* Whether the editor should be focused automatically when it's created.
*
* @default false
*/
autofocus?: FocusPosition;
/**
* When enabled, allows for collaboration between multiple users.
* See [Real-time Collaboration](https://www.blocknotejs.org/docs/advanced/real-time-collaboration) for more info.
*/
collaboration?: CollaborationOptions;
/**
* Use default BlockNote font and reset the styles of <p> <li> <h1> elements etc., that are used in BlockNote.
*
* @default true
*/
defaultStyles?: boolean;
/**
* A dictionary object containing translations for the editor.
*
* See [Localization / i18n](https://www.blocknotejs.org/docs/advanced/localization) for more info.
*
* @remarks `Dictionary` is a type that contains all the translations for the editor.
*/
dictionary?: Dictionary & Record<string, any>;
/**
* Disable internal extensions (based on keys / extension name)
*
* @note Advanced
*/
disableExtensions?: string[];
/**
* An object containing attributes that should be added to HTML elements of the editor.
*
* See [Adding DOM Attributes](https://www.blocknotejs.org/docs/theming#adding-dom-attributes) for more info.
*
* @example { editor: { class: "my-editor-class" } }
* @remarks `Record<string, Record<string, string>>`
*/
domAttributes?: Partial<BlockNoteDOMAttributes>;
/**
* A replacement indicator to use when dragging and dropping blocks. Uses the [ProseMirror drop cursor](https://github.com/ProseMirror/prosemirror-dropcursor), or a modified version when [Column Blocks](https://www.blocknotejs.org/docs/document-structure#column-blocks) are enabled.
* @remarks `() => Plugin`
*/
dropCursor?: (opts: {
editor: BlockNoteEditor<
NoInfer<BSchema>,
NoInfer<ISchema>,
NoInfer<SSchema>
>;
color?: string | false;
width?: number;
class?: string;
}) => Plugin;
/**
* The content that should be in the editor when it's created, represented as an array of {@link PartialBlock} objects.
*
* See [Partial Blocks](https://www.blocknotejs.org/docs/editor-api/manipulating-blocks#partial-blocks) for more info.
*
* @remarks `PartialBlock[]`
*/
initialContent?: PartialBlock<
NoInfer<BSchema>,
NoInfer<ISchema>,
NoInfer<SSchema>
>[];
/**
* @deprecated, provide placeholders via dictionary instead
* @internal
*/
placeholders?: Record<
string | "default" | "emptyDocument",
string | undefined
>;
/**
* Custom paste handler that can be used to override the default paste behavior.
*
* See [Paste Handling](https://www.blocknotejs.org/docs/advanced/paste-handling) for more info.
*
* @remarks `PasteHandler`
* @returns The function should return `true` if the paste event was handled, otherwise it should return `false` if it should be canceled or `undefined` if it should be handled by another handler.
*
* @example
* ```ts
* pasteHandler: ({ defaultPasteHandler }) => {
* return defaultPasteHandler({ pasteBehavior: "prefer-html" });
* }
* ```
*/
pasteHandler?: (context: {
event: ClipboardEvent;
editor: BlockNoteEditor<
NoInfer<BSchema>,
NoInfer<ISchema>,
NoInfer<SSchema>
>;
/**
* The default paste handler
* @param context The context object
* @returns Whether the paste event was handled or not
*/
defaultPasteHandler: (context?: {
/**
* Whether to prioritize Markdown content in `text/plain` over `text/html` when pasting from the clipboard.
* @default true
*/
prioritizeMarkdownOverHTML?: boolean;
/**
* Whether to parse `text/plain` content from the clipboard as Markdown content.
* @default true
*/
plainTextAsMarkdown?: boolean;
}) => boolean | undefined;
}) => boolean | undefined;
/**
* Resolve a URL of a file block to one that can be displayed or downloaded. This can be used for creating authenticated URL or
* implementing custom protocols / schemes
* @returns The URL that's
*/
resolveFileUrl?: (url: string) => Promise<string>;
/**
* The schema of the editor. The schema defines which Blocks, InlineContent, and Styles are available in the editor.
*
* See [Custom Schemas](https://www.blocknotejs.org/docs/custom-schemas) for more info.
* @remarks `BlockNoteSchema`
*/
schema: CustomBlockNoteSchema<BSchema, ISchema, SSchema>;
/**
* A flag indicating whether to set an HTML ID for every block
*
* When set to `true`, on each block an id attribute will be set with the block id
* Otherwise, the HTML ID attribute will not be set.
*
* (note that the id is always set on the `data-id` attribute)
*/
setIdAttribute?: boolean;
/**
* Determines behavior when pressing Tab (or Shift-Tab) while multiple blocks are selected and a toolbar is open.
* - `"prefer-navigate-ui"`: Changes focus to the toolbar. User must press Escape to close toolbar before indenting blocks. Better for keyboard accessibility.
* - `"prefer-indent"`: Always indents selected blocks, regardless of toolbar state. Keyboard navigation of toolbars not possible.
* @default "prefer-navigate-ui"
*/
tabBehavior?: "prefer-navigate-ui" | "prefer-indent";
/**
* Allows enabling / disabling features of tables.
*
* See [Tables](https://www.blocknotejs.org/docs/editor-basics/document-structure#tables) for more info.
*
* @remarks `TableConfig`
*/
tables?: {
/**
* Whether to allow splitting and merging cells within a table.
*
* @default false
*/
splitCells?: boolean;
/**
* Whether to allow changing the background color of cells.
*
* @default false
*/
cellBackgroundColor?: boolean;
/**
* Whether to allow changing the text color of cells.
*
* @default false
*/
cellTextColor?: boolean;
/**
* Whether to allow changing cells into headers.
*
* @default false
*/
headers?: boolean;
};
/**
* An option which user can pass with `false` value to disable the automatic creation of a trailing new block on the next line when the user types or edits any block.
*
* @default true
*/
trailingBlock?: boolean;
/**
* The `uploadFile` method is what the editor uses when files need to be uploaded (for example when selecting an image to upload).
* This method should set when creating the editor as this is application-specific.
*
* `undefined` means the application doesn't support file uploads.
*
* @param file The file that should be uploaded.
* @returns The URL of the uploaded file OR an object containing props that should be set on the file block (such as an id)
* @remarks `(file: File) => Promise<UploadFileResult>`
*/
uploadFile?: (
file: File,
blockId?: string,
) => Promise<string | Record<string, any>>;
/**
* additional tiptap options, undocumented
* @internal
*/
_tiptapOptions?: Partial<EditorOptions>;
/**
* Register extensions to the editor.
*
* See [Extensions](/docs/features/extensions) for more info.
*
* @remarks `ExtensionFactory[]`
*/
extensions?: Array<ExtensionFactoryInstance>;
}
const blockNoteTipTapOptions = {
enableInputRules: true,
enablePasteRules: true,
enableCoreExtensions: false,
};
export class BlockNoteEditor<
BSchema extends BlockSchema = DefaultBlockSchema,
ISchema extends InlineContentSchema = DefaultInlineContentSchema,
SSchema extends StyleSchema = DefaultStyleSchema,
> extends EventEmitter<{
create: void;
}> {
/**
* The underlying prosemirror schema
*/
public readonly pmSchema: Schema;
public readonly _tiptapEditor: TiptapEditor & {
contentComponent: any;
};
/**
* Used by React to store a reference to an `ElementRenderer` helper utility to make sure we can render React elements
* in the correct context (used by `ReactRenderUtil`)
*/
public elementRenderer: ((node: any, container: HTMLElement) => void) | null =
null;
/**
* Cache of all blocks. This makes sure we don't have to "recompute" blocks if underlying Prosemirror Nodes haven't changed.
* This is especially useful when we want to keep track of the same block across multiple operations,
* with this cache, blocks stay the same object reference (referential equality with ===).
*/
public blockCache: BlockCache = new WeakMap();
/**
* The dictionary contains translations for the editor.
*/
public readonly dictionary: Dictionary & Record<string, any>;
/**
* The schema of the editor. The schema defines which Blocks, InlineContent, and Styles are available in the editor.
*/
public readonly schema: BlockNoteSchema<BSchema, ISchema, SSchema>;
public readonly blockImplementations: BlockSpecs;
public readonly inlineContentImplementations: InlineContentSpecs;
public readonly styleImplementations: StyleSpecs;
/**
* The `uploadFile` method is what the editor uses when files need to be uploaded (for example when selecting an image to upload).
* This method should set when creating the editor as this is application-specific.
*
* `undefined` means the application doesn't support file uploads.
*
* @param file The file that should be uploaded.
* @returns The URL of the uploaded file OR an object containing props that should be set on the file block (such as an id)
*/
public readonly uploadFile:
| ((file: File, blockId?: string) => Promise<string | Record<string, any>>)
| undefined;
private onUploadStartCallbacks: ((blockId?: string) => void)[] = [];
private onUploadEndCallbacks: ((blockId?: string) => void)[] = [];
public readonly resolveFileUrl?: (url: string) => Promise<string>;
/**
* Editor settings
*/
public readonly settings: {
tables: {
splitCells: boolean;
cellBackgroundColor: boolean;
cellTextColor: boolean;
headers: boolean;
};
};
public static create<
Options extends Partial<BlockNoteEditorOptions<any, any, any>> | undefined,
>(
options?: Options,
): Options extends {
schema: CustomBlockNoteSchema<infer BSchema, infer ISchema, infer SSchema>;
}
? BlockNoteEditor<BSchema, ISchema, SSchema>
: BlockNoteEditor<
DefaultBlockSchema,
DefaultInlineContentSchema,
DefaultStyleSchema
> {
return new BlockNoteEditor(options ?? {}) as any;
}
protected constructor(
protected readonly options: Partial<
BlockNoteEditorOptions<BSchema, ISchema, SSchema>
>,
) {
super();
this.dictionary = options.dictionary || en;
this.settings = {
tables: {
splitCells: options?.tables?.splitCells ?? false,
cellBackgroundColor: options?.tables?.cellBackgroundColor ?? false,
cellTextColor: options?.tables?.cellTextColor ?? false,
headers: options?.tables?.headers ?? false,
},
};
// apply defaults
const newOptions = {
defaultStyles: true,
schema:
options.schema ||
(BlockNoteSchema.create() as unknown as CustomBlockNoteSchema<
BSchema,
ISchema,
SSchema
>),
...options,
placeholders: {
...this.dictionary.placeholders,
...options.placeholders,
},
};
// @ts-ignore
this.schema = newOptions.schema;
this.blockImplementations = newOptions.schema.blockSpecs;
this.inlineContentImplementations = newOptions.schema.inlineContentSpecs;
this.styleImplementations = newOptions.schema.styleSpecs;
// TODO this should just be an extension
if (newOptions.uploadFile) {
const uploadFile = newOptions.uploadFile;
this.uploadFile = async (file, blockId) => {
this.onUploadStartCallbacks.forEach((callback) =>
callback.apply(this, [blockId]),
);
try {
return await uploadFile(file, blockId);
} finally {
this.onUploadEndCallbacks.forEach((callback) =>
callback.apply(this, [blockId]),
);
}
};
}
this.resolveFileUrl = newOptions.resolveFileUrl;
this._eventManager = new EventManager(this as any);
this._extensionManager = new ExtensionManager(this, newOptions);
const tiptapExtensions = this._extensionManager.getTiptapExtensions();
const collaborationEnabled =
this._extensionManager.hasExtension("ySync") ||
this._extensionManager.hasExtension("liveblocksExtension");
if (collaborationEnabled && newOptions.initialContent) {
// eslint-disable-next-line no-console
console.warn(
"When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider",
);
}
const tiptapOptions: EditorOptions = {
...blockNoteTipTapOptions,
...newOptions._tiptapOptions,
element: null,
autofocus: newOptions.autofocus ?? false,
extensions: tiptapExtensions,
editorProps: {
...newOptions._tiptapOptions?.editorProps,
attributes: {
// As of TipTap v2.5.0 the tabIndex is removed when the editor is not
// editable, so you can't focus it. We want to revert this as we have
// UI behaviour that relies on it.
tabIndex: "0",
...newOptions._tiptapOptions?.editorProps?.attributes,
...newOptions.domAttributes?.editor,
class: mergeCSSClasses(
"bn-editor",
newOptions.defaultStyles ? "bn-default-styles" : "",
newOptions.domAttributes?.editor?.class || "",
),
},
transformPasted,
},
} as any;
try {
const initialContent =
newOptions.initialContent ||
(collaborationEnabled
? [
{
type: "paragraph",
id: "initialBlockId",
},
]
: [
{
type: "paragraph",
id: UniqueID.options.generateID(),
},
]);
if (!Array.isArray(initialContent) || initialContent.length === 0) {
throw new Error(
"initialContent must be a non-empty array of blocks, received: " +
initialContent,
);
}
const schema = getSchema(tiptapOptions.extensions!);
const pmNodes = initialContent.map((b) =>
blockToNode(b, schema, this.schema.styleSchema).toJSON(),
);
const doc = createDocument(
{
type: "doc",
content: [
{
type: "blockGroup",
content: pmNodes,
},
],
},
schema,
tiptapOptions.parseOptions,
);
this._tiptapEditor = new TiptapEditor({
...tiptapOptions,
content: doc.toJSON(),
}) as any;
this.pmSchema = this._tiptapEditor.schema;
} catch (e) {
throw new Error(
"Error creating document from blocks passed as `initialContent`",
{ cause: e },
);
}
// When y-prosemirror creates an empty document, the `blockContainer` node is created with an `id` of `null`.
// This causes the unique id extension to generate a new id for the initial block, which is not what we want
// Since it will be randomly generated & cause there to be more updates to the ydoc
// This is a hack to make it so that anytime `schema.doc.createAndFill` is called, the initial block id is already set to "initialBlockId"
let cache: Node | undefined = undefined;
const oldCreateAndFill = this.pmSchema.nodes.doc.createAndFill;
this.pmSchema.nodes.doc.createAndFill = (...args: any) => {
if (cache) {
return cache;
}
const ret = oldCreateAndFill.apply(this.pmSchema.nodes.doc, args)!;
// create a copy that we can mutate (otherwise, assigning attrs is not safe and corrupts the pm state)
const jsonNode = JSON.parse(JSON.stringify(ret.toJSON()));
jsonNode.content[0].content[0].attrs.id = "initialBlockId";
cache = Node.fromJSON(this.pmSchema, jsonNode);
return cache;
};
this.pmSchema.cached.blockNoteEditor = this;
// Initialize managers
this._blockManager = new BlockManager(this as any);
this._exportManager = new ExportManager(this as any);
this._selectionManager = new SelectionManager(this as any);
this._stateManager = new StateManager(this as any);
this._styleManager = new StyleManager(this as any);
this.emit("create");
}
// Manager instances
private readonly _blockManager: BlockManager<any, any, any>;
private readonly _eventManager: EventManager<any, any, any>;
private readonly _exportManager: ExportManager<any, any, any>;
private readonly _extensionManager: ExtensionManager;
private readonly _selectionManager: SelectionManager<any, any, any>;
private readonly _stateManager: StateManager;
private readonly _styleManager: StyleManager<any, any, any>;
/**
* BlockNote extensions that are added to the editor, keyed by the extension key
*/
public get extensions() {
return this._extensionManager.getExtensions();
}
/**
* Execute a prosemirror command. This is mostly for backwards compatibility with older code.
*
* @note You should prefer the {@link transact} method when possible, as it will automatically handle the dispatching of the transaction and work across blocknote transactions.
*
* @example
* ```ts
* editor.exec((state, dispatch, view) => {
* dispatch(state.tr.insertText("Hello, world!"));
* });
* ```
*/
public exec(command: Command) {
return this._stateManager.exec(command);
}
/**
* Check if a command can be executed. A command should return `false` if it is not valid in the current state.
*
* @example
* ```ts
* if (editor.canExec(command)) {
* // show button
* } else {
* // hide button
* }
* ```
*/
public canExec(command: Command): boolean {
return this._stateManager.canExec(command);
}
/**
* Execute a function within a "blocknote transaction".
* All changes to the editor within the transaction will be grouped together, so that
* we can dispatch them as a single operation (thus creating only a single undo step)
*
* @note There is no need to dispatch the transaction, as it will be automatically dispatched when the callback is complete.
*
* @example
* ```ts
* // All changes to the editor will be grouped together
* editor.transact((tr) => {
* tr.insertText("Hello, world!");
* // These two operations will be grouped together in a single undo step
* editor.transact((tr) => {
* tr.insertText("Hello, world!");
* });
* });
* ```
*/
public transact<T>(
callback: (
/**
* The current active transaction, this will automatically be dispatched to the editor when the callback is complete
* If another `transact` call is made within the callback, it will be passed the same transaction as the parent call.
*/
tr: Transaction,
) => T,
): T {
return this._stateManager.transact(callback);
}
/**
* Remove extension(s) from the editor
*/
public unregisterExtension: ExtensionManager["unregisterExtension"] = (
...args: Parameters<ExtensionManager["unregisterExtension"]>
) => this._extensionManager.unregisterExtension(...args);
/**
* Register extension(s) to the editor
*/
public registerExtension: ExtensionManager["registerExtension"] = (
...args: Parameters<ExtensionManager["registerExtension"]>
) => this._extensionManager.registerExtension(...args) as any;
/**
* Get an extension from the editor
*/
public getExtension: ExtensionManager["getExtension"] = ((
...args: Parameters<ExtensionManager["getExtension"]>
) => this._extensionManager.getExtension(...args)) as any;
/**
* Mount the editor to a DOM element.
*
* @warning Not needed to call manually when using React, use BlockNoteView to take care of mounting
*/
public mount = (element: HTMLElement) => {
this._tiptapEditor.mount({ mount: element });
};
/**
* Unmount the editor from the DOM element it is bound to
*/
public unmount = () => {
this._tiptapEditor.unmount();
};
/**
* Get the underlying prosemirror state
* @note Prefer using `editor.transact` to read the current editor state, as that will ensure the state is up to date
* @see https://prosemirror.net/docs/ref/#state.EditorState
*/
public get prosemirrorState() {
return this._stateManager.prosemirrorState;
}
/**
* Get the underlying prosemirror view
* @see https://prosemirror.net/docs/ref/#view.EditorView
*/
public get prosemirrorView() {
return this._stateManager.prosemirrorView;
}
public get domElement() {
if (this.headless) {
return undefined;
}
return this.prosemirrorView?.dom as HTMLDivElement | undefined;
}
public isFocused() {
if (this.headless) {
return false;
}
return this.prosemirrorView?.hasFocus() || false;
}
public get headless() {
return !this._tiptapEditor.isInitialized;
}
/**
* Focus on the editor
*/
public focus() {
if (this.headless) {
return;
}
this.prosemirrorView.focus();
}
/**
* Blur the editor
*/
public blur() {
if (this.headless) {
return;
}
this.domElement?.blur();
}
// TODO move to extension
public onUploadStart(callback: (blockId?: string) => void) {
this.onUploadStartCallbacks.push(callback);
return () => {
const index = this.onUploadStartCallbacks.indexOf(callback);
if (index > -1) {
this.onUploadStartCallbacks.splice(index, 1);
}
};
}
public onUploadEnd(callback: (blockId?: string) => void) {
this.onUploadEndCallbacks.push(callback);
return () => {
const index = this.onUploadEndCallbacks.indexOf(callback);
if (index > -1) {
this.onUploadEndCallbacks.splice(index, 1);
}
};
}
/**
* @deprecated, use `editor.document` instead
*/
public get topLevelBlocks(): Block<BSchema, ISchema, SSchema>[] {
return this.document;
}
/**
* Gets a snapshot of all top-level (non-nested) blocks in the editor.
* @returns A snapshot of all top-level (non-nested) blocks in the editor.
*/
public get document(): Block<BSchema, ISchema, SSchema>[] {
return this._blockManager.document;
}
/**
* Gets a snapshot of an existing block from the editor.
* @param blockIdentifier The identifier of an existing block that should be
* retrieved.
* @returns The block that matches the identifier, or `undefined` if no
* matching block was found.
*/
public getBlock(
blockIdentifier: BlockIdentifier,
): Block<BSchema, ISchema, SSchema> | undefined {
return this._blockManager.getBlock(blockIdentifier);
}
/**
* Gets a snapshot of the previous sibling of an existing block from the
* editor.
* @param blockIdentifier The identifier of an existing block for which the
* previous sibling should be retrieved.
* @returns The previous sibling of the block that matches the identifier.
* `undefined` if no matching block was found, or it's the first child/block
* in the document.
*/
public getPrevBlock(
blockIdentifier: BlockIdentifier,
): Block<BSchema, ISchema, SSchema> | undefined {
return this._blockManager.getPrevBlock(blockIdentifier);
}
/**
* Gets a snapshot of the next sibling of an existing block from the editor.
* @param blockIdentifier The identifier of an existing block for which the
* next sibling should be retrieved.
* @returns The next sibling of the block that matches the identifier.
* `undefined` if no matching block was found, or it's the last child/block in
* the document.
*/
public getNextBlock(
blockIdentifier: BlockIdentifier,
): Block<BSchema, ISchema, SSchema> | undefined {
return this._blockManager.getNextBlock(blockIdentifier);
}
/**
* Gets a snapshot of the parent of an existing block from the editor.
* @param blockIdentifier The identifier of an existing block for which the
* parent should be retrieved.
* @returns The parent of the block that matches the identifier. `undefined`
* if no matching block was found, or the block isn't nested.
*/
public getParentBlock(
blockIdentifier: BlockIdentifier,
): Block<BSchema, ISchema, SSchema> | undefined {
return this._blockManager.getParentBlock(blockIdentifier);
}
/**
* Traverses all blocks in the editor depth-first, and executes a callback for each.
* @param callback The callback to execute for each block. Returning `false` stops the traversal.
* @param reverse Whether the blocks should be traversed in reverse order.
*/
public forEachBlock(
callback: (block: Block<BSchema, ISchema, SSchema>) => boolean,
reverse = false,
): void {
this._blockManager.forEachBlock(callback, reverse);
}
/**
* Executes a callback whenever the editor's contents change.
* @param callback The callback to execute.
*
* @deprecated use {@link BlockNoteEditor.onChange} instead
*/
public onEditorContentChange(callback: () => void) {
this._tiptapEditor.on("update", callback);
}
/**
* Executes a callback whenever the editor's selection changes.
* @param callback The callback to execute.
*
* @deprecated use `onSelectionChange` instead
*/
public onEditorSelectionChange(callback: () => void) {
this._tiptapEditor.on("selectionUpdate", callback);
}
/**
* Executes a callback before any change is applied to the editor, allowing you to cancel the change.
* @param callback The callback to execute.
* @returns A function to remove the callback.
*/
public onBeforeChange(
callback: (context: {
getChanges: () => BlocksChanged<BSchema, ISchema, SSchema>;
tr: Transaction;
}) => boolean | void,
): () => void {
return this._extensionManager
.getExtension(BlockChangeExtension)!
.subscribe(callback);
}
/**
* Gets a snapshot of the current text cursor position.
* @returns A snapshot of the current text cursor position.
*/
public getTextCursorPosition(): TextCursorPosition<
BSchema,
ISchema,
SSchema
> {
return this._selectionManager.getTextCursorPosition();
}
/**
* Sets the text cursor position to the start or end of an existing block. Throws an error if the target block could
* not be found.
* @param targetBlock The identifier of an existing block that the text cursor should be moved to.
* @param placement Whether the text cursor should be placed at the start or end of the block.
*/
public setTextCursorPosition(
targetBlock: BlockIdentifier,
placement: "start" | "end" = "start",
) {
return this._selectionManager.setTextCursorPosition(targetBlock, placement);
}
/**
* Gets a snapshot of the current selection. This contains all blocks (included nested blocks)
* that the selection spans across.
*
* If the selection starts / ends halfway through a block, the returned data will contain the entire block.
*/
public getSelection(): Selection<BSchema, ISchema, SSchema> | undefined {
return this._selectionManager.getSelection();
}
/**
* Gets a snapshot of the current selection. This contains all blocks (included nested blocks)
* that the selection spans across.
*
* If the selection starts / ends halfway through a block, the returned block will be
* only the part of the block that is included in the selection.
*/
public getSelectionCutBlocks(expandToWords = false) {
return this._selectionManager.getSelectionCutBlocks(expandToWords);
}
/**
* Sets the selection to a range of blocks.
* @param startBlock The identifier of the block that should be the start of the selection.
* @param endBlock The identifier of the block that should be the end of the selection.
*/
public setSelection(startBlock: BlockIdentifier, endBlock: BlockIdentifier) {
return this._selectionManager.setSelection(startBlock, endBlock);
}
/**
* Checks if the editor is currently editable, or if it's locked.
* @returns True if the editor is editable, false otherwise.
*/
public get isEditable(): boolean {
return this._stateManager.isEditable;
}
/**
* Makes the editor editable or locks it, depending on the argument passed.
* @param editable True to make the editor editable, or false to lock it.
*/
public set isEditable(editable: boolean) {
this._stateManager.isEditable = editable;
}
/**
* Inserts new blocks into the editor. If a block's `id` is undefined, BlockNote generates one automatically. Throws an
* error if the reference block could not be found.
* @param blocksToInsert An array of partial blocks that should be inserted.
* @param referenceBlock An identifier for an existing block, at which the new blocks should be inserted.
* @param placement Whether the blocks should be inserted just before, just after, or nested inside the
* `referenceBlock`.
*/
public insertBlocks(
blocksToInsert: PartialBlock<BSchema, ISchema, SSchema>[],
referenceBlock: BlockIdentifier,
placement: "before" | "after" = "before",
) {
return this._blockManager.insertBlocks(
blocksToInsert,
referenceBlock,
placement,
);
}
/**
* Updates an existing block in the editor. Since updatedBlock is a PartialBlock object, some fields might not be
* defined. These undefined fields are kept as-is from the existing block. Throws an error if the block to update could
* not be found.
* @param blockToUpdate The block that should be updated.
* @param update A partial block which defines how the existing block should be changed.
*/
public updateBlock(
blockToUpdate: BlockIdentifier,
update: PartialBlock<BSchema, ISchema, SSchema>,
) {
return this._blockManager.updateBlock(blockToUpdate, update);
}
/**
* Removes existing blocks from the editor. Throws an error if any of the blocks could not be found.