diff --git a/examples/vanilla/src/main.tsx b/examples/vanilla/src/main.tsx index 28a1478fb2..97b8c0131e 100644 --- a/examples/vanilla/src/main.tsx +++ b/examples/vanilla/src/main.tsx @@ -1,22 +1,12 @@ import { BlockNoteEditor } from "@blocknote/core"; import "./index.css"; -import { blockSideMenuFactory } from "./ui/blockSideMenuFactory"; -import { formattingToolbarFactory } from "./ui/formattingToolbarFactory"; -import { hyperlinkToolbarFactory } from "./ui/hyperlinkToolbarFactory"; -import { slashMenuFactory } from "./ui/slashMenuFactory"; +import { addSideMenu } from "./ui/addSideMenu"; +import { addFormattingToolbar } from "./ui/addFormattingToolbar"; +import { addSlashMenu } from "./ui/addSlashMenu"; +import { addHyperlinkToolbar } from "./ui/addHyperlinkToolbar"; const editor = new BlockNoteEditor({ parentElement: document.getElementById("root")!, - uiFactories: { - // Create an example formatting toolbar which just consists of a bold toggle - formattingToolbarFactory, - // Create an example menu for hyperlinks - hyperlinkToolbarFactory, - // Create an example menu for the /-menu - slashMenuFactory: slashMenuFactory, - // Create an example menu for when a block is hovered - blockSideMenuFactory, - }, onEditorContentChange: () => { console.log(editor.topLevelBlocks); }, @@ -26,3 +16,8 @@ const editor = new BlockNoteEditor({ }); console.log("editor created", editor); + +addSideMenu(editor); +addFormattingToolbar(editor); +addSlashMenu(editor); +addHyperlinkToolbar(editor); diff --git a/examples/vanilla/src/ui/addFormattingToolbar.ts b/examples/vanilla/src/ui/addFormattingToolbar.ts new file mode 100644 index 0000000000..bae8673512 --- /dev/null +++ b/examples/vanilla/src/ui/addFormattingToolbar.ts @@ -0,0 +1,43 @@ +import { BlockNoteEditor } from "@blocknote/core"; +import { createButton } from "./util"; + +export const addFormattingToolbar = (editor: BlockNoteEditor) => { + let element: HTMLElement; + let boldBtn: HTMLAnchorElement; + + editor.formattingToolbar.onUpdate((formattingToolbarState) => { + if (!element) { + element = document.createElement("div"); + element.style.background = "gray"; + element.style.position = "absolute"; + element.style.padding = "10px"; + element.style.opacity = "0.8"; + boldBtn = createButton("set bold", () => { + editor.toggleStyles({ bold: true }); + }); + element.appendChild(boldBtn); + + const linkBtn = createButton("set link", () => { + editor.createLink("https://www.google.com"); + }); + + element.appendChild(boldBtn); + element.appendChild(linkBtn); + element.style.display = "none"; + + document.getElementById("root")!.appendChild(element); + } + + if (formattingToolbarState.show) { + element.style.display = "block"; + + boldBtn.text = + "bold" in editor.getActiveStyles() ? "unset bold" : "set bold"; + element.style.top = formattingToolbarState.referencePos.top + "px"; + element.style.left = + formattingToolbarState.referencePos.x - element.offsetWidth + "px"; + } else { + element.style.display = "none"; + } + }); +}; diff --git a/examples/vanilla/src/ui/addHyperlinkToolbar.ts b/examples/vanilla/src/ui/addHyperlinkToolbar.ts new file mode 100644 index 0000000000..866ba7c24c --- /dev/null +++ b/examples/vanilla/src/ui/addHyperlinkToolbar.ts @@ -0,0 +1,46 @@ +import { BlockNoteEditor } from "@blocknote/core"; +import { createButton } from "./util"; + +export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { + let element: HTMLElement; + + editor.hyperlinkToolbar.onUpdate((hyperlinkToolbarState) => { + if (!element) { + element = document.createElement("div"); + element.style.background = "gray"; + element.style.position = "absolute"; + element.style.padding = "10px"; + element.style.opacity = "0.8"; + + let url = hyperlinkToolbarState.url; + let text = hyperlinkToolbarState.text; + + const editBtn = createButton("edit", () => { + const newUrl = prompt("new url") || url; + editor.hyperlinkToolbar.editHyperlink(newUrl, text); + }); + + element.appendChild(editBtn); + + const removeBtn = createButton("remove", () => { + editor.hyperlinkToolbar.deleteHyperlink(); + }); + + element.appendChild(editBtn); + element.appendChild(removeBtn); + element.style.display = "none"; + + document.getElementById("root")!.appendChild(element); + } + + if (hyperlinkToolbarState.show) { + element.style.display = "block"; + + element.style.top = hyperlinkToolbarState.referencePos.top + "px"; + element.style.left = + hyperlinkToolbarState.referencePos.x - element.offsetWidth + "px"; + } else { + element.style.display = "none"; + } + }); +}; diff --git a/examples/vanilla/src/ui/addSideMenu.ts b/examples/vanilla/src/ui/addSideMenu.ts new file mode 100644 index 0000000000..de277aabcc --- /dev/null +++ b/examples/vanilla/src/ui/addSideMenu.ts @@ -0,0 +1,42 @@ +import { BlockNoteEditor } from "@blocknote/core"; +import { createButton } from "./util"; + +export const addSideMenu = (editor: BlockNoteEditor) => { + let element: HTMLElement; + + editor.sideMenu.onUpdate((sideMenuState) => { + if (!element) { + element = document.createElement("div"); + element.style.background = "gray"; + element.style.position = "absolute"; + element.style.padding = "10px"; + element.style.opacity = "0.8"; + const addBtn = createButton("+", () => { + editor.sideMenu.addBlock(); + }); + element.appendChild(addBtn); + + const dragBtn = createButton("::", () => { + // TODO: render a submenu with a delete option that calls "props.deleteBlock" + }); + + dragBtn.addEventListener("dragstart", editor.sideMenu.blockDragStart); + dragBtn.addEventListener("dragend", editor.sideMenu.blockDragEnd); + dragBtn.draggable = true; + element.style.display = "none"; + element.appendChild(dragBtn); + + document.getElementById("root")!.appendChild(element); + } + + if (sideMenuState.show) { + element.style.display = "block"; + + element.style.top = sideMenuState.referencePos.top + "px"; + element.style.left = + sideMenuState.referencePos.x - element.offsetWidth + "px"; + } else { + element.style.display = "none"; + } + }); +}; diff --git a/examples/vanilla/src/ui/addSlashMenu.ts b/examples/vanilla/src/ui/addSlashMenu.ts new file mode 100644 index 0000000000..3ecbd7fc46 --- /dev/null +++ b/examples/vanilla/src/ui/addSlashMenu.ts @@ -0,0 +1,59 @@ +import { + BaseSlashMenuItem, + BlockNoteEditor, + DefaultBlockSchema, +} from "@blocknote/core"; +import { createButton } from "./util"; + +export const addSlashMenu = (editor: BlockNoteEditor) => { + let element: HTMLElement; + + function updateItems( + items: BaseSlashMenuItem[], + onClick: (item: BaseSlashMenuItem) => void, + selected: number + ) { + element.innerHTML = ""; + const domItems = items.map((val, i) => { + const element = createButton(val.name, () => { + onClick(val); + }); + element.style.display = "block"; + if (selected === i) { + element.style.fontWeight = "bold"; + } + return element; + }); + element.append(...domItems); + return domItems; + } + + editor.slashMenu.onUpdate((slashMenuState) => { + if (!element) { + element = document.createElement("div"); + element.style.background = "gray"; + element.style.position = "absolute"; + element.style.padding = "10px"; + element.style.opacity = "0.8"; + element.style.display = "none"; + + document.getElementById("root")!.appendChild(element); + } + + if (slashMenuState.show) { + updateItems( + slashMenuState.filteredItems, + editor.slashMenu.itemCallback, + slashMenuState.keyboardHoveredItemIndex + ); + + element.style.display = "block"; + + element.style.top = slashMenuState.referencePos.top + "px"; + element.style.left = + slashMenuState.referencePos.x - element.offsetWidth + "px"; + } else { + element.style.display = "none"; + } + }); +}; diff --git a/examples/vanilla/src/ui/blockSideMenuFactory.ts b/examples/vanilla/src/ui/blockSideMenuFactory.ts deleted file mode 100644 index 799b648476..0000000000 --- a/examples/vanilla/src/ui/blockSideMenuFactory.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { BlockSideMenuFactory, DefaultBlockSchema } from "@blocknote/core"; -import { createButton } from "./util"; - -/** - * This menu is drawn next to a block, when it's hovered over - * It renders a drag handle and + button to create a new block - */ -export const blockSideMenuFactory: BlockSideMenuFactory = ( - staticParams -) => { - const container = document.createElement("div"); - container.style.background = "gray"; - container.style.position = "absolute"; - container.style.padding = "10px"; - container.style.opacity = "0.8"; - const addBtn = createButton("+", () => { - staticParams.addBlock(); - }); - container.appendChild(addBtn); - - const dragBtn = createButton("::", () => { - // TODO: render a submenu with a delete option that calls "props.deleteBlock" - }); - - dragBtn.addEventListener("dragstart", staticParams.blockDragStart); - dragBtn.addEventListener("dragend", staticParams.blockDragEnd); - dragBtn.draggable = true; - container.style.display = "none"; - container.appendChild(dragBtn); - - document.body.appendChild(container); - - return { - element: container, - render: (params, isHidden) => { - if (isHidden) { - container.style.display = "block"; - } - - container.style.top = staticParams.getReferenceRect()!.y + "px"; - container.style.left = - staticParams.getReferenceRect()!.x - container.offsetWidth + "px"; - }, - hide: () => { - container.style.display = "none"; - }, - }; -}; diff --git a/examples/vanilla/src/ui/formattingToolbarFactory.ts b/examples/vanilla/src/ui/formattingToolbarFactory.ts deleted file mode 100644 index d64600f9c5..0000000000 --- a/examples/vanilla/src/ui/formattingToolbarFactory.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { DefaultBlockSchema, FormattingToolbarFactory } from "@blocknote/core"; -import { createButton } from "./util"; - -/** - * This menu is drawn when a piece of text is selected. We can use it to change formatting options - * such as bold, italic, indentation, etc. - */ -export const formattingToolbarFactory: FormattingToolbarFactory< - DefaultBlockSchema -> = (staticParams) => { - const container = document.createElement("div"); - container.style.background = "gray"; - container.style.position = "absolute"; - container.style.padding = "10px"; - container.style.opacity = "0.8"; - const boldBtn = createButton("set bold", () => { - staticParams.editor.toggleStyles({ bold: true }); - }); - container.appendChild(boldBtn); - - const linkBtn = createButton("set link", () => { - staticParams.editor.createLink("https://www.google.com"); - }); - - container.appendChild(boldBtn); - container.appendChild(linkBtn); - container.style.display = "none"; - document.body.appendChild(container); - - return { - element: container, - render: (params, isHidden) => { - if (isHidden) { - container.style.display = "block"; - } - - boldBtn.text = - "bold" in staticParams.editor.getActiveStyles() - ? "unset bold" - : "set bold"; - container.style.top = staticParams.getReferenceRect()!.y + "px"; - container.style.left = staticParams.getReferenceRect()!.x + "px"; - }, - hide: () => { - container.style.display = "none"; - }, - }; -}; diff --git a/examples/vanilla/src/ui/hyperlinkToolbarFactory.ts b/examples/vanilla/src/ui/hyperlinkToolbarFactory.ts deleted file mode 100644 index 7450e73bcb..0000000000 --- a/examples/vanilla/src/ui/hyperlinkToolbarFactory.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { HyperlinkToolbarFactory } from "@blocknote/core"; -import { createButton } from "./util"; - -/** - * This menu is drawn when the cursor is moved to a hyperlink (using the keyboard), - * or when the mouse is hovering over a hyperlink - */ -export const hyperlinkToolbarFactory: HyperlinkToolbarFactory = ( - staticParams -) => { - const container = document.createElement("div"); - container.style.background = "gray"; - container.style.position = "absolute"; - container.style.padding = "10px"; - container.style.opacity = "0.8"; - - let url = ""; - let text = ""; - - const editBtn = createButton("edit", () => { - const newUrl = prompt("new url") || url; - staticParams.editHyperlink(newUrl, text); - }); - - container.appendChild(editBtn); - - const removeBtn = createButton("remove", () => { - staticParams.deleteHyperlink(); - }); - - container.appendChild(editBtn); - container.appendChild(removeBtn); - container.style.display = "none"; - document.body.appendChild(container); - - return { - element: container, - render: (params, isHidden) => { - if (isHidden) { - url = params.url; - text = params.text; - - container.style.display = "block"; - } - - container.style.top = staticParams.getReferenceRect()!.y + "px"; - container.style.left = staticParams.getReferenceRect()!.x + "px"; - }, - hide: () => { - container.style.display = "none"; - }, - }; -}; diff --git a/examples/vanilla/src/ui/slashMenuFactory.ts b/examples/vanilla/src/ui/slashMenuFactory.ts deleted file mode 100644 index aba00536bd..0000000000 --- a/examples/vanilla/src/ui/slashMenuFactory.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { - BaseSlashMenuItem, - DefaultBlockSchema, - SuggestionsMenuFactory, -} from "@blocknote/core"; -import { createButton } from "./util"; - -/** - * This menu is drawn when the cursor is moved to a hyperlink (using the keyboard), - * or when the mouse is hovering over a hyperlink - */ -export const slashMenuFactory: SuggestionsMenuFactory< - BaseSlashMenuItem -> = (staticParams) => { - const container = document.createElement("div"); - container.style.background = "gray"; - container.style.position = "absolute"; - container.style.padding = "10px"; - container.style.opacity = "0.8"; - container.style.display = "none"; - document.body.appendChild(container); - - function updateItems( - items: BaseSlashMenuItem[], - onClick: (item: BaseSlashMenuItem) => void, - selected: number - ) { - container.innerHTML = ""; - const domItems = items.map((val, i) => { - const element = createButton(val.name, () => { - onClick(val); - }); - element.style.display = "block"; - if (selected === i) { - element.style.fontWeight = "bold"; - } - return element; - }); - container.append(...domItems); - return domItems; - } - - return { - element: container, - render: (params, isHidden) => { - updateItems( - params.items, - staticParams.itemCallback, - params.keyboardHoveredItemIndex - ); - - if (isHidden) { - container.style.display = "block"; - } - - container.style.top = staticParams.getReferenceRect()!.y + "px"; - container.style.left = staticParams.getReferenceRect()!.x + "px"; - }, - hide: () => { - container.style.display = "none"; - }, - }; -}; diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 87fe240136..524967c824 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -1,8 +1,9 @@ -import { Editor, EditorOptions } from "@tiptap/core"; +import { Editor, EditorOptions, Extension } from "@tiptap/core"; import { Node } from "prosemirror-model"; // import "./blocknote.css"; import { Editor as TiptapEditor } from "@tiptap/core/dist/packages/core/src/Editor"; import * as Y from "yjs"; +import { getBlockNoteExtensions } from "./BlockNoteExtensions"; import { insertBlocks, removeBlocks, @@ -10,14 +11,16 @@ import { updateBlock, } from "./api/blockManipulation/blockManipulation"; import { + HTMLToBlocks, blocksToHTML, blocksToMarkdown, - HTMLToBlocks, markdownToBlocks, } from "./api/formatConversions/formatConversions"; -import { nodeToBlock } from "./api/nodeConversions/nodeConversions"; +import { + blockToNode, + nodeToBlock, +} from "./api/nodeConversions/nodeConversions"; import { getNodeById } from "./api/util/nodeUtil"; -import { getBlockNoteExtensions, UiFactories } from "./BlockNoteExtensions"; import styles from "./editor.module.css"; import { Block, @@ -37,28 +40,25 @@ import { } from "./extensions/Blocks/api/inlineContentTypes"; import { Selection } from "./extensions/Blocks/api/selectionTypes"; import { getBlockInfoFromPos } from "./extensions/Blocks/helpers/getBlockInfoFromPos"; -import { - BaseSlashMenuItem, - defaultSlashMenuItems, -} from "./extensions/SlashMenu"; + +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"; +import { UniqueID } from "./extensions/UniqueID/UniqueID"; export type BlockNoteEditorOptions = { // TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them. enableBlockNoteExtensions: boolean; - /** - * UI element factories for creating a custom UI, including custom positioning - * & rendering. - */ - uiFactories: UiFactories; - /** - * TODO: why is this called slashCommands and not slashMenuItems? * * (couldn't fix any type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771) * * @default defaultSlashMenuItems from `./extensions/SlashMenu` */ - slashCommands: BaseSlashMenuItem[]; + slashMenuItems: BaseSlashMenuItem[]; /** * The HTML element that should be used as the parent element for the editor. @@ -149,19 +149,12 @@ export class BlockNoteEditor { public readonly _tiptapEditor: TiptapEditor & { contentComponent: any }; public blockCache = new WeakMap>(); public readonly schema: BSchema; - private ready = false; - - public get domElement() { - return this._tiptapEditor.view.dom as HTMLDivElement; - } + public ready = false; - public isFocused() { - return this._tiptapEditor.view.hasFocus(); - } - - public focus() { - this._tiptapEditor.view.focus(); - } + public readonly sideMenu: SideMenuProsemirrorPlugin; + public readonly formattingToolbar: FormattingToolbarProsemirrorPlugin; + public readonly slashMenu: SlashMenuProsemirrorPlugin; + public readonly hyperlinkToolbar: HyperlinkToolbarProsemirrorPlugin; constructor( private readonly options: Partial> = {} @@ -181,32 +174,65 @@ export class BlockNoteEditor { ...options, }; + this.sideMenu = new SideMenuProsemirrorPlugin(this); + this.formattingToolbar = new FormattingToolbarProsemirrorPlugin(this); + this.slashMenu = new SlashMenuProsemirrorPlugin( + this, + newOptions.slashMenuItems || + getDefaultSlashMenuItems(newOptions.blockSchema) + ); + this.hyperlinkToolbar = new HyperlinkToolbarProsemirrorPlugin(this); + const extensions = getBlockNoteExtensions({ editor: this, - uiFactories: newOptions.uiFactories || {}, - slashCommands: newOptions.slashCommands || defaultSlashMenuItems, blockSchema: newOptions.blockSchema, collaboration: newOptions.collaboration, }); + const blockNoteUIExtension = Extension.create({ + name: "BlockNoteUIExtension", + + addProseMirrorPlugins: () => { + return [ + this.sideMenu.plugin, + this.formattingToolbar.plugin, + this.slashMenu.plugin, + this.hyperlinkToolbar.plugin, + ]; + }, + }); + extensions.push(blockNoteUIExtension); + this.schema = newOptions.blockSchema; + const initialContent = newOptions.initialContent || [ + { + type: "paragraph", + id: UniqueID.options.generateID(), + }, + ]; + const tiptapOptions: EditorOptions = { - // TODO: This approach to setting initial content is "cleaner" but requires the PM editor schema, which is only - // created after initializing the TipTap editor. Not sure it's feasible. - // content: - // options.initialContent && - // options.initialContent.map((block) => - // blockToNode(block, this._tiptapEditor.schema).toJSON() - // ), ...blockNoteTipTapOptions, ...newOptions._tiptapOptions, onCreate: () => { newOptions.onEditorReady?.(this); - newOptions.initialContent && - this.replaceBlocks(this.topLevelBlocks, newOptions.initialContent); this.ready = true; }, + onBeforeCreate(editor) { + // we have to set the initial content here, because now we can use the editor schema + // which has been created at this point + const schema = editor.editor.schema; + const ic = initialContent.map((block) => blockToNode(block, schema)); + + const root = schema.node( + "doc", + undefined, + schema.node("blockGroup", undefined, ic) + ); + // override the initialcontent + editor.editor.options.content = root.toJSON(); + }, onUpdate: () => { // This seems to be necessary due to a bug in TipTap: // https://github.com/ueberdosis/tiptap/issues/2583 @@ -253,6 +279,22 @@ export class BlockNoteEditor { }; } + public get prosemirrorView() { + return this._tiptapEditor.view; + } + + public get domElement() { + return this._tiptapEditor.view.dom as HTMLDivElement; + } + + public isFocused() { + return this._tiptapEditor.view.hasFocus(); + } + + public focus() { + this._tiptapEditor.view.focus(); + } + /** * 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. @@ -344,6 +386,14 @@ export class BlockNoteEditor { this._tiptapEditor.on("update", callback); } + /** + * Executes a callback whenever the editor's selection changes. + * @param callback The callback to execute. + */ + public onEditorSelectionChange(callback: () => void) { + this._tiptapEditor.on("selectionUpdate", callback); + } + /** * Gets a snapshot of the current text cursor position. * @returns A snapshot of the current text cursor position. diff --git a/packages/core/src/BlockNoteExtensions.ts b/packages/core/src/BlockNoteExtensions.ts index f26deb9774..9dba2510f2 100644 --- a/packages/core/src/BlockNoteExtensions.ts +++ b/packages/core/src/BlockNoteExtensions.ts @@ -23,38 +23,18 @@ import { blocks } from "./extensions/Blocks"; import { BlockSchema } from "./extensions/Blocks/api/blockTypes"; import { CustomBlockSerializerExtension } from "./extensions/Blocks/api/serialization"; import blockStyles from "./extensions/Blocks/nodes/Block.module.css"; -import { BlockSideMenuFactory } from "./extensions/DraggableBlocks/BlockSideMenuFactoryTypes"; -import { createDraggableBlocksExtension } from "./extensions/DraggableBlocks/DraggableBlocksExtension"; -import { createFormattingToolbarExtension } from "./extensions/FormattingToolbar/FormattingToolbarExtension"; -import { FormattingToolbarFactory } from "./extensions/FormattingToolbar/FormattingToolbarFactoryTypes"; -import HyperlinkMark from "./extensions/HyperlinkToolbar/HyperlinkMark"; -import { HyperlinkToolbarFactory } from "./extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes"; import { Placeholder } from "./extensions/Placeholder/PlaceholderExtension"; -import { - BaseSlashMenuItem, - createSlashMenuExtension, -} from "./extensions/SlashMenu"; import { TextAlignmentExtension } from "./extensions/TextAlignment/TextAlignmentExtension"; import { TextColorExtension } from "./extensions/TextColor/TextColorExtension"; import { TextColorMark } from "./extensions/TextColor/TextColorMark"; import { TrailingNode } from "./extensions/TrailingNode/TrailingNodeExtension"; import UniqueID from "./extensions/UniqueID/UniqueID"; -import { SuggestionsMenuFactory } from "./shared/plugins/suggestion/SuggestionsMenuFactoryTypes"; - -export type UiFactories = Partial<{ - formattingToolbarFactory: FormattingToolbarFactory; - hyperlinkToolbarFactory: HyperlinkToolbarFactory; - slashMenuFactory: SuggestionsMenuFactory>; - blockSideMenuFactory: BlockSideMenuFactory; -}>; /** * Get all the Tiptap extensions BlockNote is configured with by default */ export const getBlockNoteExtensions = (opts: { editor: BlockNoteEditor; - uiFactories: UiFactories; - slashCommands: BaseSlashMenuItem[]; // couldn't fix type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771 blockSchema: BSchema; collaboration?: { fragment: Y.XmlFragment; @@ -99,6 +79,7 @@ export const getBlockNoteExtensions = (opts: { Italic, Strike, Underline, + Link, TextColorMark, TextColorExtension, BackgroundColorMark, @@ -155,43 +136,5 @@ export const getBlockNoteExtensions = (opts: { ret.push(History); } - if (opts.uiFactories.blockSideMenuFactory) { - ret.push( - createDraggableBlocksExtension().configure({ - editor: opts.editor, - blockSideMenuFactory: opts.uiFactories.blockSideMenuFactory, - }) - ); - } - - if (opts.uiFactories.formattingToolbarFactory) { - ret.push( - createFormattingToolbarExtension().configure({ - editor: opts.editor, - formattingToolbarFactory: opts.uiFactories.formattingToolbarFactory, - }) - ); - } - - if (opts.uiFactories.hyperlinkToolbarFactory) { - ret.push( - HyperlinkMark.configure({ - hyperlinkToolbarFactory: opts.uiFactories.hyperlinkToolbarFactory, - }) - ); - } else { - ret.push(Link); - } - - if (opts.uiFactories.slashMenuFactory) { - ret.push( - createSlashMenuExtension().configure({ - editor: opts.editor, - commands: opts.slashCommands, - slashMenuFactory: opts.uiFactories.slashMenuFactory, - }) - ); - } - return ret; }; diff --git a/packages/core/src/api/formatConversions/__snapshots__/formatConversions.test.ts.snap b/packages/core/src/api/formatConversions/__snapshots__/formatConversions.test.ts.snap index dbc0b0741e..f3b3ccee94 100644 --- a/packages/core/src/api/formatConversions/__snapshots__/formatConversions.test.ts.snap +++ b/packages/core/src/api/formatConversions/__snapshots__/formatConversions.test.ts.snap @@ -65,7 +65,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested HTML to "type": "text", }, ], - "id": "27", + "id": "1", "props": { "backgroundColor": "default", "level": "1", @@ -83,7 +83,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested HTML to "type": "text", }, ], - "id": "28", + "id": "2", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -100,7 +100,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested HTML to "type": "text", }, ], - "id": "29", + "id": "3", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -117,7 +117,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested HTML to "type": "text", }, ], - "id": "30", + "id": "4", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -139,7 +139,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested Markdow "type": "text", }, ], - "id": "27", + "id": "1", "props": { "backgroundColor": "default", "level": "1", @@ -157,7 +157,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested Markdow "type": "text", }, ], - "id": "28", + "id": "2", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -174,7 +174,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested Markdow "type": "text", }, ], - "id": "29", + "id": "3", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -191,7 +191,7 @@ exports[`Non-Nested Block/HTML/Markdown Conversions > Convert non-nested Markdow "type": "text", }, ], - "id": "30", + "id": "4", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -271,7 +271,7 @@ exports[`Styled Block/HTML/Markdown Conversions > Convert styled HTML to blocks "type": "text", }, ], - "id": "27", + "id": "1", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -327,7 +327,7 @@ exports[`Styled Block/HTML/Markdown Conversions > Convert styled Markdown to blo "type": "text", }, ], - "id": "27", + "id": "1", "props": { "backgroundColor": "default", "textAlignment": "left", diff --git a/packages/core/src/api/formatConversions/formatConversions.test.ts b/packages/core/src/api/formatConversions/formatConversions.test.ts index 0d8e4054c1..ab986bce7b 100644 --- a/packages/core/src/api/formatConversions/formatConversions.test.ts +++ b/packages/core/src/api/formatConversions/formatConversions.test.ts @@ -1,662 +1,587 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { Block, BlockNoteEditor } from "../.."; import UniqueID from "../../extensions/UniqueID/UniqueID"; -import { DefaultBlockSchema } from "../../extensions/Blocks/api/defaultBlocks"; let editor: BlockNoteEditor; -let nonNestedBlocks: Block[]; -let nonNestedHTML: string; -let nonNestedMarkdown: string; - -let nestedBlocks: Block[]; -// let nestedHTML: string; -// let nestedMarkdown: string; - -let styledBlocks: Block[]; -let styledHTML: string; -let styledMarkdown: string; - -let complexBlocks: Block[]; -// let complexHTML: string; -// let complexMarkdown: string; - -function removeInlineContentClass(html: string) { - return html.replace(/ class="_inlineContent_1c48ad"/g, ""); -} - -beforeEach(() => { - (window as Window & { __TEST_OPTIONS?: {} }).__TEST_OPTIONS = {}; - - editor = new BlockNoteEditor(); - - nonNestedBlocks = [ - { - id: UniqueID.options.generateID(), - type: "heading", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", - level: "1", +const getNonNestedBlocks = (): Block[] => [ + { + id: UniqueID.options.generateID(), + type: "heading", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", + level: "1", + }, + content: [ + { + type: "text", + text: "Heading", + styles: {}, }, - content: [ - { - type: "text", - text: "Heading", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "paragraph", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "paragraph", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Paragraph", + styles: {}, }, - content: [ - { - type: "text", - text: "Paragraph", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "numberedListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "numberedListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Numbered List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Numbered List Item", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, +]; + +const getNestedBlocks = (): Block[] => [ + { + id: UniqueID.options.generateID(), + type: "heading", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", + level: "1", }, - ]; - nonNestedHTML = `

Heading

Paragraph

  • Bullet List Item

  1. Numbered List Item

`; - nonNestedMarkdown = `# Heading - -Paragraph - -* Bullet List Item - -1. Numbered List Item -`; - - nestedBlocks = [ - { - id: UniqueID.options.generateID(), - type: "heading", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", - level: "1", + content: [ + { + type: "text", + text: "Heading", + styles: {}, }, - content: [ - { - type: "text", - text: "Heading", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "paragraph", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "paragraph", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Paragraph", + styles: {}, }, - content: [ - { - type: "text", - text: "Paragraph", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "numberedListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "numberedListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Numbered List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Numbered List Item", - styles: {}, - }, - ], - children: [], - }, - ], - }, - ], - }, - ], - }, - ]; - // nestedHTML = `

Heading

Paragraph

  • Bullet List Item

    1. Numbered List Item

`; - // nestedMarkdown = `# Heading - // - // Paragraph - // - // * Bullet List Item - // - // 1. Numbered List Item - // `; - - styledBlocks = [ - { - id: UniqueID.options.generateID(), - type: "paragraph", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", - }, - content: [ - { - type: "text", - text: "Bold", - styles: { - bold: true, + ], + children: [], + }, + ], }, + ], + }, + ], + }, +]; + +const getStyledBlocks = (): Block[] => [ + { + id: UniqueID.options.generateID(), + type: "paragraph", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", + }, + content: [ + { + type: "text", + text: "Bold", + styles: { + bold: true, }, - { - type: "text", - text: "Italic", - styles: { - italic: true, - }, + }, + { + type: "text", + text: "Italic", + styles: { + italic: true, }, - { - type: "text", - text: "Underline", - styles: { - underline: true, - }, + }, + { + type: "text", + text: "Underline", + styles: { + underline: true, }, - { - type: "text", - text: "Strikethrough", - styles: { - strike: true, - }, + }, + { + type: "text", + text: "Strikethrough", + styles: { + strike: true, }, - { - type: "text", - text: "TextColor", - styles: { - textColor: "red", - }, + }, + { + type: "text", + text: "TextColor", + styles: { + textColor: "red", }, - { - type: "text", - text: "BackgroundColor", - styles: { - backgroundColor: "red", - }, + }, + { + type: "text", + text: "BackgroundColor", + styles: { + backgroundColor: "red", }, - { - type: "text", - text: "Multiple", - styles: { - bold: true, - italic: true, - }, + }, + { + type: "text", + text: "Multiple", + styles: { + bold: true, + italic: true, }, - ], - children: [], + }, + ], + children: [], + }, +]; + +const getComplexBlocks = (): Block[] => [ + { + id: UniqueID.options.generateID(), + type: "heading", + props: { + backgroundColor: "red", + textColor: "yellow", + textAlignment: "right", + level: "1", }, - ]; - styledHTML = `

BoldItalicUnderlineStrikethroughTextColorBackgroundColorMultiple

`; - styledMarkdown = `**Bold***Italic*Underline~~Strikethrough~~TextColorBackgroundColor***Multiple***`; - - complexBlocks = [ - { - id: UniqueID.options.generateID(), - type: "heading", - props: { - backgroundColor: "red", - textColor: "yellow", - textAlignment: "right", - level: "1", + content: [ + { + type: "text", + text: "Heading 1", + styles: {}, }, - content: [ - { - type: "text", - text: "Heading 1", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "heading", + props: { + backgroundColor: "orange", + textColor: "orange", + textAlignment: "center", + level: "2", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "heading", - props: { - backgroundColor: "orange", - textColor: "orange", - textAlignment: "center", - level: "2", + content: [ + { + type: "text", + text: "Heading 2", + styles: {}, }, - content: [ - { - type: "text", - text: "Heading 2", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "heading", + props: { + backgroundColor: "yellow", + textColor: "red", + textAlignment: "left", + level: "3", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "heading", - props: { - backgroundColor: "yellow", - textColor: "red", - textAlignment: "left", - level: "3", + content: [ + { + type: "text", + text: "Heading 3", + styles: {}, }, - content: [ - { - type: "text", - text: "Heading 3", - styles: {}, - }, - ], - children: [], - }, - ], - }, - ], - }, - { - id: UniqueID.options.generateID(), - type: "paragraph", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", - }, - content: [ - { - type: "text", - text: "Paragraph", - styles: { - textColor: "purple", - backgroundColor: "green", + ], + children: [], }, + ], + }, + ], + }, + { + id: UniqueID.options.generateID(), + type: "paragraph", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", + }, + content: [ + { + type: "text", + text: "Paragraph", + styles: { + textColor: "purple", + backgroundColor: "green", }, - ], - children: [], + }, + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "paragraph", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "paragraph", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "P", + styles: {}, }, - content: [ - { - type: "text", - text: "P", - styles: {}, - }, - { - type: "text", - text: "ara", - styles: { - bold: true, - }, + { + type: "text", + text: "ara", + styles: { + bold: true, }, - { - type: "text", - text: "grap", - styles: { - italic: true, - }, - }, - { - type: "text", - text: "h", - styles: {}, + }, + { + type: "text", + text: "grap", + styles: { + italic: true, }, - ], - children: [], + }, + { + type: "text", + text: "h", + styles: {}, + }, + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "paragraph", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "paragraph", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "P", + styles: {}, }, - content: [ - { - type: "text", - text: "P", - styles: {}, - }, - { - type: "text", - text: "ara", - styles: { - underline: true, - }, - }, - { - type: "text", - text: "grap", - styles: { - strike: true, - }, + { + type: "text", + text: "ara", + styles: { + underline: true, }, - { - type: "text", - text: "h", - styles: {}, + }, + { + type: "text", + text: "grap", + styles: { + strike: true, }, - ], - children: [], + }, + { + type: "text", + text: "h", + styles: {}, + }, + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "paragraph", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "paragraph", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Paragraph", + styles: {}, }, - content: [ - { - type: "text", - text: "Paragraph", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "numberedListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "numberedListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Numbered List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Numbered List Item", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "numberedListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "numberedListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Numbered List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Numbered List Item", - styles: {}, - }, - ], - children: [], + ], + children: [], + }, + { + id: UniqueID.options.generateID(), + type: "numberedListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - { - id: UniqueID.options.generateID(), - type: "numberedListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Numbered List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Numbered List Item", - styles: {}, + ], + children: [ + { + id: UniqueID.options.generateID(), + type: "numberedListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [ - { - id: UniqueID.options.generateID(), - type: "numberedListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Numbered List Item", + styles: {}, }, - content: [ - { - type: "text", - text: "Numbered List Item", - styles: {}, - }, - ], - children: [], - }, - ], - }, - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + ], + children: [], }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, - }, - ], - children: [], - }, - ], - }, - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + ], }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [], - }, - ], - }, - { - id: UniqueID.options.generateID(), - type: "bulletListItem", - props: { - backgroundColor: "default", - textColor: "default", - textAlignment: "left", + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, + }, + ], + children: [], + }, + ], }, - content: [ - { - type: "text", - text: "Bullet List Item", - styles: {}, + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ], - children: [], + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, + }, + ], + children: [], + }, + ], + }, + { + id: UniqueID.options.generateID(), + type: "bulletListItem", + props: { + backgroundColor: "default", + textColor: "default", + textAlignment: "left", }, - ]; + content: [ + { + type: "text", + text: "Bullet List Item", + styles: {}, + }, + ], + children: [], + }, +]; - // complexHTML = `

Heading 1

Heading 2

Heading 3

Paragraph

Paragraph

Paragraph

  • Bullet List Item

  • Bullet List Item

    • Bullet List Item

      • Bullet List Item

      Paragraph

      1. Numbered List Item

      2. Numbered List Item

      3. Numbered List Item

        1. Numbered List Item

      • Bullet List Item

    • Bullet List Item

  • Bullet List Item

`; - // complexMarkdown = `# Heading 1 - // - // ## Heading 2 - // - // ### Heading 3 - // - // Paragraph - // - // P**ara***grap*h - // - // P*ara*~~grap~~h - // - // * Bullet List Item - // - // * Bullet List Item - // - // * Bullet List Item - // - // * Bullet List Item - // - // Paragraph - // - // 1. Numbered List Item - // - // 2. Numbered List Item - // - // 3. Numbered List Item - // - // 1. Numbered List Item - // - // * Bullet List Item - // - // * Bullet List Item - // - // * Bullet List Item - // `; +function removeInlineContentClass(html: string) { + return html.replace(/ class="_inlineContent_([a-zA-Z0-9_-])+"/g, ""); +} + +beforeEach(() => { + (window as Window & { __TEST_OPTIONS?: {} }).__TEST_OPTIONS = {}; + + editor = new BlockNoteEditor(); }); afterEach(() => { @@ -668,25 +593,34 @@ afterEach(() => { describe("Non-Nested Block/HTML/Markdown Conversions", () => { it("Convert non-nested blocks to HTML", async () => { - const output = await editor.blocksToHTML(nonNestedBlocks); + const output = await editor.blocksToHTML(getNonNestedBlocks()); expect(removeInlineContentClass(output)).toMatchSnapshot(); }); it("Convert non-nested blocks to Markdown", async () => { - const output = await editor.blocksToMarkdown(nonNestedBlocks); + const output = await editor.blocksToMarkdown(getNonNestedBlocks()); expect(output).toMatchSnapshot(); }); it("Convert non-nested HTML to blocks", async () => { - const output = await editor.HTMLToBlocks(nonNestedHTML); + const html = `

Heading

Paragraph

  • Bullet List Item

  1. Numbered List Item

`; + const output = await editor.HTMLToBlocks(html); expect(output).toMatchSnapshot(); }); it("Convert non-nested Markdown to blocks", async () => { - const output = await editor.markdownToBlocks(nonNestedMarkdown); + const markdown = `# Heading + +Paragraph + +* Bullet List Item + +1. Numbered List Item +`; + const output = await editor.markdownToBlocks(markdown); expect(output).toMatchSnapshot(); }); @@ -694,25 +628,34 @@ describe("Non-Nested Block/HTML/Markdown Conversions", () => { describe("Nested Block/HTML/Markdown Conversions", () => { it("Convert nested blocks to HTML", async () => { - const output = await editor.blocksToHTML(nestedBlocks); + const output = await editor.blocksToHTML(getNestedBlocks()); expect(removeInlineContentClass(output)).toMatchSnapshot(); }); it("Convert nested blocks to Markdown", async () => { - const output = await editor.blocksToMarkdown(nestedBlocks); + const output = await editor.blocksToMarkdown(getNestedBlocks()); expect(output).toMatchSnapshot(); }); // // Failing due to nested block parsing bug. // it("Convert nested HTML to blocks", async () => { - // const output = await editor.HTMLToBlocks(nestedHTML); + // const html = `

Heading

Paragraph

  • Bullet List Item

    1. Numbered List Item

`; + // const output = await editor.HTMLToBlocks(html); // // expect(output).toMatchSnapshot(); // }); // // Failing due to nested block parsing bug. // it("Convert nested Markdown to blocks", async () => { - // const output = await editor.markdownToBlocks(nestedMarkdown); + // const markdown = `# Heading + // + // Paragraph + // + // * Bullet List Item + // + // 1. Numbered List Item + // `; + // const output = await editor.markdownToBlocks(markdown); // // expect(output).toMatchSnapshot(); // }); @@ -720,25 +663,27 @@ describe("Nested Block/HTML/Markdown Conversions", () => { describe("Styled Block/HTML/Markdown Conversions", () => { it("Convert styled blocks to HTML", async () => { - const output = await editor.blocksToHTML(styledBlocks); + const output = await editor.blocksToHTML(getStyledBlocks()); expect(removeInlineContentClass(output)).toMatchSnapshot(); }); it("Convert styled blocks to Markdown", async () => { - const output = await editor.blocksToMarkdown(styledBlocks); + const output = await editor.blocksToMarkdown(getStyledBlocks()); expect(output).toMatchSnapshot(); }); it("Convert styled HTML to blocks", async () => { - const output = await editor.HTMLToBlocks(styledHTML); + const html = `

BoldItalicUnderlineStrikethroughTextColorBackgroundColorMultiple

`; + const output = await editor.HTMLToBlocks(html); expect(output).toMatchSnapshot(); }); it("Convert styled Markdown to blocks", async () => { - const output = await editor.markdownToBlocks(styledMarkdown); + const markdown = `**Bold***Italic*Underline~~Strikethrough~~TextColorBackgroundColor***Multiple***`; + const output = await editor.markdownToBlocks(markdown); expect(output).toMatchSnapshot(); }); @@ -746,25 +691,62 @@ describe("Styled Block/HTML/Markdown Conversions", () => { describe("Complex Block/HTML/Markdown Conversions", () => { it("Convert complex blocks to HTML", async () => { - const output = await editor.blocksToHTML(complexBlocks); + const output = await editor.blocksToHTML(getComplexBlocks()); expect(removeInlineContentClass(output)).toMatchSnapshot(); }); it("Convert complex blocks to Markdown", async () => { - const output = await editor.blocksToMarkdown(complexBlocks); + const output = await editor.blocksToMarkdown(getComplexBlocks()); expect(output).toMatchSnapshot(); }); // // Failing due to nested block parsing bug. // it("Convert complex HTML to blocks", async () => { - // const output = await editor.HTMLToBlocks(complexHTML); + // const html = `

Heading 1

Heading 2

Heading 3

Paragraph

Paragraph

Paragraph

  • Bullet List Item

  • Bullet List Item

    • Bullet List Item

      • Bullet List Item

      Paragraph

      1. Numbered List Item

      2. Numbered List Item

      3. Numbered List Item

        1. Numbered List Item

      • Bullet List Item

    • Bullet List Item

  • Bullet List Item

`; + // const output = await editor.HTMLToBlocks(html); // // expect(output).toMatchSnapshot(); // }); // // Failing due to nested block parsing bug. // it("Convert complex Markdown to blocks", async () => { - // const output = await editor.markdownToBlocks(complexMarkdown); + // const markdown = `# Heading 1 + // + // ## Heading 2 + // + // ### Heading 3 + // + // Paragraph + // + // P**ara***grap*h + // + // P*ara*~~grap~~h + // + // * Bullet List Item + // + // * Bullet List Item + // + // * Bullet List Item + // + // * Bullet List Item + // + // Paragraph + // + // 1. Numbered List Item + // + // 2. Numbered List Item + // + // 3. Numbered List Item + // + // 1. Numbered List Item + // + // * Bullet List Item + // + // * Bullet List Item + // + // * Bullet List Item + // `; + // const output = await editor.markdownToBlocks(markdown); // // expect(output).toMatchSnapshot(); // }); diff --git a/packages/core/src/api/nodeConversions/__snapshots__/nodeConversions.test.ts.snap b/packages/core/src/api/nodeConversions/__snapshots__/nodeConversions.test.ts.snap index 668f67673a..e88f74dfbd 100644 --- a/packages/core/src/api/nodeConversions/__snapshots__/nodeConversions.test.ts.snap +++ b/packages/core/src/api/nodeConversions/__snapshots__/nodeConversions.test.ts.snap @@ -4,7 +4,7 @@ exports[`Complex ProseMirror Node Conversions > Convert complex block to node 1` { "attrs": { "backgroundColor": "blue", - "id": "4", + "id": "1", "textColor": "yellow", }, "content": [ @@ -46,7 +46,7 @@ exports[`Complex ProseMirror Node Conversions > Convert complex block to node 1` { "attrs": { "backgroundColor": "red", - "id": "5", + "id": "2", "textColor": "default", }, "content": [ @@ -68,7 +68,7 @@ exports[`Complex ProseMirror Node Conversions > Convert complex block to node 1` { "attrs": { "backgroundColor": "default", - "id": "6", + "id": "3", "textColor": "default", }, "content": [ @@ -154,7 +154,7 @@ exports[`Simple ProseMirror Node Conversions > Convert simple block to node 1`] { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -173,7 +173,7 @@ exports[`Simple ProseMirror Node Conversions > Convert simple node to block 1`] { "children": [], "content": [], - "id": "0", + "id": "1", "props": { "backgroundColor": "default", "textAlignment": "left", @@ -187,7 +187,7 @@ exports[`hard breaks > Convert a block with a hard break 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -219,7 +219,7 @@ exports[`hard breaks > Convert a block with a hard break and different styles 1` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -256,7 +256,7 @@ exports[`hard breaks > Convert a block with a hard break at the end 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -284,7 +284,7 @@ exports[`hard breaks > Convert a block with a hard break at the start 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -312,7 +312,7 @@ exports[`hard breaks > Convert a block with a hard break between links 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -364,7 +364,7 @@ exports[`hard breaks > Convert a block with a hard break in a link 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -416,7 +416,7 @@ exports[`hard breaks > Convert a block with multiple hard breaks 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -455,7 +455,7 @@ exports[`hard breaks > Convert a block with only a hard break 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -479,7 +479,7 @@ exports[`links > Convert a block with link 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ @@ -514,7 +514,7 @@ exports[`links > Convert two adjacent links in a block 1`] = ` { "attrs": { "backgroundColor": "default", - "id": "4", + "id": "1", "textColor": "default", }, "content": [ diff --git a/packages/core/src/api/nodeConversions/nodeConversions.test.ts b/packages/core/src/api/nodeConversions/nodeConversions.test.ts index 5e44432db4..a39c25bdee 100644 --- a/packages/core/src/api/nodeConversions/nodeConversions.test.ts +++ b/packages/core/src/api/nodeConversions/nodeConversions.test.ts @@ -1,5 +1,4 @@ import { Editor } from "@tiptap/core"; -import { Node } from "prosemirror-model"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { BlockNoteEditor, PartialBlock } from "../.."; import UniqueID from "../../extensions/UniqueID/UniqueID"; @@ -13,98 +12,11 @@ import { let editor: BlockNoteEditor; let tt: Editor; -let simpleBlock: PartialBlock; -let simpleNode: Node; - -let complexBlock: PartialBlock; -let complexNode: Node; - beforeEach(() => { (window as Window & { __TEST_OPTIONS?: {} }).__TEST_OPTIONS = {}; editor = new BlockNoteEditor(); tt = editor._tiptapEditor; - - simpleBlock = { - type: "paragraph", - }; - simpleNode = tt.schema.nodes["blockContainer"].create( - { id: UniqueID.options.generateID() }, - tt.schema.nodes["paragraph"].create() - ); - - complexBlock = { - type: "heading", - props: { - backgroundColor: "blue", - textColor: "yellow", - textAlignment: "right", - level: "2", - }, - content: [ - { - type: "text", - text: "Heading ", - styles: { - bold: true, - underline: true, - }, - }, - { - type: "text", - text: "2", - styles: { - italic: true, - strike: true, - }, - }, - ], - children: [ - { - type: "paragraph", - props: { - backgroundColor: "red", - }, - content: "Paragraph", - children: [], - }, - { - type: "bulletListItem", - }, - ], - }; - complexNode = tt.schema.nodes["blockContainer"].create( - { - id: UniqueID.options.generateID(), - backgroundColor: "blue", - textColor: "yellow", - }, - [ - tt.schema.nodes["heading"].create( - { textAlignment: "right", level: "2" }, - [ - tt.schema.text("Heading ", [ - tt.schema.mark("bold"), - tt.schema.mark("underline"), - ]), - tt.schema.text("2", [ - tt.schema.mark("italic"), - tt.schema.mark("strike"), - ]), - ] - ), - tt.schema.nodes["blockGroup"].create({}, [ - tt.schema.nodes["blockContainer"].create( - { id: UniqueID.options.generateID(), backgroundColor: "red" }, - [tt.schema.nodes["paragraph"].create({}, tt.schema.text("Paragraph"))] - ), - tt.schema.nodes["blockContainer"].create( - { id: UniqueID.options.generateID() }, - [tt.schema.nodes["bulletListItem"].create()] - ), - ]), - ] - ); }); afterEach(() => { @@ -117,14 +29,21 @@ afterEach(() => { describe("Simple ProseMirror Node Conversions", () => { it("Convert simple block to node", async () => { - const firstNodeConversion = blockToNode(simpleBlock, tt.schema); + const block: PartialBlock = { + type: "paragraph", + }; + const firstNodeConversion = blockToNode(block, tt.schema); expect(firstNodeConversion).toMatchSnapshot(); }); it("Convert simple node to block", async () => { + const node = tt.schema.nodes["blockContainer"].create( + { id: UniqueID.options.generateID() }, + tt.schema.nodes["paragraph"].create() + ); const firstBlockConversion = nodeToBlock( - simpleNode, + node, defaultBlockSchema ); @@ -132,20 +51,97 @@ describe("Simple ProseMirror Node Conversions", () => { const firstNodeConversion = blockToNode(firstBlockConversion, tt.schema); - expect(firstNodeConversion).toStrictEqual(simpleNode); + expect(firstNodeConversion).toStrictEqual(node); }); }); describe("Complex ProseMirror Node Conversions", () => { it("Convert complex block to node", async () => { - const firstNodeConversion = blockToNode(complexBlock, tt.schema); + const block: PartialBlock = { + type: "heading", + props: { + backgroundColor: "blue", + textColor: "yellow", + textAlignment: "right", + level: "2", + }, + content: [ + { + type: "text", + text: "Heading ", + styles: { + bold: true, + underline: true, + }, + }, + { + type: "text", + text: "2", + styles: { + italic: true, + strike: true, + }, + }, + ], + children: [ + { + type: "paragraph", + props: { + backgroundColor: "red", + }, + content: "Paragraph", + children: [], + }, + { + type: "bulletListItem", + }, + ], + }; + const firstNodeConversion = blockToNode(block, tt.schema); expect(firstNodeConversion).toMatchSnapshot(); }); it("Convert complex node to block", async () => { + const node = tt.schema.nodes["blockContainer"].create( + { + id: UniqueID.options.generateID(), + backgroundColor: "blue", + textColor: "yellow", + }, + [ + tt.schema.nodes["heading"].create( + { textAlignment: "right", level: "2" }, + [ + tt.schema.text("Heading ", [ + tt.schema.mark("bold"), + tt.schema.mark("underline"), + ]), + tt.schema.text("2", [ + tt.schema.mark("italic"), + tt.schema.mark("strike"), + ]), + ] + ), + tt.schema.nodes["blockGroup"].create({}, [ + tt.schema.nodes["blockContainer"].create( + { id: UniqueID.options.generateID(), backgroundColor: "red" }, + [ + tt.schema.nodes["paragraph"].create( + {}, + tt.schema.text("Paragraph") + ), + ] + ), + tt.schema.nodes["blockContainer"].create( + { id: UniqueID.options.generateID() }, + [tt.schema.nodes["bulletListItem"].create()] + ), + ]), + ] + ); const firstBlockConversion = nodeToBlock( - complexNode, + node, defaultBlockSchema ); @@ -153,7 +149,7 @@ describe("Complex ProseMirror Node Conversions", () => { const firstNodeConversion = blockToNode(firstBlockConversion, tt.schema); - expect(firstNodeConversion).toStrictEqual(complexNode); + expect(firstNodeConversion).toStrictEqual(node); }); }); diff --git a/packages/core/src/extensions/Blocks/api/blockTypes.ts b/packages/core/src/extensions/Blocks/api/blockTypes.ts index ee49d9921d..a5a8eba4d1 100644 --- a/packages/core/src/extensions/Blocks/api/blockTypes.ts +++ b/packages/core/src/extensions/Blocks/api/blockTypes.ts @@ -2,6 +2,7 @@ import { Node, NodeConfig } from "@tiptap/core"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { InlineContent, PartialInlineContent } from "./inlineContentTypes"; +import { DefaultBlockSchema } from "./defaultBlocks"; // A configuration for a TipTap node, but with stricter type constraints on the // "name" and "group" properties. The "name" property is now always a string @@ -143,7 +144,7 @@ type BlocksWithoutChildren = { // Converts each block spec into a Block object without children, merges them // into a union type, and adds a children property -export type Block = +export type Block = BlocksWithoutChildren[keyof BlocksWithoutChildren] & { children: Block[]; }; @@ -168,7 +169,7 @@ type PartialBlocksWithoutChildren = { // Same as Block, but as a partial type with some changes to make it easier to // create/update blocks in the editor. -export type PartialBlock = +export type PartialBlock = PartialBlocksWithoutChildren[keyof PartialBlocksWithoutChildren] & Partial<{ children: PartialBlock[]; diff --git a/packages/core/src/extensions/Blocks/helpers/getBlockInfoFromPos.ts b/packages/core/src/extensions/Blocks/helpers/getBlockInfoFromPos.ts index d0a6a0e513..b5183833f7 100644 --- a/packages/core/src/extensions/Blocks/helpers/getBlockInfoFromPos.ts +++ b/packages/core/src/extensions/Blocks/helpers/getBlockInfoFromPos.ts @@ -26,6 +26,12 @@ export function getBlockInfoFromPos( return undefined; } + // This gets triggered when a node selection on a block is active, i.e. when + // you drag and drop a block. + if (doc.resolve(posInBlock).parent.type.name === "blockGroup") { + posInBlock++; + } + const $pos = doc.resolve(posInBlock); const maxDepth = $pos.depth; diff --git a/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts b/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts deleted file mode 100644 index 97507121c6..0000000000 --- a/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { EditorElement, ElementFactory } from "../../shared/EditorElement"; -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { Block, BlockSchema } from "../Blocks/api/blockTypes"; - -export type BlockSideMenuStaticParams = { - editor: BlockNoteEditor; - - addBlock: () => void; - - blockDragStart: (event: DragEvent) => void; - blockDragEnd: () => void; - - freezeMenu: () => void; - unfreezeMenu: () => void; - - getReferenceRect: () => DOMRect; -}; - -export type BlockSideMenuDynamicParams = { - block: Block; -}; - -export type BlockSideMenu = EditorElement< - BlockSideMenuDynamicParams ->; -export type BlockSideMenuFactory = ElementFactory< - BlockSideMenuStaticParams, - BlockSideMenuDynamicParams ->; diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts deleted file mode 100644 index 6db0fde3da..0000000000 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Editor, Extension } from "@tiptap/core"; -import { BlockSideMenuFactory } from "./BlockSideMenuFactoryTypes"; -import { createDraggableBlocksPlugin } from "./DraggableBlocksPlugin"; -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BlockSchema } from "../Blocks/api/blockTypes"; - -export type DraggableBlocksOptions = { - tiptapEditor: Editor; - editor: BlockNoteEditor; - blockSideMenuFactory: BlockSideMenuFactory; -}; - -/** - * This extension adds a menu to the side of blocks which features various BlockNote functions such as adding and - * removing blocks. More importantly, it adds a drag handle which allows the user to drag and drop blocks. - * - * code based on https://github.com/ueberdosis/tiptap/issues/323#issuecomment-506637799 - */ -export const createDraggableBlocksExtension = () => - Extension.create>({ - name: "DraggableBlocksExtension", - priority: 1000, // Need to be high, in order to hide menu when typing slash - addProseMirrorPlugins() { - if (!this.options.blockSideMenuFactory) { - throw new Error( - "UI Element factory not defined for DraggableBlocksExtension" - ); - } - return [ - createDraggableBlocksPlugin({ - tiptapEditor: this.editor, - editor: this.options.editor, - blockSideMenuFactory: this.options.blockSideMenuFactory, - }), - ]; - }, - }); diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts deleted file mode 100644 index a7389c4c8b..0000000000 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Extension } from "@tiptap/core"; -import { PluginKey } from "prosemirror-state"; -import { BlockNoteEditor, BlockSchema } from "../.."; -import { FormattingToolbarFactory } from "./FormattingToolbarFactoryTypes"; -import { createFormattingToolbarPlugin } from "./FormattingToolbarPlugin"; - -export type FormattingToolbarOptions = { - formattingToolbarFactory: FormattingToolbarFactory; - editor: BlockNoteEditor; -}; - -/** - * The menu that is displayed when selecting a piece of text. - */ -export const createFormattingToolbarExtension = < - BSchema extends BlockSchema ->() => - Extension.create>({ - name: "FormattingToolbarExtension", - - addProseMirrorPlugins() { - if (!this.options.formattingToolbarFactory || !this.options.editor) { - throw new Error( - "required args not defined for FormattingToolbarExtension" - ); - } - - return [ - createFormattingToolbarPlugin({ - tiptapEditor: this.editor, - editor: this.options.editor, - formattingToolbarFactory: this.options.formattingToolbarFactory, - pluginKey: new PluginKey("FormattingToolbarPlugin"), - }), - ]; - }, - }); diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarFactoryTypes.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarFactoryTypes.ts deleted file mode 100644 index 0c257caf67..0000000000 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarFactoryTypes.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { EditorElement, ElementFactory } from "../../shared/EditorElement"; -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BlockSchema } from "../Blocks/api/blockTypes"; - -export type FormattingToolbarStaticParams = { - editor: BlockNoteEditor; - - getReferenceRect: () => DOMRect; -}; - -export type FormattingToolbarDynamicParams = {}; - -export type FormattingToolbar = EditorElement; -export type FormattingToolbarFactory = - ElementFactory< - FormattingToolbarStaticParams, - FormattingToolbarDynamicParams - >; diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index c96eac3dc2..29d893fccb 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -1,50 +1,26 @@ -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 { BlockNoteEditor, BlockSchema } from "../.."; import { - FormattingToolbar, - FormattingToolbarFactory, - FormattingToolbarStaticParams, -} from "./FormattingToolbarFactoryTypes"; - -// Same as TipTap bubblemenu plugin, but with these changes: -// https://github.com/ueberdosis/tiptap/pull/2596/files -export interface FormattingToolbarPluginProps { - pluginKey: PluginKey; - tiptapEditor: Editor; - editor: BlockNoteEditor; - formattingToolbarFactory: FormattingToolbarFactory; -} + BaseUiElementCallbacks, + BaseUiElementState, + BlockNoteEditor, + BlockSchema, +} from "../.."; +import { EventEmitter } from "../../shared/EventEmitter"; -export type FormattingToolbarViewProps = - FormattingToolbarPluginProps & { - view: EditorView; - }; +export type FormattingToolbarCallbacks = BaseUiElementCallbacks; -export class FormattingToolbarView { - public editor: BlockNoteEditor; - private ttEditor: Editor; +export type FormattingToolbarState = BaseUiElementState; - public view: EditorView; - - public formattingToolbar: FormattingToolbar; +export class FormattingToolbarView { + private formattingToolbarState?: FormattingToolbarState; + public updateFormattingToolbar: () => void; public preventHide = false; - public preventShow = false; - - public toolbarIsOpen = false; - public prevWasEditable: boolean | null = null; - private lastPosition: DOMRect | undefined; - public shouldShow: (props: { view: EditorView; state: EditorState; @@ -63,24 +39,31 @@ export class FormattingToolbarView { return !(!view.hasFocus() || empty || isEmptyTextBlock); }; - constructor({ - editor, - tiptapEditor, - formattingToolbarFactory, - view, - }: FormattingToolbarViewProps) { - this.editor = editor; - this.ttEditor = tiptapEditor; - this.view = view; + constructor( + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, + updateFormattingToolbar: ( + formattingToolbarState: FormattingToolbarState + ) => void + ) { + this.updateFormattingToolbar = () => { + if (!this.formattingToolbarState) { + throw new Error( + "Attempting to update uninitialized formatting toolbar" + ); + } + + updateFormattingToolbar(this.formattingToolbarState); + }; - this.formattingToolbar = formattingToolbarFactory(this.getStaticParams()); + pmView.dom.addEventListener("mousedown", this.viewMousedownHandler); + pmView.dom.addEventListener("mouseup", this.viewMouseupHandler); + pmView.dom.addEventListener("dragstart", this.dragstartHandler); - this.view.dom.addEventListener("mousedown", this.viewMousedownHandler); - this.view.dom.addEventListener("mouseup", this.viewMouseupHandler); - this.view.dom.addEventListener("dragstart", this.dragstartHandler); + pmView.dom.addEventListener("focus", this.focusHandler); + pmView.dom.addEventListener("blur", this.blurHandler); - this.ttEditor.on("focus", this.focusHandler); - this.ttEditor.on("blur", this.blurHandler); + document.addEventListener("scroll", this.scrollHandler); } viewMousedownHandler = () => { @@ -89,42 +72,54 @@ export class FormattingToolbarView { viewMouseupHandler = () => { this.preventShow = false; - setTimeout(() => this.update(this.ttEditor.view)); + setTimeout(() => this.update(this.pmView)); }; + // For dragging the whole editor. dragstartHandler = () => { - this.formattingToolbar.hide(); - this.toolbarIsOpen = false; + if (this.formattingToolbarState?.show) { + this.formattingToolbarState.show = false; + this.updateFormattingToolbar(); + } }; 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.pmView.dom.parentElement!; + // Checks if the focus is moving to an element outside the editor. If it is, // the toolbar is hidden. if ( // An element is clicked. event && event.relatedTarget && - // Element is outside the toolbar. - (this.formattingToolbar.element === (event.relatedTarget as Node) || - this.formattingToolbar.element?.contains(event.relatedTarget as Node)) + // Element is inside the editor. + (editorWrapper === (event.relatedTarget as Node) || + editorWrapper.contains(event.relatedTarget as Node)) ) { return; } - if (this.toolbarIsOpen) { - this.formattingToolbar.hide(); - this.toolbarIsOpen = false; + if (this.formattingToolbarState?.show) { + this.formattingToolbarState.show = false; + this.updateFormattingToolbar(); + } + }; + + scrollHandler = () => { + if (this.formattingToolbarState?.show) { + this.formattingToolbarState.referencePos = this.getSelectionBoundingBox(); + this.updateFormattingToolbar(); } }; @@ -156,53 +151,48 @@ export class FormattingToolbarView { to, }); - // Checks if menu should be shown. + // Checks if menu should be shown/updated. if ( this.editor.isEditable && - !this.toolbarIsOpen && !this.preventShow && (shouldShow || this.preventHide) ) { - this.formattingToolbar.render({}, true); - this.toolbarIsOpen = true; + this.formattingToolbarState = { + show: true, + referencePos: this.getSelectionBoundingBox(), + }; - return; - } + this.updateFormattingToolbar(); - // Checks if menu should be updated. - if ( - this.toolbarIsOpen && - !this.preventShow && - (shouldShow || this.preventHide) - ) { - this.formattingToolbar.render({}, false); return; } // Checks if menu should be hidden. if ( - this.toolbarIsOpen && + this.formattingToolbarState?.show && !this.preventHide && (!shouldShow || this.preventShow || !this.editor.isEditable) ) { - this.formattingToolbar.hide(); - this.toolbarIsOpen = false; + this.formattingToolbarState.show = false; + this.updateFormattingToolbar(); return; } } destroy() { - this.view.dom.removeEventListener("mousedown", this.viewMousedownHandler); - this.view.dom.removeEventListener("mouseup", this.viewMouseupHandler); - this.view.dom.removeEventListener("dragstart", this.dragstartHandler); + this.pmView.dom.removeEventListener("mousedown", this.viewMousedownHandler); + this.pmView.dom.removeEventListener("mouseup", this.viewMouseupHandler); + this.pmView.dom.removeEventListener("dragstart", this.dragstartHandler); - this.ttEditor.off("focus", this.focusHandler); - this.ttEditor.off("blur", this.blurHandler); + 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 @@ -211,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); } +} - getStaticParams(): FormattingToolbarStaticParams { - return { - editor: this.editor, - getReferenceRect: () => { - if (!this.toolbarIsOpen) { - if (this.lastPosition === undefined) { - throw new Error( - "Attempted to access selection reference rect before rendering formatting toolbar." - ); - } - - return this.lastPosition; - } - - const selectionBoundingBox = this.getSelectionBoundingBox(); - this.lastPosition = selectionBoundingBox; - - return selectionBoundingBox; +export const formattingToolbarPluginKey = new PluginKey( + "FormattingToolbarPlugin" +); + +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: (editorView) => { + this.view = new FormattingToolbarView(editor, editorView, (state) => { + this.emit("update", state); + }); + return this.view; }, - }; + }); } -} -export const createFormattingToolbarPlugin = ( - options: FormattingToolbarPluginProps -) => { - return new Plugin({ - key: new PluginKey("FormattingToolbarPlugin"), - view: (view) => new FormattingToolbarView({ view, ...options }), - }); -}; + public onUpdate(callback: (state: FormattingToolbarState) => void) { + return this.on("update", callback); + } +} diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts deleted file mode 100644 index e61cc46dfd..0000000000 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Link } from "@tiptap/extension-link"; -import { - createHyperlinkToolbarPlugin, - HyperlinkToolbarPluginProps, -} from "./HyperlinkToolbarPlugin"; - -/** - * This custom link includes a special menu for editing/deleting/opening the link. - * The menu will be triggered by hovering over the link with the mouse, - * or by moving the cursor inside the link text - */ -const Hyperlink = Link.extend({ - priority: 500, - addProseMirrorPlugins() { - if (!this.options.hyperlinkToolbarFactory) { - throw new Error("UI Element factory not defined for HyperlinkMark"); - } - - return [ - ...(this.parent?.() || []), - createHyperlinkToolbarPlugin(this.editor, { - hyperlinkToolbarFactory: this.options.hyperlinkToolbarFactory, - }), - ]; - }, -}); - -export default Hyperlink; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts deleted file mode 100644 index fe2e7b5e07..0000000000 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { EditorElement, ElementFactory } from "../../shared/EditorElement"; - -export type HyperlinkToolbarStaticParams = { - editHyperlink: (url: string, text: string) => void; - deleteHyperlink: () => void; - - getReferenceRect: () => DOMRect; -}; - -export type HyperlinkToolbarDynamicParams = { - url: string; - text: string; -}; - -export type HyperlinkToolbar = EditorElement; -export type HyperlinkToolbarFactory = ElementFactory< - HyperlinkToolbarStaticParams, - HyperlinkToolbarDynamicParams ->; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index e5a74fb2c9..65ae274279 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -1,27 +1,22 @@ -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 { - HyperlinkToolbar, - HyperlinkToolbarDynamicParams, - HyperlinkToolbarFactory, - HyperlinkToolbarStaticParams, -} from "./HyperlinkToolbarFactoryTypes"; -const PLUGIN_KEY = new PluginKey("HyperlinkToolbarPlugin"); - -export type HyperlinkToolbarPluginProps = { - hyperlinkToolbarFactory: HyperlinkToolbarFactory; +import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { BaseUiElementState } from "../../shared/BaseUiElementTypes"; +import { EventEmitter } from "../../shared/EventEmitter"; +import { BlockSchema } from "../Blocks/api/blockTypes"; + +export type HyperlinkToolbarState = BaseUiElementState & { + // The hovered hyperlink's URL, and the text it's displayed with in the + // editor. + url: string; + text: string; }; -export type HyperlinkToolbarViewProps = { - editor: Editor; - hyperlinkToolbarFactory: HyperlinkToolbarFactory; -}; - -class HyperlinkToolbarView { - editor: Editor; - - hyperlinkToolbar: HyperlinkToolbar; +class HyperlinkToolbarView { + private hyperlinkToolbarState?: HyperlinkToolbarState; + public updateHyperlinkToolbar: () => void; menuUpdateTimer: NodeJS.Timeout | undefined; startMenuUpdateTimer: () => void; @@ -36,12 +31,20 @@ class HyperlinkToolbarView { hyperlinkMark: Mark | undefined; hyperlinkMarkRange: Range | undefined; - private lastPosition: DOMRect | undefined; - - constructor({ editor, hyperlinkToolbarFactory }: HyperlinkToolbarViewProps) { - this.editor = editor; + constructor( + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, + updateHyperlinkToolbar: ( + hyperlinkToolbarState: HyperlinkToolbarState + ) => void + ) { + this.updateHyperlinkToolbar = () => { + if (!this.hyperlinkToolbarState) { + throw new Error("Attempting to update uninitialized hyperlink toolbar"); + } - this.hyperlinkToolbar = hyperlinkToolbarFactory(this.getStaticParams()); + updateHyperlinkToolbar(this.hyperlinkToolbarState); + }; this.startMenuUpdateTimer = () => { this.menuUpdateTimer = setTimeout(() => { @@ -58,8 +61,9 @@ class HyperlinkToolbarView { return false; }; - this.editor.view.dom.addEventListener("mouseover", this.mouseOverHandler); + this.pmView.dom.addEventListener("mouseover", this.mouseOverHandler); document.addEventListener("click", this.clickHandler, true); + document.addEventListener("scroll", this.scrollHandler); } mouseOverHandler = (event: MouseEvent) => { @@ -77,14 +81,16 @@ class HyperlinkToolbarView { // mouseHoveredHyperlinkMarkRange. const hoveredHyperlinkElement = event.target; const posInHoveredHyperlinkMark = - this.editor.view.posAtDOM(hoveredHyperlinkElement, 0) + 1; - const resolvedPosInHoveredHyperlinkMark = this.editor.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.editor.schema.mark("link").type.name) { + if ( + mark.type.name === this.pmView.state.schema.mark("link").type.name + ) { this.mouseHoveredHyperlinkMark = mark; this.mouseHoveredHyperlinkMarkRange = getMarkRange( @@ -104,25 +110,80 @@ class HyperlinkToolbarView { }; clickHandler = (event: MouseEvent) => { + const editorWrapper = this.pmView.dom.parentElement!; + if ( // Toolbar is open. this.hyperlinkMark && // An element is clicked. event && event.target && - // Element is outside the editor. - this.editor.view.dom !== (event.target as Node) && - !this.editor.view.dom.contains(event.target as Node) && - // Element is outside the toolbar. - this.hyperlinkToolbar.element !== (event.target as Node) && - !this.hyperlinkToolbar.element?.contains(event.target as Node) + // The clicked element is not the editor. + !( + editorWrapper === (event.target as Node) || + editorWrapper.contains(event.target as Node) + ) ) { - this.hyperlinkToolbar.hide(); + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.show = false; + this.updateHyperlinkToolbar(); + } + } + }; + + scrollHandler = () => { + if (this.hyperlinkMark !== undefined) { + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.referencePos = posToDOMRect( + this.pmView, + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ); + this.updateHyperlinkToolbar(); + } } }; + editHyperlink(url: string, text: string) { + const tr = this.pmView.state.tr.insertText( + text, + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ); + tr.addMark( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.from + text.length, + this.pmView.state.schema.mark("link", { href: url }) + ); + this.pmView.dispatch(tr); + this.pmView.focus(); + + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.show = false; + this.updateHyperlinkToolbar(); + } + } + + deleteHyperlink() { + this.pmView.dispatch( + this.pmView.state.tr + .removeMark( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to, + this.hyperlinkMark!.type + ) + .setMeta("preventAutolink", true) + ); + this.pmView.focus(); + + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.show = false; + this.updateHyperlinkToolbar(); + } + } + update() { - if (!this.editor.view.hasFocus()) { + if (!this.pmView.hasFocus()) { return; } @@ -139,15 +200,17 @@ class HyperlinkToolbarView { // Finds link mark at the editor selection's position to update keyboardHoveredHyperlinkMark and // keyboardHoveredHyperlinkMarkRange. - if (this.editor.state.selection.empty) { - const marksAtPos = this.editor.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.editor.schema.mark("link").type.name) { + if ( + mark.type.name === this.pmView.state.schema.mark("link").type.name + ) { this.keyboardHoveredHyperlinkMark = mark; this.keyboardHoveredHyperlinkMarkRange = getMarkRange( - this.editor.state.selection.$from, + this.pmView.state.selection.$from, mark.type, mark.attrs ) || undefined; @@ -169,130 +232,102 @@ class HyperlinkToolbarView { } if (this.hyperlinkMark && this.editor.isEditable) { - this.getDynamicParams(); - - // Shows menu. - if (!prevHyperlinkMark) { - this.hyperlinkToolbar.render(this.getDynamicParams(), true); - - this.hyperlinkToolbar.element?.addEventListener( - "mouseleave", - this.startMenuUpdateTimer - ); - this.hyperlinkToolbar.element?.addEventListener( - "mouseenter", - this.stopMenuUpdateTimer - ); - - return; - } - - // Updates menu. - this.hyperlinkToolbar.render(this.getDynamicParams(), false); + this.hyperlinkToolbarState = { + show: true, + referencePos: posToDOMRect( + this.pmView, + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ), + url: this.hyperlinkMark!.attrs.href, + text: this.pmView.state.doc.textBetween( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ), + }; + this.updateHyperlinkToolbar(); return; } // Hides menu. - if (prevHyperlinkMark && (!this.hyperlinkMark || !this.editor.isEditable)) { - this.hyperlinkToolbar.element?.removeEventListener( - "mouseleave", - this.startMenuUpdateTimer - ); - this.hyperlinkToolbar.element?.removeEventListener( - "mouseenter", - this.stopMenuUpdateTimer - ); - - this.hyperlinkToolbar.hide(); + if ( + this.hyperlinkToolbarState?.show && + prevHyperlinkMark && + (!this.hyperlinkMark || !this.editor.isEditable) + ) { + this.hyperlinkToolbarState.show = false; + this.updateHyperlinkToolbar(); return; } } destroy() { - this.editor.view.dom.removeEventListener( - "mouseover", - this.mouseOverHandler - ); + this.pmView.dom.removeEventListener("mouseover", this.mouseOverHandler); + document.removeEventListener("scroll", this.scrollHandler); + document.removeEventListener("click", this.clickHandler, true); } +} - getStaticParams(): HyperlinkToolbarStaticParams { - return { - editHyperlink: (url: string, text: string) => { - const tr = this.editor.view.state.tr.insertText( - text, - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ); - tr.addMark( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.from + text.length, - this.editor.schema.mark("link", { href: url }) - ); - this.editor.view.dispatch(tr); - this.editor.view.focus(); - - this.hyperlinkToolbar.hide(); +export const hyperlinkToolbarPluginKey = new PluginKey( + "HyperlinkToolbarPlugin" +); + +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: (editorView) => { + this.view = new HyperlinkToolbarView(editor, editorView, (state) => { + this.emit("update", state); + }); + return this.view; }, - deleteHyperlink: () => { - this.editor.view.dispatch( - this.editor.view.state.tr - .removeMark( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to, - this.hyperlinkMark!.type - ) - .setMeta("preventAutolink", true) - ); - this.editor.view.focus(); + }); + } - this.hyperlinkToolbar.hide(); - }, - getReferenceRect: () => { - if (!this.hyperlinkMark) { - if (this.lastPosition === undefined) { - throw new Error( - "Attempted to access hyperlink reference rect before rendering hyperlink toolbar." - ); - } - - return this.lastPosition; - } + public onUpdate(callback: (state: HyperlinkToolbarState) => void) { + return this.on("update", callback); + } - const hyperlinkBoundingBox = posToDOMRect( - this.editor.view, - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ); - this.lastPosition = hyperlinkBoundingBox; + /** + * Edit the currently hovered hyperlink. + */ + public editHyperlink = (url: string, text: string) => { + this.view!.editHyperlink(url, text); + }; - return hyperlinkBoundingBox; - }, - }; - } + /** + * Delete the currently hovered hyperlink. + */ + public deleteHyperlink = () => { + this.view!.deleteHyperlink(); + }; - getDynamicParams(): HyperlinkToolbarDynamicParams { - return { - url: this.hyperlinkMark!.attrs.href, - text: this.editor.view.state.doc.textBetween( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ), - }; - } -} + /** + * 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(); + }; -export const createHyperlinkToolbarPlugin = ( - editor: Editor, - options: HyperlinkToolbarPluginProps -) => { - return new Plugin({ - key: PLUGIN_KEY, - view: () => - new HyperlinkToolbarView({ - editor: editor, - hyperlinkToolbarFactory: options.hyperlinkToolbarFactory, - }), - }); -}; + /** + * 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/Placeholder/PlaceholderExtension.ts b/packages/core/src/extensions/Placeholder/PlaceholderExtension.ts index 9def2e85d9..7f31321c59 100644 --- a/packages/core/src/extensions/Placeholder/PlaceholderExtension.ts +++ b/packages/core/src/extensions/Placeholder/PlaceholderExtension.ts @@ -2,7 +2,7 @@ import { Editor, Extension } from "@tiptap/core"; import { Node as ProsemirrorNode } from "prosemirror-model"; import { Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; -import { SlashMenuPluginKey } from "../SlashMenu/SlashMenuExtension"; +import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; const PLUGIN_KEY = new PluginKey(`blocknote-placeholder`); @@ -55,7 +55,7 @@ export const Placeholder = Extension.create({ decorations: (state) => { const { doc, selection } = state; // Get state of slash menu - const menuState = SlashMenuPluginKey.getState(state); + const menuState = slashMenuPluginKey.getState(state); const active = this.editor.isEditable || !this.options.showOnlyWhenEditable; const { anchor } = selection; 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 68% rename from packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts rename to packages/core/src/extensions/SideMenu/SideMenuPlugin.ts index fedf775fac..1d8b40fdbb 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts @@ -1,27 +1,27 @@ -import { Editor } from "@tiptap/core"; +import { PluginView } from "@tiptap/pm/state"; import { Node } from "prosemirror-model"; import { NodeSelection, Plugin, PluginKey, Selection } from "prosemirror-state"; import * as pv from "prosemirror-view"; import { EditorView } from "prosemirror-view"; +import { BlockNoteEditor } from "../../BlockNoteEditor"; import styles from "../../editor.module.css"; +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/SlashMenuExtension"; -import { - BlockSideMenu, - BlockSideMenuDynamicParams, - BlockSideMenuFactory, - BlockSideMenuStaticParams, -} from "./BlockSideMenuFactoryTypes"; -import { DraggableBlocksOptions } from "./DraggableBlocksExtension"; +import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; import { MultipleNodeSelection } from "./MultipleNodeSelection"; -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BlockSchema } from "../Blocks/api/blockTypes"; const serializeForClipboard = (pv as any).__serializeForClipboard; // code based on https://github.com/ueberdosis/tiptap/issues/323#issuecomment-506637799 let dragImageElement: Element | undefined; +export type SideMenuState = BaseUiElementState & { + // The block that the side menu is attached to. + block: Block; +}; + function getDraggableBlockFromCoords( coords: { left: number; top: number }, view: EditorView @@ -176,7 +176,10 @@ function unsetDragImage() { } } -function dragStart(e: DragEvent, view: EditorView) { +function dragStart( + e: { dataTransfer: DataTransfer | null; clientY: number }, + view: EditorView +) { if (!e.dataTransfer) { return; } @@ -224,59 +227,45 @@ function dragStart(e: DragEvent, view: EditorView) { } } -export type BlockMenuViewProps = { - tiptapEditor: Editor; - editor: BlockNoteEditor; - blockMenuFactory: BlockSideMenuFactory; - horizontalPosAnchoredAtRoot: boolean; -}; - -export class BlockMenuView { - editor: BlockNoteEditor; - private ttEditor: Editor; +export class SideMenuView implements PluginView { + private sideMenuState?: SideMenuState; // 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 - horizontalPosAnchoredAtRoot: boolean; + // TODO: Is there any case where we want this to be false? + private horizontalPosAnchoredAtRoot: boolean; + private horizontalPosAnchor: number; - horizontalPosAnchor: number; + private hoveredBlock: HTMLElement | undefined; - blockMenu: BlockSideMenu; + // Used to check if currently dragged content comes from this editor instance. + public isDragging = false; - hoveredBlock: HTMLElement | undefined; + public menuFrozen = false; - // Used to check if currently dragged content comes from this editor instance. - isDragging = false; - menuOpen = false; - menuFrozen = false; - - private lastPosition: DOMRect | undefined; - - constructor({ - tiptapEditor, - editor, - blockMenuFactory, - horizontalPosAnchoredAtRoot, - }: BlockMenuViewProps) { - this.editor = editor; - this.ttEditor = tiptapEditor; - this.horizontalPosAnchoredAtRoot = horizontalPosAnchoredAtRoot; + constructor( + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, + private readonly updateSideMenu: ( + sideMenuState: SideMenuState + ) => void + ) { + this.horizontalPosAnchoredAtRoot = true; this.horizontalPosAnchor = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect().x; - this.blockMenu = blockMenuFactory(this.getStaticParams()); - 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); - // 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); + // Makes menu scroll with the page. + document.addEventListener("scroll", this.onScroll); + + // Hides and unfreezes the menu whenever the user presses a key. document.body.addEventListener("keydown", this.onKeyDown, true); } @@ -293,10 +282,13 @@ export class BlockMenuView { * when dragging / dropping to the side of the editor */ onDrop = (event: DragEvent) => { + 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, }); @@ -306,7 +298,7 @@ export class BlockMenuView { 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; @@ -314,7 +306,7 @@ export class BlockMenuView { 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); } }; @@ -327,7 +319,7 @@ export class BlockMenuView { 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, }); @@ -335,7 +327,7 @@ export class BlockMenuView { 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; @@ -343,29 +335,15 @@ export class BlockMenuView { 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.menuOpen) { - this.menuOpen = false; - this.blockMenu.hide(); + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(this.sideMenuState); } - - this.menuFrozen = false; - }; - - onMouseDown = (event: MouseEvent) => { - if (this.blockMenu.element?.contains(event.target as HTMLElement)) { - return; - } - - if (this.menuOpen) { - this.menuOpen = false; - this.blockMenu.hide(); - } - this.menuFrozen = false; }; @@ -379,18 +357,19 @@ export class BlockMenuView { // 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.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. if ( @@ -400,15 +379,14 @@ export class BlockMenuView { event && event.target && // Element is outside the editor - this.ttEditor.view.dom !== event.target && - !this.ttEditor.view.dom.contains(event.target as HTMLElement) && - // Element is outside the side menu - this.blockMenu.element !== event.target && - !this.blockMenu.element?.contains(event.target as HTMLElement) + !( + editorWrapper === event.target || + editorWrapper.contains(event.target as HTMLElement) + ) ) { - if (this.menuOpen) { - this.menuOpen = false; - this.blockMenu.hide(); + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(this.sideMenuState); } return; @@ -421,13 +399,13 @@ export class BlockMenuView { 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.menuOpen) { - this.menuOpen = false; - this.blockMenu.hide(); + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(this.sideMenuState); } return; @@ -435,7 +413,7 @@ export class BlockMenuView { // Doesn't update if the menu is already open and the mouse cursor is still hovering the same block. if ( - this.menuOpen && + this.sideMenuState?.show && this.hoveredBlock?.hasAttribute("data-id") && this.hoveredBlock?.getAttribute("data-id") === block.id ) { @@ -453,37 +431,69 @@ export class BlockMenuView { // Shows or updates elements. if (this.editor.isEditable) { - if (!this.menuOpen) { - this.menuOpen = true; - this.blockMenu.render(this.getDynamicParams(), true); - } else { - this.blockMenu.render(this.getDynamicParams(), false); - } + const blockContentBoundingBox = blockContent.getBoundingClientRect(); + + this.sideMenuState = { + show: true, + referencePos: new DOMRect( + this.horizontalPosAnchoredAtRoot + ? this.horizontalPosAnchor + : blockContentBoundingBox.x, + blockContentBoundingBox.y, + blockContentBoundingBox.width, + blockContentBoundingBox.height + ), + block: this.editor.getBlock( + this.hoveredBlock!.getAttribute("data-id")! + )!, + }; + + this.updateSideMenu(this.sideMenuState); + } + }; + + onScroll = () => { + if (this.sideMenuState?.show) { + const blockContent = this.hoveredBlock!.firstChild as HTMLElement; + const blockContentBoundingBox = blockContent.getBoundingClientRect(); + + this.sideMenuState.referencePos = new DOMRect( + this.horizontalPosAnchoredAtRoot + ? this.horizontalPosAnchor + : blockContentBoundingBox.x, + blockContentBoundingBox.y, + blockContentBoundingBox.width, + blockContentBoundingBox.height + ); + this.updateSideMenu(this.sideMenuState); } }; destroy() { - if (this.menuOpen) { - this.menuOpen = false; - this.blockMenu.hide(); + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(this.sideMenuState); } document.body.removeEventListener("mousemove", this.onMouseMove); document.body.removeEventListener("dragover", this.onDragOver); - this.ttEditor.view.dom.removeEventListener("dragstart", this.onDragStart); - document.body.removeEventListener("drop", this.onDrop); - document.body.removeEventListener("mousedown", this.onMouseDown); - document.body.removeEventListener("keydown", this.onKeyDown); + this.pmView.dom.removeEventListener("dragstart", this.onDragStart); + document.body.removeEventListener("drop", this.onDrop, true); + document.removeEventListener("scroll", this.onScroll); + document.body.removeEventListener("keydown", this.onKeyDown, true); } addBlock() { - this.menuOpen = false; + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(this.sideMenuState); + } + this.menuFrozen = true; - this.blockMenu.hide(); 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, }); @@ -491,7 +501,10 @@ export class BlockMenuView { return; } - const blockInfo = getBlockInfoFromPos(this.ttEditor.state.doc, pos.pos); + const blockInfo = getBlockInfoFromPos( + this.editor._tiptapEditor.state.doc, + pos.pos + ); if (blockInfo === undefined) { return; } @@ -503,84 +516,88 @@ export class BlockMenuView { 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", }) ); } +} - getStaticParams(): BlockSideMenuStaticParams { - return { - editor: this.editor, - addBlock: () => this.addBlock(), - blockDragStart: (event: DragEvent) => { - // Sets isDragging when dragging blocks. - this.isDragging = true; - dragStart(event, this.ttEditor.view); - }, - blockDragEnd: () => unsetDragImage(), - freezeMenu: () => { - this.menuFrozen = true; - }, - unfreezeMenu: () => { - this.menuFrozen = false; - }, - getReferenceRect: () => { - if (!this.menuOpen) { - if (this.lastPosition === undefined) { - throw new Error( - "Attempted to access block reference rect before rendering block side menu." - ); +export const sideMenuPluginKey = new PluginKey("SideMenuPlugin"); + +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: (editorView) => { + this.sideMenuView = new SideMenuView( + editor, + editorView, + (sideMenuState) => { + this.emit("update", sideMenuState); } - - return this.lastPosition; - } - - const blockContent = this.hoveredBlock!.firstChild! as HTMLElement; - const blockContentBoundingBox = blockContent.getBoundingClientRect(); - if (this.horizontalPosAnchoredAtRoot) { - blockContentBoundingBox.x = this.horizontalPosAnchor; - } - this.lastPosition = blockContentBoundingBox; - - return blockContentBoundingBox; + ); + return this.sideMenuView; }, - }; + }); } - getDynamicParams(): BlockSideMenuDynamicParams { - return { - block: this.editor.getBlock(this.hoveredBlock!.getAttribute("data-id")!)!, - }; + public onUpdate(callback: (state: SideMenuState) => void) { + return this.on("update", callback); } -} -export const createDraggableBlocksPlugin = ( - options: DraggableBlocksOptions -) => { - return new Plugin({ - key: new PluginKey("DraggableBlocksPlugin"), - view: () => - new BlockMenuView({ - tiptapEditor: options.tiptapEditor, - editor: options.editor, - blockMenuFactory: options.blockSideMenuFactory, - horizontalPosAnchoredAtRoot: true, - }), - }); -}; + /** + * 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: { + dataTransfer: DataTransfer | null; + clientY: number; + }) => { + 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/BaseSlashMenuItem.ts b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts index 355cc0b1f6..41fc78917c 100644 --- a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts +++ b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts @@ -1,34 +1,11 @@ import { SuggestionItem } from "../../shared/plugins/suggestion/SuggestionItem"; import { BlockNoteEditor } from "../../BlockNoteEditor"; import { BlockSchema } from "../Blocks/api/blockTypes"; +import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; -/** - * A class that defines a slash command (/). - * - * (Not to be confused with ProseMirror commands nor TipTap commands.) - */ -export class BaseSlashMenuItem< - BSchema extends BlockSchema -> extends SuggestionItem { - /** - * Constructs a new slash-command. - * - * @param name The name of the command - * @param execute The callback for creating a new node - * @param aliases Aliases for this command - */ - constructor( - public readonly name: string, - public readonly execute: (editor: BlockNoteEditor) => void, - public readonly aliases: string[] = [] - ) { - super(name, (query: string): boolean => { - return ( - this.name.toLowerCase().startsWith(query.toLowerCase()) || - this.aliases.filter((alias) => - alias.toLowerCase().startsWith(query.toLowerCase()) - ).length !== 0 - ); - }); - } -} +export type BaseSlashMenuItem< + BSchema extends BlockSchema = DefaultBlockSchema +> = SuggestionItem & { + execute: (editor: BlockNoteEditor) => void; + aliases?: string[]; +}; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts b/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts deleted file mode 100644 index d51aeb3458..0000000000 --- a/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { Extension } from "@tiptap/core"; -import { PluginKey } from "prosemirror-state"; -import { createSuggestionPlugin } from "../../shared/plugins/suggestion/SuggestionPlugin"; -import { SuggestionsMenuFactory } from "../../shared/plugins/suggestion/SuggestionsMenuFactoryTypes"; -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BlockSchema } from "../Blocks/api/blockTypes"; - -export type SlashMenuOptions = { - editor: BlockNoteEditor | undefined; - commands: BaseSlashMenuItem[] | undefined; - slashMenuFactory: SuggestionsMenuFactory | undefined; -}; - -export const SlashMenuPluginKey = new PluginKey("suggestions-slash-commands"); - -export const createSlashMenuExtension = () => - Extension.create>({ - name: "slash-command", - - addOptions() { - return { - editor: undefined, - commands: undefined, - slashMenuFactory: undefined, - }; - }, - - addProseMirrorPlugins() { - if (!this.options.slashMenuFactory || !this.options.commands) { - throw new Error("required args not defined for SlashMenuExtension"); - } - - const commands = this.options.commands; - - return [ - createSuggestionPlugin, BSchema>({ - pluginKey: SlashMenuPluginKey, - editor: this.options.editor!, - defaultTriggerCharacter: "/", - suggestionsMenuFactory: this.options.slashMenuFactory!, - items: (query) => { - return commands.filter((cmd: BaseSlashMenuItem) => - cmd.match(query) - ); - }, - onSelectItem: ({ item, editor }) => { - item.execute(editor); - }, - }), - ]; - }, - }); diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts new file mode 100644 index 0000000000..a190cc3209 --- /dev/null +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -0,0 +1,51 @@ +import { Plugin, PluginKey } from "prosemirror-state"; + +import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { EventEmitter } from "../../shared/EventEmitter"; +import { + SuggestionsMenuState, + setupSuggestionsMenu, +} from "../../shared/plugins/suggestion/SuggestionPlugin"; +import { BlockSchema } from "../Blocks/api/blockTypes"; +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; + +export const slashMenuPluginKey = new PluginKey("SlashMenuPlugin"); + +export class SlashMenuProsemirrorPlugin< + BSchema extends BlockSchema, + SlashMenuItem extends BaseSlashMenuItem +> 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; + } + + public onUpdate( + callback: (state: SuggestionsMenuState) => void + ) { + return this.on("update", callback); + } +} diff --git a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts new file mode 100644 index 0000000000..e6bc7830dd --- /dev/null +++ b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts @@ -0,0 +1,109 @@ +import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { BlockSchema, PartialBlock } from "../Blocks/api/blockTypes"; +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; +import { defaultBlockSchema } from "../Blocks/api/defaultBlocks"; + +function insertOrUpdateBlock( + editor: BlockNoteEditor, + block: PartialBlock +) { + const currentBlock = editor.getTextCursorPosition().block; + + if ( + (currentBlock.content.length === 1 && + currentBlock.content[0].type === "text" && + currentBlock.content[0].text === "/") || + currentBlock.content.length === 0 + ) { + editor.updateBlock(currentBlock, block); + } else { + editor.insertBlocks([block], currentBlock, "after"); + editor.setTextCursorPosition(editor.getTextCursorPosition().nextBlock!); + } +} + +export const getDefaultSlashMenuItems = ( + // This type casting is weird, but it's the best way of doing it, as it allows + // the schema type to be automatically inferred if it is defined, or be + // inferred as any if it is not defined. I don't think it's possible to make it + // infer to DefaultBlockSchema if it is not defined. + schema: BSchema = defaultBlockSchema as unknown as BSchema +) => { + const slashMenuItems: BaseSlashMenuItem[] = []; + + if ("heading" in schema && "level" in schema.heading.propSchema) { + // Command for creating a level 1 heading + if (schema.heading.propSchema.level.values?.includes("1")) { + slashMenuItems.push({ + name: "Heading", + aliases: ["h", "heading1", "h1"], + execute: (editor) => + insertOrUpdateBlock(editor, { + type: "heading", + props: { level: "1" }, + } as PartialBlock), + }); + } + + // Command for creating a level 2 heading + if (schema.heading.propSchema.level.values?.includes("2")) { + slashMenuItems.push({ + name: "Heading 2", + aliases: ["h2", "heading2", "subheading"], + execute: (editor) => + insertOrUpdateBlock(editor, { + type: "heading", + props: { level: "2" }, + } as PartialBlock), + }); + } + + // Command for creating a level 3 heading + if (schema.heading.propSchema.level.values?.includes("3")) { + slashMenuItems.push({ + name: "Heading 3", + aliases: ["h3", "heading3", "subheading"], + execute: (editor) => + insertOrUpdateBlock(editor, { + type: "heading", + props: { level: "3" }, + } as PartialBlock), + }); + } + } + + if ("bulletListItem" in schema) { + slashMenuItems.push({ + name: "Bullet List", + aliases: ["ul", "list", "bulletlist", "bullet list"], + execute: (editor) => + insertOrUpdateBlock(editor, { + type: "bulletListItem", + } as PartialBlock), + }); + } + + if ("numberedListItem" in schema) { + slashMenuItems.push({ + name: "Numbered List", + aliases: ["li", "list", "numberedlist", "numbered list"], + execute: (editor) => + insertOrUpdateBlock(editor, { + type: "numberedListItem", + } as PartialBlock), + }); + } + + if ("paragraph" in schema) { + slashMenuItems.push({ + name: "Paragraph", + aliases: ["p"], + execute: (editor) => + insertOrUpdateBlock(editor, { + type: "paragraph", + } as PartialBlock), + }); + } + + return slashMenuItems; +}; diff --git a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.tsx b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.tsx deleted file mode 100644 index 2375996560..0000000000 --- a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.tsx +++ /dev/null @@ -1,195 +0,0 @@ -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { PartialBlock } from "../Blocks/api/blockTypes"; -import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; - -function insertOrUpdateBlock( - editor: BlockNoteEditor, - block: PartialBlock -) { - const currentBlock = editor.getTextCursorPosition().block; - - if ( - (currentBlock.content.length === 1 && - currentBlock.content[0].type === "text" && - currentBlock.content[0].text === "/") || - currentBlock.content.length === 0 - ) { - editor.updateBlock(currentBlock, block); - } else { - editor.insertBlocks([block], currentBlock, "after"); - editor.setTextCursorPosition(editor.getTextCursorPosition().nextBlock!); - } -} - -/** - * An array containing commands for creating all default blocks. - */ -export const defaultSlashMenuItems = [ - // Command for creating a level 1 heading - new BaseSlashMenuItem( - "Heading", - (editor) => - insertOrUpdateBlock(editor, { - type: "heading", - props: { level: "1" }, - }), - ["h", "heading1", "h1"] - ), - - // Command for creating a level 2 heading - new BaseSlashMenuItem( - "Heading 2", - (editor) => - insertOrUpdateBlock(editor, { - type: "heading", - props: { level: "2" }, - }), - ["h2", "heading2", "subheading"] - ), - - // Command for creating a level 3 heading - new BaseSlashMenuItem( - "Heading 3", - (editor) => - insertOrUpdateBlock(editor, { - type: "heading", - props: { level: "3" }, - }), - ["h3", "heading3", "subheading"] - ), - - // Command for creating an ordered list - new BaseSlashMenuItem( - "Numbered List", - (editor) => - insertOrUpdateBlock(editor, { - type: "numberedListItem", - }), - ["li", "list", "numberedlist", "numbered list"] - ), - - // Command for creating a bullet list - new BaseSlashMenuItem( - "Bullet List", - (editor) => - insertOrUpdateBlock(editor, { - type: "bulletListItem", - }), - ["ul", "list", "bulletlist", "bullet list"] - ), - - // Command for creating a paragraph (pretty useless) - new BaseSlashMenuItem( - "Paragraph", - (editor) => - insertOrUpdateBlock(editor, { - type: "paragraph", - }), - ["p"] - ), - - // replaceRangeWithNode(editor, range, node); - - // return true; - // }, - // ["ol", "orderedlist"], - // OrderedListIcon, - // "Used to display an ordered (enumerated) list item" - // ), - - // Command for creating a blockquote - // blockquote: new SlashCommand( - // "Block Quote", - // CommandGroup.BASIC_BLOCKS, - // (editor, range) => { - // const paragraph = editor.schema.node("paragraph"); - // const node = editor.schema.node( - // "blockquote", - // { "block-id": uniqueId.generate() }, - // paragraph - // ); - - // replaceRangeWithNode(editor, range, node); - - // return true; - // }, - // ["quote", "blockquote"], - // QuoteIcon, - // "Used to make a quote stand out", - // "Ctrl+Shift+B" - // ), - - // Command for creating a horizontal rule - // horizontalRule: new SlashCommand( - // "Horizontal Rule", - // CommandGroup.BASIC_BLOCKS, - // (editor, range) => { - // const node = editor.schema.node("horizontalRule", { - // "block-id": uniqueId.generate(), - // }); - - // // insert horizontal rule, create a new block after the horizontal rule if applicable - // // and put the cursor in the block after the horizontal rule. - // editor - // .chain() - // .focus() - // .replaceRangeAndUpdateSelection(range, node) - // .command(({ tr, dispatch }) => { - // if (dispatch) { - // // the node immediately after the cursor - // const nodeAfter = tr.selection.$to.nodeAfter; - - // // the position of the cursor - // const cursorPos = tr.selection.$to.pos; - - // // check if there is no node after the cursor (end of document) - // if (!nodeAfter) { - // // create a new block of the default type (probably paragraph) after the cursor - // const { parent } = tr.selection.$to; - // const node = parent.type.contentMatch.defaultType?.create(); - - // if (node) { - // tr.insert(cursorPos, node); - // } - // } - - // // try to put the cursor at the start of the node directly after the inserted horizontal rule - // tr.doc.nodesBetween(cursorPos, cursorPos + 1, (node, pos) => { - // if (node.type.name !== "horizontalRule") { - // tr.setSelection(TextSelection.create(tr.doc, pos)); - // } - // }); - // } - - // return true; - // }) - // .scrollIntoView() - // .run(); - // return true; - // }, - // ["hr", "horizontalrule"], - // SeparatorIcon, - // "Used to separate sections with a horizontal line" - // ), - - // Command for creating a table - // table: new SlashCommand( - // "Table", - // CommandGroup.BASIC_BLOCKS, - // (editor, range) => { - // editor.chain().focus().deleteRange(range).run(); - // // TODO: add blockid, pending https://github.com/ueberdosis/tiptap/pull/1469 - // editor - // .chain() - // .focus() - // .insertTable({ rows: 1, cols: 2, withHeaderRow: false }) - // .scrollIntoView() - // .run(); - // return true; - // }, - // ["table", "database"], - // TableIcon, - // "Used to create a simple table" - // ), -]; diff --git a/packages/core/src/extensions/SlashMenu/index.ts b/packages/core/src/extensions/SlashMenu/index.ts deleted file mode 100644 index 3fae65095c..0000000000 --- a/packages/core/src/extensions/SlashMenu/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { defaultSlashMenuItems } from "./defaultSlashMenuItems"; -import { createSlashMenuExtension } from "./SlashMenuExtension"; -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; - -export { defaultSlashMenuItems, BaseSlashMenuItem, createSlashMenuExtension }; diff --git a/packages/core/src/extensions/UniqueID/UniqueID.ts b/packages/core/src/extensions/UniqueID/UniqueID.ts index 5cb4f2da60..9250545cb1 100644 --- a/packages/core/src/extensions/UniqueID/UniqueID.ts +++ b/packages/core/src/extensions/UniqueID/UniqueID.ts @@ -1,7 +1,6 @@ import { combineTransactionSteps, Extension, - findChildren, findChildrenInRange, getChangedRanges, } from "@tiptap/core"; @@ -87,35 +86,35 @@ const UniqueID = Extension.create({ ]; }, // check initial content for missing ids - onCreate() { - // Don’t do this when the collaboration extension is active - // because this may update the content, so Y.js tries to merge these changes. - // This leads to empty block nodes. - // See: https://github.com/ueberdosis/tiptap/issues/2400 - if ( - this.editor.extensionManager.extensions.find( - (extension) => extension.name === "collaboration" - ) - ) { - return; - } - const { view, state } = this.editor; - const { tr, doc } = state; - const { types, attributeName, generateID } = this.options; - const nodesWithoutId = findChildren(doc, (node) => { - return ( - types.includes(node.type.name) && node.attrs[attributeName] === null - ); - }); - nodesWithoutId.forEach(({ node, pos }) => { - tr.setNodeMarkup(pos, undefined, { - ...node.attrs, - [attributeName]: generateID(), - }); - }); - tr.setMeta("addToHistory", false); - view.dispatch(tr); - }, + // onCreate() { + // // Don’t do this when the collaboration extension is active + // // because this may update the content, so Y.js tries to merge these changes. + // // This leads to empty block nodes. + // // See: https://github.com/ueberdosis/tiptap/issues/2400 + // if ( + // this.editor.extensionManager.extensions.find( + // (extension) => extension.name === "collaboration" + // ) + // ) { + // return; + // } + // const { view, state } = this.editor; + // const { tr, doc } = state; + // const { types, attributeName, generateID } = this.options; + // const nodesWithoutId = findChildren(doc, (node) => { + // return ( + // types.includes(node.type.name) && node.attrs[attributeName] === null + // ); + // }); + // nodesWithoutId.forEach(({ node, pos }) => { + // tr.setNodeMarkup(pos, undefined, { + // ...node.attrs, + // [attributeName]: generateID(), + // }); + // }); + // tr.setMeta("addToHistory", false); + // view.dispatch(tr); + // }, addProseMirrorPlugins() { let dragSourceElement: any = null; let transformPasted = false; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 8b4b935cb2..f80626d5cf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,14 +3,15 @@ export * from "./BlockNoteExtensions"; export * from "./extensions/Blocks/api/block"; export * from "./extensions/Blocks/api/blockTypes"; export * from "./extensions/Blocks/api/defaultBlocks"; -export * from "./extensions/DraggableBlocks/BlockSideMenuFactoryTypes"; -export * from "./extensions/FormattingToolbar/FormattingToolbarFactoryTypes"; -export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes"; -export { defaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; -export * from "./extensions/SlashMenu/BaseSlashMenuItem"; -export * from "./shared/EditorElement"; -export type { SuggestionItem } from "./shared/plugins/suggestion/SuggestionItem"; -export * from "./shared/plugins/suggestion/SuggestionsMenuFactoryTypes"; 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/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/BaseUiElementTypes.ts b/packages/core/src/shared/BaseUiElementTypes.ts new file mode 100644 index 0000000000..4ca4cc9f4c --- /dev/null +++ b/packages/core/src/shared/BaseUiElementTypes.ts @@ -0,0 +1,8 @@ +export type BaseUiElementCallbacks = { + destroy: () => void; +}; + +export type BaseUiElementState = { + show: boolean; + referencePos: DOMRect; +}; diff --git a/packages/core/src/shared/EditorElement.ts b/packages/core/src/shared/EditorElement.ts index 48c0c40593..e69de29bb2 100644 --- a/packages/core/src/shared/EditorElement.ts +++ b/packages/core/src/shared/EditorElement.ts @@ -1,16 +0,0 @@ -export type RequiredStaticParams = Record & { - getReferenceRect: () => DOMRect; -}; -export type RequiredDynamicParams = Record & {}; - -export type EditorElement = - { - element: HTMLElement | undefined; - render: (params: ElementDynamicParams, isHidden: boolean) => void; - hide: () => void; - }; - -export type ElementFactory< - ElementStaticParams extends RequiredStaticParams, - ElementDynamicParams extends RequiredDynamicParams -> = (staticParams: ElementStaticParams) => EditorElement; 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/SuggestionItem.ts b/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts index 7fe85af195..aebd7be2cd 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts @@ -1,6 +1,3 @@ -/** - * A generic interface used in all suggestion menus (slash menu, mentions, etc) - */ -export class SuggestionItem { - constructor(public name: string, public match: (query: string) => boolean) {} -} +export type SuggestionItem = { + name: string; +}; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index edbed53178..9381d7988f 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -1,146 +1,59 @@ -import { Editor, Range } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; -import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; -import { - SuggestionsMenu, - SuggestionsMenuDynamicParams, - SuggestionsMenuFactory, - SuggestionsMenuStaticParams, -} from "./SuggestionsMenuFactoryTypes"; -import { SuggestionItem } from "./SuggestionItem"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; +import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; +import { BaseUiElementState } from "../../BaseUiElementTypes"; +import { SuggestionItem } from "./SuggestionItem"; -export type SuggestionPluginOptions< - T extends SuggestionItem, - BSchema extends BlockSchema -> = { - /** - * The name of the plugin. - * - * Used for ensuring that the plugin key is unique when more than one instance of the SuggestionPlugin is used. - */ - pluginKey: PluginKey; - - /** - * The BlockNote editor. - */ - editor: BlockNoteEditor; - - /** - * The character that should trigger the suggestion menu to pop up (e.g. a '/' for commands), when typed by the user. - */ - defaultTriggerCharacter: string; - - suggestionsMenuFactory: SuggestionsMenuFactory; - - /** - * The callback that gets executed when an item is selected by the user. - * - * **NOTE:** The command text is not removed automatically from the editor by this plugin, - * this should be done manually. The `editor` and `range` properties passed - * to the callback function might come in handy when doing this. - */ - onSelectItem?: (props: { item: T; editor: BlockNoteEditor }) => void; - - /** - * A function that should supply the plugin with items to suggest, based on a certain query string. - */ - items?: (query: string) => T[]; - - allow?: (props: { editor: Editor; range: Range }) => boolean; -}; - -type SuggestionPluginState = { - // True when the menu is shown, false when hidden. - active: boolean; - // The character that triggered the menu being shown. Allowing the trigger to be different to the default - // trigger allows other extensions to open it programmatically. - triggerCharacter: string | undefined; - // The editor position just after the trigger character, i.e. where the user query begins. Used to figure out - // which menu items to show and can also be used to delete the trigger character. - queryStartPos: number | undefined; - // The items that should be shown in the menu. - items: T[]; - // The index of the item in the menu that's currently hovered using the keyboard. - keyboardHoveredItemIndex: number | undefined; - // The number of characters typed after the last query that matched with at least 1 item. Used to close the - // menu if the user keeps entering queries that don't return any results. - notFoundCount: number | undefined; - decorationId: string | undefined; -}; - -function getDefaultPluginState< - T extends SuggestionItem ->(): SuggestionPluginState { - return { - active: false, - triggerCharacter: undefined, - queryStartPos: undefined, - items: [] as T[], - keyboardHoveredItemIndex: undefined, - notFoundCount: 0, - decorationId: undefined, +export type SuggestionsMenuState = + BaseUiElementState & { + // The suggested items to display. + filteredItems: T[]; + // The index of the suggested item that's currently hovered by the keyboard. + keyboardHoveredItemIndex: number; }; -} -type SuggestionPluginViewOptions< - T extends SuggestionItem, - BSchema extends BlockSchema -> = { - editor: BlockNoteEditor; - pluginKey: PluginKey; - onSelectItem: (props: { item: T; editor: BlockNoteEditor }) => void; - suggestionsMenuFactory: SuggestionsMenuFactory; -}; - -class SuggestionPluginView< +class SuggestionsMenuView< T extends SuggestionItem, BSchema extends BlockSchema > { - editor: BlockNoteEditor; - pluginKey: PluginKey; - - suggestionsMenu: SuggestionsMenu; + private suggestionsMenuState?: SuggestionsMenuState; + public updateSuggestionsMenu: () => void; pluginState: SuggestionPluginState; - itemCallback: (item: T) => void; - - private lastPosition: DOMRect | undefined; - - constructor({ - editor, - pluginKey, - onSelectItem: selectItemCallback = () => {}, - suggestionsMenuFactory, - }: SuggestionPluginViewOptions) { - this.editor = editor; - this.pluginKey = pluginKey; + constructor( + private readonly editor: BlockNoteEditor, + private readonly pluginKey: PluginKey, + updateSuggestionsMenu: ( + suggestionsMenuState: SuggestionsMenuState + ) => void = () => {} + ) { this.pluginState = getDefaultPluginState(); - this.itemCallback = (item: T) => { - editor._tiptapEditor - .chain() - .focus() - .deleteRange({ - from: - this.pluginState.queryStartPos! - - this.pluginState.triggerCharacter!.length, - to: editor._tiptapEditor.state.selection.from, - }) - .run(); + this.updateSuggestionsMenu = () => { + if (!this.suggestionsMenuState) { + throw new Error("Attempting to update uninitialized suggestions menu"); + } - selectItemCallback({ - item: item, - editor: editor, - }); + updateSuggestionsMenu(this.suggestionsMenuState); }; - this.suggestionsMenu = suggestionsMenuFactory(this.getStaticParams()); + document.addEventListener("scroll", this.handleScroll); } + handleScroll = () => { + if (this.suggestionsMenuState?.show) { + const decorationNode = document.querySelector( + `[data-decoration-id="${this.pluginState.decorationId}"]` + ); + this.suggestionsMenuState.referencePos = + decorationNode!.getBoundingClientRect(); + this.updateSuggestionsMenu(); + } + }; + update(view: EditorView, prevState: EditorState) { const prev = this.pluginKey.getState(prevState); const next = this.pluginKey.getState(view.state); @@ -160,61 +73,64 @@ class SuggestionPluginView< this.pluginState = stopped ? prev : next; if (stopped || !this.editor.isEditable) { - this.suggestionsMenu.hide(); + this.suggestionsMenuState!.show = false; + this.updateSuggestionsMenu(); - // Listener stops focus moving to the menu on click. - this.suggestionsMenu.element!.removeEventListener("mousedown", (event) => - event.preventDefault() - ); + return; } - if (changed) { - this.suggestionsMenu.render(this.getDynamicParams(), false); - } + const decorationNode = document.querySelector( + `[data-decoration-id="${this.pluginState.decorationId}"]` + ); - if (started && this.editor.isEditable) { - this.suggestionsMenu.render(this.getDynamicParams(), true); + if (this.editor.isEditable) { + this.suggestionsMenuState = { + show: true, + referencePos: decorationNode!.getBoundingClientRect(), + filteredItems: this.pluginState.items, + keyboardHoveredItemIndex: this.pluginState.keyboardHoveredItemIndex!, + }; - // Listener stops focus moving to the menu on click. - this.suggestionsMenu.element!.addEventListener("mousedown", (event) => - event.preventDefault() - ); + this.updateSuggestionsMenu(); } } - getStaticParams(): SuggestionsMenuStaticParams { - return { - itemCallback: (item: T) => this.itemCallback(item), - getReferenceRect: () => { - const decorationNode = document.querySelector( - `[data-decoration-id="${this.pluginState.decorationId}"]` - ); - - if (!decorationNode) { - if (this.lastPosition === undefined) { - throw new Error( - "Attempted to access trigger character reference rect before rendering suggestions menu." - ); - } - - return this.lastPosition; - } - - const triggerCharacterBoundingBox = - decorationNode.getBoundingClientRect(); - this.lastPosition = triggerCharacterBoundingBox; - - return triggerCharacterBoundingBox; - }, - }; + destroy() { + document.removeEventListener("scroll", this.handleScroll); } +} - getDynamicParams(): SuggestionsMenuDynamicParams { - return { - items: this.pluginState.items, - keyboardHoveredItemIndex: this.pluginState.keyboardHoveredItemIndex!, - }; - } +type SuggestionPluginState = { + // True when the menu is shown, false when hidden. + active: boolean; + // The character that triggered the menu being shown. Allowing the trigger to be different to the default + // trigger allows other extensions to open it programmatically. + triggerCharacter: string | undefined; + // The editor position just after the trigger character, i.e. where the user query begins. Used to figure out + // which menu items to show and can also be used to delete the trigger character. + queryStartPos: number | undefined; + // The items that should be shown in the menu. + items: T[]; + // The index of the item in the menu that's currently hovered using the keyboard. + keyboardHoveredItemIndex: number | undefined; + // The number of characters typed after the last query that matched with at least 1 item. Used to close the + // menu if the user keeps entering queries that don't return any results. + notFoundCount: number | undefined; + decorationId: string | undefined; +}; + +function getDefaultPluginState< + T extends SuggestionItem +>(): SuggestionPluginState { + return { + active: false, + triggerCharacter: undefined, + queryStartPos: undefined, + items: [] as T[], + keyboardHoveredItemIndex: undefined, + notFoundCount: 0, + decorationId: undefined, + }; } /** @@ -226,271 +142,293 @@ class SuggestionPluginView< * - This version supports generic items instead of only strings (to allow for more advanced filtering for example) * - This version hides some unnecessary complexity from the user of the plugin. * - This version handles key events differently - * - * @param options options for configuring the plugin - * @returns the prosemirror plugin */ -export function createSuggestionPlugin< +export const setupSuggestionsMenu = < T extends SuggestionItem, BSchema extends BlockSchema ->({ - pluginKey, - editor, - defaultTriggerCharacter, - suggestionsMenuFactory, - onSelectItem: selectItemCallback = () => {}, - items = () => [], -}: SuggestionPluginOptions) { +>( + editor: BlockNoteEditor, + updateSuggestionsMenu: ( + suggestionsMenuState: SuggestionsMenuState + ) => void, + + pluginKey: PluginKey, + defaultTriggerCharacter: string, + items: (query: string) => T[] = () => [], + onSelectItem: (props: { + item: T; + editor: BlockNoteEditor; + }) => void = () => {} +) => { // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); } + let suggestionsPluginView: SuggestionsMenuView; + const deactivate = (view: EditorView) => { view.dispatch(view.state.tr.setMeta(pluginKey, { deactivate: true })); }; - // Plugin key is passed in as a parameter, so it can be exported and used in the DraggableBlocksPlugin. - return new Plugin({ - key: pluginKey, + return { + plugin: new Plugin({ + key: pluginKey, - view: (view: EditorView) => - new SuggestionPluginView({ - editor: editor, - pluginKey: pluginKey, - onSelectItem: (props: { - item: T; - editor: BlockNoteEditor; - }) => { - deactivate(view); - selectItemCallback(props); - }, - suggestionsMenuFactory: suggestionsMenuFactory, - }), + view: () => { + suggestionsPluginView = new SuggestionsMenuView( + editor, + pluginKey, - state: { - // Initialize the plugin's internal state. - init(): SuggestionPluginState { - return getDefaultPluginState(); + updateSuggestionsMenu + ); + return suggestionsPluginView; }, - // Apply changes to the plugin state from an editor transaction. - apply(transaction, prev, oldState, newState): SuggestionPluginState { - // TODO: More clearly define which transactions should be ignored. - if (transaction.getMeta("orderedListIndexing") !== undefined) { - return prev; - } - - // Checks if the menu should be shown. - if (transaction.getMeta(pluginKey)?.activate) { - return { - active: true, - triggerCharacter: - transaction.getMeta(pluginKey)?.triggerCharacter || "", - queryStartPos: newState.selection.from, - items: items(""), - keyboardHoveredItemIndex: 0, - // TODO: Maybe should be 1 if the menu has no possible items? Probably redundant since a menu with no items - // is useless in practice. - notFoundCount: 0, - decorationId: `id_${Math.floor(Math.random() * 0xffffffff)}`, - }; - } - - // Checks if the menu is hidden, in which case it doesn't need to be hidden or updated. - if (!prev.active) { - return prev; - } - - const next = { ...prev }; - - // Updates which menu items to show by checking which items the current query (the text between the trigger - // character and caret) matches with. - next.items = items( - newState.doc.textBetween(prev.queryStartPos!, newState.selection.from) - ); + state: { + // Initialize the plugin's internal state. + init(): SuggestionPluginState { + return getDefaultPluginState(); + }, + + // Apply changes to the plugin state from an editor transaction. + apply(transaction, prev, oldState, newState): SuggestionPluginState { + // TODO: More clearly define which transactions should be ignored. + if (transaction.getMeta("orderedListIndexing") !== undefined) { + return prev; + } + + // Checks if the menu should be shown. + if (transaction.getMeta(pluginKey)?.activate) { + return { + active: true, + triggerCharacter: + transaction.getMeta(pluginKey)?.triggerCharacter || "", + queryStartPos: newState.selection.from, + items: items(""), + keyboardHoveredItemIndex: 0, + // TODO: Maybe should be 1 if the menu has no possible items? Probably redundant since a menu with no items + // is useless in practice. + notFoundCount: 0, + decorationId: `id_${Math.floor(Math.random() * 0xffffffff)}`, + }; + } + + // Checks if the menu is hidden, in which case it doesn't need to be hidden or updated. + if (!prev.active) { + return prev; + } - // Updates notFoundCount if the query doesn't match any items. - next.notFoundCount = 0; - if (next.items.length === 0) { - // Checks how many characters were typed or deleted since the last transaction, and updates the notFoundCount - // accordingly. Also ensures the notFoundCount does not become negative. - next.notFoundCount = Math.max( - 0, - prev.notFoundCount! + - (newState.selection.from - oldState.selection.from) + const next = { ...prev }; + + // Updates which menu items to show by checking which items the current query (the text between the trigger + // character and caret) matches with. + next.items = items( + newState.doc.textBetween( + prev.queryStartPos!, + newState.selection.from + ) ); - } - - // Hides the menu. This is done after items and notFoundCount are already updated as notFoundCount is needed to - // check if the menu should be hidden. - if ( - // Highlighting text should hide the menu. - newState.selection.from !== newState.selection.to || - // Transactions with plugin metadata {deactivate: true} should hide the menu. - transaction.getMeta(pluginKey)?.deactivate || - // Certain mouse events should hide the menu. - // TODO: Change to global mousedown listener. - transaction.getMeta("focus") || - transaction.getMeta("blur") || - transaction.getMeta("pointer") || - // Moving the caret before the character which triggered the menu should hide it. - (prev.active && newState.selection.from < prev.queryStartPos!) || - // Entering more than 3 characters, after the last query that matched with at least 1 menu item, should hide - // the menu. - next.notFoundCount > 3 - ) { - return getDefaultPluginState(); - } - - // Updates keyboardHoveredItemIndex if necessary. - if ( - transaction.getMeta(pluginKey)?.selectedItemIndexChanged !== undefined - ) { - let newIndex = - transaction.getMeta(pluginKey).selectedItemIndexChanged; - - // Allows selection to jump between first and last items. - if (newIndex < 0) { - newIndex = prev.items.length - 1; - } else if (newIndex >= prev.items.length) { - newIndex = 0; + + // Updates notFoundCount if the query doesn't match any items. + next.notFoundCount = 0; + if (next.items.length === 0) { + // Checks how many characters were typed or deleted since the last transaction, and updates the notFoundCount + // accordingly. Also ensures the notFoundCount does not become negative. + next.notFoundCount = Math.max( + 0, + prev.notFoundCount! + + (newState.selection.from - oldState.selection.from) + ); } - next.keyboardHoveredItemIndex = newIndex; - } + // Hides the menu. This is done after items and notFoundCount are already updated as notFoundCount is needed to + // check if the menu should be hidden. + if ( + // Highlighting text should hide the menu. + newState.selection.from !== newState.selection.to || + // Transactions with plugin metadata {deactivate: true} should hide the menu. + transaction.getMeta(pluginKey)?.deactivate || + // Certain mouse events should hide the menu. + // TODO: Change to global mousedown listener. + transaction.getMeta("focus") || + transaction.getMeta("blur") || + transaction.getMeta("pointer") || + // Moving the caret before the character which triggered the menu should hide it. + (prev.active && newState.selection.from < prev.queryStartPos!) || + // Entering more than 3 characters, after the last query that matched with at least 1 menu item, should hide + // the menu. + next.notFoundCount > 3 + ) { + return getDefaultPluginState(); + } - return next; + // Updates keyboardHoveredItemIndex if the up or down arrow key was + // pressed, or resets it if the keyboard cursor moved. + if ( + transaction.getMeta(pluginKey)?.selectedItemIndexChanged !== + undefined + ) { + let newIndex = + transaction.getMeta(pluginKey).selectedItemIndexChanged; + + // Allows selection to jump between first and last items. + if (newIndex < 0) { + newIndex = prev.items.length - 1; + } else if (newIndex >= prev.items.length) { + newIndex = 0; + } + + next.keyboardHoveredItemIndex = newIndex; + } else if (oldState.selection.from !== newState.selection.from) { + next.keyboardHoveredItemIndex = 0; + } + + return next; + }, }, - }, - props: { - handleKeyDown(view, event) { - const menuIsActive = (this as Plugin).getState(view.state).active; - - // Shows the menu if the default trigger character was pressed and the menu isn't active. - if (event.key === defaultTriggerCharacter && !menuIsActive) { - view.dispatch( - view.state.tr - .insertText(defaultTriggerCharacter) - .scrollIntoView() - .setMeta(pluginKey, { - activate: true, - triggerCharacter: defaultTriggerCharacter, + props: { + handleKeyDown(view, event) { + const menuIsActive = (this as Plugin).getState(view.state).active; + + // Shows the menu if the default trigger character was pressed and the menu isn't active. + if (event.key === defaultTriggerCharacter && !menuIsActive) { + view.dispatch( + view.state.tr + .insertText(defaultTriggerCharacter) + .scrollIntoView() + .setMeta(pluginKey, { + activate: true, + triggerCharacter: defaultTriggerCharacter, + }) + ); + + return true; + } + + // Doesn't handle other keystrokes if the menu isn't active. + if (!menuIsActive) { + return false; + } + + // Handles keystrokes for navigating the menu. + const { + triggerCharacter, + queryStartPos, + items, + keyboardHoveredItemIndex, + } = pluginKey.getState(view.state); + + // Moves the keyboard selection to the previous item. + if (event.key === "ArrowUp") { + view.dispatch( + view.state.tr.setMeta(pluginKey, { + selectedItemIndexChanged: keyboardHoveredItemIndex - 1, }) - ); + ); + return true; + } + + // Moves the keyboard selection to the next item. + if (event.key === "ArrowDown") { + view.dispatch( + view.state.tr.setMeta(pluginKey, { + selectedItemIndexChanged: keyboardHoveredItemIndex + 1, + }) + ); + return true; + } - return true; - } + // Selects an item and closes the menu. + if (event.key === "Enter") { + deactivate(view); + editor._tiptapEditor + .chain() + .focus() + .deleteRange({ + from: queryStartPos! - triggerCharacter!.length, + to: editor._tiptapEditor.state.selection.from, + }) + .run(); + + onSelectItem({ + item: items[keyboardHoveredItemIndex], + editor: editor, + }); + + return true; + } + + // Closes the menu. + if (event.key === "Escape") { + deactivate(view); + return true; + } - // Doesn't handle other keystrokes if the menu isn't active. - if (!menuIsActive) { return false; - } - - // Handles keystrokes for navigating the menu. - const { - triggerCharacter, - queryStartPos, - items, - keyboardHoveredItemIndex, - } = pluginKey.getState(view.state); - - // Moves the keyboard selection to the previous item. - if (event.key === "ArrowUp") { - view.dispatch( - view.state.tr.setMeta(pluginKey, { - selectedItemIndexChanged: keyboardHoveredItemIndex - 1, - }) - ); - return true; - } - - // Moves the keyboard selection to the next item. - if (event.key === "ArrowDown") { - view.dispatch( - view.state.tr.setMeta(pluginKey, { - selectedItemIndexChanged: keyboardHoveredItemIndex + 1, - }) - ); - return true; - } - - // Selects an item and closes the menu. - if (event.key === "Enter") { - deactivate(view); - editor._tiptapEditor - .chain() - .focus() - .deleteRange({ - from: queryStartPos! - triggerCharacter!.length, - to: editor._tiptapEditor.state.selection.from, - }) - .run(); - - selectItemCallback({ - item: items[keyboardHoveredItemIndex], - editor: editor, - }); - - return true; - } - - // Closes the menu. - if (event.key === "Escape") { - deactivate(view); - return true; - } - - return false; - }, + }, - // Hides menu in cases where mouse click does not cause an editor state change. - handleClick(view) { - deactivate(view); - }, + // Setup decorator on the currently active suggestion. + decorations(state) { + const { active, decorationId, queryStartPos, triggerCharacter } = ( + this as Plugin + ).getState(state); - // Setup decorator on the currently active suggestion. - decorations(state) { - const { active, decorationId, queryStartPos, triggerCharacter } = ( - this as Plugin - ).getState(state); - - if (!active) { - return null; - } - - // If the menu was opened programmatically by another extension, it may not use a trigger character. In this - // case, the decoration is set on the whole block instead, as the decoration range would otherwise be empty. - if (triggerCharacter === "") { - const blockNode = findBlock(state.selection); - if (blockNode) { - return DecorationSet.create(state.doc, [ - Decoration.node( - blockNode.pos, - blockNode.pos + blockNode.node.nodeSize, - { - nodeName: "span", - class: "suggestion-decorator", - "data-decoration-id": decorationId, - } - ), - ]); + if (!active) { + return null; } - } - // Creates an inline decoration around the trigger character. - return DecorationSet.create(state.doc, [ - Decoration.inline( - queryStartPos - triggerCharacter.length, - queryStartPos, - { - nodeName: "span", - class: "suggestion-decorator", - "data-decoration-id": decorationId, + + // If the menu was opened programmatically by another extension, it may not use a trigger character. In this + // case, the decoration is set on the whole block instead, as the decoration range would otherwise be empty. + if (triggerCharacter === "") { + const blockNode = findBlock(state.selection); + if (blockNode) { + return DecorationSet.create(state.doc, [ + Decoration.node( + blockNode.pos, + blockNode.pos + blockNode.node.nodeSize, + { + nodeName: "span", + class: "suggestion-decorator", + "data-decoration-id": decorationId, + } + ), + ]); } - ), - ]); + } + // Creates an inline decoration around the trigger character. + return DecorationSet.create(state.doc, [ + Decoration.inline( + queryStartPos - triggerCharacter.length, + queryStartPos, + { + nodeName: "span", + class: "suggestion-decorator", + "data-decoration-id": decorationId, + } + ), + ]); + }, }, + }), + itemCallback: (item: T) => { + deactivate(editor._tiptapEditor.view); + 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/core/src/shared/plugins/suggestion/SuggestionsMenuFactoryTypes.ts b/packages/core/src/shared/plugins/suggestion/SuggestionsMenuFactoryTypes.ts deleted file mode 100644 index 20fd5dda39..0000000000 --- a/packages/core/src/shared/plugins/suggestion/SuggestionsMenuFactoryTypes.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { EditorElement, ElementFactory } from "../../EditorElement"; -import { SuggestionItem } from "./SuggestionItem"; - -export type SuggestionsMenuStaticParams = { - itemCallback: (item: T) => void; - - getReferenceRect: () => DOMRect; -}; - -export type SuggestionsMenuDynamicParams = { - items: T[]; - keyboardHoveredItemIndex: number; -}; - -export type SuggestionsMenu = EditorElement< - SuggestionsMenuDynamicParams ->; -export type SuggestionsMenuFactory = ElementFactory< - SuggestionsMenuStaticParams, - SuggestionsMenuDynamicParams ->; diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index ffc0ae860c..6e237ad1c1 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -1,15 +1,33 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; -// import { BlockNoteTheme } from "./BlockNoteTheme"; -// import { MantineProvider } from "@mantine/core"; +import { HTMLAttributes, ReactNode } from "react"; +import { getBlockNoteTheme } from "./BlockNoteTheme"; +import { FormattingToolbarPositioner } from "./FormattingToolbar/components/FormattingToolbarPositioner"; +import { HyperlinkToolbarPositioner } from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; +import { SideMenuPositioner } from "./SideMenu/components/SideMenuPositioner"; +import { SlashMenuPositioner } from "./SlashMenu/components/SlashMenuPositioner"; + +export function BlockNoteView( + props: { + editor: BlockNoteEditor; + children?: ReactNode; + } & HTMLAttributes +) { + const { editor, children, ...rest } = props; -export function BlockNoteView(props: { - editor: BlockNoteEditor | null; -}) { return ( - // TODO: Should we wrap editor in MantineProvider? Otherwise we have to duplicate color hex values. - // - - // + + + {props.children || ( + <> + + + + + + )} + + ); } diff --git a/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx b/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx deleted file mode 100644 index 6d8b608a5a..0000000000 --- a/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { FC } from "react"; -import { - BlockSchema, - BlockSideMenuDynamicParams, - BlockSideMenuStaticParams, -} from "@blocknote/core"; -import { MantineThemeOverride } from "@mantine/core"; -import { ReactElementFactory } from "../ElementFactory/components/ReactElementFactory"; -import { BlockSideMenu as ReactBlockSideMenu } from "./components/BlockSideMenu"; -import { DragHandleMenuProps } from "./components/DragHandleMenu"; -import { DefaultDragHandleMenu } from "./components/DefaultDragHandleMenu"; - -export const createReactBlockSideMenuFactory = ( - theme: MantineThemeOverride, - dragHandleMenu: FC> = DefaultDragHandleMenu -) => { - const CustomDragHandleMenu = dragHandleMenu; - const CustomBlockSideMenu = ( - props: BlockSideMenuStaticParams & - BlockSideMenuDynamicParams - ) => ; - - return (staticParams: BlockSideMenuStaticParams) => - ReactElementFactory< - BlockSideMenuStaticParams, - BlockSideMenuDynamicParams - >(staticParams, CustomBlockSideMenu, theme, { - animation: "fade", - offset: [0, 0], - placement: "left", - popperOptions: { - modifiers: [ - { - name: "flip", - options: { - fallbackPlacements: [], - }, - }, - { - name: "preventOverflow", - options: { - mainAxis: false, - altAxis: false, - }, - }, - ], - }, - }); -}; diff --git a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx deleted file mode 100644 index 1f5555bab6..0000000000 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import { Block, BlockNoteEditor, BlockSchema } from "@blocknote/core"; -import { ActionIcon, Group, Menu } from "@mantine/core"; -import { FC, useEffect, useRef, useState } from "react"; -import { AiOutlinePlus } from "react-icons/ai"; -import { MdDragIndicator } from "react-icons/md"; -import { DefaultDragHandleMenu } from "./DefaultDragHandleMenu"; -import { DragHandleMenuProps } from "./DragHandleMenu"; - -export type BlockSideMenuProps = { - editor: BlockNoteEditor; - block: Block; - dragHandleMenu?: FC>; - addBlock: () => void; - blockDragStart: (event: DragEvent) => void; - blockDragEnd: () => void; - freezeMenu: () => void; - unfreezeMenu: () => void; -}; - -export const BlockSideMenu = ( - props: BlockSideMenuProps -) => { - const [dragHandleMenuOpened, setDragHandleMenuOpened] = useState(false); - - const dragHandleRef = useRef(null); - - useEffect(() => { - const dragHandle = dragHandleRef.current; - - if (dragHandle instanceof HTMLDivElement) { - dragHandle.addEventListener("dragstart", props.blockDragStart); - dragHandle.addEventListener("dragend", props.blockDragEnd); - - return () => { - dragHandle.removeEventListener("dragstart", props.blockDragStart); - dragHandle.removeEventListener("dragend", props.blockDragEnd); - }; - } - - return; - }, [props.blockDragEnd, props.blockDragStart]); - - const closeMenu = () => { - setDragHandleMenuOpened(false); - props.unfreezeMenu(); - }; - - const DragHandleMenu = props.dragHandleMenu || DefaultDragHandleMenu; - - return ( - - - { - { - props.addBlock(); - }} - /> - } - - - -
- { - setDragHandleMenuOpened(true); - props.freezeMenu(); - }} - size={24} - data-test={"dragHandle"}> - {} - -
-
- -
-
- ); -}; diff --git a/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx b/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx deleted file mode 100644 index f8ce980238..0000000000 --- a/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { Menu } from "@mantine/core"; -import { PolymorphicComponentProps } from "@mantine/utils"; - -export type DragHandleMenuItemProps = PolymorphicComponentProps<"button"> & { - closeMenu: () => void; -}; - -export const DragHandleMenuItem = (props: DragHandleMenuItemProps) => { - const {closeMenu, onClick, ...propsToPassThrough} = props; - return { - closeMenu(); - onClick?.(event); - }}> - {props.children} - ; -}; diff --git a/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx b/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx index 6c41ee5f26..e69de29bb2 100644 --- a/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx +++ b/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx @@ -1,65 +0,0 @@ -import { MantineProvider, MantineThemeOverride } from "@mantine/core"; -import Tippy, { TippyProps } from "@tippyjs/react"; -import { RequiredDynamicParams, RequiredStaticParams } from "@blocknote/core"; -import { FC, useCallback, useState } from "react"; - -/** - * Component used in the ReactElementFactory to wrap the EditorElementComponent in a MantineProvider and Tippy - * component. The MantineProvider is used to add theming while the Tippy component is used to control show/hide - * behavior. - * - * @param props The component props. Includes the same props as ReactElementFactory, as well as the current set of - * EditorDynamicParams. Also provides props to determine if the element should be open and which element it should be - * mounted under. - */ -export function EditorElementComponentWrapper< - ElementStaticParams extends RequiredStaticParams, - ElementDynamicParams extends RequiredDynamicParams ->(props: { - rootElement: HTMLElement; - isOpen: boolean; - staticParams: ElementStaticParams; - dynamicParams: ElementDynamicParams; - editorElementComponent: FC; - theme: MantineThemeOverride; - tippyProps?: TippyProps; -}) { - const EditorElementComponent = props.editorElementComponent; - - const [contentCleared, setContentCleared] = useState(false); - - const onShow = useCallback(() => { - setContentCleared(false); - document.body.appendChild(props.rootElement); - }, [props.rootElement]); - - const onHidden = useCallback(() => { - props.rootElement.remove(); - setContentCleared(true); - }, [props.rootElement]); - - return ( - - - ) : undefined - } - // Type cast is needed as getReferenceRect will return `undefined` when - // the editor is initialized but the element hasn't been rendered yet. - // Otherwise, it will always return a `DOMRect`. - getReferenceClientRect={props.staticParams.getReferenceRect} - interactive={true} - onShow={onShow} - onHidden={onHidden} - visible={props.isOpen} - {...props.tippyProps} - /> - - ); -} diff --git a/packages/react/src/ElementFactory/components/ReactElementFactory.tsx b/packages/react/src/ElementFactory/components/ReactElementFactory.tsx index 79d3261269..e69de29bb2 100644 --- a/packages/react/src/ElementFactory/components/ReactElementFactory.tsx +++ b/packages/react/src/ElementFactory/components/ReactElementFactory.tsx @@ -1,74 +0,0 @@ -import { FC } from "react"; -import { TippyProps } from "@tippyjs/react"; -import { createRoot } from "react-dom/client"; -import { - EditorElement, - RequiredDynamicParams, - RequiredStaticParams, -} from "@blocknote/core"; -import { EditorElementComponentWrapper } from "./EditorElementComponentWrapper"; -import { MantineThemeOverride } from "@mantine/core"; - -/** - * The ReactElementFactory is a generic function used to create all other ElementFactories, which are then used in the - * BlockNote editor. The type of ElementFactory created depends on the provided ElementStaticParams and - * ElementDynamicParams, which determine what static/dynamic properties are used in rendering the element. - * ElementStaticParams are initialized when the editor mounts and do not change, while ElementDynamicParams change based - * on the editor state. - * - * @param staticParams Properties used in rendering the element which do not change, regardless of editor state. - * @param EditorElementComponent The element to render, which is a React component. Takes EditorStaticParams and - * EditorDynamicParams as props. - * @param theme The Mantine theme used to style the element. - * @param tippyProps Tippy props, which affect the elements' popup behaviour, e.g. popup position, animation, etc. - */ -export const ReactElementFactory = < - ElementStaticParams extends RequiredStaticParams, - ElementDynamicParams extends RequiredDynamicParams ->( - staticParams: ElementStaticParams, - EditorElementComponent: FC, - theme: MantineThemeOverride, - tippyProps?: TippyProps -): EditorElement => { - const rootElement = document.createElement("div"); - const root = createRoot(rootElement); - - // Used when hiding the element. Without being passed a set of dynamic params, - // certain menus/toolbars will not render correctly. - let prevDynamicParams: ElementDynamicParams | undefined = undefined; - - return { - element: rootElement, - render: (dynamicParams: ElementDynamicParams, _isHidden: boolean) => { - prevDynamicParams = dynamicParams; - - root.render( - - ); - }, - hide: () => { - root.render( - - ); - - prevDynamicParams = undefined; - }, - }; -}; diff --git a/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx b/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx deleted file mode 100644 index bb9c521fb3..0000000000 --- a/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { - FormattingToolbarStaticParams, - FormattingToolbarDynamicParams, - BlockNoteEditor, - BlockSchema, -} from "@blocknote/core"; -import { FormattingToolbar as ReactFormattingToolbar } from "./components/FormattingToolbar"; -import { ReactElementFactory } from "../ElementFactory/components/ReactElementFactory"; -import { FC } from "react"; -import { MantineThemeOverride } from "@mantine/core"; - -export const createReactFormattingToolbarFactory = < - BSchema extends BlockSchema ->( - theme: MantineThemeOverride, - toolbar: FC<{ - editor: BlockNoteEditor; - }> = ReactFormattingToolbar -) => { - return (staticParams: FormattingToolbarStaticParams) => - ReactElementFactory< - FormattingToolbarStaticParams, - FormattingToolbarDynamicParams - >(staticParams, toolbar, theme, { - animation: "fade", - placement: "top-start", - }); -}; diff --git a/packages/react/src/FormattingToolbar/components/DefaultButtons/ColorStyleButton.tsx b/packages/react/src/FormattingToolbar/components/DefaultButtons/ColorStyleButton.tsx index dcd6439d78..2eca1eb91a 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/ColorStyleButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/ColorStyleButton.tsx @@ -1,13 +1,36 @@ -import { useCallback } from "react"; +import { useCallback, useState } from "react"; import { Menu } from "@mantine/core"; import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { ToolbarButton } from "../../../SharedComponents/Toolbar/components/ToolbarButton"; import { ColorIcon } from "../../../SharedComponents/ColorPicker/components/ColorIcon"; import { ColorPicker } from "../../../SharedComponents/ColorPicker/components/ColorPicker"; +import { useEditorContentChange } from "../../../hooks/useEditorContentChange"; +import { useEditorSelectionChange } from "../../../hooks/useEditorSelectionChange"; export const ColorStyleButton = (props: { editor: BlockNoteEditor; }) => { + const [currentTextColor, setCurrentTextColor] = useState( + props.editor.getActiveStyles().textColor || "default" + ); + const [currentBackgroundColor, setCurrentBackgroundColor] = useState( + props.editor.getActiveStyles().backgroundColor || "default" + ); + + useEditorContentChange(props.editor, () => { + setCurrentTextColor(props.editor.getActiveStyles().textColor || "default"); + setCurrentBackgroundColor( + props.editor.getActiveStyles().backgroundColor || "default" + ); + }); + + useEditorSelectionChange(props.editor, () => { + setCurrentTextColor(props.editor.getActiveStyles().textColor || "default"); + setCurrentBackgroundColor( + props.editor.getActiveStyles().backgroundColor || "default" + ); + }); + const setTextColor = useCallback( (color: string) => { props.editor.focus(); @@ -35,10 +58,8 @@ export const ColorStyleButton = (props: { mainTooltip={"Colors"} icon={() => ( )} @@ -46,11 +67,9 @@ export const ColorStyleButton = (props: { diff --git a/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx b/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx index 016b6f4d3e..465c89ab7d 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx @@ -1,12 +1,25 @@ -import { useCallback } from "react"; +import { useCallback, useState } from "react"; import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { RiLink } from "react-icons/ri"; import LinkToolbarButton from "../LinkToolbarButton"; import { formatKeyboardShortcut } from "../../../utils"; +import { useEditorSelectionChange } from "../../../hooks/useEditorSelectionChange"; export const CreateLinkButton = (props: { editor: BlockNoteEditor; }) => { + const [url, setUrl] = useState( + props.editor.getSelectedLinkUrl() || "" + ); + const [text, setText] = useState( + props.editor.getSelectedText() || "" + ); + + useEditorSelectionChange(props.editor, () => { + setText(props.editor.getSelectedText() || ""); + setUrl(props.editor.getSelectedLinkUrl() || ""); + }); + const setLink = useCallback( (url: string, text?: string) => { props.editor.focus(); @@ -17,13 +30,13 @@ export const CreateLinkButton = (props: { return ( ); diff --git a/packages/react/src/FormattingToolbar/components/DefaultButtons/NestBlockButtons.tsx b/packages/react/src/FormattingToolbar/components/DefaultButtons/NestBlockButtons.tsx index fd05fae03e..50b5bbe9eb 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/NestBlockButtons.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/NestBlockButtons.tsx @@ -2,11 +2,23 @@ import { formatKeyboardShortcut } from "../../../utils"; import { RiIndentDecrease, RiIndentIncrease } from "react-icons/ri"; import { ToolbarButton } from "../../../SharedComponents/Toolbar/components/ToolbarButton"; import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; -import { useCallback } from "react"; +import { useCallback, useState } from "react"; +import { useEditorSelectionChange } from "../../../hooks/useEditorSelectionChange"; +import { useEditorContentChange } from "../../../hooks/useEditorContentChange"; export const NestBlockButton = (props: { editor: BlockNoteEditor; }) => { + const [canNestBlock, setCanNestBlock] = useState(); + + useEditorContentChange(props.editor, () => { + setCanNestBlock(props.editor.canNestBlock()); + }); + + useEditorSelectionChange(props.editor, () => { + setCanNestBlock(props.editor.canNestBlock()); + }); + const nestBlock = useCallback(() => { props.editor.focus(); props.editor.nestBlock(); @@ -15,7 +27,7 @@ export const NestBlockButton = (props: { return ( (props: { export const UnnestBlockButton = (props: { editor: BlockNoteEditor; }) => { + const [canUnnestBlock, setCanUnnestBlock] = useState(); + + useEditorContentChange(props.editor, () => { + setCanUnnestBlock(props.editor.canUnnestBlock()); + }); + + useEditorSelectionChange(props.editor, () => { + setCanUnnestBlock(props.editor.canUnnestBlock()); + }); + const unnestBlock = useCallback(() => { props.editor.focus(); props.editor.unnestBlock(); @@ -34,7 +56,7 @@ export const UnnestBlockButton = (props: { return ( (props: { editor: BlockNoteEditor; textAlignment: TextAlignment; }) => { + const [activeTextAlignment, setActiveTextAlignment] = useState(() => { + const block = props.editor.getTextCursorPosition().block; + + if ("textAlignment" in block.props) { + return block.props.textAlignment as TextAlignment; + } + + return; + }); + + useEditorContentChange(props.editor, () => { + const block = props.editor.getTextCursorPosition().block; + + if ("textAlignment" in block.props) { + setActiveTextAlignment(block.props.textAlignment as TextAlignment); + } + }); + + useEditorSelectionChange(props.editor, () => { + const block = props.editor.getTextCursorPosition().block; + + if ("textAlignment" in block.props) { + setActiveTextAlignment(block.props.textAlignment as TextAlignment); + } + }); + const show = useMemo(() => { const selection = props.editor.getSelection(); @@ -77,10 +105,7 @@ export const TextAlignButton = (props: { return ( setTextAlignment(props.textAlignment)} - isSelected={ - props.editor.getTextCursorPosition().block.props.textAlignment === - props.textAlignment - } + isSelected={activeTextAlignment === props.textAlignment} mainTooltip={ props.textAlignment === "justify" ? "Justify Text" diff --git a/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx b/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx index 375d9475ab..5328b5e5ba 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx @@ -9,6 +9,9 @@ import { } from "react-icons/ri"; import { BlockNoteEditor, BlockSchema, ToggledStyle } from "@blocknote/core"; import { IconType } from "react-icons"; +import { useState } from "react"; +import { useEditorContentChange } from "../../../hooks/useEditorContentChange"; +import { useEditorSelectionChange } from "../../../hooks/useEditorSelectionChange"; const shortcuts: Record = { bold: "Mod+B", @@ -30,6 +33,17 @@ export const ToggledStyleButton = (props: { editor: BlockNoteEditor; toggledStyle: ToggledStyle; }) => { + const [active, setActive] = useState( + props.toggledStyle in props.editor.getActiveStyles() + ); + + useEditorContentChange(props.editor, () => { + setActive(props.toggledStyle in props.editor.getActiveStyles()); + }); + + useEditorSelectionChange(props.editor, () => { + setActive(props.toggledStyle in props.editor.getActiveStyles()); + }); const toggleStyle = (style: ToggledStyle) => { props.editor.focus(); @@ -39,7 +53,7 @@ export const ToggledStyleButton = (props: { return ( toggleStyle(props.toggledStyle)} - isSelected={props.toggledStyle in props.editor.getActiveStyles()} + isSelected={active} mainTooltip={ props.toggledStyle.slice(0, 1).toUpperCase() + props.toggledStyle.slice(1) diff --git a/packages/react/src/FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown.tsx b/packages/react/src/FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown.tsx index b6ce8fe6f5..3391da14e7 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown.tsx @@ -3,7 +3,7 @@ import { BlockSchema, DefaultBlockSchema, } from "@blocknote/core"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { IconType } from "react-icons"; import { RiH1, @@ -14,6 +14,8 @@ import { RiText, } from "react-icons/ri"; import { ToolbarDropdown } from "../../../SharedComponents/Toolbar/components/ToolbarDropdown"; +import { useEditorSelectionChange } from "../../../hooks/useEditorSelectionChange"; +import { useEditorContentChange } from "../../../hooks/useEditorContentChange"; type HeadingLevels = "1" | "2" | "3"; @@ -39,10 +41,13 @@ export const BlockTypeDropdown = (props: { props.editor.getTextCursorPosition().block ); - useEffect( - () => setBlock(props.editor.getTextCursorPosition().block), - [props] - ); + useEditorContentChange(props.editor, () => { + setBlock(props.editor.getTextCursorPosition().block); + }); + + useEditorSelectionChange(props.editor, () => { + setBlock(props.editor.getTextCursorPosition().block); + }); if (!shouldShow(props.editor.schema)) { return null; diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx similarity index 84% rename from packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx rename to packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx index 85b3650d0b..17591e17c6 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx @@ -1,18 +1,20 @@ -import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { BlockSchema } from "@blocknote/core"; + +import { FormattingToolbarProps } from "./FormattingToolbarPositioner"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; +import { BlockTypeDropdown } from "./DefaultDropdowns/BlockTypeDropdown"; +import { ToggledStyleButton } from "./DefaultButtons/ToggledStyleButton"; +import { TextAlignButton } from "./DefaultButtons/TextAlignButton"; import { ColorStyleButton } from "./DefaultButtons/ColorStyleButton"; -import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; import { NestBlockButton, UnnestBlockButton, } from "./DefaultButtons/NestBlockButtons"; -import { TextAlignButton } from "./DefaultButtons/TextAlignButton"; -import { ToggledStyleButton } from "./DefaultButtons/ToggledStyleButton"; -import { BlockTypeDropdown } from "./DefaultDropdowns/BlockTypeDropdown"; +import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; -export const FormattingToolbar = (props: { - editor: BlockNoteEditor; -}) => { +export const DefaultFormattingToolbar = ( + props: FormattingToolbarProps +) => { return ( diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx new file mode 100644 index 0000000000..2baaca73cb --- /dev/null +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -0,0 +1,72 @@ +import { + BlockNoteEditor, + BlockSchema, + DefaultBlockSchema, +} 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"; + +export type FormattingToolbarProps< + BSchema extends BlockSchema = DefaultBlockSchema +> = { + editor: BlockNoteEditor; +}; + +export const FormattingToolbarPositioner = < + BSchema extends BlockSchema = DefaultBlockSchema +>(props: { + editor: BlockNoteEditor; + formattingToolbar?: FC>; +}) => { + const [show, setShow] = useState(false); + + const referencePos = useRef(); + + useEffect(() => { + return props.editor.formattingToolbar.onUpdate((state) => { + setShow(state.show); + + referencePos.current = state.referencePos; + }); + }, [props.editor]); + + const getReferenceClientRect = useMemo( + () => { + if (!referencePos) { + return undefined; + } + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); + + const formattingToolbarElement = useMemo(() => { + const FormattingToolbar = + props.formattingToolbar || DefaultFormattingToolbar; + + return ; + }, [props.editor, props.formattingToolbar]); + + return ( + + ); +}; + +// We want Tippy to call `getReferenceClientRect` whenever the reference +// DOMRect's position changes. This happens automatically on scroll, but we need +// the `sticky` plugin to make it happen in all cases. This is most evident +// when changing the text alignment using the formatting toolbar. +const tippyPlugins = [sticky]; diff --git a/packages/react/src/HyperlinkToolbar/EditHyperlinkMenu/components/EditHyperlinkMenu.tsx b/packages/react/src/HyperlinkToolbar/EditHyperlinkMenu/components/EditHyperlinkMenu.tsx index d2c2eee650..dfc9135e4a 100644 --- a/packages/react/src/HyperlinkToolbar/EditHyperlinkMenu/components/EditHyperlinkMenu.tsx +++ b/packages/react/src/HyperlinkToolbar/EditHyperlinkMenu/components/EditHyperlinkMenu.tsx @@ -1,5 +1,5 @@ import { createStyles, Stack } from "@mantine/core"; -import { forwardRef, useState } from "react"; +import { forwardRef, HTMLAttributes, useState } from "react"; import { RiLink, RiText } from "react-icons/ri"; import { EditHyperlinkMenuItem } from "./EditHyperlinkMenuItem"; @@ -15,33 +15,36 @@ export type EditHyperlinkMenuProps = { */ export const EditHyperlinkMenu = forwardRef< HTMLDivElement, - EditHyperlinkMenuProps ->((props, ref) => { + EditHyperlinkMenuProps & HTMLAttributes +>(({ url, text, update, className, ...props }, ref) => { const { classes } = createStyles({ root: {} })(undefined, { name: "EditHyperlinkMenu", }); - const [url, setUrl] = useState(props.url); - const [title, setTitle] = useState(props.text); + const [currentUrl, setCurrentUrl] = useState(url); + const [currentText, setCurrentText] = useState(text); return ( - + setUrl(value)} - onSubmit={() => props.update(url, title)} + value={currentUrl} + onChange={(value) => setCurrentUrl(value)} + onSubmit={() => update(currentUrl, currentText)} /> setTitle(value)} - onSubmit={() => props.update(url, title)} + value={currentText} + onChange={(value) => setCurrentText(value)} + onSubmit={() => update(url, currentText)} /> ); diff --git a/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx b/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx deleted file mode 100644 index 5bf7e0ad27..0000000000 --- a/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { - HyperlinkToolbar, - HyperlinkToolbarDynamicParams, - HyperlinkToolbarFactory, - HyperlinkToolbarStaticParams, -} from "@blocknote/core"; -import { HyperlinkToolbar as ReactHyperlinkToolbar } from "./components/HyperlinkToolbar"; -import { ReactElementFactory } from "../ElementFactory/components/ReactElementFactory"; -import { MantineThemeOverride } from "@mantine/core"; - -export const createReactHyperlinkToolbarFactory = - (theme: MantineThemeOverride): HyperlinkToolbarFactory => - (staticParams): HyperlinkToolbar => - ReactElementFactory< - HyperlinkToolbarStaticParams, - HyperlinkToolbarDynamicParams - >(staticParams, ReactHyperlinkToolbar, theme, { - animation: "fade", - placement: "top-start", - }); diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx similarity index 56% rename from packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx rename to packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx index f2ce16b66b..ec0850ec34 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx @@ -1,36 +1,40 @@ -import { useState } from "react"; -import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; -import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; -import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; +import { useRef, useState } from "react"; import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; -// import rootStyles from "../../../root.module.css"; -export type HyperlinkToolbarProps = { - url: string; - text: string; - editHyperlink: (url: string, text: string) => void; - deleteHyperlink: () => void; -}; +import { HyperlinkToolbarProps } from "./HyperlinkToolbarPositioner"; + +import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; +import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; +import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; -/** - * Main menu component for the hyperlink extension. - * Renders a toolbar that appears on hyperlink hover. - */ -export const HyperlinkToolbar = (props: HyperlinkToolbarProps) => { - const [isEditing, setIsEditing] = useState(false); +export const DefaultHyperlinkToolbar = (props: HyperlinkToolbarProps) => { + const [isEditing, setIsEditing] = useState(false); + const editMenuRef = useRef(null); if (isEditing) { return ( props.editHyperlink(url, text)} + // TODO: Better way of waiting for fade out + onBlur={(event) => + setTimeout(() => { + if (editMenuRef.current?.contains(event.relatedTarget)) { + return; + } + setIsEditing(false); + }, 500) + } + ref={editMenuRef} /> ); } return ( - + , + "editHyperlink" | "deleteHyperlink" | "startHideTimer" | "stopHideTimer" +> & + Omit; + +export const HyperlinkToolbarPositioner = < + BSchema extends BlockSchema = DefaultBlockSchema +>(props: { + editor: BlockNoteEditor; + hyperlinkToolbar?: FC; +}) => { + const [show, setShow] = useState(false); + const [url, setUrl] = useState(); + const [text, setText] = useState(); + + const referencePos = useRef(); + + useEffect(() => { + return props.editor.hyperlinkToolbar.on( + "update", + (hyperlinkToolbarState) => { + setShow(hyperlinkToolbarState.show); + setUrl(hyperlinkToolbarState.url); + setText(hyperlinkToolbarState.text); + + referencePos.current = hyperlinkToolbarState.referencePos; + } + ); + }, [props.editor]); + + const getReferenceClientRect = useMemo( + () => { + if (!referencePos.current) { + return undefined; + } + + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); + + const hyperlinkToolbarElement = useMemo(() => { + if (!url || !text) { + return null; + } + + const HyperlinkToolbar = props.hyperlinkToolbar || DefaultHyperlinkToolbar; + + return ( + + ); + }, [props.hyperlinkToolbar, props.editor, text, url]); + + return ( + setIsEditing(false)} + content={hyperlinkToolbarElement} + getReferenceClientRect={getReferenceClientRect} + interactive={true} + visible={show} + animation={"fade"} + placement={"top-start"} + /> + ); +}; diff --git a/packages/react/src/SharedComponents/Toolbar/components/Toolbar.tsx b/packages/react/src/SharedComponents/Toolbar/components/Toolbar.tsx index df46517e30..cd10c4f601 100644 --- a/packages/react/src/SharedComponents/Toolbar/components/Toolbar.tsx +++ b/packages/react/src/SharedComponents/Toolbar/components/Toolbar.tsx @@ -1,10 +1,22 @@ import { createStyles, Group } from "@mantine/core"; -import { ReactNode } from "react"; +import { forwardRef, HTMLAttributes } from "react"; -export const Toolbar = (props: { children: ReactNode }) => { +export const Toolbar = forwardRef< + HTMLDivElement, + HTMLAttributes +>((props, ref) => { const { classes } = createStyles({ root: {} })(undefined, { name: "Toolbar", }); - return {props.children}; -}; + return ( + + {props.children} + + ); +}); diff --git a/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx b/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx index 9e8e5ff474..8d7a6ca02d 100644 --- a/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx +++ b/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx @@ -16,7 +16,9 @@ export type ToolbarDropdownProps = { }; export function ToolbarDropdown(props: ToolbarDropdownProps) { - const activeItem = props.items.filter((p) => p.isSelected)[0]; + const { isSelected, ...activeItem } = props.items.filter( + (p) => p.isSelected + )[0]; if (!activeItem) { return null; @@ -25,7 +27,11 @@ export function ToolbarDropdown(props: ToolbarDropdownProps) { return ( - + {props.items.map((item) => ( diff --git a/packages/react/src/SideMenu/components/DefaultButtons/AddBlockButton.tsx b/packages/react/src/SideMenu/components/DefaultButtons/AddBlockButton.tsx new file mode 100644 index 0000000000..aa4985d700 --- /dev/null +++ b/packages/react/src/SideMenu/components/DefaultButtons/AddBlockButton.tsx @@ -0,0 +1,16 @@ +import { AiOutlinePlus } from "react-icons/ai"; +import { SideMenuButton } from "../SideMenuButton"; +import { SideMenuProps } from "../SideMenuPositioner"; +import { BlockSchema } from "@blocknote/core"; + +export const AddBlockButton = ( + props: SideMenuProps +) => ( + + + +); diff --git a/packages/react/src/SideMenu/components/DefaultButtons/DragHandle.tsx b/packages/react/src/SideMenu/components/DefaultButtons/DragHandle.tsx new file mode 100644 index 0000000000..8c457fc75c --- /dev/null +++ b/packages/react/src/SideMenu/components/DefaultButtons/DragHandle.tsx @@ -0,0 +1,33 @@ +import { Menu } from "@mantine/core"; +import { SideMenuButton } from "../SideMenuButton"; +import { MdDragIndicator } from "react-icons/md"; +import { SideMenuProps } from "../SideMenuPositioner"; +import { BlockSchema } from "@blocknote/core"; +import { DefaultDragHandleMenu } from "../DragHandleMenu/DefaultDragHandleMenu"; + +export const DragHandle = ( + props: SideMenuProps +) => { + const DragHandleMenu = props.dragHandleMenu || DefaultDragHandleMenu; + + return ( + + +
+ + + +
+
+ +
+ ); +}; diff --git a/packages/react/src/SideMenu/components/DefaultSideMenu.tsx b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx new file mode 100644 index 0000000000..46623a9c12 --- /dev/null +++ b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx @@ -0,0 +1,15 @@ +import { BlockSchema } from "@blocknote/core"; + +import { SideMenuProps } from "./SideMenuPositioner"; +import { SideMenu } from "./SideMenu"; +import { AddBlockButton } from "./DefaultButtons/AddBlockButton"; +import { DragHandle } from "./DefaultButtons/DragHandle"; + +export const DefaultSideMenu = ( + props: SideMenuProps +) => ( + + + + +); diff --git a/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton.tsx similarity index 95% rename from packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton.tsx index 3fc435b275..f506655b85 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton.tsx @@ -1,10 +1,11 @@ import { ReactNode, useCallback, useRef, useState } from "react"; import { Box, Menu } from "@mantine/core"; -import { BlockSchema, PartialBlock } from "@blocknote/core"; import { HiChevronRight } from "react-icons/hi"; +import { BlockSchema, PartialBlock } from "@blocknote/core"; + import { DragHandleMenuProps } from "../DragHandleMenu"; import { DragHandleMenuItem } from "../DragHandleMenuItem"; -import { ColorPicker } from "../../../SharedComponents/ColorPicker/components/ColorPicker"; +import { ColorPicker } from "../../../../SharedComponents/ColorPicker/components/ColorPicker"; export const BlockColorsButton = ( props: DragHandleMenuProps & { children: ReactNode } @@ -38,7 +39,6 @@ export const BlockColorsButton = ( return ( diff --git a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton.tsx similarity index 93% rename from packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton.tsx index 70d9cd60ab..bbd5e2331c 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton.tsx @@ -9,7 +9,6 @@ export const RemoveBlockButton = ( ) => { return ( props.editor.removeBlocks([props.block])}> {props.children} diff --git a/packages/react/src/BlockSideMenu/components/DefaultDragHandleMenu.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx similarity index 99% rename from packages/react/src/BlockSideMenu/components/DefaultDragHandleMenu.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx index 0f8ffa3b1a..0e66af7195 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultDragHandleMenu.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx @@ -1,7 +1,8 @@ +import { BlockSchema } from "@blocknote/core"; + import { DragHandleMenu, DragHandleMenuProps } from "./DragHandleMenu"; import { RemoveBlockButton } from "./DefaultButtons/RemoveBlockButton"; import { BlockColorsButton } from "./DefaultButtons/BlockColorsButton"; -import { BlockSchema } from "@blocknote/core"; export const DefaultDragHandleMenu = ( props: DragHandleMenuProps diff --git a/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx similarity index 84% rename from packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx index 816f3ed344..1062799004 100644 --- a/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx @@ -1,11 +1,10 @@ import { ReactNode } from "react"; import { createStyles, Menu } from "@mantine/core"; -import { Block, BlockSchema, BlockNoteEditor } from "@blocknote/core"; +import { Block, BlockNoteEditor, BlockSchema } from "@blocknote/core"; export type DragHandleMenuProps = { editor: BlockNoteEditor; block: Block; - closeMenu: () => void; }; export const DragHandleMenu = (props: { children: ReactNode }) => { diff --git a/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenuItem.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenuItem.tsx new file mode 100644 index 0000000000..e5da796147 --- /dev/null +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenuItem.tsx @@ -0,0 +1,9 @@ +import { Menu } from "@mantine/core"; +import { PolymorphicComponentProps } from "@mantine/utils"; + +export const DragHandleMenuItem = ( + props: PolymorphicComponentProps<"button"> +) => { + const { children, ...remainingProps } = props; + return {children}; +}; diff --git a/packages/react/src/SideMenu/components/SideMenu.tsx b/packages/react/src/SideMenu/components/SideMenu.tsx new file mode 100644 index 0000000000..136914620f --- /dev/null +++ b/packages/react/src/SideMenu/components/SideMenu.tsx @@ -0,0 +1,6 @@ +import { Group } from "@mantine/core"; +import { ReactNode } from "react"; + +export const SideMenu = (props: { children: ReactNode }) => ( + {props.children} +); diff --git a/packages/react/src/SideMenu/components/SideMenuButton.tsx b/packages/react/src/SideMenu/components/SideMenuButton.tsx new file mode 100644 index 0000000000..2415ff7a4d --- /dev/null +++ b/packages/react/src/SideMenu/components/SideMenuButton.tsx @@ -0,0 +1,5 @@ +import { ActionIcon } from "@mantine/core"; + +export const SideMenuButton = (props: { children: JSX.Element }) => ( + {props.children} +); diff --git a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx new file mode 100644 index 0000000000..9b9503fbe3 --- /dev/null +++ b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx @@ -0,0 +1,110 @@ +import { + Block, + BlockNoteEditor, + BlockSchema, + DefaultBlockSchema, + SideMenuProsemirrorPlugin, +} from "@blocknote/core"; +import Tippy from "@tippyjs/react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; + +import { DefaultSideMenu } from "./DefaultSideMenu"; +import { DragHandleMenuProps } from "./DragHandleMenu/DragHandleMenu"; + +export type SideMenuProps = + Pick< + SideMenuProsemirrorPlugin, + | "blockDragStart" + | "blockDragEnd" + | "addBlock" + | "freezeMenu" + | "unfreezeMenu" + > & { + block: Block; + editor: BlockNoteEditor; + dragHandleMenu?: FC>; + }; + +export const SideMenuPositioner = < + BSchema extends BlockSchema = DefaultBlockSchema +>(props: { + editor: BlockNoteEditor; + sideMenu?: FC>; +}) => { + const [show, setShow] = useState(false); + const [block, setBlock] = useState>(); + + const referencePos = useRef(); + + useEffect(() => { + return props.editor.sideMenu.onUpdate((sideMenuState) => { + setShow(sideMenuState.show); + setBlock(sideMenuState.block); + referencePos.current = sideMenuState.referencePos; + }); + }, [props.editor]); + + const getReferenceClientRect = useMemo( + () => { + if (!referencePos.current) { + return undefined; + } + + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); + + const sideMenuElement = useMemo(() => { + if (!block) { + return null; + } + + const SideMenu = props.sideMenu || DefaultSideMenu; + + return ( + + ); + }, [block, props.editor, props.sideMenu]); + + return ( + + ); +}; + +const offset: [number, number] = [0, 0]; +const popperOptions = { + modifiers: [ + { + name: "flip", + options: { + fallbackPlacements: [], + }, + }, + { + name: "preventOverflow", + options: { + mainAxis: false, + altAxis: false, + }, + }, + ], +}; diff --git a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts index 44ff73c2a1..b5e6f24091 100644 --- a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts +++ b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts @@ -1,21 +1,14 @@ import { BaseSlashMenuItem, - BlockNoteEditor, BlockSchema, + DefaultBlockSchema, } from "@blocknote/core"; -export class ReactSlashMenuItem< - BSchema extends BlockSchema -> extends BaseSlashMenuItem { - constructor( - public readonly name: string, - public readonly execute: (editor: BlockNoteEditor) => void, - public readonly aliases: string[] = [], - public readonly group: string, - public readonly icon: JSX.Element, - public readonly hint?: string, - public readonly shortcut?: string - ) { - super(name, execute, aliases); - } -} +export type ReactSlashMenuItem< + BSchema extends BlockSchema = DefaultBlockSchema +> = BaseSlashMenuItem & { + group: string; + icon: JSX.Element; + hint?: string; + shortcut?: string; +}; diff --git a/packages/react/src/SlashMenu/SlashMenuFactory.tsx b/packages/react/src/SlashMenu/SlashMenuFactory.tsx deleted file mode 100644 index 3eda458e7d..0000000000 --- a/packages/react/src/SlashMenu/SlashMenuFactory.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { - BlockSchema, - SuggestionsMenu, - SuggestionsMenuDynamicParams, - SuggestionsMenuFactory, - SuggestionsMenuStaticParams, -} from "@blocknote/core"; -import { SlashMenu } from "./components/SlashMenu"; -import { ReactSlashMenuItem } from "./ReactSlashMenuItem"; -import { ReactElementFactory } from "../ElementFactory/components/ReactElementFactory"; -import { MantineThemeOverride } from "@mantine/core"; - -export const createReactSlashMenuFactory = - (theme: MantineThemeOverride): SuggestionsMenuFactory> => - (staticParams): SuggestionsMenu> => - ReactElementFactory< - SuggestionsMenuStaticParams>, - SuggestionsMenuDynamicParams> - >(staticParams, SlashMenu, theme, { - animation: "fade", - placement: "bottom-start", - }); diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx similarity index 71% rename from packages/react/src/SlashMenu/components/SlashMenu.tsx rename to packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx index f775ec7728..382b6c8964 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx @@ -1,16 +1,11 @@ import { createStyles, Menu } from "@mantine/core"; import * as _ from "lodash"; + import { SlashMenuItem } from "./SlashMenuItem"; -import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; +import { SlashMenuProps } from "./SlashMenuPositioner"; import { BlockSchema } from "@blocknote/core"; -export type SlashMenuProps = { - items: ReactSlashMenuItem[]; - keyboardHoveredItemIndex: number; - itemCallback: (item: ReactSlashMenuItem) => void; -}; - -export function SlashMenu( +export function DefaultSlashMenu( props: SlashMenuProps ) { const { classes } = createStyles({ root: {} })(undefined, { @@ -19,14 +14,16 @@ export function SlashMenu( const renderedItems: any[] = []; let index = 0; - const groups = _.groupBy(props.items, (i) => i.group); + const groups = _.groupBy(props.filteredItems, (i) => i.group); - _.forEach(groups, (el) => { + _.forEach(groups, (groupedItems) => { renderedItems.push( - {el[0].group} + + {groupedItems[0].group} + ); - for (const item of el) { + for (const item of groupedItems) { renderedItems.push( ( defaultOpened={true} trigger={"hover"} closeDelay={10000000}> - + event.preventDefault()} + className={classes.root}> {renderedItems.length > 0 ? ( renderedItems ) : ( diff --git a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx new file mode 100644 index 0000000000..35b79eb423 --- /dev/null +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -0,0 +1,88 @@ +import { + BlockNoteEditor, + BlockSchema, + 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 = + Pick, "itemCallback"> & + Pick< + SuggestionsMenuState>, + "filteredItems" | "keyboardHoveredItemIndex" + >; + +export const SlashMenuPositioner = < + BSchema extends BlockSchema = DefaultBlockSchema +>(props: { + editor: BlockNoteEditor; + slashMenu?: FC>; +}) => { + const [show, setShow] = useState(false); + const [filteredItems, setFilteredItems] = + useState[]>(); + const [keyboardHoveredItemIndex, setKeyboardHoveredItemIndex] = + useState(); + + const referencePos = useRef(); + + useEffect(() => { + return props.editor.slashMenu.onUpdate((slashMenuState) => { + setShow(slashMenuState.show); + setFilteredItems(slashMenuState.filteredItems); + setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); + + referencePos.current = slashMenuState.referencePos; + }); + }, [props.editor]); + + const getReferenceClientRect = useMemo( + () => { + if (!referencePos.current) { + return undefined; + } + + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); + + const slashMenuElement = useMemo(() => { + if (!filteredItems || keyboardHoveredItemIndex === undefined) { + return null; + } + + const SlashMenu = props.slashMenu || DefaultSlashMenu; + + return ( + props.editor.slashMenu.itemCallback(item)} + keyboardHoveredItemIndex={keyboardHoveredItemIndex} + /> + ); + }, [ + filteredItems, + keyboardHoveredItemIndex, + props.editor.slashMenu, + props.slashMenu, + ]); + + return ( + + ); +}; diff --git a/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx b/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx index 740265e12d..3c13b21d61 100644 --- a/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx +++ b/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx @@ -1,7 +1,9 @@ import { BaseSlashMenuItem, + BlockSchema, + defaultBlockSchema, DefaultBlockSchema, - defaultSlashMenuItems, + getDefaultSlashMenuItems, } from "@blocknote/core"; import { RiH1, @@ -13,6 +15,7 @@ import { } from "react-icons/ri"; import { formatKeyboardShortcut } from "../utils"; import { ReactSlashMenuItem } from "./ReactSlashMenuItem"; + const extraFields: Record< string, Omit< @@ -58,15 +61,18 @@ const extraFields: Record< }, }; -export const defaultReactSlashMenuItems = defaultSlashMenuItems.map( - (item) => - new ReactSlashMenuItem( - item.name, - item.execute, - item.aliases, - extraFields[item.name].group, - extraFields[item.name].icon, - extraFields[item.name].hint, - extraFields[item.name].shortcut - ) -); +export function getDefaultReactSlashMenuItems( + // This type casting is weird, but it's the best way of doing it, as it allows + // the schema type to be automatically inferred if it is defined, or be + // inferred as any if it is not defined. I don't think it's possible to make it + // infer to DefaultBlockSchema if it is not defined. + schema: BSchema = defaultBlockSchema as unknown as BSchema +): ReactSlashMenuItem[] { + const slashMenuItems: BaseSlashMenuItem[] = + getDefaultSlashMenuItems(schema); + + return slashMenuItems.map((item) => ({ + ...item, + ...extraFields[item.name], + })); +} diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 323c050306..39a8dc238f 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -2,106 +2,37 @@ import { BlockNoteEditor, BlockNoteEditorOptions, BlockSchema, + defaultBlockSchema, DefaultBlockSchema, } from "@blocknote/core"; -import { DependencyList, FC, useEffect, useState } from "react"; -import { getBlockNoteTheme } from "../BlockNoteTheme"; -import { createReactBlockSideMenuFactory } from "../BlockSideMenu/BlockSideMenuFactory"; -import { DragHandleMenuProps } from "../BlockSideMenu/components/DragHandleMenu"; -import { createReactFormattingToolbarFactory } from "../FormattingToolbar/FormattingToolbarFactory"; -import { createReactHyperlinkToolbarFactory } from "../HyperlinkToolbar/HyperlinkToolbarFactory"; -import { defaultReactSlashMenuItems } from "../SlashMenu/defaultReactSlashMenuItems"; -import { createReactSlashMenuFactory } from "../SlashMenu/SlashMenuFactory"; - -//based on https://github.com/ueberdosis/tiptap/blob/main/packages/react/src/useEditor.ts - -type CustomElements = Partial<{ - formattingToolbar: FC<{ editor: BlockNoteEditor }>; - dragHandleMenu: FC>; -}>; - -function useForceUpdate() { - const [, setValue] = useState(0); - - return () => setValue((value) => value + 1); -} +import { DependencyList, useMemo, useRef } from "react"; +import { getDefaultReactSlashMenuItems } from "../SlashMenu/defaultReactSlashMenuItems"; + +const initEditor = ( + options: Partial> +) => + new BlockNoteEditor({ + slashMenuItems: getDefaultReactSlashMenuItems( + options.blockSchema || defaultBlockSchema + ), + ...options, + }); /** * Main hook for importing a BlockNote editor into a React project */ export const useBlockNote = ( - options: Partial< - BlockNoteEditorOptions & { - customElements: CustomElements; - } - > = {}, + options: Partial> = {}, deps: DependencyList = [] -) => { - const [editor, setEditor] = useState | null>(null); - const forceUpdate = useForceUpdate(); - - useEffect(() => { - let isMounted = true; - // TODO: Fix typing. UiFactories expects only BaseSlashMenuItems, not extended types. Can be fixed with a generic, - // but it would have to be on several different classes (BlockNoteEditor, BlockNoteEditorOptions, UiFactories) and - // gets messy quick. - let newOptions: Record = { - slashCommands: defaultReactSlashMenuItems, - ...options, - }; +): BlockNoteEditor => { + const editorRef = useRef>(); - if (newOptions.customElements && newOptions.uiFactories) { - console.warn( - "BlockNote editor initialized with both `customElements` and `uiFactories` options, prioritizing `uiFactories`." - ); + return useMemo(() => { + if (editorRef.current) { + editorRef.current._tiptapEditor.destroy(); } - let uiFactories = { - formattingToolbarFactory: createReactFormattingToolbarFactory( - getBlockNoteTheme(newOptions.theme === "dark"), - newOptions.customElements?.formattingToolbar - ), - hyperlinkToolbarFactory: createReactHyperlinkToolbarFactory( - getBlockNoteTheme(newOptions.theme === "dark") - ), - slashMenuFactory: createReactSlashMenuFactory( - getBlockNoteTheme(newOptions.theme === "dark") - ), - blockSideMenuFactory: createReactBlockSideMenuFactory( - getBlockNoteTheme(newOptions.theme === "dark"), - newOptions.customElements?.dragHandleMenu - ), - ...newOptions.uiFactories, - }; - - newOptions = { - ...newOptions, - uiFactories, - }; - - console.log("create new blocknote instance"); - const instance = new BlockNoteEditor( - newOptions as Partial> - ); - - setEditor(instance); - - instance._tiptapEditor.on("transaction", () => { - requestAnimationFrame(() => { - requestAnimationFrame(() => { - if (isMounted) { - forceUpdate(); - } - }); - }); - }); - - return () => { - instance._tiptapEditor.destroy(); - isMounted = false; - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, deps); - - return editor; + editorRef.current = initEditor(options); + return editorRef.current; + }, deps); //eslint-disable-line react-hooks/exhaustive-deps }; diff --git a/packages/react/src/hooks/useEditorContentChange.ts b/packages/react/src/hooks/useEditorContentChange.ts new file mode 100644 index 0000000000..64882bcf29 --- /dev/null +++ b/packages/react/src/hooks/useEditorContentChange.ts @@ -0,0 +1,15 @@ +import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { useEffect } from "react"; + +export function useEditorContentChange( + editor: BlockNoteEditor, + callback: () => void +) { + useEffect(() => { + editor._tiptapEditor.on("update", callback); + + return () => { + editor._tiptapEditor.off("update", callback); + }; + }, [callback, editor._tiptapEditor]); +} diff --git a/packages/react/src/hooks/useEditorSelectionChange.ts b/packages/react/src/hooks/useEditorSelectionChange.ts new file mode 100644 index 0000000000..1072b31973 --- /dev/null +++ b/packages/react/src/hooks/useEditorSelectionChange.ts @@ -0,0 +1,15 @@ +import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { useEffect } from "react"; + +export function useEditorSelectionChange( + editor: BlockNoteEditor, + callback: () => void +) { + useEffect(() => { + editor._tiptapEditor.on("selectionUpdate", callback); + + return () => { + editor._tiptapEditor.off("selectionUpdate", callback); + }; + }, [callback, editor._tiptapEditor]); +} diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 55edb7a45a..7c6983df2e 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -1,32 +1,43 @@ // TODO: review directories export * from "./BlockNoteView"; -export * from "./ReactBlockSpec"; - -export * from "./BlockSideMenu/BlockSideMenuFactory"; -export * from "./BlockSideMenu/components/DragHandleMenu"; -export * from "./BlockSideMenu/components/DragHandleMenuItem"; -export * from "./BlockSideMenu/components/DefaultButtons/RemoveBlockButton"; -export * from "./BlockSideMenu/components/DefaultButtons/BlockColorsButton"; - -export * from "./FormattingToolbar/FormattingToolbarFactory"; -export * from "./FormattingToolbar/components/FormattingToolbar"; +export * from "./FormattingToolbar/components/FormattingToolbarPositioner"; +export * from "./FormattingToolbar/components/DefaultFormattingToolbar"; export * from "./FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown"; -export * from "./FormattingToolbar/components/DefaultButtons/ToggledStyleButton"; -export * from "./FormattingToolbar/components/DefaultButtons/TextAlignButton"; export * from "./FormattingToolbar/components/DefaultButtons/ColorStyleButton"; -export * from "./FormattingToolbar/components/DefaultButtons/NestBlockButtons"; export * from "./FormattingToolbar/components/DefaultButtons/CreateLinkButton"; +export * from "./FormattingToolbar/components/DefaultButtons/NestBlockButtons"; +export * from "./FormattingToolbar/components/DefaultButtons/TextAlignButton"; +export * from "./FormattingToolbar/components/DefaultButtons/ToggledStyleButton"; -export * from "./hooks/useBlockNote"; -export * from "./hooks/useEditorForceUpdate"; +export * from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; -export * from "./HyperlinkToolbar/HyperlinkToolbarFactory"; +export * from "./SideMenu/components/SideMenuPositioner"; +export * from "./SideMenu/components/SideMenu"; +export * from "./SideMenu/components/SideMenuButton"; +export * from "./SideMenu/components/DefaultSideMenu"; +export * from "./SideMenu/components/DefaultButtons/AddBlockButton"; +export * from "./SideMenu/components/DefaultButtons/DragHandle"; -export * from "./SlashMenu/SlashMenuFactory"; +export * from "./SideMenu/components/DragHandleMenu/DragHandleMenu"; +export * from "./SideMenu/components/DragHandleMenu/DragHandleMenuItem"; +export * from "./SideMenu/components/DragHandleMenu/DefaultDragHandleMenu"; +export * from "./SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton"; +export * from "./SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton"; + +export * from "./SlashMenu/components/SlashMenuPositioner"; +export * from "./SlashMenu/components/SlashMenuItem"; +export * from "./SlashMenu/components/DefaultSlashMenu"; export * from "./SlashMenu/ReactSlashMenuItem"; export * from "./SlashMenu/defaultReactSlashMenuItems"; export * from "./SharedComponents/Toolbar/components/Toolbar"; export * from "./SharedComponents/Toolbar/components/ToolbarButton"; export * from "./SharedComponents/Toolbar/components/ToolbarDropdown"; + +export * from "./hooks/useBlockNote"; +export * from "./hooks/useEditorForceUpdate"; +export * from "./hooks/useEditorContentChange"; +export * from "./hooks/useEditorSelectionChange"; + +export * from "./ReactBlockSpec"; diff --git a/packages/website/docs/.vitepress/config.ts b/packages/website/docs/.vitepress/config.ts index 65f1f97e10..d6f4a2102f 100644 --- a/packages/website/docs/.vitepress/config.ts +++ b/packages/website/docs/.vitepress/config.ts @@ -28,9 +28,10 @@ const SIDEBAR_DEFAULT = [ collapsed: false, items: [ { text: "Customizing the Editor", link: "/docs/editor" }, - { text: "Slash Menu", link: "/docs/slash-menu" }, { text: "Formatting Toolbar", link: "/docs/formatting-toolbar" }, + { text: "Slash Menu", link: "/docs/slash-menu" }, { text: "Side Menu", link: "/docs/side-menu" }, + { text: "Changing UI Elements", link: "/docs/ui-elements" }, ], }, { diff --git a/packages/website/docs/docs/formatting-toolbar.md b/packages/website/docs/docs/formatting-toolbar.md index 881ba087f1..e72fa1db52 100644 --- a/packages/website/docs/docs/formatting-toolbar.md +++ b/packages/website/docs/docs/formatting-toolbar.md @@ -20,87 +20,119 @@ The Formatting Toolbar appears whenever you highlight text in the editor, and is ## Custom Formatting Toolbar -You can create a custom Formatting Toolbar using a React component. This component should take the following props: +If you want to change the buttons/dropdowns in the Formatting Toolbar, or replace it altogether, you can do that using a React component. -```typescript -type CustomFormattingToolbarProps = { - editor: BlockNoteEditor -}; +You can see how this is done in the example below, which has a custom Formatting Toolbar with four items. The first three are default items to toggle bold, italic, and underline, while the last one is a custom button which toggles the text and background colors to be blue. -const CustomFormattingToolbar = (props: CustomFormattingToolbarProps): JSX.Element => ...; -``` +::: sandbox {template=react-ts} -You can then tell BlockNote to use your custom Formatting Toolbar using -the `customElements` option in `useBlockNote`: +```typescript-vue /App.tsx +import { BlockNoteEditor } from "@blocknote/core"; +import { + BlockNoteView, + FormattingToolbarPositioner, + HyperlinkToolbarPositioner, + SideMenuPositioner, + SlashMenuPositioner, + ToggledStyleButton, + Toolbar, + ToolbarButton, + useBlockNote, + useEditorContentChange, + useEditorSelectionChange, +} from "@blocknote/react"; +import "@blocknote/core/style.css"; +import { useState } from "react"; -```typescript -const editor = useBlockNote({ - customElements: { - formattingToolbar: CustomFormattingToolbar - }, -}); -``` +const CustomFormattingToolbar = (props: { editor: BlockNoteEditor }) => { + // Tracks whether the text & background are both blue. + const [isSelected, setIsSelected] = useState( + props.editor.getActiveStyles().textColor === "blue" && + props.editor.getActiveStyles().backgroundColor === "blue" + ); -## Default Items + // Updates state on content change. + useEditorContentChange(props.editor, () => { + setIsSelected( + props.editor.getActiveStyles().textColor === "blue" && + props.editor.getActiveStyles().backgroundColor === "blue" + ); + }); -It might seem daunting to create your own Formatting Toolbar from scratch, which is why BlockNote provides React components for everything you see in the default layout - both the toolbar itself and the items in it. Below are all the default components you can use to build your custom toolbar: + // Updates state on selection change. + useEditorSelectionChange(props.editor, () => { + setIsSelected( + props.editor.getActiveStyles().textColor === "blue" && + props.editor.getActiveStyles().backgroundColor === "blue" + ); + }); -```typescript -// Toolbar which wraps all the items. -type ToolbarProps = { - children: ReactNode; + return ( + + {/*Default button to toggle bold.*/} + + {/*Default button to toggle italic.*/} + + {/*Default button to toggle underline.*/} + + {/*Custom button to toggle blue text & background color.*/} + { + props.editor.toggleStyles({ + textColor: "blue", + backgroundColor: "blue", + }); + }} + isSelected={isSelected}> + Blue + + + ); }; -const Toolbar = (props: ToolbarProps) => ...; -// Dropdown which changes the block type. -type BlockTypeDropdownProps = { - editor: BlockNoteEditor -}; -const BlockTypeDropdown = (props: BlockTypeDropdownProps) => ...; +export default function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({ + theme: "{{ getTheme(isDark) }}", + }); -// Button which toggles a simple style on the highlighted text. -type ToggledStyleButtonProps = { - editor: BlockNoteEditor; - toggledStyle: "bold" | "italic" | "underline" | "strike" | "code"; -}; -const ToggledStyleButton = (props: ToggledStyleButtonProps) => ...; + // Renders the editor instance. + return ( + + + + + + + ); +} +``` -// Button which sets the text alignment on the block. -type TextAlignButtonProps = { - editor: BlockNoteEditor; - textAlignment: "left" | "center" | "right" | "center"; -}; -const TextAlignButton = (props: TextAlignButtonProps) => ...; +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} +``` -// Button which opens a dropdown on hover. The dropdown lets you set the -// highlighted text's color. -type ColorStyleButtonProps = { - editor: BlockNoteEditor -}; -const ColorStyleButton = (props: ColorStyleButtonProps) => ...; +::: -// Button which nests the block, if it can be nested. -type NestBlockButtonProps = { - editor: BlockNoteEditor -}; -const NestBlockButton = (props: NestBlockButtonProps) => ...; +`CustomFormattingToolbar` is the component we use to replace the default Formatting Toolbar. You can see it's made up of a bunch of other components that are exported by BlockNote. Read on to [Components](/docs/formatting-toolbar#components) to find out more about these. -// Button which unnests the block, if it can be nested. -type UnestBlockButtonProps = { - editor: BlockNoteEditor -}; -const UnestBlockButton = (props: UnestBlockButtonProps) => ...; +After creating `CustomFormattingToolbar`, we tell BlockNote to use it inside `BlockNoteView`. [Changing UI Elements](/docs/ui-elements) has more information about how this is done. -// Button which opens a dialog box to create a new link. -type CreateLinkButtonProps = { - editor: BlockNoteEditor -}; -const CreateLinkButton = (props: CreateLinkButtonProps) => ...; -``` +## Components + +It might seem daunting to create your own Formatting Toolbar from scratch, which is why BlockNote provides React components that you can use which match the default styling. -## Custom Items +### Default Components -BlockNote also provides components that you can use to make your own toolbar items, which match BlockNote's UI styling: +BlockNote exports all components used to create the default layout - both the toolbar itself and the items in it. Head to the [default Formatting Toolbar's source code](https://github.com/TypeCellOS/BlockNote/blob/main/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx) to see all the components that you can use. + +### Custom Components + +BlockNote also provides components that you can use to make your own toolbar items, which also match the default styling: ```typescript // Custom dropdown. @@ -143,72 +175,3 @@ type ToolbarButtonProps = { }; export const ToolbarButton = (props: ToolbarButtonProps) => ...; ``` - -## Demo: Simple Custom Formatting Toolbar - -The example below shows a basic custom formatting toolbar with four items. The first three are default items to toggle bold, italic, and underline, while the last one is a custom button which toggles the text and background colors to be blue. - -::: sandbox {template=react-ts} - -```typescript-vue /App.tsx -import { BlockNoteEditor } from "@blocknote/core"; -import { - BlockNoteView, - createReactFormattingToolbarFactory, - ToggledStyleButton, - Toolbar, - ToolbarButton, - useBlockNote, -} from "@blocknote/react"; -import "@blocknote/core/style.css"; - -const CustomFormattingToolbar = (props: { editor: BlockNoteEditor }) => { - return ( - - {/*Default button to toggle bold.*/} - - {/*Default button to toggle italic.*/} - - {/*Default button to toggle underline.*/} - - {/*Custom button to toggle blue text & background color.*/} - { - props.editor.toggleStyles({ - textColor: "blue", - backgroundColor: "blue", - }); - }} - isSelected={ - props.editor.getActiveStyles().textColor === "blue" && - props.editor.getActiveStyles().backgroundColor === "blue" - }> - Blue - - - ); -}; - -export default function App() { - // Creates a new editor instance. - const editor: BlockNoteEditor = useBlockNote({ - theme: "{{ getTheme(isDark) }}", - customElements: { - // Makes the editor instance use the custom toolbar. - formattingToolbar: CustomFormattingToolbar - } - }); - - // Renders the editor instance. - return ; -} -``` - -```css-vue /styles.css [hidden] -{{ getStyles(isDark) }} -``` - -::: - -If you're unsure about what's happening inside `onClick` and `isSelected`, head to [Introduction to Blocks](/docs/blocks), which will guide you through reading & manipulating blocks in the editor using code. \ No newline at end of file diff --git a/packages/website/docs/docs/introduction.md b/packages/website/docs/docs/introduction.md index c5d34c0c75..cf01ab1f72 100644 --- a/packages/website/docs/docs/introduction.md +++ b/packages/website/docs/docs/introduction.md @@ -51,7 +51,7 @@ import { BlockNoteView, useBlockNote } from "@blocknote/react"; import "@blocknote/core/style.css"; export default function App() { // Creates a new editor instance. - const editor: BlockNoteEditor | null = useBlockNote({ + const editor: BlockNoteEditor = useBlockNote({ theme: "{{ getTheme(isDark) }}" }); // Renders the editor instance using a React component. diff --git a/packages/website/docs/docs/quickstart.md b/packages/website/docs/docs/quickstart.md index f4e78adc7f..ba958e4bcf 100644 --- a/packages/website/docs/docs/quickstart.md +++ b/packages/website/docs/docs/quickstart.md @@ -37,7 +37,7 @@ import "@blocknote/core/style.css"; function App() { // Creates a new editor instance. - const editor: BlockNoteEditor | null = useBlockNote({}); + const editor: BlockNoteEditor = useBlockNote({}); // Renders the editor instance using a React component. return ; @@ -63,7 +63,7 @@ import "@blocknote/core/style.css"; export default function App() { // Creates a new editor instance. - const editor: BlockNoteEditor | null = useBlockNote({ + const editor: BlockNoteEditor = useBlockNote({ theme: "{{ getTheme(isDark) }}" }); diff --git a/packages/website/docs/docs/side-menu.md b/packages/website/docs/docs/side-menu.md index d6d2733a66..f1c846f156 100644 --- a/packages/website/docs/docs/side-menu.md +++ b/packages/website/docs/docs/side-menu.md @@ -19,13 +19,80 @@ The Block Side Menu appears whenever you hover over a block, and is used to drag image -You can also click the drag handle in the Block Side Menu (`⠿`) to open the Drag Handle Menu. +You can also click the drag handle (`⠿`) in the Block Side Menu to open the Drag Handle Menu. image +## Custom Side Menu + +If you want to change the items in the Side Menu, or replace it altogether, you can do that using a React component. + +You can see how this is done in the example below, which has a custom Side Menu with two items. The first one deletes the selected block, while the second one is a drag handle, which opens a menu on click. + +::: sandbox {template=react-ts} + +```typescript-vue /App.tsx +import { BlockNoteEditor } from "@blocknote/core"; +import { + BlockNoteView, + DragHandle, + FormattingToolbarPositioner, + HyperlinkToolbarPositioner, + SideMenu, + SideMenuButton, + SideMenuPositioner, + SideMenuProps, + SlashMenuPositioner, + useBlockNote, +} from "@blocknote/react"; +import "@blocknote/core/style.css"; +import { MdDelete } from "react-icons/md"; + +const CustomSideMenu = (props: SideMenuProps) => ( + + + props.editor.removeBlocks([props.block])} + /> + + + +); + +export default function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({ + theme: "{{ getTheme(isDark) }}", + }); + + // Renders the editor instance. + return ( + + + + + + + ); +} +``` + +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} +``` + +::: + +`CustomSideMenu` is the component we use to replace the default Side Menu. You can see it's made up of a bunch of other components that are exported by BlockNote. Read on to [Components](/docs/side-menu#components) to find out more about these. + +After creating `CustomSideMenu`, we tell BlockNote to use it inside `BlockNoteView`. [Changing UI Elements](/docs/ui-elements) has more information about how this is done. + ## Custom Drag Handle Menu -BlockNote lets you customize which items appear in the Drag Handle Menu. Have a look at the example below, in which the color picker item is replaced with a custom item that opens an alert. +If you want to change the items in the Drag Handle Menu, or replace it altogether, you can do that using a React component. + +You can see how this is done in the example below, which has a custom Drag Handle Menu with two items. The first one deletes the selected block, while the second opens an alert. ::: sandbox {template=react-ts} @@ -33,10 +100,14 @@ BlockNote lets you customize which items appear in the Drag Handle Menu. Have a import { Block, BlockNoteEditor } from "@blocknote/core"; import { BlockNoteView, - createReactBlockSideMenuFactory, + DefaultSideMenu, DragHandleMenu, DragHandleMenuItem, + FormattingToolbarPositioner, + HyperlinkToolbarPositioner, RemoveBlockButton, + SideMenuPositioner, + SlashMenuPositioner, useBlockNote, } from "@blocknote/react"; import "@blocknote/core/style.css"; @@ -44,21 +115,13 @@ import "@blocknote/core/style.css"; const CustomDragHandleMenu = (props: { editor: BlockNoteEditor; block: Block; - closeMenu: () => void; }) => { return ( - {/*Default button to remove the block.*/} - - Delete - + {/*Default item to remove the block.*/} + Delete {/*Custom item which opens an alert when clicked.*/} - { - window.alert("Button Pressed!"); - props.closeMenu(); - }}> + window.alert("Button Pressed!")}> Open Alert @@ -69,13 +132,22 @@ export default function App() { // Creates a new editor instance. const editor: BlockNoteEditor = useBlockNote({ theme: "{{ getTheme(isDark) }}", - customElements: { - // Makes the editor instance use the custom menu. - dragHandleMenu: CustomDragHandleMenu - }, }); + // Renders the editor instance. - return ; + return ( + + + + + ( + + )} + /> + + ); } ``` @@ -85,67 +157,30 @@ export default function App() { ::: -Let's look at how this is done. We first need to create a custom Drag Handle Menu using a React component. This component should take the following props: +`CustomDragHandleMenu` is the component we use to replace the default Drag Handle Menu. You can see it's made up of a bunch of other components that are exported by BlockNote. Read on to [Components](/docs/side-menu#components) to find out more about these. -```typescript -type CustomDragHandleMenuProps = { - editor: BlockNoteEditor; - block: Block; - closeMenu: () => void; -}; -const CustomDragHandleMenu = (props: CustomDragHandleMenuProps): JSX.Element => ...; -``` +Here, we're passing it as a prop to the `DefaultSideMenu` component, but you can also pass it to the `DragHandle` component we saw in the [previous demo](/docs/side-menu#custom-side-menu), if you don't want to use the default Side Menu layout. -You can then tell BlockNote to use your custom Drag Handle Menu using -the `customElements` option in `useBlockNote`: +After creating `CustomDragHandleMenu`, we tell BlockNote to use it inside `BlockNoteView`. [Changing UI Elements](/docs/ui-elements) has more information about how this is done. -```typescript -const editor = useBlockNote({ - customElements: { - blockSideMenuFactory: CustomBlockSideMenu - }, -}); -``` +## Components -## Default Items +BlockNote provides React components that you can reuse, to easily create your menus while matching the default styling. -It might seem daunting to create your own Drag Handle Menu from scratch, which is why BlockNote provides React components for everything you see in the default layout - both the menu itself and the items in it. Below are all the default components you can use to build your custom menu: +### Default Components -```typescript -// Menu which wraps all the items. -type BlockSideMenuProps = { - children: ReactNode -} -const BlockSideMenu = (props: BlockSideMenuProps) => ...; - -// Button which removes the block. -type RemoveBlockButtonProps = { - editor: BlockNoteEditor; - block: Block; - closeMenu: () => void; - children: ReactNode; -}; -const RemoveBlockButton = (props: RemoveBlockButtonProps) => ...; - -// Button which opens a dropdown on hover. The dropdown lets you set the block's color. -type BlockColorsButtonProps = { - editor: BlockNoteEditor; - block: Block; - closeMenu: () => void; - children: ReactNode; -}; -const BlockColorsButton = (props: BlockColorsButtonProps) => ...; -``` +BlockNote exports all components used to create the default layout - both the menu itself and the items in it. Head to the [default Side Menu's source code](https://github.com/TypeCellOS/BlockNote/blob/main/packages/react/src/SideMenu/components/DefaultSideMenu.tsx) and [default Drag Handle Menu's source code](https://github.com/TypeCellOS/BlockNote/blob/main/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx) to see all the components that you can use. -## Custom Items +### Custom Components -BlockNote also provides components that you can use to make your own menu items, which match BlockNote's UI styling: +BlockNote also provides components that you can use to make your own menu items, which also match the default styling: ```typescript -// Also includes all props of button elements, e.g. onClick. -type DragHandleMenuItemProps = { - // Closes the menu when called. - closeMenu: () => void; -}; -export const DragHandleMenuItem = (props: DragHandleMenuItemProps) => ...; -``` \ No newline at end of file +type SideMenuButtonProps = { + children: JSX.Element; +} +export const SideMenuButton = (props: SideMenuButtonProps) => ...; + +// Takes same props as `button` elements, e.g. onClick. +export const DragHandleMenuItem = (props) => ...; +``` diff --git a/packages/website/docs/docs/slash-menu.md b/packages/website/docs/docs/slash-menu.md index 272e6c1458..c2c554565d 100644 --- a/packages/website/docs/docs/slash-menu.md +++ b/packages/website/docs/docs/slash-menu.md @@ -18,38 +18,80 @@ The Slash Menu is the list of commands which shows up whenever you type the "/" image -## Slash Menu Items +## Custom Slash Menu Item List -In the options passed to `useBlockNote`, there's a field: +If you want to change the items that appear in the Slash Menu, you can do that using the `slashMenuItems` [editor option](/docs/editor#editor-options). -`slashMenuItems: ReactSlashMenuItem[]` +You can see how this is done in the example below, which has a custom Slash Menu item list. It includes all the default Slash Menu items, as well as a custom item, which inserts a new block below with "Hello World" in bold. -Which you can use to customize the contents of the Slash Menu. Let's take a look at what's in a `ReactSlashMenuItem`: +::: sandbox {template=react-ts} -```typescript -type ReactSlashMenuItem = { - name: string; - execute: (editor: BlockNoteEditor) => void; - aliases: string[]; - group: string; - hint?: string; - shortcut?: string; +```typescript-vue /App.tsx +import { Block, BlockNoteEditor, PartialBlock } from "@blocknote/core"; +import { + BlockNoteView, + getDefaultReactSlashMenuItems, + ReactSlashMenuItem, + useBlockNote, +} from "@blocknote/react"; +import "@blocknote/core/style.css"; +import { HiOutlineGlobeAlt } from "react-icons/hi"; + +// Command to insert "Hello World" in bold in a new block below. +const insertHelloWorld = (editor: BlockNoteEditor) => { + // Block that the text cursor is currently in. + const currentBlock: Block = editor.getTextCursorPosition().block; + + // New block we want to insert. + const helloWorldBlock: PartialBlock = { + type: "paragraph", + content: [{ type: "text", text: "Hello World", styles: { bold: true } }], + }; + + // Inserting the new block after the current one. + editor.insertBlocks([helloWorldBlock], currentBlock, "after"); }; -``` -`name:` The item's name, which is the same string you see displayed in the menu, e.g. "Heading" or "Paragraph". +// Custom Slash Menu item which executes the above function. +const insertHelloWorldItem: ReactSlashMenuItem = { + name: "Insert Hello World", + group: "Other", + icon: , + execute: insertHelloWorld, + aliases: ["helloworld", "hw"], + hint: "Used to insert a block with 'Hello World' below.", +}; -`execute:` A function that runs when the item is selected. +// List containing all default Slash Menu Items, as well as our custom one. +const customSlashMenuItemList = [ + ...getDefaultReactSlashMenuItems(), + insertHelloWorldItem, +]; -`aliases:` Other names for the item, which as used as shortcuts for search. +export default function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({ + theme: "{{ getTheme(isDark) }}", + slashCommands: customSlashMenuItemList, + }); -`group:` The name of the group the item belongs to, e.g. "Headings" or "Basic Blocks". + // Renders the editor instance. + return ; +} -`hint:` A short phrase to describe what the item is for, which is displayed below its name. +``` + +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} +``` + +::: + +To find out how to get the default Slash Menu items, as well as how to make custom items, read on to [Slash Menu Items](/docs/slash-menu#slash-menu-items) -`shortcuts:` A keyboard shortcut which can be used to run the item's `execute` function outside the Slash Menu. +## Slash Menu Items -## Default Items +### Default Items BlockNote comes with a variety of built-in Slash Menu items, which are used to change the type of the block containing the text cursor. If you don't pass anything to `slashMenuItems`, BlockNote will use these to set the Slash Menu contents. @@ -58,13 +100,15 @@ If you want to change, remove & reorder the default items , you first import and ```typescript import { BlockNoteView, - defaultReactSlashMenuItems, + getDefaultReactSlashMenuItems, + ReactSlashMenuItem, useBlockNote } from "@blocknote/react"; import "@blocknote/core/style.css"; function App() { - const newSlashMenuItems: ReactSlashMenuItem[] = defaultReactSlashMenuItems; + const newSlashMenuItems: ReactSlashMenuItem[] = + getDefaultReactSlashMenuItems(); // Edit newSlashMenuItems ... @@ -75,65 +119,32 @@ function App() { } ``` -## Custom Items - -You can also create your own, custom menu items too, as you can see in the example below. The new item, with the name "Insert Hello World", inserts a new block below with "Hello World" in bold: +### Custom Items -::: sandbox {template=react-ts} +Creating a custom Slash Menu item is easy! Just declare a plain JavaScript object with the following fields: -```typescript-vue /App.tsx -import { Block, BlockNoteEditor, PartialBlock } from "@blocknote/core"; -import { - BlockNoteView, - defaultReactSlashMenuItems, - ReactSlashMenuItem, - useBlockNote, -} from "@blocknote/react"; -import "@blocknote/core/style.css"; -import { HiOutlineGlobeAlt } from "react-icons/hi"; +```typescript +type SlashMenuItem = { + name: string; + group: string; + icon: JSX.Element; + execute: (editor: BlockNoteEditor) => void; + aliases?: string[]; + hint?: string; + shortcut?: string; +}; +``` -export default function App() { - // Command to insert "Hello World" in bold in a new block below. - const insertHelloWorld = (editor: BlockNoteEditor) => { - // Block that the text cursor is currently in. - const currentBlock: Block = editor.getTextCursorPosition().block; - - // New block we want to insert. - const helloWorldBlock: PartialBlock = { - type: "paragraph", - content: [{ type: "text", text: "Hello World", styles: { bold: true } }], - }; - - // Inserting the new block after the current one. - editor.insertBlocks([helloWorldBlock], currentBlock, "after"); - }; +`name:` The item's name, which is the same string you see displayed in the menu, e.g. "Heading" or "Paragraph". - // Slash Menu item which executes the command. - const insertHelloWorldItem = new ReactSlashMenuItem( - "Insert Hello World", - insertHelloWorld, - ["helloworld", "hw"], - "Other", - , - "Used to insert a block with 'Hello World' below." - ); +`group:` The name of the group the item belongs to, e.g. "Headings" or "Basic Blocks". - // Creates a new editor instance. - const editor: BlockNoteEditor = useBlockNote({ - theme: "{{ getTheme(isDark) }}", - // Adds all default Slash Menu items as well as our custom one. - slashCommands: [...defaultReactSlashMenuItems, insertHelloWorldItem], - }); +`icon:` The item's icon. - // Renders the editor instance. - return ; -} -``` +`execute:` A function that runs when the item is selected. -```css-vue /styles.css [hidden] -{{ getStyles(isDark) }} -``` +`aliases:` Other names for the item, used as shortcuts for search. -::: +`hint:` A short phrase to describe what the item is for, which is displayed below its name. -If you're confused about what's happening inside `execute`, head to [Introduction to Blocks](/docs/blocks), which will guide you through manipulating blocks in the editor using code. When creating your own `ReactSlashMenuItem`s, also make sure you use the class constructor like in the demo. +`shortcuts:` A keyboard shortcut which can be used to run the item's `execute` function without the Slash Menu being open. diff --git a/packages/website/docs/docs/ui-elements.md b/packages/website/docs/docs/ui-elements.md new file mode 100644 index 0000000000..d0f9b76794 --- /dev/null +++ b/packages/website/docs/docs/ui-elements.md @@ -0,0 +1,144 @@ +--- +title: Changing UI Elements +description: Along with the editor itself, BlockNote includes menus and toolbars which you can replace or remove. +imageTitle: Changing UI Elements +path: /docs/ui-elements +--- + + + + +# Changing UI Elements + +Along with the editor itself, BlockNote includes a few additional UI elements in the forms of menus and toolbars: + +- [Formatting Toolbar](/docs/formatting-toolbar) +- Hyperlink Toolbar +- [Slash Menu](/docs/slash-menu) +- [Side Menu](/docs/side-menu) + +By default, these are all included in the editor, but you can remove or replace each of them with your own React components. + +## Default Setup + +In many of the examples, you'll see we render `BlockNoteView` like so: + +```jsx + +``` + +But this is actually shorthand for the following: + +```jsx + + + + + + +``` + +As you can see, `BlockNoteView` by default renders out four children - one for each UI element. Each child is a `Positioner` component, which controls where and when the UI element is shown. + +Explicitly adding `Positioner` components as children of `BlockNoteView` allows you to customize which UI elements to show, and what to show inside them, as you'll see in the upcoming subsections. + +## Removing UI Elements + +In the following example, we remove the Side Menu from the editor. This is done by adding all `Positioner` components as children of `BlockNoteView`, for each UI element except the Side Menu: + +::: sandbox {template=react-ts} + +```typescript-vue /App.tsx +import { BlockNoteEditor } from "@blocknote/core"; +import { + BlockNoteView, + FormattingToolbarPositioner, + HyperlinkToolbarPositioner, + SlashMenuPositioner, + useBlockNote, +} from "@blocknote/react"; +import "@blocknote/core/style.css"; + +export default function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({ + theme: "{{ getTheme(isDark) }}", + }); + + // Renders the editor instance. + return ( + + + + + + ); +} + +``` + +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} +``` + +::: + +Each further `Positioner` component you remove will remove its corresponding UI element from the editor. If you only want to keep the editor itself, add only an empty fragment (`<>`) to `BlockNoteView`'s children. + +## Replacing UI Elements + +In the following example, the Side Menu is replaced with a simple component which just displays the name of the element: + +::: sandbox {template=react-ts} + +```typescript-vue /App.tsx +import { BlockNoteEditor } from "@blocknote/core"; +import { + BlockNoteView, + FormattingToolbarPositioner, + HyperlinkToolbarPositioner, + SideMenuPositioner, + SlashMenuPositioner, + useBlockNote, +} from "@blocknote/react"; +import "@blocknote/core/style.css"; + +export default function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({ + theme: "{{ getTheme(isDark) }}", + }); + + // Renders the editor instance. + return ( + + + + +
Side Menu
} + /> +
+ ); +} + +``` + +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} + +.sideMenu { + size: 14; +} +``` + +::: + +As you can see, this is done by passing a React component to the `sideMenu` prop of `SideMenuPositioner`. Each `Positioner` element has a prop through which you can pass the component you want to render (`formattingToolbar` for the Formatting Toolbar, etc.). If nothing is passed, the `Positioner` will render the default UI element. + diff --git a/packages/website/partykitserver.ts b/packages/website/partykitserver.ts index 61853cb81d..8ecc2e4ef8 100644 --- a/packages/website/partykitserver.ts +++ b/packages/website/partykitserver.ts @@ -5,6 +5,6 @@ import { onConnect } from "y-partykit"; // preview with npx partykit@beta dev partykitserver.ts export default { onConnect(ws, room) { - return onConnect(ws, room, { persist: true }); + return onConnect(ws, room, { persist: false, gc: true }); }, } satisfies PartyKitServer; diff --git a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-chromium-linux.json b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-chromium-linux.json index 16ff3ebf23..82987e5be0 100644 --- a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-chromium-linux.json +++ b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-chromium-linux.json @@ -30,7 +30,7 @@ { "type": "blockContainer", "attrs": { - "id": "6", + "id": "0", "textColor": "default", "backgroundColor": "default" }, @@ -76,7 +76,7 @@ { "type": "blockContainer", "attrs": { - "id": "7", + "id": "2", "textColor": "default", "backgroundColor": "default" }, @@ -107,7 +107,7 @@ { "type": "blockContainer", "attrs": { - "id": "8", + "id": "4", "textColor": "default", "backgroundColor": "default" }, diff --git a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-webkit-linux.json b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-webkit-linux.json index 16ff3ebf23..82987e5be0 100644 --- a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-webkit-linux.json +++ b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropnested-webkit-linux.json @@ -30,7 +30,7 @@ { "type": "blockContainer", "attrs": { - "id": "6", + "id": "0", "textColor": "default", "backgroundColor": "default" }, @@ -76,7 +76,7 @@ { "type": "blockContainer", "attrs": { - "id": "7", + "id": "2", "textColor": "default", "backgroundColor": "default" }, @@ -107,7 +107,7 @@ { "type": "blockContainer", "attrs": { - "id": "8", + "id": "4", "textColor": "default", "backgroundColor": "default" }, diff --git a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-chromium-linux.json b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-chromium-linux.json index cf5ef17797..088abd5027 100644 --- a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-chromium-linux.json +++ b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-chromium-linux.json @@ -30,7 +30,7 @@ { "type": "blockContainer", "attrs": { - "id": "4", + "id": "0", "textColor": "default", "backgroundColor": "default" }, diff --git a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-webkit-linux.json b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-webkit-linux.json index cf5ef17797..088abd5027 100644 --- a/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-webkit-linux.json +++ b/tests/end-to-end/dragdrop/dragdrop.test.ts-snapshots/dragdropsingle-webkit-linux.json @@ -30,7 +30,7 @@ { "type": "blockContainer", "attrs": { - "id": "4", + "id": "0", "textColor": "default", "backgroundColor": "default" }, diff --git a/tests/utils/components/Editor.tsx b/tests/utils/components/Editor.tsx index fd42103672..d719605e44 100644 --- a/tests/utils/components/Editor.tsx +++ b/tests/utils/components/Editor.tsx @@ -2,7 +2,7 @@ import { defaultBlockSchema } from "@blocknote/core"; import "@blocknote/core/style.css"; import { BlockNoteView, - defaultReactSlashMenuItems, + getDefaultReactSlashMenuItems, useBlockNote, } from "@blocknote/react"; import { Alert, insertAlert } from "../customblocks/Alert"; @@ -29,7 +29,7 @@ export default function Editor() { toc: TableOfContents, } as const; - const slashCommands = [ + const slashMenuItems = [ insertAlert, insertButton, insertEmbed, @@ -44,7 +44,7 @@ export default function Editor() { "data-test": "editor", }, blockSchema: blockSchema, - slashCommands: [...defaultReactSlashMenuItems, ...slashCommands], + slashMenuItems: [...getDefaultReactSlashMenuItems(), ...slashMenuItems], }); console.log(editor);