diff --git a/examples/editor/src/App.tsx b/examples/editor/src/App.tsx index 00d96815f9..ada4b8c3b9 100644 --- a/examples/editor/src/App.tsx +++ b/examples/editor/src/App.tsx @@ -2,11 +2,11 @@ import "@blocknote/core/style.css"; import { BlockNoteView, - useBlockNote, FormattingToolbarPositioner, HyperlinkToolbarPositioner, - SlashMenuPositioner, SideMenuPositioner, + SlashMenuPositioner, + useBlockNote, } from "@blocknote/react"; import styles from "./App.module.css"; diff --git a/examples/vanilla/src/ui/addFormattingToolbar.ts b/examples/vanilla/src/ui/addFormattingToolbar.ts index c2d95b8e81..bae8673512 100644 --- a/examples/vanilla/src/ui/addFormattingToolbar.ts +++ b/examples/vanilla/src/ui/addFormattingToolbar.ts @@ -5,7 +5,7 @@ export const addFormattingToolbar = (editor: BlockNoteEditor) => { let element: HTMLElement; let boldBtn: HTMLAnchorElement; - editor.createFormattingToolbar((formattingToolbarState) => { + editor.formattingToolbar.onUpdate((formattingToolbarState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; diff --git a/examples/vanilla/src/ui/addHyperlinkToolbar.ts b/examples/vanilla/src/ui/addHyperlinkToolbar.ts index bf2fd299bb..866ba7c24c 100644 --- a/examples/vanilla/src/ui/addHyperlinkToolbar.ts +++ b/examples/vanilla/src/ui/addHyperlinkToolbar.ts @@ -4,7 +4,7 @@ import { createButton } from "./util"; export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { let element: HTMLElement; - const callbacks = editor.createHyperlinkToolbar((hyperlinkToolbarState) => { + editor.hyperlinkToolbar.onUpdate((hyperlinkToolbarState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -17,13 +17,13 @@ export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { const editBtn = createButton("edit", () => { const newUrl = prompt("new url") || url; - callbacks.editHyperlink(newUrl, text); + editor.hyperlinkToolbar.editHyperlink(newUrl, text); }); element.appendChild(editBtn); const removeBtn = createButton("remove", () => { - callbacks.deleteHyperlink(); + editor.hyperlinkToolbar.deleteHyperlink(); }); element.appendChild(editBtn); diff --git a/examples/vanilla/src/ui/addSideMenu.ts b/examples/vanilla/src/ui/addSideMenu.ts index cc4f829553..de277aabcc 100644 --- a/examples/vanilla/src/ui/addSideMenu.ts +++ b/examples/vanilla/src/ui/addSideMenu.ts @@ -4,7 +4,7 @@ import { createButton } from "./util"; export const addSideMenu = (editor: BlockNoteEditor) => { let element: HTMLElement; - const callbacks = editor.createSideMenu((sideMenuState) => { + editor.sideMenu.onUpdate((sideMenuState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -12,7 +12,7 @@ export const addSideMenu = (editor: BlockNoteEditor) => { element.style.padding = "10px"; element.style.opacity = "0.8"; const addBtn = createButton("+", () => { - callbacks.addBlock(); + editor.sideMenu.addBlock(); }); element.appendChild(addBtn); @@ -20,8 +20,8 @@ export const addSideMenu = (editor: BlockNoteEditor) => { // TODO: render a submenu with a delete option that calls "props.deleteBlock" }); - dragBtn.addEventListener("dragstart", callbacks.blockDragStart); - dragBtn.addEventListener("dragend", callbacks.blockDragEnd); + dragBtn.addEventListener("dragstart", editor.sideMenu.blockDragStart); + dragBtn.addEventListener("dragend", editor.sideMenu.blockDragEnd); dragBtn.draggable = true; element.style.display = "none"; element.appendChild(dragBtn); diff --git a/examples/vanilla/src/ui/addSlashMenu.ts b/examples/vanilla/src/ui/addSlashMenu.ts index 25ff74a057..3ecbd7fc46 100644 --- a/examples/vanilla/src/ui/addSlashMenu.ts +++ b/examples/vanilla/src/ui/addSlashMenu.ts @@ -28,7 +28,7 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { return domItems; } - const callbacks = editor.createSlashMenu((slashMenuState) => { + editor.slashMenu.onUpdate((slashMenuState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -43,7 +43,7 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { if (slashMenuState.show) { updateItems( slashMenuState.filteredItems, - callbacks.itemCallback, + editor.slashMenu.itemCallback, slashMenuState.keyboardHoveredItemIndex ); diff --git a/examples/vanilla/src/ui/blockSideMenuFactory.ts b/examples/vanilla/src/ui/blockSideMenuFactory.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/vanilla/src/ui/formattingToolbarFactory.ts b/examples/vanilla/src/ui/formattingToolbarFactory.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 4591c64645..bf954f7776 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -37,27 +37,12 @@ import { } from "./extensions/Blocks/api/inlineContentTypes"; import { Selection } from "./extensions/Blocks/api/selectionTypes"; import { getBlockInfoFromPos } from "./extensions/Blocks/helpers/getBlockInfoFromPos"; -import { - setupFormattingToolbar, - FormattingToolbarState, - FormattingToolbarCallbacks, -} from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; -import { - HyperlinkToolbarCallbacks, - HyperlinkToolbarState, - setupHyperlinkToolbar, -} from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; -import { - SuggestionsMenuCallbacks, - SuggestionsMenuState, -} from "./shared/plugins/suggestion/SuggestionPlugin"; -import { setupSlashMenu } from "./extensions/SlashMenu/SlashMenuPlugin"; -import { - setupSideMenu, - SideMenuCallbacks, - SideMenuState, -} from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; + +import { FormattingToolbarProsemirrorPlugin } from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; +import { HyperlinkToolbarProsemirrorPlugin } from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; +import { SideMenuProsemirrorPlugin } from "./extensions/SideMenu/SideMenuPlugin"; import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; +import { SlashMenuProsemirrorPlugin } from "./extensions/SlashMenu/SlashMenuPlugin"; import { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; export type BlockNoteEditorOptions = { @@ -163,81 +148,10 @@ export class BlockNoteEditor { public readonly schema: BSchema; public ready = false; - private uiElementCallbacks: { - formattingToolbar: FormattingToolbarCallbacks; - hyperlinkToolbar: HyperlinkToolbarCallbacks; - slashMenu: SuggestionsMenuCallbacks>; - sideMenu: SideMenuCallbacks; - }; - - private uiElementListeners: Partial<{ - formattingToolbar: (formattingToolbarState: FormattingToolbarState) => void; - hyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void; - slashMenu: ( - slashMenuState: SuggestionsMenuState> - ) => void; - sideMenu: (sideMenuState: SideMenuState) => void; - }> = {}; - - public createFormattingToolbar = ( - updateFormattingToolbar: ( - formattingToolbarState: FormattingToolbarState - ) => void - ) => { - if ("formattingToolbar" in this.uiElementListeners) { - throw Error( - "You have already created a Formatting Toolbar. You can only create a single Formatting Toolbar per BlockNote editor instance." - ); - } - - this.uiElementListeners.formattingToolbar = updateFormattingToolbar; - - return this.uiElementCallbacks.formattingToolbar; - }; - - public createHyperlinkToolbar = ( - updateHyperlinkToolbar: ( - hyperlinkToolbarState: HyperlinkToolbarState - ) => void - ) => { - if ("hyperlinkToolbar" in this.uiElementListeners) { - throw Error( - "You have already created a Hyperlink Toolbar. You can only create a single Hyperlink Toolbar per BlockNote editor instance." - ); - } - - this.uiElementListeners.hyperlinkToolbar = updateHyperlinkToolbar; - - return this.uiElementCallbacks.hyperlinkToolbar; - }; - - public createSlashMenu = >( - updateSlashMenu: (slashMenuState: SuggestionsMenuState) => void - ) => { - if ("slashMenu" in this.uiElementListeners) { - throw Error( - "You have already created a Slash Menu. You can only create a single Slash Menu per BlockNote editor instance." - ); - } - - this.uiElementListeners.slashMenu = updateSlashMenu as any; - - return this.uiElementCallbacks.slashMenu; - }; - - public createSideMenu = ( - updateSideMenu: (sideMenuState: SideMenuState) => void - ) => { - if ("sideMenu" in this.uiElementListeners) { - throw Error( - "You have already created a Side Menu. You can only create a single Side Menu per BlockNote editor instance." - ); - } - - this.uiElementListeners.sideMenu = updateSideMenu; - - return this.uiElementCallbacks.sideMenu; - }; + public readonly sideMenu: SideMenuProsemirrorPlugin; + public readonly formattingToolbar: FormattingToolbarProsemirrorPlugin; + public readonly slashMenu: SlashMenuProsemirrorPlugin; + public readonly hyperlinkToolbar: HyperlinkToolbarProsemirrorPlugin; constructor( private readonly options: Partial> = {} @@ -257,140 +171,36 @@ export class BlockNoteEditor { ...options, }; - const editor = this; + this.sideMenu = new SideMenuProsemirrorPlugin(this); + this.formattingToolbar = new FormattingToolbarProsemirrorPlugin(this); + this.slashMenu = new SlashMenuProsemirrorPlugin( + this, + newOptions.slashCommands || + getDefaultSlashMenuItems(newOptions.blockSchema) + ); + this.hyperlinkToolbar = new HyperlinkToolbarProsemirrorPlugin(this); const extensions = getBlockNoteExtensions({ editor: this, - slashCommands: - newOptions.slashCommands || - getDefaultSlashMenuItems(newOptions.blockSchema), blockSchema: newOptions.blockSchema, collaboration: newOptions.collaboration, }); - this.schema = newOptions.blockSchema; - - let formattingToolbarCallbacks: FormattingToolbarCallbacks; - const formattingToolbarExtension = Extension.create({ - name: "FormattingToolbarExtension", + const blockNoteUIExtension = Extension.create({ + name: "BlockNoteUIExtension", - addProseMirrorPlugins() { - const { plugin, callbacks } = setupFormattingToolbar( - editor, - this.editor, - (formattingToolbarState) => { - const formattingToolbarListener = - editor.uiElementListeners.formattingToolbar; - - if (!formattingToolbarListener) { - return; - } - - formattingToolbarListener(formattingToolbarState); - } - ); - - formattingToolbarCallbacks = { - destroy: () => delete editor.uiElementListeners.formattingToolbar, - ...callbacks, - }; - - return [plugin]; - }, - }); - extensions.push(formattingToolbarExtension); - - let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks; - const hyperlinkToolbarExtension = Extension.create({ - name: "HyperlinkToolbarExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupHyperlinkToolbar( - editor, - this.editor, - (hyperlinkToolbarState) => { - const hyperlinkToolbarListener = - editor.uiElementListeners.hyperlinkToolbar; - - if (!hyperlinkToolbarListener) { - return; - } - - hyperlinkToolbarListener(hyperlinkToolbarState); - } - ); - - hyperlinkToolbarCallbacks = { - destroy: () => delete editor.uiElementListeners.hyperlinkToolbar, - ...callbacks, - }; - - return [plugin]; + addProseMirrorPlugins: () => { + return [ + this.sideMenu.plugin, + this.formattingToolbar.plugin, + this.slashMenu.plugin, + this.hyperlinkToolbar.plugin, + ]; }, }); - extensions.push(hyperlinkToolbarExtension); - - let slashMenuCallbacks: SuggestionsMenuCallbacks< - BaseSlashMenuItem - >; - const slashMenuExtension = Extension.create({ - name: "SlashMenuExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupSlashMenu( - editor, - this.editor, - (slashMenuState) => { - const slashMenuListener = editor.uiElementListeners.slashMenu; - - if (!slashMenuListener) { - return; - } - - slashMenuListener(slashMenuState as any); - }, - newOptions.slashCommands || - getDefaultSlashMenuItems(newOptions.blockSchema) - ); - - slashMenuCallbacks = { - destroy: () => delete editor.uiElementListeners.slashMenu, - ...callbacks, - }; - - return [plugin]; - }, - }); - extensions.push(slashMenuExtension); - - let sideMenuCallbacks: SideMenuCallbacks; - const sideMenuExtension = Extension.create({ - name: "SideMenuExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupSideMenu( - editor, - this.editor, - (sideMenuState) => { - const sideMenuListener = editor.uiElementListeners.sideMenu; - - if (!sideMenuListener) { - return; - } - - sideMenuListener(sideMenuState as any); - } - ); + extensions.push(blockNoteUIExtension); - sideMenuCallbacks = { - destroy: () => delete editor.uiElementListeners.sideMenu, - ...callbacks, - }; - - return [plugin]; - }, - }); - extensions.push(sideMenuExtension); + this.schema = newOptions.blockSchema; const tiptapOptions: EditorOptions = { // TODO: This approach to setting initial content is "cleaner" but requires the PM editor schema, which is only @@ -452,15 +262,10 @@ export class BlockNoteEditor { this._tiptapEditor = new Editor(tiptapOptions) as Editor & { contentComponent: any; }; + } - // These need to be assigned after the TipTap editor is created as they are - // initialized in a plugin, which is only loaded on editor creation. - this.uiElementCallbacks = { - formattingToolbar: formattingToolbarCallbacks!, - hyperlinkToolbar: hyperlinkToolbarCallbacks!, - slashMenu: slashMenuCallbacks!, - sideMenu: sideMenuCallbacks!, - }; + public get prosemirrorView() { + return this._tiptapEditor.view; } public get domElement() { diff --git a/packages/core/src/BlockNoteExtensions.ts b/packages/core/src/BlockNoteExtensions.ts index 3a4a23b574..9dba2510f2 100644 --- a/packages/core/src/BlockNoteExtensions.ts +++ b/packages/core/src/BlockNoteExtensions.ts @@ -24,7 +24,6 @@ import { BlockSchema } from "./extensions/Blocks/api/blockTypes"; import { CustomBlockSerializerExtension } from "./extensions/Blocks/api/serialization"; import blockStyles from "./extensions/Blocks/nodes/Block.module.css"; import { Placeholder } from "./extensions/Placeholder/PlaceholderExtension"; -import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; import { TextAlignmentExtension } from "./extensions/TextAlignment/TextAlignmentExtension"; import { TextColorExtension } from "./extensions/TextColor/TextColorExtension"; import { TextColorMark } from "./extensions/TextColor/TextColorMark"; @@ -36,7 +35,6 @@ import UniqueID from "./extensions/UniqueID/UniqueID"; */ export const getBlockNoteExtensions = (opts: { editor: BlockNoteEditor; - slashCommands: BaseSlashMenuItem[]; // couldn't fix type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771 blockSchema: BSchema; collaboration?: { fragment: Y.XmlFragment; diff --git a/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts b/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 4c65d8224a..29d893fccb 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -1,9 +1,4 @@ -import { - Editor, - isNodeSelection, - isTextSelection, - posToDOMRect, -} from "@tiptap/core"; +import { isNodeSelection, isTextSelection, posToDOMRect } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; import { @@ -12,15 +7,13 @@ import { BlockNoteEditor, BlockSchema, } from "../.."; +import { EventEmitter } from "../../shared/EventEmitter"; export type FormattingToolbarCallbacks = BaseUiElementCallbacks; export type FormattingToolbarState = BaseUiElementState; export class FormattingToolbarView { - public editor: BlockNoteEditor; - private ttEditor: Editor; - private formattingToolbarState?: FormattingToolbarState; public updateFormattingToolbar: () => void; @@ -47,15 +40,12 @@ export class FormattingToolbarView { }; constructor( - editor: BlockNoteEditor, - tipTapEditor: Editor, + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState ) => void ) { - this.editor = editor; - this.ttEditor = tipTapEditor; - this.updateFormattingToolbar = () => { if (!this.formattingToolbarState) { throw new Error( @@ -66,15 +56,12 @@ export class FormattingToolbarView { updateFormattingToolbar(this.formattingToolbarState); }; - this.ttEditor.view.dom.addEventListener( - "mousedown", - this.viewMousedownHandler - ); - this.ttEditor.view.dom.addEventListener("mouseup", this.viewMouseupHandler); - this.ttEditor.view.dom.addEventListener("dragstart", this.dragstartHandler); + pmView.dom.addEventListener("mousedown", this.viewMousedownHandler); + pmView.dom.addEventListener("mouseup", this.viewMouseupHandler); + pmView.dom.addEventListener("dragstart", this.dragstartHandler); - this.ttEditor.on("focus", this.focusHandler); - this.ttEditor.on("blur", this.blurHandler); + pmView.dom.addEventListener("focus", this.focusHandler); + pmView.dom.addEventListener("blur", this.blurHandler); document.addEventListener("scroll", this.scrollHandler); } @@ -85,7 +72,7 @@ export class FormattingToolbarView { viewMouseupHandler = () => { this.preventShow = false; - setTimeout(() => this.update(this.ttEditor.view)); + setTimeout(() => this.update(this.pmView)); }; // For dragging the whole editor. @@ -98,17 +85,17 @@ export class FormattingToolbarView { focusHandler = () => { // we use `setTimeout` to make sure `selection` is already updated - setTimeout(() => this.update(this.ttEditor.view)); + setTimeout(() => this.update(this.pmView)); }; - blurHandler = ({ event }: { event: FocusEvent }) => { + blurHandler = (event: FocusEvent) => { if (this.preventHide) { this.preventHide = false; return; } - const editorWrapper = this.ttEditor.view.dom.parentElement!; + const editorWrapper = this.pmView.dom.parentElement!; // Checks if the focus is moving to an element outside the editor. If it is, // the toolbar is hidden. @@ -194,27 +181,18 @@ export class FormattingToolbarView { } destroy() { - this.ttEditor.view.dom.removeEventListener( - "mousedown", - this.viewMousedownHandler - ); - this.ttEditor.view.dom.removeEventListener( - "mouseup", - this.viewMouseupHandler - ); - this.ttEditor.view.dom.removeEventListener( - "dragstart", - this.dragstartHandler - ); - - this.ttEditor.off("focus", this.focusHandler); - this.ttEditor.off("blur", this.blurHandler); + this.pmView.dom.removeEventListener("mousedown", this.viewMousedownHandler); + this.pmView.dom.removeEventListener("mouseup", this.viewMouseupHandler); + this.pmView.dom.removeEventListener("dragstart", this.dragstartHandler); + + this.pmView.dom.removeEventListener("focus", this.focusHandler); + this.pmView.dom.removeEventListener("blur", this.blurHandler); document.removeEventListener("scroll", this.scrollHandler); } getSelectionBoundingBox() { - const { state } = this.ttEditor.view; + const { state } = this.pmView; const { selection } = state; // support for CellSelections @@ -223,44 +201,41 @@ export class FormattingToolbarView { const to = Math.max(...ranges.map((range) => range.$to.pos)); if (isNodeSelection(selection)) { - const node = this.ttEditor.view.nodeDOM(from) as HTMLElement; + const node = this.pmView.nodeDOM(from) as HTMLElement; if (node) { return node.getBoundingClientRect(); } } - return posToDOMRect(this.ttEditor.view, from, to); + return posToDOMRect(this.pmView, from, to); } } export const formattingToolbarPluginKey = new PluginKey( "FormattingToolbarPlugin" ); -export const setupFormattingToolbar = ( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateFormattingToolbar: ( - formattingToolbarState: FormattingToolbarState - ) => void -): { - plugin: Plugin; - callbacks: Omit; -} => { - let formattingToolbarView: FormattingToolbarView; - - return { - plugin: new Plugin({ + +export class FormattingToolbarProsemirrorPlugin< + BSchema extends BlockSchema +> extends EventEmitter { + private view: FormattingToolbarView | undefined; + public readonly plugin: Plugin; + + constructor(editor: BlockNoteEditor) { + super(); + this.plugin = new Plugin({ key: formattingToolbarPluginKey, - view: () => { - formattingToolbarView = new FormattingToolbarView( - editor, - tiptapEditor, - updateFormattingToolbar - ); - return formattingToolbarView; + view: (editorView) => { + this.view = new FormattingToolbarView(editor, editorView, (state) => { + this.emit("update", state); + }); + return this.view; }, - }), - callbacks: {}, - }; -}; + }); + } + + public onUpdate(callback: (state: FormattingToolbarState) => void) { + return this.on("update", callback); + } +} diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index 6731e60453..65ae274279 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -1,26 +1,12 @@ -import { Editor, getMarkRange, posToDOMRect, Range } from "@tiptap/core"; +import { getMarkRange, posToDOMRect, Range } from "@tiptap/core"; +import { EditorView } from "@tiptap/pm/view"; import { Mark } from "prosemirror-model"; import { Plugin, PluginKey } from "prosemirror-state"; import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { - BaseUiElementCallbacks, - BaseUiElementState, -} from "../../shared/BaseUiElementTypes"; +import { BaseUiElementState } from "../../shared/BaseUiElementTypes"; +import { EventEmitter } from "../../shared/EventEmitter"; import { BlockSchema } from "../Blocks/api/blockTypes"; -export type HyperlinkToolbarCallbacks = BaseUiElementCallbacks & { - // Updates or deletes the hovered hyperlink. - editHyperlink: (url: string, text: string) => void; - deleteHyperlink: () => void; - - // When hovering on/off hyperlinks using the mouse cursor, the hyperlink - // toolbar will open & close with a delay. These functions start & stop the - // delay timer, and should be used for when the mouse cursor enters & exits - // the hyperlink toolbar. - startHideTimer: () => void; - stopHideTimer: () => void; -}; - export type HyperlinkToolbarState = BaseUiElementState & { // The hovered hyperlink's URL, and the text it's displayed with in the // editor. @@ -29,9 +15,6 @@ export type HyperlinkToolbarState = BaseUiElementState & { }; class HyperlinkToolbarView { - editor: BlockNoteEditor; - ttEditor: Editor; - private hyperlinkToolbarState?: HyperlinkToolbarState; public updateHyperlinkToolbar: () => void; @@ -49,15 +32,12 @@ class HyperlinkToolbarView { hyperlinkMarkRange: Range | undefined; constructor( - editor: BlockNoteEditor, - tiptapEditor: Editor, + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, updateHyperlinkToolbar: ( hyperlinkToolbarState: HyperlinkToolbarState ) => void ) { - this.editor = editor; - this.ttEditor = tiptapEditor; - this.updateHyperlinkToolbar = () => { if (!this.hyperlinkToolbarState) { throw new Error("Attempting to update uninitialized hyperlink toolbar"); @@ -81,7 +61,7 @@ class HyperlinkToolbarView { return false; }; - this.ttEditor.view.dom.addEventListener("mouseover", this.mouseOverHandler); + this.pmView.dom.addEventListener("mouseover", this.mouseOverHandler); document.addEventListener("click", this.clickHandler, true); document.addEventListener("scroll", this.scrollHandler); } @@ -101,14 +81,16 @@ class HyperlinkToolbarView { // mouseHoveredHyperlinkMarkRange. const hoveredHyperlinkElement = event.target; const posInHoveredHyperlinkMark = - this.ttEditor.view.posAtDOM(hoveredHyperlinkElement, 0) + 1; - const resolvedPosInHoveredHyperlinkMark = this.ttEditor.state.doc.resolve( + this.pmView.posAtDOM(hoveredHyperlinkElement, 0) + 1; + const resolvedPosInHoveredHyperlinkMark = this.pmView.state.doc.resolve( posInHoveredHyperlinkMark ); const marksAtPos = resolvedPosInHoveredHyperlinkMark.marks(); for (const mark of marksAtPos) { - if (mark.type.name === this.ttEditor.schema.mark("link").type.name) { + if ( + mark.type.name === this.pmView.state.schema.mark("link").type.name + ) { this.mouseHoveredHyperlinkMark = mark; this.mouseHoveredHyperlinkMarkRange = getMarkRange( @@ -128,7 +110,7 @@ class HyperlinkToolbarView { }; clickHandler = (event: MouseEvent) => { - const editorWrapper = this.ttEditor.view.dom.parentElement!; + const editorWrapper = this.pmView.dom.parentElement!; if ( // Toolbar is open. @@ -153,7 +135,7 @@ class HyperlinkToolbarView { if (this.hyperlinkMark !== undefined) { if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.referencePos = posToDOMRect( - this.ttEditor.view, + this.pmView, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ); @@ -163,7 +145,7 @@ class HyperlinkToolbarView { }; editHyperlink(url: string, text: string) { - const tr = this.ttEditor.view.state.tr.insertText( + const tr = this.pmView.state.tr.insertText( text, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to @@ -171,10 +153,10 @@ class HyperlinkToolbarView { tr.addMark( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.from + text.length, - this.ttEditor.schema.mark("link", { href: url }) + this.pmView.state.schema.mark("link", { href: url }) ); - this.ttEditor.view.dispatch(tr); - this.ttEditor.view.focus(); + this.pmView.dispatch(tr); + this.pmView.focus(); if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.show = false; @@ -183,8 +165,8 @@ class HyperlinkToolbarView { } deleteHyperlink() { - this.ttEditor.view.dispatch( - this.ttEditor.view.state.tr + this.pmView.dispatch( + this.pmView.state.tr .removeMark( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to, @@ -192,7 +174,7 @@ class HyperlinkToolbarView { ) .setMeta("preventAutolink", true) ); - this.ttEditor.view.focus(); + this.pmView.focus(); if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.show = false; @@ -201,7 +183,7 @@ class HyperlinkToolbarView { } update() { - if (!this.ttEditor.view.hasFocus()) { + if (!this.pmView.hasFocus()) { return; } @@ -218,15 +200,17 @@ class HyperlinkToolbarView { // Finds link mark at the editor selection's position to update keyboardHoveredHyperlinkMark and // keyboardHoveredHyperlinkMarkRange. - if (this.ttEditor.state.selection.empty) { - const marksAtPos = this.ttEditor.state.selection.$from.marks(); + if (this.pmView.state.selection.empty) { + const marksAtPos = this.pmView.state.selection.$from.marks(); for (const mark of marksAtPos) { - if (mark.type.name === this.ttEditor.schema.mark("link").type.name) { + if ( + mark.type.name === this.pmView.state.schema.mark("link").type.name + ) { this.keyboardHoveredHyperlinkMark = mark; this.keyboardHoveredHyperlinkMarkRange = getMarkRange( - this.ttEditor.state.selection.$from, + this.pmView.state.selection.$from, mark.type, mark.attrs ) || undefined; @@ -251,12 +235,12 @@ class HyperlinkToolbarView { this.hyperlinkToolbarState = { show: true, referencePos: posToDOMRect( - this.ttEditor.view, + this.pmView, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ), url: this.hyperlinkMark!.attrs.href, - text: this.ttEditor.view.state.doc.textBetween( + text: this.pmView.state.doc.textBetween( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ), @@ -280,10 +264,7 @@ class HyperlinkToolbarView { } destroy() { - this.ttEditor.view.dom.removeEventListener( - "mouseover", - this.mouseOverHandler - ); + this.pmView.dom.removeEventListener("mouseover", this.mouseOverHandler); document.removeEventListener("scroll", this.scrollHandler); document.removeEventListener("click", this.clickHandler, true); } @@ -292,34 +273,61 @@ class HyperlinkToolbarView { export const hyperlinkToolbarPluginKey = new PluginKey( "HyperlinkToolbarPlugin" ); -export const setupHyperlinkToolbar = ( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void -): { - plugin: Plugin; - callbacks: Omit; -} => { - let hyperlinkToolbarView: HyperlinkToolbarView; - - return { - plugin: new Plugin({ + +export class HyperlinkToolbarProsemirrorPlugin< + BSchema extends BlockSchema +> extends EventEmitter { + private view: HyperlinkToolbarView | undefined; + public readonly plugin: Plugin; + + constructor(editor: BlockNoteEditor) { + super(); + this.plugin = new Plugin({ key: hyperlinkToolbarPluginKey, - view: () => { - hyperlinkToolbarView = new HyperlinkToolbarView( - editor, - tiptapEditor, - updateHyperlinkToolbar - ); - return hyperlinkToolbarView; + view: (editorView) => { + this.view = new HyperlinkToolbarView(editor, editorView, (state) => { + this.emit("update", state); + }); + return this.view; }, - }), - callbacks: { - editHyperlink: (url, text) => - hyperlinkToolbarView.editHyperlink(url, text), - deleteHyperlink: () => hyperlinkToolbarView.deleteHyperlink(), - startHideTimer: () => hyperlinkToolbarView.startMenuUpdateTimer(), - stopHideTimer: () => hyperlinkToolbarView.stopMenuUpdateTimer(), - }, + }); + } + + public onUpdate(callback: (state: HyperlinkToolbarState) => void) { + return this.on("update", callback); + } + + /** + * Edit the currently hovered hyperlink. + */ + public editHyperlink = (url: string, text: string) => { + this.view!.editHyperlink(url, text); }; -}; + + /** + * Delete the currently hovered hyperlink. + */ + public deleteHyperlink = () => { + this.view!.deleteHyperlink(); + }; + + /** + * When hovering on/off hyperlinks using the mouse cursor, the hyperlink + * toolbar will open & close with a delay. + * + * This function starts the delay timer, and should be used for when the mouse cursor enters the hyperlink toolbar. + */ + public startHideTimer = () => { + this.view!.startMenuUpdateTimer(); + }; + + /** + * When hovering on/off hyperlinks using the mouse cursor, the hyperlink + * toolbar will open & close with a delay. + * + * This function stops the delay timer, and should be used for when the mouse cursor exits the hyperlink toolbar. + */ + public stopHideTimer = () => { + this.view!.stopMenuUpdateTimer(); + }; +} diff --git a/packages/core/src/extensions/DraggableBlocks/MultipleNodeSelection.ts b/packages/core/src/extensions/SideMenu/MultipleNodeSelection.ts similarity index 100% rename from packages/core/src/extensions/DraggableBlocks/MultipleNodeSelection.ts rename to packages/core/src/extensions/SideMenu/MultipleNodeSelection.ts diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts similarity index 80% rename from packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts rename to packages/core/src/extensions/SideMenu/SideMenuPlugin.ts index 74014f7ba8..63e5aa1bd6 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts @@ -5,37 +5,18 @@ import * as pv from "prosemirror-view"; import { EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../BlockNoteEditor"; import styles from "../../editor.module.css"; -import { - BaseUiElementCallbacks, - BaseUiElementState, -} from "../../shared/BaseUiElementTypes"; +import { BaseUiElementState } from "../../shared/BaseUiElementTypes"; +import { EventEmitter } from "../../shared/EventEmitter"; import { Block, BlockSchema } from "../Blocks/api/blockTypes"; import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; import { MultipleNodeSelection } from "./MultipleNodeSelection"; -import { Editor } from "@tiptap/core"; const serializeForClipboard = (pv as any).__serializeForClipboard; // code based on https://github.com/ueberdosis/tiptap/issues/323#issuecomment-506637799 let dragImageElement: Element | undefined; -export type SideMenuCallbacks = BaseUiElementCallbacks & { - // If the block is empty, opens the slash menu. If the block has content, - // creates a new block below and opens the slash menu in it. - addBlock: () => void; - - // Freezes/unfreezes the side menu. When frozen, the side menu will stay - // attached to the same block regardless of which block is hovered by the - // mouse cursor. - freezeMenu: () => void; - unfreezeMenu: () => void; - - // Handles drag & drop events for blocks. - blockDragStart: (event: DragEvent) => void; - blockDragEnd: () => void; -}; - export type SideMenuState = BaseUiElementState & { // The block that the side menu is attached to. block: Block; @@ -244,49 +225,36 @@ function dragStart(e: DragEvent, view: EditorView) { } export class SideMenuView implements PluginView { - editor: BlockNoteEditor; - ttEditor: Editor; - private sideMenuState?: SideMenuState; - public updateSideMenu: () => void; // When true, the drag handle with be anchored at the same level as root elements // When false, the drag handle with be just to the left of the element // TODO: Is there any case where we want this to be false? - horizontalPosAnchoredAtRoot: boolean; - horizontalPosAnchor: number; + private horizontalPosAnchoredAtRoot: boolean; + private horizontalPosAnchor: number; - hoveredBlock: HTMLElement | undefined; + private hoveredBlock: HTMLElement | undefined; // Used to check if currently dragged content comes from this editor instance. - isDragging = false; + public isDragging = false; - menuFrozen = false; + public menuFrozen = false; constructor( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateSideMenu: (sideMenuState: SideMenuState) => void + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, + private readonly updateSideMenu: ( + sideMenuState: SideMenuState + ) => void ) { - this.editor = editor; - this.ttEditor = tiptapEditor; - this.horizontalPosAnchoredAtRoot = true; this.horizontalPosAnchor = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect().x; - this.updateSideMenu = () => { - if (!this.sideMenuState) { - throw new Error("Attempting to update uninitialized side menu"); - } - - updateSideMenu(this.sideMenuState); - }; - document.body.addEventListener("drop", this.onDrop, true); document.body.addEventListener("dragover", this.onDragOver); - this.ttEditor.view.dom.addEventListener("dragstart", this.onDragStart); + this.pmView.dom.addEventListener("dragstart", this.onDragStart); // Shows or updates menu position whenever the cursor moves, if the menu isn't frozen. document.body.addEventListener("mousemove", this.onMouseMove, true); @@ -296,7 +264,7 @@ export class SideMenuView implements PluginView { // Hides and unfreezes the menu whenever the user selects the editor with the mouse or presses a key. // TODO: Better integration with suggestions menu and only editor scope? - document.body.addEventListener("mousedown", this.onMouseDown, true); + // document.body.addEventListener("mousedown", this.onMouseDown, true); document.body.addEventListener("keydown", this.onKeyDown, true); } @@ -313,13 +281,13 @@ export class SideMenuView implements PluginView { * when dragging / dropping to the side of the editor */ onDrop = (event: DragEvent) => { - this.ttEditor.commands.blur(); + this.editor._tiptapEditor.commands.blur(); if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.ttEditor.view.posAtCoords({ + let pos = this.pmView.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -329,7 +297,7 @@ export class SideMenuView implements PluginView { if (!pos || pos.inside === -1) { const evt = new Event("drop", event) as any; const editorBoundingBox = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -337,7 +305,7 @@ export class SideMenuView implements PluginView { evt.preventDefault = () => event.preventDefault(); evt.synthetic = true; // prevent recursion // console.log("dispatch fake drop"); - this.ttEditor.view.dom.dispatchEvent(evt); + this.pmView.dom.dispatchEvent(evt); } }; @@ -350,7 +318,7 @@ export class SideMenuView implements PluginView { if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.ttEditor.view.posAtCoords({ + let pos = this.pmView.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -358,7 +326,7 @@ export class SideMenuView implements PluginView { if (!pos || pos.inside === -1) { const evt = new Event("dragover", event) as any; const editorBoundingBox = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -366,32 +334,18 @@ export class SideMenuView implements PluginView { evt.preventDefault = () => event.preventDefault(); evt.synthetic = true; // prevent recursion // console.log("dispatch fake dragover"); - this.ttEditor.view.dom.dispatchEvent(evt); + this.pmView.dom.dispatchEvent(evt); } }; onKeyDown = (_event: KeyboardEvent) => { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } this.menuFrozen = false; }; - onMouseDown = (_event: MouseEvent) => { - // TODO: Fix - // if (this.blockMenu.element?.contains(event.target as HTMLElement)) { - // return; - // } - // - // if (this.sideMenuState?.show) { - // this.sideMenuState.show = false; - // this.updateSideMenu(); - // } - // - // this.menuFrozen = false; - }; - onMouseMove = (event: MouseEvent) => { if (this.menuFrozen) { return; @@ -402,19 +356,18 @@ export class SideMenuView implements PluginView { // blockGroup that wraps all blocks in the editor) for more accurate side // menu placement. const editorBoundingBox = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect(); // We want the full area of the editor to check if the cursor is hovering // above it though. - const editorOuterBoundingBox = - this.ttEditor.view.dom.getBoundingClientRect(); + const editorOuterBoundingBox = this.pmView.dom.getBoundingClientRect(); const cursorWithinEditor = event.clientX >= editorOuterBoundingBox.left && event.clientX <= editorOuterBoundingBox.right && event.clientY >= editorOuterBoundingBox.top && event.clientY <= editorOuterBoundingBox.bottom; - const editorWrapper = this.ttEditor.view.dom.parentElement!; + const editorWrapper = this.pmView.dom.parentElement!; // Doesn't update if the mouse hovers an element that's over the editor but // isn't a part of it or the side menu. @@ -432,7 +385,7 @@ export class SideMenuView implements PluginView { ) { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } return; @@ -445,13 +398,13 @@ export class SideMenuView implements PluginView { left: editorBoundingBox.left + editorBoundingBox.width / 2, // take middle of editor top: event.clientY, }; - const block = getDraggableBlockFromCoords(coords, this.ttEditor.view); + const block = getDraggableBlockFromCoords(coords, this.pmView); // Closes the menu if the mouse cursor is beyond the editor vertically. if (!block || !this.editor.isEditable) { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } return; @@ -494,7 +447,7 @@ export class SideMenuView implements PluginView { )!, }; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } }; @@ -511,20 +464,20 @@ export class SideMenuView implements PluginView { blockContentBoundingBox.width, blockContentBoundingBox.height ); - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } }; destroy() { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } document.body.removeEventListener("mousemove", this.onMouseMove); document.body.removeEventListener("dragover", this.onDragOver); - this.ttEditor.view.dom.removeEventListener("dragstart", this.onDragStart); + this.pmView.dom.removeEventListener("dragstart", this.onDragStart); document.body.removeEventListener("drop", this.onDrop, true); - document.body.removeEventListener("mousedown", this.onMouseDown, true); + // document.body.removeEventListener("mousedown", this.onMouseDown, true); document.removeEventListener("scroll", this.onScroll); document.body.removeEventListener("keydown", this.onKeyDown, true); } @@ -532,7 +485,7 @@ export class SideMenuView implements PluginView { addBlock() { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } this.menuFrozen = true; @@ -540,7 +493,7 @@ export class SideMenuView implements PluginView { const blockContent = this.hoveredBlock!.firstChild! as HTMLElement; const blockContentBoundingBox = blockContent.getBoundingClientRect(); - const pos = this.ttEditor.view.posAtCoords({ + const pos = this.pmView.posAtCoords({ left: blockContentBoundingBox.left + blockContentBoundingBox.width / 2, top: blockContentBoundingBox.top + blockContentBoundingBox.height / 2, }); @@ -548,7 +501,10 @@ export class SideMenuView implements PluginView { return; } - const blockInfo = getBlockInfoFromPos(this.ttEditor.state.doc, pos.pos); + const blockInfo = getBlockInfoFromPos( + this.editor._tiptapEditor.state.doc, + pos.pos + ); if (blockInfo === undefined) { return; } @@ -560,20 +516,20 @@ export class SideMenuView implements PluginView { const newBlockInsertionPos = endPos + 1; const newBlockContentPos = newBlockInsertionPos + 2; - this.ttEditor + this.editor._tiptapEditor .chain() .BNCreateBlock(newBlockInsertionPos) .BNUpdateBlock(newBlockContentPos, { type: "paragraph", props: {} }) .setTextSelection(newBlockContentPos) .run(); } else { - this.ttEditor.commands.setTextSelection(endPos); + this.editor._tiptapEditor.commands.setTextSelection(endPos); } // Focuses and activates the suggestion menu. - this.ttEditor.view.focus(); - this.ttEditor.view.dispatch( - this.ttEditor.view.state.tr.scrollIntoView().setMeta(slashMenuPluginKey, { + this.pmView.focus(); + this.pmView.dispatch( + this.pmView.state.tr.scrollIntoView().setMeta(slashMenuPluginKey, { // TODO import suggestion plugin key activate: true, type: "drag", @@ -584,33 +540,61 @@ export class SideMenuView implements PluginView { export const sideMenuPluginKey = new PluginKey("SideMenuPlugin"); -export function setupSideMenu( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateSideMenu: (sideMenuState: SideMenuState) => void -): { - plugin: Plugin; - callbacks: Omit; -} { - let sideMenuView: SideMenuView; - - return { - plugin: new Plugin({ +export class SideMenuProsemirrorPlugin< + BSchema extends BlockSchema +> extends EventEmitter { + private sideMenuView: SideMenuView | undefined; + public readonly plugin: Plugin; + + constructor(private readonly editor: BlockNoteEditor) { + super(); + this.plugin = new Plugin({ key: sideMenuPluginKey, - view: () => { - sideMenuView = new SideMenuView(editor, tiptapEditor, updateSideMenu); - return sideMenuView; + view: (editorView) => { + this.sideMenuView = new SideMenuView( + editor, + editorView, + (sideMenuState) => { + this.emit("update", sideMenuState); + } + ); + return this.sideMenuView; }, - }), - callbacks: { - addBlock: () => sideMenuView.addBlock(), - blockDragStart: (event: DragEvent) => { - sideMenuView.isDragging = true; - dragStart(event, sideMenuView.ttEditor.view); - }, - blockDragEnd: () => unsetDragImage(), - freezeMenu: () => (sideMenuView.menuFrozen = true), - unfreezeMenu: () => (sideMenuView.menuFrozen = false), - }, + }); + } + + public onUpdate(callback: (state: SideMenuState) => void) { + return this.on("update", callback); + } + + /** + * If the block is empty, opens the slash menu. If the block has content, + * creates a new block below and opens the slash menu in it. + */ + addBlock = () => this.sideMenuView!.addBlock(); + + /** + * Handles drag & drop events for blocks. + */ + blockDragStart = (event: DragEvent) => { + this.sideMenuView!.isDragging = true; + dragStart(event, this.editor.prosemirrorView); }; + + /** + * Handles drag & drop events for blocks. + */ + blockDragEnd = () => unsetDragImage(); + /** + * Freezes the side menu. When frozen, the side menu will stay + * attached to the same block regardless of which block is hovered by the + * mouse cursor. + */ + freezeMenu = () => (this.sideMenuView!.menuFrozen = true); + /** + * Unfreezes the side menu. When frozen, the side menu will stay + * attached to the same block regardless of which block is hovered by the + * mouse cursor. + */ + unfreezeMenu = () => (this.sideMenuView!.menuFrozen = false); } diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index bc6c058b0b..a190cc3209 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -1,45 +1,51 @@ import { Plugin, PluginKey } from "prosemirror-state"; + import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { EventEmitter } from "../../shared/EventEmitter"; import { - setupSuggestionsMenu, SuggestionsMenuState, - SuggestionsMenuCallbacks, + setupSuggestionsMenu, } from "../../shared/plugins/suggestion/SuggestionPlugin"; -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; -import { Editor } from "@tiptap/core"; import { BlockSchema } from "../Blocks/api/blockTypes"; +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; export const slashMenuPluginKey = new PluginKey("SlashMenuPlugin"); -export const setupSlashMenu = < + +export class SlashMenuProsemirrorPlugin< BSchema extends BlockSchema, SlashMenuItem extends BaseSlashMenuItem ->( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateSlashMenu: ( - slashMenuState: SuggestionsMenuState - ) => void, - items: SlashMenuItem[] -): { - plugin: Plugin; - callbacks: Omit, "destroy">; -} => { - return setupSuggestionsMenu( - editor, - tiptapEditor, - updateSlashMenu, +> extends EventEmitter { + public readonly plugin: Plugin; + public readonly itemCallback: (item: SlashMenuItem) => void; + + constructor(editor: BlockNoteEditor, items: SlashMenuItem[]) { + super(); + const suggestions = setupSuggestionsMenu( + editor, + (state) => { + this.emit("update", state); + }, + slashMenuPluginKey, + "/", + (query) => + items.filter( + ({ name, aliases }: SlashMenuItem) => + name.toLowerCase().startsWith(query.toLowerCase()) || + (aliases && + aliases.filter((alias) => + alias.toLowerCase().startsWith(query.toLowerCase()) + ).length !== 0) + ), + ({ item, editor }) => item.execute(editor) + ); + + this.plugin = suggestions.plugin; + this.itemCallback = suggestions.itemCallback; + } - slashMenuPluginKey, - "/", - (query) => - items.filter( - ({ name, aliases }: SlashMenuItem) => - name.toLowerCase().startsWith(query.toLowerCase()) || - (aliases && - aliases.filter((alias) => - alias.toLowerCase().startsWith(query.toLowerCase()) - ).length !== 0) - ), - ({ item, editor }) => item.execute(editor) - ); -}; + public onUpdate( + callback: (state: SuggestionsMenuState) => void + ) { + return this.on("update", callback); + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7ecea91239..f80626d5cf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,21 +1,17 @@ export * from "./BlockNoteEditor"; export * from "./BlockNoteExtensions"; - export * from "./extensions/Blocks/api/block"; export * from "./extensions/Blocks/api/blockTypes"; export * from "./extensions/Blocks/api/defaultBlocks"; export * from "./extensions/Blocks/api/inlineContentTypes"; export * from "./extensions/Blocks/api/serialization"; - +export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; export * from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; -export * from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; -export * from "./shared/plugins/suggestion/SuggestionPlugin"; -export * from "./extensions/SlashMenu/SlashMenuPlugin"; -export * from "./shared/BaseUiElementTypes"; - -export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; - +export * from "./extensions/SideMenu/SideMenuPlugin"; export * from "./extensions/SlashMenu/BaseSlashMenuItem"; +export * from "./extensions/SlashMenu/SlashMenuPlugin"; export { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; +export * from "./shared/BaseUiElementTypes"; export type { SuggestionItem } from "./shared/plugins/suggestion/SuggestionItem"; +export * from "./shared/plugins/suggestion/SuggestionPlugin"; diff --git a/packages/core/src/shared/EventEmitter.ts b/packages/core/src/shared/EventEmitter.ts new file mode 100644 index 0000000000..538473488d --- /dev/null +++ b/packages/core/src/shared/EventEmitter.ts @@ -0,0 +1,58 @@ +// from https://raw.githubusercontent.com/ueberdosis/tiptap/develop/packages/core/src/EventEmitter.ts (MIT) + +type StringKeyOf = Extract; +type CallbackType< + T extends Record, + EventName extends StringKeyOf +> = T[EventName] extends any[] ? T[EventName] : [T[EventName]]; +type CallbackFunction< + T extends Record, + EventName extends StringKeyOf +> = (...props: CallbackType) => any; + +export class EventEmitter> { + private callbacks: { [key: string]: Function[] } = {}; + + public on>( + event: EventName, + fn: CallbackFunction + ) { + if (!this.callbacks[event]) { + this.callbacks[event] = []; + } + + this.callbacks[event].push(fn); + + return () => this.off(event, fn); + } + + protected emit>( + event: EventName, + ...args: CallbackType + ) { + const callbacks = this.callbacks[event]; + + if (callbacks) { + callbacks.forEach((callback) => callback.apply(this, args)); + } + } + + public off>( + event: EventName, + fn?: CallbackFunction + ) { + const callbacks = this.callbacks[event]; + + if (callbacks) { + if (fn) { + this.callbacks[event] = callbacks.filter((callback) => callback !== fn); + } else { + delete this.callbacks[event]; + } + } + } + + protected removeAllListeners(): void { + this.callbacks = {}; + } +} diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 46c3c55461..0c63690bee 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -3,18 +3,8 @@ import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; -import { - BaseUiElementCallbacks, - BaseUiElementState, -} from "../../BaseUiElementTypes"; +import { BaseUiElementState } from "../../BaseUiElementTypes"; import { SuggestionItem } from "./SuggestionItem"; -import { Editor } from "@tiptap/core"; - -export type SuggestionsMenuCallbacks = - BaseUiElementCallbacks & { - // The function to execute when selecting a suggested item. - itemCallback: (item: T) => void; - }; export type SuggestionsMenuState = BaseUiElementState & { @@ -28,32 +18,18 @@ class SuggestionsMenuView< T extends SuggestionItem, BSchema extends BlockSchema > { - editor: BlockNoteEditor; - ttEditor: Editor; - pluginKey: PluginKey; - private suggestionsMenuState?: SuggestionsMenuState; public updateSuggestionsMenu: () => void; pluginState: SuggestionPluginState; - itemCallback: (item: T) => void; constructor( - editor: BlockNoteEditor, - tiptapEditor: Editor, - pluginKey: PluginKey, - onSelectItem: (props: { - item: T; - editor: BlockNoteEditor; - }) => void = () => {}, + private readonly editor: BlockNoteEditor, + private readonly pluginKey: PluginKey, updateSuggestionsMenu: ( suggestionsMenuState: SuggestionsMenuState ) => void = () => {} ) { - this.editor = editor; - this.ttEditor = tiptapEditor; - - this.pluginKey = pluginKey; this.pluginState = getDefaultPluginState(); this.updateSuggestionsMenu = () => { @@ -64,24 +40,6 @@ class SuggestionsMenuView< updateSuggestionsMenu(this.suggestionsMenuState); }; - this.itemCallback = (item: T) => { - this.ttEditor - .chain() - .focus() - .deleteRange({ - from: - this.pluginState.queryStartPos! - - this.pluginState.triggerCharacter!.length, - to: this.ttEditor.state.selection.from, - }) - .run(); - - onSelectItem({ - item: item, - editor: editor, - }); - }; - document.addEventListener("scroll", this.handleScroll); } @@ -190,7 +148,6 @@ export const setupSuggestionsMenu = < BSchema extends BlockSchema >( editor: BlockNoteEditor, - tiptapEditor: Editor, updateSuggestionsMenu: ( suggestionsMenuState: SuggestionsMenuState ) => void, @@ -202,10 +159,7 @@ export const setupSuggestionsMenu = < item: T; editor: BlockNoteEditor; }) => void = () => {} -): { - plugin: Plugin; - callbacks: Omit, "destroy">; -} => { +) => { // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); @@ -224,12 +178,8 @@ export const setupSuggestionsMenu = < view: () => { suggestionsPluginView = new SuggestionsMenuView( editor, - tiptapEditor, pluginKey, - (props: { item: T; editor: BlockNoteEditor }) => { - deactivate(tiptapEditor.view); - onSelectItem(props); - }, + updateSuggestionsMenu ); return suggestionsPluginView; @@ -393,12 +343,12 @@ export const setupSuggestionsMenu = < // Selects an item and closes the menu. if (event.key === "Enter") { deactivate(view); - tiptapEditor + editor._tiptapEditor .chain() .focus() .deleteRange({ from: queryStartPos! - triggerCharacter!.length, - to: tiptapEditor.state.selection.from, + to: editor._tiptapEditor.state.selection.from, }) .run(); @@ -467,24 +417,22 @@ export const setupSuggestionsMenu = < }, }, }), - callbacks: { - itemCallback: (item: T) => { - tiptapEditor - .chain() - .focus() - .deleteRange({ - from: - suggestionsPluginView.pluginState.queryStartPos! - - suggestionsPluginView.pluginState.triggerCharacter!.length, - to: tiptapEditor.state.selection.from, - }) - .run(); - - onSelectItem({ - item: item, - editor: editor, - }); - }, + itemCallback: (item: T) => { + editor._tiptapEditor + .chain() + .focus() + .deleteRange({ + from: + suggestionsPluginView.pluginState.queryStartPos! - + suggestionsPluginView.pluginState.triggerCharacter!.length, + to: editor._tiptapEditor.state.selection.from, + }) + .run(); + + onSelectItem({ + item: item, + editor: editor, + }); }, }; }; diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index ee6182884a..90b115f5ec 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -1,17 +1,20 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; -import { getBlockNoteTheme } from "./BlockNoteTheme"; import { ReactNode, useEffect, useState } from "react"; +import { getBlockNoteTheme } from "./BlockNoteTheme"; import { FormattingToolbarPositioner } from "./FormattingToolbar/components/FormattingToolbarPositioner"; import { HyperlinkToolbarPositioner } from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; -import { SlashMenuPositioner } from "./SlashMenu/components/SlashMenuPositioner"; import { SideMenuPositioner } from "./SideMenu/components/SideMenuPositioner"; +import { SlashMenuPositioner } from "./SlashMenu/components/SlashMenuPositioner"; -export function BlockNoteView(props: { - editor: BlockNoteEditor; - children?: ReactNode; -}) { +export function BlockNoteView( + props: { + editor: BlockNoteEditor; + children?: ReactNode; + } & React.HTMLAttributes +) { + const { editor, children, ...rest } = props; const [ready, setReady] = useState(false); useEffect(() => { @@ -33,10 +36,7 @@ export function BlockNoteView(props: { return ( - + {ready && (props.children || ( <> diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 86b14174cd..2db0b7d238 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -1,12 +1,11 @@ -import { FC, useEffect, useMemo, useRef, useState } from "react"; -import Tippy from "@tippyjs/react"; -import { sticky } from "tippy.js"; import { BlockNoteEditor, BlockSchema, DefaultBlockSchema, - FormattingToolbarCallbacks, } from "@blocknote/core"; +import Tippy from "@tippyjs/react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; +import { sticky } from "tippy.js"; import { DefaultFormattingToolbar } from "./DefaultFormattingToolbar"; @@ -15,6 +14,7 @@ export type FormattingToolbarProps< > = { editor: BlockNoteEditor; }; + export const FormattingToolbarPositioner = < BSchema extends BlockSchema = DefaultBlockSchema >(props: { @@ -24,16 +24,13 @@ export const FormattingToolbarPositioner = < const [show, setShow] = useState(false); const referencePos = useRef(); - const callbacks = useRef(); useEffect(() => { - callbacks.current = props.editor.createFormattingToolbar((state) => { + return props.editor.formattingToolbar.onUpdate((state) => { setShow(state.show); referencePos.current = state.referencePos; }); - - return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo( @@ -63,7 +60,9 @@ export const FormattingToolbarPositioner = < animation={"fade"} placement={"top-start"} sticky={true} - plugins={[sticky]} + plugins={tippyPlugins} /> ); }; + +const tippyPlugins = [sticky]; diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx index 1fa0a2d7e5..9f93103e43 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx @@ -1,20 +1,19 @@ -import { FC, useEffect, useMemo, useRef, useState } from "react"; -import Tippy from "@tippyjs/react"; import { - BaseUiElementCallbacks, BaseUiElementState, BlockNoteEditor, BlockSchema, DefaultBlockSchema, - HyperlinkToolbarCallbacks, + HyperlinkToolbarProsemirrorPlugin, HyperlinkToolbarState, } from "@blocknote/core"; +import Tippy from "@tippyjs/react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; import { DefaultHyperlinkToolbar } from "./DefaultHyperlinkToolbar"; -export type HyperlinkToolbarProps = Omit< - HyperlinkToolbarCallbacks, - keyof BaseUiElementCallbacks +export type HyperlinkToolbarProps = Pick< + HyperlinkToolbarProsemirrorPlugin, + "editHyperlink" | "deleteHyperlink" | "startHideTimer" | "stopHideTimer" > & Omit; @@ -29,10 +28,10 @@ export const HyperlinkToolbarPositioner = < const [text, setText] = useState(); const referencePos = useRef(); - const callbacks = useRef(); useEffect(() => { - callbacks.current = props.editor.createHyperlinkToolbar( + return props.editor.hyperlinkToolbar.on( + "update", (hyperlinkToolbarState) => { setShow(hyperlinkToolbarState.show); setUrl(hyperlinkToolbarState.url); @@ -41,8 +40,6 @@ export const HyperlinkToolbarPositioner = < referencePos.current = hyperlinkToolbarState.referencePos; } ); - - return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo( @@ -57,7 +54,7 @@ export const HyperlinkToolbarPositioner = < ); const hyperlinkToolbarElement = useMemo(() => { - if (!url || !text || !callbacks.current) { + if (!url || !text) { return null; } @@ -67,13 +64,13 @@ export const HyperlinkToolbarPositioner = < ); - }, [props.hyperlinkToolbar, text, url]); + }, [props.hyperlinkToolbar, props.editor, text, url]); return ( = - Omit & - Omit, keyof BaseUiElementState> & { - editor: BlockNoteEditor; - }; - -// export type a = { -// callbacks: SideMenuCallbacks; -// state: SideMenuState; -// }; -// -// export type b = { -// callbacks: Omit; -// state: SideMenuState; -// }; + Pick< + SideMenuProsemirrorPlugin, + | "blockDragStart" + | "blockDragEnd" + | "addBlock" + | "freezeMenu" + | "unfreezeMenu" + > & { + block: Block; + editor: BlockNoteEditor; + }; export const SideMenuPositioner = < BSchema extends BlockSchema = DefaultBlockSchema @@ -39,17 +33,13 @@ export const SideMenuPositioner = < const [block, setBlock] = useState>(); const referencePos = useRef(); - const callbacks = useRef(); useEffect(() => { - callbacks.current = props.editor.createSideMenu((sideMenuState) => { + return props.editor.sideMenu.onUpdate((sideMenuState) => { setShow(sideMenuState.show); setBlock(sideMenuState.block); - referencePos.current = sideMenuState.referencePos; }); - - return callbacks.current!.destroy; }, [props.editor]); const getReferenceClientRect = useMemo( @@ -64,7 +54,7 @@ export const SideMenuPositioner = < ); const sideMenuElement = useMemo(() => { - if (!block || !callbacks.current) { + if (!block) { return null; } @@ -74,11 +64,11 @@ export const SideMenuPositioner = < ); }, [block, props.editor, props.sideMenu]); diff --git a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx index 82a79f2308..35b79eb423 100644 --- a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -1,26 +1,21 @@ -import { FC, useEffect, useMemo, useRef, useState } from "react"; -import Tippy from "@tippyjs/react"; import { BlockNoteEditor, BlockSchema, - BaseUiElementCallbacks, - SuggestionsMenuState, - BaseUiElementState, - SuggestionsMenuCallbacks, DefaultBlockSchema, + SlashMenuProsemirrorPlugin, + SuggestionsMenuState, } from "@blocknote/core"; +import Tippy from "@tippyjs/react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { DefaultSlashMenu } from "./DefaultSlashMenu"; export type SlashMenuProps = - Omit< - SuggestionsMenuCallbacks>, - keyof BaseUiElementCallbacks - > & - Omit< + Pick, "itemCallback"> & + Pick< SuggestionsMenuState>, - keyof BaseUiElementState + "filteredItems" | "keyboardHoveredItemIndex" >; export const SlashMenuPositioner = < @@ -36,21 +31,15 @@ export const SlashMenuPositioner = < useState(); const referencePos = useRef(); - const callbacks = - useRef>>(); useEffect(() => { - callbacks.current = props.editor.createSlashMenu((slashMenuState) => { + return props.editor.slashMenu.onUpdate((slashMenuState) => { setShow(slashMenuState.show); - setFilteredItems( - slashMenuState.filteredItems as ReactSlashMenuItem[] - ); + setFilteredItems(slashMenuState.filteredItems); setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); referencePos.current = slashMenuState.referencePos; - }) as SuggestionsMenuCallbacks>; - - return callbacks.current!.destroy; + }); }, [props.editor]); const getReferenceClientRect = useMemo( @@ -65,11 +54,7 @@ export const SlashMenuPositioner = < ); const slashMenuElement = useMemo(() => { - if ( - !filteredItems || - keyboardHoveredItemIndex === undefined || - !callbacks.current - ) { + if (!filteredItems || keyboardHoveredItemIndex === undefined) { return null; } @@ -77,12 +62,17 @@ export const SlashMenuPositioner = < return ( callbacks.current!.itemCallback(item)} - keyboardHoveredItemIndex={keyboardHoveredItemIndex!} + filteredItems={filteredItems} + itemCallback={(item) => props.editor.slashMenu.itemCallback(item)} + keyboardHoveredItemIndex={keyboardHoveredItemIndex} /> ); - }, [filteredItems, keyboardHoveredItemIndex, props.slashMenu]); + }, [ + filteredItems, + keyboardHoveredItemIndex, + props.editor.slashMenu, + props.slashMenu, + ]); return (