From 33f521379aefde6deab810c5c5a2f420367843e9 Mon Sep 17 00:00:00 2001 From: yousefed Date: Thu, 29 Jun 2023 09:27:22 +0200 Subject: [PATCH 01/42] test react components as children --- packages/core/src/index.ts | 10 +- .../plugins/suggestion/SuggestionPlugin.ts | 8 +- packages/react/src/BlockNoteView.tsx | 8 +- .../EditorElementComponentWrapper.tsx | 6 +- .../components/FormattingToolbar.tsx | 72 ++++++++++- .../src/SlashMenu/components/SlashMenu.tsx | 112 +++++++++++++++++- packages/react/src/hooks/useBlockNote.ts | 11 +- packages/react/src/index.ts | 34 +++--- 8 files changed, 215 insertions(+), 46 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 8b4b935cb2..551885e440 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,14 +3,16 @@ export * from "./BlockNoteExtensions"; export * from "./extensions/Blocks/api/block"; export * from "./extensions/Blocks/api/blockTypes"; export * from "./extensions/Blocks/api/defaultBlocks"; +export * from "./extensions/Blocks/api/inlineContentTypes"; +export * from "./extensions/Blocks/api/serialization"; +export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; export * from "./extensions/DraggableBlocks/BlockSideMenuFactoryTypes"; export * from "./extensions/FormattingToolbar/FormattingToolbarFactoryTypes"; +export { createFormattingToolbarPlugin } from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes"; -export { defaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; export * from "./extensions/SlashMenu/BaseSlashMenuItem"; +export { defaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; export * from "./shared/EditorElement"; export type { SuggestionItem } from "./shared/plugins/suggestion/SuggestionItem"; +export { createSuggestionPlugin } from "./shared/plugins/suggestion/SuggestionPlugin"; 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"; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 0eaf7d7c20..6660932469 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -1,16 +1,16 @@ import { Editor, Range } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; +import { BlockNoteEditor } from "../../../BlockNoteEditor"; +import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; +import { SuggestionItem } from "./SuggestionItem"; import { SuggestionsMenu, SuggestionsMenuDynamicParams, SuggestionsMenuFactory, SuggestionsMenuStaticParams, } from "./SuggestionsMenuFactoryTypes"; -import { SuggestionItem } from "./SuggestionItem"; -import { BlockNoteEditor } from "../../../BlockNoteEditor"; -import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; export type SuggestionPluginOptions< T extends SuggestionItem, @@ -143,7 +143,7 @@ class SuggestionPluginView< handleScroll = () => { if (this.pluginKey.getState(this.editor._tiptapEditor.state).active) { - this.suggestionsMenu.render(this.getDynamicParams(), false); + // this.suggestionsMenu.render(this.getDynamicParams(), false); } }; diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index ffc0ae860c..666bd29e8a 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -1,5 +1,7 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { EditorContent } from "@tiptap/react"; +import { FormattingToolbar } from "./FormattingToolbar/components/FormattingToolbar"; +import { SlashMenu2 } from "./SlashMenu/components/SlashMenu"; // import { BlockNoteTheme } from "./BlockNoteTheme"; // import { MantineProvider } from "@mantine/core"; @@ -9,7 +11,11 @@ export function BlockNoteView(props: { return ( // TODO: Should we wrap editor in MantineProvider? Otherwise we have to duplicate color hex values. // - + <> + + + + // ); } diff --git a/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx b/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx index 3113bc55eb..b1c54830f8 100644 --- a/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx +++ b/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx @@ -1,6 +1,6 @@ +import { RequiredDynamicParams } from "@blocknote/core"; import { MantineProvider, MantineThemeOverride } from "@mantine/core"; import Tippy, { TippyProps } from "@tippyjs/react"; -import { RequiredDynamicParams } from "@blocknote/core"; import { FC, useCallback, useState } from "react"; /** @@ -35,11 +35,11 @@ export function EditorElementComponentWrapper< const onShow = useCallback(() => { setContentCleared(false); - document.body.appendChild(props.rootElement); + // document.body.appendChild(props.rootElement); }, [props.rootElement]); const onHidden = useCallback(() => { - props.rootElement.remove(); + // props.rootElement.remove(); setContentCleared(true); }, [props.rootElement]); diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx index 85b3650d0b..21cd753de5 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx @@ -1,4 +1,13 @@ -import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { + BlockNoteEditor, + BlockSchema, + createFormattingToolbarPlugin, +} from "@blocknote/core"; + +import { PluginKey } from "prosemirror-state"; +import { useEffect, useRef, useState } from "react"; +import { getBlockNoteTheme } from "../../BlockNoteTheme"; +import { EditorElementComponentWrapper } from "../../ElementFactory/components/EditorElementComponentWrapper"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ColorStyleButton } from "./DefaultButtons/ColorStyleButton"; import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; @@ -10,7 +19,7 @@ import { TextAlignButton } from "./DefaultButtons/TextAlignButton"; import { ToggledStyleButton } from "./DefaultButtons/ToggledStyleButton"; import { BlockTypeDropdown } from "./DefaultDropdowns/BlockTypeDropdown"; -export const FormattingToolbar = (props: { +export const FormattingToolbarOld = (props: { editor: BlockNoteEditor; }) => { return ( @@ -35,3 +44,62 @@ export const FormattingToolbar = (props: { ); }; + +export const FormattingToolbar = (props: { + editor: BlockNoteEditor; +}) => { + const [params, setParams] = useState(); + const [isHidden, setIsHidden] = useState(true); + + const elementRef = useRef(null); + useEffect(() => { + if (!elementRef.current || !props.editor) { + return; + } + + if (props.editor._tiptapEditor.isDestroyed) { + return; + } + + const pluginKey = new PluginKey("FormattingToolbarPlugin2"); + + const plugin = createFormattingToolbarPlugin({ + tiptapEditor: props.editor._tiptapEditor, + editor: props.editor, + formattingToolbarFactory: () => ({ + element: elementRef.current!, + render: (params, isHidden) => { + setParams(params); + setIsHidden(false); + }, + hide: () => { + setIsHidden(true); + }, + }), + pluginKey, + }); + + props.editor._tiptapEditor.registerPlugin(plugin); + return () => props.editor._tiptapEditor.unregisterPlugin(pluginKey); + }, [props.editor, elementRef.current]); + console.log("FormattingToolbar", params, isHidden); + return ( +
+ {elementRef.current && props.editor && ( + + )} +
+ ); +}; diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index f775ec7728..a16234daa2 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -1,9 +1,18 @@ -import { createStyles, Menu } from "@mantine/core"; +import { + BaseSlashMenuItem, + BlockNoteEditor, + BlockSchema, + createSuggestionPlugin, + defaultSlashMenuItems, +} from "@blocknote/core"; +import { Menu, createStyles } from "@mantine/core"; import * as _ from "lodash"; -import { SlashMenuItem } from "./SlashMenuItem"; +import { useCallback, useEffect, useRef, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; -import { BlockSchema } from "@blocknote/core"; +import { SlashMenuItem } from "./SlashMenuItem"; +import Tippy from "@tippyjs/react"; +import { PluginKey } from "prosemirror-state"; export type SlashMenuProps = { items: ReactSlashMenuItem[]; keyboardHoveredItemIndex: number; @@ -63,3 +72,100 @@ export function SlashMenu( ); } + +export const SlashMenu2 = (props: { + editor: BlockNoteEditor; +}) => { + const [params, setParams] = useState(); + const [isHidden, setIsHidden] = useState(true); + + const elementRef = useRef(null); + useEffect(() => { + if (!elementRef.current || !props.editor) { + return; + } + + if (props.editor._tiptapEditor.isDestroyed) { + return; + } + + const pluginKey = new PluginKey("SlashMenu2"); + + const plugin = createSuggestionPlugin, BSchema>({ + pluginKey, + editor: props.editor!, + defaultTriggerCharacter: "/", + suggestionsMenuFactory: () => ({ + element: elementRef.current!, + render: (params, isHidden) => { + console.log("params", params.referenceRect); + setParams(params); + setIsHidden(false); + }, + hide: () => { + setIsHidden(true); + }, + }), + items: (query) => { + return defaultSlashMenuItems.filter((cmd: BaseSlashMenuItem) => + cmd.match(query) + ); + }, + onSelectItem: ({ item, editor }) => { + item.execute(editor); + }, + }); + + props.editor._tiptapEditor.registerPlugin(plugin); + return () => props.editor._tiptapEditor.unregisterPlugin(pluginKey); + }, [props.editor, elementRef.current]); + console.log("FormattingToolbar", params, isHidden); + + const getReferenceClientRect = useCallback( + () => params.referenceRect, + [params] + ); + + return ( +
+ {elementRef.current && props.editor && params && ( + // + } + getReferenceClientRect={getReferenceClientRect} + interactive={true} + // onShow={onShow} + // onHidden={onHidden} + visible={true} + // popperOptions={{ + // modifiers: [ + // { + // name: "preventOverflow", + // options: { + // altAxis: true, // false by default + // altBoundary: true, + // }, + // }, + // ], + // }} + // {...props.tippyProps} + > +
+ + )} +
+ ); +}; diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 323c050306..89c8bc5cbc 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -8,10 +8,8 @@ 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 @@ -57,16 +55,11 @@ export const useBlockNote = ( } let uiFactories = { - formattingToolbarFactory: createReactFormattingToolbarFactory( - getBlockNoteTheme(newOptions.theme === "dark"), - newOptions.customElements?.formattingToolbar - ), + formattingToolbarFactory: undefined, hyperlinkToolbarFactory: createReactHyperlinkToolbarFactory( getBlockNoteTheme(newOptions.theme === "dark") ), - slashMenuFactory: createReactSlashMenuFactory( - getBlockNoteTheme(newOptions.theme === "dark") - ), + slashMenuFactory: undefined, blockSideMenuFactory: createReactBlockSideMenuFactory( getBlockNoteTheme(newOptions.theme === "dark"), newOptions.customElements?.dragHandleMenu diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 55edb7a45a..88fa18eee0 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -1,32 +1,26 @@ // TODO: review directories export * from "./BlockNoteView"; - -export * from "./ReactBlockSpec"; - export * from "./BlockSideMenu/BlockSideMenuFactory"; +export * from "./BlockSideMenu/components/DefaultButtons/BlockColorsButton"; +export * from "./BlockSideMenu/components/DefaultButtons/RemoveBlockButton"; 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/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 "./hooks/useBlockNote"; -export * from "./hooks/useEditorForceUpdate"; - +export * from "./FormattingToolbar/components/DefaultButtons/NestBlockButtons"; +export * from "./FormattingToolbar/components/DefaultButtons/TextAlignButton"; +export * from "./FormattingToolbar/components/DefaultButtons/ToggledStyleButton"; +export * from "./FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown"; +export * from "./FormattingToolbar/components/FormattingToolbar"; export * from "./HyperlinkToolbar/HyperlinkToolbarFactory"; - -export * from "./SlashMenu/SlashMenuFactory"; -export * from "./SlashMenu/ReactSlashMenuItem"; -export * from "./SlashMenu/defaultReactSlashMenuItems"; - +export * from "./ReactBlockSpec"; export * from "./SharedComponents/Toolbar/components/Toolbar"; export * from "./SharedComponents/Toolbar/components/ToolbarButton"; export * from "./SharedComponents/Toolbar/components/ToolbarDropdown"; +export * from "./SlashMenu/ReactSlashMenuItem"; +export * from "./SlashMenu/SlashMenuFactory"; +export * from "./SlashMenu/components/SlashMenu"; +export * from "./SlashMenu/defaultReactSlashMenuItems"; +export * from "./hooks/useBlockNote"; +export * from "./hooks/useEditorForceUpdate"; From 1e3d42142cc8398433d25c16f9891bf3d78d4cae Mon Sep 17 00:00:00 2001 From: yousefed Date: Fri, 30 Jun 2023 10:39:00 +0200 Subject: [PATCH 02/42] slashmenu --- examples/editor/src/main.tsx | 2 + packages/core/src/BlockNoteEditor.ts | 22 ++- packages/core/src/BlockNoteExtensions.ts | 23 ++- .../SlashMenu/SlashMenuExtension.ts | 13 +- packages/core/src/shared/EventEmitter.ts | 62 +++++++ .../plugins/suggestion/SuggestionPlugin.ts | 70 ++++---- .../src/SlashMenu/components/SlashMenu.tsx | 170 +++++++++--------- packages/react/src/hooks/useBlockNote.ts | 18 +- 8 files changed, 226 insertions(+), 154 deletions(-) create mode 100644 packages/core/src/shared/EventEmitter.ts diff --git a/examples/editor/src/main.tsx b/examples/editor/src/main.tsx index 0808f1a4d8..5c948c1c61 100644 --- a/examples/editor/src/main.tsx +++ b/examples/editor/src/main.tsx @@ -11,3 +11,5 @@ root.render( ); + +// root.render(); diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 5b86a5aaa4..f0025942c2 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -2,7 +2,9 @@ import { Editor, EditorOptions } 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 { UiFactories, getBlockNoteExtensions } from "./BlockNoteExtensions"; import { insertBlocks, removeBlocks, @@ -10,14 +12,13 @@ import { updateBlock, } from "./api/blockManipulation/blockManipulation"; import { + HTMLToBlocks, blocksToHTML, blocksToMarkdown, - HTMLToBlocks, markdownToBlocks, } from "./api/formatConversions/formatConversions"; import { nodeToBlock } from "./api/nodeConversions/nodeConversions"; import { getNodeById } from "./api/util/nodeUtil"; -import { getBlockNoteExtensions, UiFactories } from "./BlockNoteExtensions"; import styles from "./editor.module.css"; import { Block, @@ -39,8 +40,10 @@ import { Selection } from "./extensions/Blocks/api/selectionTypes"; import { getBlockInfoFromPos } from "./extensions/Blocks/helpers/getBlockInfoFromPos"; import { BaseSlashMenuItem, + createSlashMenuExtension, defaultSlashMenuItems, } from "./extensions/SlashMenu"; +import { EventEmitter } from "./shared/EventEmitter"; export type BlockNoteEditorOptions = { // TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them. @@ -145,7 +148,9 @@ const blockNoteTipTapOptions = { enableCoreExtensions: false, }; -export class BlockNoteEditor { +export class BlockNoteEditor< + BSchema extends BlockSchema = DefaultBlockSchema +> extends EventEmitter { public readonly _tiptapEditor: TiptapEditor & { contentComponent: any }; public blockCache = new WeakMap>(); public readonly schema: BSchema; @@ -165,6 +170,7 @@ export class BlockNoteEditor { constructor( private readonly options: Partial> = {} ) { + super(); // apply defaults const newOptions: Omit & { defaultStyles: boolean; @@ -188,6 +194,16 @@ export class BlockNoteEditor { collaboration: newOptions.collaboration, }); + extensions.push( + createSlashMenuExtension().configure({ + editor: this, + commands: newOptions.slashCommands, + onUpdate: (data: any) => { + this.emit("slashMenuUpdate", data); + }, + }) + ); + this.schema = newOptions.blockSchema; const tiptapOptions: EditorOptions = { diff --git a/packages/core/src/BlockNoteExtensions.ts b/packages/core/src/BlockNoteExtensions.ts index f26deb9774..b71e94ec80 100644 --- a/packages/core/src/BlockNoteExtensions.ts +++ b/packages/core/src/BlockNoteExtensions.ts @@ -30,10 +30,7 @@ import { FormattingToolbarFactory } from "./extensions/FormattingToolbar/Formatt 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 { BaseSlashMenuItem } from "./extensions/SlashMenu"; import { TextAlignmentExtension } from "./extensions/TextAlignment/TextAlignmentExtension"; import { TextColorExtension } from "./extensions/TextColor/TextColorExtension"; import { TextColorMark } from "./extensions/TextColor/TextColorMark"; @@ -183,15 +180,15 @@ export const getBlockNoteExtensions = (opts: { ret.push(Link); } - if (opts.uiFactories.slashMenuFactory) { - ret.push( - createSlashMenuExtension().configure({ - editor: opts.editor, - commands: opts.slashCommands, - slashMenuFactory: opts.uiFactories.slashMenuFactory, - }) - ); - } + // 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/extensions/SlashMenu/SlashMenuExtension.ts b/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts index d51aeb3458..a8f2d9c3f4 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts @@ -1,15 +1,14 @@ 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 { createSuggestionPlugin } from "../../shared/plugins/suggestion/SuggestionPlugin"; import { BlockSchema } from "../Blocks/api/blockTypes"; +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; export type SlashMenuOptions = { editor: BlockNoteEditor | undefined; commands: BaseSlashMenuItem[] | undefined; - slashMenuFactory: SuggestionsMenuFactory | undefined; + onUpdate: any; //SuggestionsMenuFactory | undefined; }; export const SlashMenuPluginKey = new PluginKey("suggestions-slash-commands"); @@ -22,12 +21,12 @@ export const createSlashMenuExtension = () => return { editor: undefined, commands: undefined, - slashMenuFactory: undefined, + onUpdate: undefined, }; }, addProseMirrorPlugins() { - if (!this.options.slashMenuFactory || !this.options.commands) { + if (!this.options.onUpdate || !this.options.commands) { throw new Error("required args not defined for SlashMenuExtension"); } @@ -38,7 +37,7 @@ export const createSlashMenuExtension = () => pluginKey: SlashMenuPluginKey, editor: this.options.editor!, defaultTriggerCharacter: "/", - suggestionsMenuFactory: this.options.slashMenuFactory!, + onUpdate: this.options.onUpdate!, items: (query) => { return commands.filter((cmd: BaseSlashMenuItem) => cmd.match(query) diff --git a/packages/core/src/shared/EventEmitter.ts b/packages/core/src/shared/EventEmitter.ts new file mode 100644 index 0000000000..674ed14e9f --- /dev/null +++ b/packages/core/src/shared/EventEmitter.ts @@ -0,0 +1,62 @@ +//from tiptap. Could also use a package like nanoevents + +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 + ): this { + if (!this.callbacks[event]) { + this.callbacks[event] = []; + } + + this.callbacks[event].push(fn); + + return this; + } + + protected emit>( + event: EventName, + ...args: CallbackType + ): this { + const callbacks = this.callbacks[event]; + + if (callbacks) { + callbacks.forEach((callback) => callback.apply(this, args)); + } + + return this; + } + + public off>( + event: EventName, + fn?: CallbackFunction + ): this { + const callbacks = this.callbacks[event]; + + if (callbacks) { + if (fn) { + this.callbacks[event] = callbacks.filter((callback) => callback !== fn); + } else { + delete this.callbacks[event]; + } + } + + return this; + } + + protected removeAllListeners(): void { + this.callbacks = {}; + } +} diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 6660932469..6f46aa9114 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -5,12 +5,6 @@ import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; import { SuggestionItem } from "./SuggestionItem"; -import { - SuggestionsMenu, - SuggestionsMenuDynamicParams, - SuggestionsMenuFactory, - SuggestionsMenuStaticParams, -} from "./SuggestionsMenuFactoryTypes"; export type SuggestionPluginOptions< T extends SuggestionItem, @@ -33,7 +27,7 @@ export type SuggestionPluginOptions< */ defaultTriggerCharacter: string; - suggestionsMenuFactory: SuggestionsMenuFactory; + onUpdate: any; /** * The callback that gets executed when an item is selected by the user. @@ -92,7 +86,7 @@ type SuggestionPluginViewOptions< editor: BlockNoteEditor; pluginKey: PluginKey; onSelectItem: (props: { item: T; editor: BlockNoteEditor }) => void; - suggestionsMenuFactory: SuggestionsMenuFactory; + onUpdate: any; }; class SuggestionPluginView< @@ -102,7 +96,7 @@ class SuggestionPluginView< editor: BlockNoteEditor; pluginKey: PluginKey; - suggestionsMenu: SuggestionsMenu; + onUpdate: any; pluginState: SuggestionPluginState; itemCallback: (item: T) => void; @@ -111,11 +105,11 @@ class SuggestionPluginView< editor, pluginKey, onSelectItem: selectItemCallback = () => {}, - suggestionsMenuFactory, + onUpdate, }: SuggestionPluginViewOptions) { this.editor = editor; this.pluginKey = pluginKey; - + this.onUpdate = onUpdate; this.pluginState = getDefaultPluginState(); this.itemCallback = (item: T) => { @@ -136,7 +130,7 @@ class SuggestionPluginView< }); }; - this.suggestionsMenu = suggestionsMenuFactory(this.getStaticParams()); + // this.suggestionsMenu = suggestionsMenuFactory(this.getStaticParams()); document.addEventListener("scroll", this.handleScroll); } @@ -166,25 +160,29 @@ class SuggestionPluginView< this.pluginState = stopped ? prev : next; if (stopped || !this.editor.isEditable) { - this.suggestionsMenu.hide(); - + this.params.active = false; + this.onUpdate(this.params); + // this.suggestionsMenu.hide(); // Listener stops focus moving to the menu on click. - this.suggestionsMenu.element!.removeEventListener("mousedown", (event) => - event.preventDefault() - ); + // this.suggestionsMenu.element!.removeEventListener("mousedown", (event) => + // event.preventDefault() + // ); } if (changed) { - this.suggestionsMenu.render(this.getDynamicParams(), false); + this.updateActiveParams(); + this.onUpdate(this.params); + // this.suggestionsMenu.render(this.getDynamicParams(), false); } if (started && this.editor.isEditable) { - this.suggestionsMenu.render(this.getDynamicParams(), true); - + // this.suggestionsMenu.render(this.getDynamicParams(), true); + this.updateActiveParams(); + this.onUpdate(this.params); // Listener stops focus moving to the menu on click. - this.suggestionsMenu.element!.addEventListener("mousedown", (event) => - event.preventDefault() - ); + // this.suggestionsMenu.element!.addEventListener("mousedown", (event) => + // event.preventDefault() + // ); } } @@ -192,22 +190,20 @@ class SuggestionPluginView< document.removeEventListener("scroll", this.handleScroll); } - getStaticParams(): SuggestionsMenuStaticParams { - return { - itemCallback: (item: T) => this.itemCallback(item), - }; - } + private params: any = { + active: false, + itemCallback: (item: T) => this.itemCallback(item), + }; - getDynamicParams(): SuggestionsMenuDynamicParams { + updateActiveParams(): any { const decorationNode = document.querySelector( `[data-decoration-id="${this.pluginState.decorationId}"]` ); - - return { - items: this.pluginState.items, - keyboardHoveredItemIndex: this.pluginState.keyboardHoveredItemIndex!, - referenceRect: decorationNode!.getBoundingClientRect(), - }; + this.params.active = true; + this.params.items = this.pluginState.items; + this.params.keyboardHoveredItemIndex = + this.pluginState.keyboardHoveredItemIndex!; + this.params.referenceRect = decorationNode!.getBoundingClientRect(); } } @@ -231,7 +227,7 @@ export function createSuggestionPlugin< pluginKey, editor, defaultTriggerCharacter, - suggestionsMenuFactory, + onUpdate, onSelectItem: selectItemCallback = () => {}, items = () => [], }: SuggestionPluginOptions) { @@ -259,7 +255,7 @@ export function createSuggestionPlugin< deactivate(view); selectItemCallback(props); }, - suggestionsMenuFactory: suggestionsMenuFactory, + onUpdate, }), state: { diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index a16234daa2..1782f8404a 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -1,18 +1,12 @@ -import { - BaseSlashMenuItem, - BlockNoteEditor, - BlockSchema, - createSuggestionPlugin, - defaultSlashMenuItems, -} from "@blocknote/core"; +import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { Menu, createStyles } from "@mantine/core"; import * as _ from "lodash"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { SlashMenuItem } from "./SlashMenuItem"; import Tippy from "@tippyjs/react"; -import { PluginKey } from "prosemirror-state"; + export type SlashMenuProps = { items: ReactSlashMenuItem[]; keyboardHoveredItemIndex: number; @@ -77,95 +71,101 @@ export const SlashMenu2 = (props: { editor: BlockNoteEditor; }) => { const [params, setParams] = useState(); - const [isHidden, setIsHidden] = useState(true); - const elementRef = useRef(null); useEffect(() => { - if (!elementRef.current || !props.editor) { + if (!props.editor) { return; } + const cb = (params: any) => { + setParams({ ...params }); + }; + props.editor.on("slashMenuUpdate", cb); + return () => { + props.editor.off("slashMenuUpdate", cb); + }; + }, [props.editor]); - if (props.editor._tiptapEditor.isDestroyed) { - return; - } + // This commented out part can be removed, + // but it shows the original way according to tiptap examples where they make the components instantiate + // the plugin. We now do this in BlockNoteEditor by default, making the code in the component more concise + + // useEffect(() => { + // if (!elementRef.current || !props.editor) { + // return; + // } + + // if (props.editor._tiptapEditor.isDestroyed) { + // return; + // } + + // const pluginKey = new PluginKey("SlashMenu2"); + + // const plugin = createSuggestionPlugin, BSchema>({ + // pluginKey, + // editor: props.editor!, + // defaultTriggerCharacter: "/", + // suggestionsMenuFactory: () => ({ + // element: elementRef.current!, + // render: (params, isHidden) => { + // console.log("params", params.referenceRect); + // setParams(params); + // setIsHidden(false); + // }, + // hide: () => { + // setIsHidden(true); + // }, + // }), + // items: (query) => { + // return defaultSlashMenuItems.filter((cmd: BaseSlashMenuItem) => + // cmd.match(query) + // ); + // }, + // onSelectItem: ({ item, editor }) => { + // item.execute(editor); + // }, + // }); - const pluginKey = new PluginKey("SlashMenu2"); - - const plugin = createSuggestionPlugin, BSchema>({ - pluginKey, - editor: props.editor!, - defaultTriggerCharacter: "/", - suggestionsMenuFactory: () => ({ - element: elementRef.current!, - render: (params, isHidden) => { - console.log("params", params.referenceRect); - setParams(params); - setIsHidden(false); - }, - hide: () => { - setIsHidden(true); - }, - }), - items: (query) => { - return defaultSlashMenuItems.filter((cmd: BaseSlashMenuItem) => - cmd.match(query) - ); - }, - onSelectItem: ({ item, editor }) => { - item.execute(editor); - }, - }); - - props.editor._tiptapEditor.registerPlugin(plugin); - return () => props.editor._tiptapEditor.unregisterPlugin(pluginKey); - }, [props.editor, elementRef.current]); - console.log("FormattingToolbar", params, isHidden); + // props.editor._tiptapEditor.registerPlugin(plugin); + // return () => props.editor._tiptapEditor.unregisterPlugin(pluginKey); + // }, [props.editor, elementRef.current]); const getReferenceClientRect = useCallback( () => params.referenceRect, [params] ); + console.log("slashmenu render"); + if (!props.editor || !params) { + return null; + } return ( -
- {elementRef.current && props.editor && params && ( - // - } - getReferenceClientRect={getReferenceClientRect} - interactive={true} - // onShow={onShow} - // onHidden={onHidden} - visible={true} - // popperOptions={{ - // modifiers: [ - // { - // name: "preventOverflow", - // options: { - // altAxis: true, // false by default - // altBoundary: true, - // }, - // }, - // ], - // }} - // {...props.tippyProps} - > -
- - )} +
{ + // prevent blur + e.preventDefault(); + e.stopPropagation(); + }}> + } + getReferenceClientRect={getReferenceClientRect} + interactive={true} + visible={params.active} + popperOptions={{ + // if the window height is too small, prevent the menu from causing + // the body to be scrollable + modifiers: [ + { + name: "preventOverflow", + options: { + altAxis: true, + }, + }, + ], + }} + animation="fade" + placement="bottom-start"> +
+
); }; diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 89c8bc5cbc..e11f9a22c7 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -79,15 +79,15 @@ export const useBlockNote = ( setEditor(instance); - instance._tiptapEditor.on("transaction", () => { - requestAnimationFrame(() => { - requestAnimationFrame(() => { - if (isMounted) { - forceUpdate(); - } - }); - }); - }); + // instance._tiptapEditor.on("transaction", () => { + // requestAnimationFrame(() => { + // requestAnimationFrame(() => { + // if (isMounted) { + // forceUpdate(); + // } + // }); + // }); + // }); return () => { instance._tiptapEditor.destroy(); From 44fb0d210d6bf2f7596b9aa1e239775f49cb70ba Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 13:30:10 +0200 Subject: [PATCH 03/42] Major refactor --- examples/vanilla/src/main.tsx | 23 +- .../vanilla/src/ui/addFormattingToolbar.ts | 43 +++ .../vanilla/src/ui/addHyperlinkToolbar.ts | 46 +++ examples/vanilla/src/ui/addSideMenu.ts | 42 +++ examples/vanilla/src/ui/addSlashMenu.ts | 60 ++++ .../vanilla/src/ui/blockSideMenuFactory.ts | 48 --- .../src/ui/formattingToolbarFactory.ts | 48 --- .../vanilla/src/ui/hyperlinkToolbarFactory.ts | 53 --- examples/vanilla/src/ui/slashMenuFactory.ts | 63 ---- packages/core/src/BlockNoteEditor.ts | 20 +- packages/core/src/BlockNoteExtensions.ts | 54 +-- .../BlockSideMenuFactoryTypes.ts | 29 -- .../DraggableBlocksExtension.ts | 74 ++-- .../DraggableBlocks/DraggableBlocksPlugin.ts | 320 ++++++++++-------- .../FormattingToolbarExtension.ts | 74 ++-- .../FormattingToolbarFactoryTypes.ts | 20 -- .../FormattingToolbarPlugin.ts | 144 ++++---- .../HyperlinkToolbar/HyperlinkMark.ts | 56 +-- .../HyperlinkToolbarFactoryTypes.ts | 19 -- .../HyperlinkToolbarPlugin.ts | 285 +++++++++------- .../SlashMenu/SlashMenuExtension.ts | 104 +++--- packages/core/src/index.ts | 16 +- packages/core/src/shared/EditorElement.ts | 18 +- .../plugins/suggestion/SuggestionPlugin.ts | 285 ++++++++-------- .../suggestion/SuggestionsMenuFactoryTypes.ts | 21 -- packages/react/src/BlockNoteTheme.ts | 1 + packages/react/src/BlockNoteView.tsx | 21 +- .../BlockSideMenu/BlockSideMenuFactory.tsx | 98 +++--- .../components/BlockSideMenu.tsx | 91 +++-- .../FormattingToolbarFactory.tsx | 56 +-- .../components/FormattingToolbar.tsx | 83 ++--- .../HyperlinkToolbarFactory.tsx | 40 +-- .../components/HyperlinkToolbar.tsx | 51 ++- .../react/src/SlashMenu/SlashMenuFactory.tsx | 44 +-- .../src/SlashMenu/components/SlashMenu.tsx | 159 ++++----- packages/react/src/hooks/useBlockNote.ts | 169 +++++---- 36 files changed, 1356 insertions(+), 1422 deletions(-) create mode 100644 examples/vanilla/src/ui/addFormattingToolbar.ts create mode 100644 examples/vanilla/src/ui/addHyperlinkToolbar.ts create mode 100644 examples/vanilla/src/ui/addSideMenu.ts create mode 100644 examples/vanilla/src/ui/addSlashMenu.ts delete mode 100644 examples/vanilla/src/ui/blockSideMenuFactory.ts delete mode 100644 examples/vanilla/src/ui/formattingToolbarFactory.ts delete mode 100644 examples/vanilla/src/ui/hyperlinkToolbarFactory.ts delete mode 100644 examples/vanilla/src/ui/slashMenuFactory.ts delete mode 100644 packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts delete mode 100644 packages/core/src/extensions/FormattingToolbar/FormattingToolbarFactoryTypes.ts delete mode 100644 packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts delete mode 100644 packages/core/src/shared/plugins/suggestion/SuggestionsMenuFactoryTypes.ts 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..c8d36d18ef --- /dev/null +++ b/examples/vanilla/src/ui/addFormattingToolbar.ts @@ -0,0 +1,43 @@ +import { BlockNoteEditor, createFormattingToolbar } from "@blocknote/core"; +import { createButton } from "./util"; + +export const addFormattingToolbar = (editor: BlockNoteEditor) => { + let element: HTMLElement; + let boldBtn: HTMLAnchorElement; + + createFormattingToolbar(editor, (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..51b07f1740 --- /dev/null +++ b/examples/vanilla/src/ui/addHyperlinkToolbar.ts @@ -0,0 +1,46 @@ +import { BlockNoteEditor, createHyperlinkToolbar } from "@blocknote/core"; +import { createButton } from "./util"; + +export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { + let element: HTMLElement; + + createHyperlinkToolbar(editor, (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; + hyperlinkToolbarState.editHyperlink(newUrl, text); + }); + + element.appendChild(editBtn); + + const removeBtn = createButton("remove", () => { + hyperlinkToolbarState.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..7f3e2589f2 --- /dev/null +++ b/examples/vanilla/src/ui/addSideMenu.ts @@ -0,0 +1,42 @@ +import { BlockNoteEditor, createSideMenu } from "@blocknote/core"; +import { createButton } from "./util"; + +export const addSideMenu = (editor: BlockNoteEditor) => { + let element: HTMLElement; + + createSideMenu(editor, (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("+", () => { + sideMenuState.addBlock(); + }); + element.appendChild(addBtn); + + const dragBtn = createButton("::", () => { + // TODO: render a submenu with a delete option that calls "props.deleteBlock" + }); + + dragBtn.addEventListener("dragstart", sideMenuState.blockDragStart); + dragBtn.addEventListener("dragend", sideMenuState.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..62b837b189 --- /dev/null +++ b/examples/vanilla/src/ui/addSlashMenu.ts @@ -0,0 +1,60 @@ +import { + BaseSlashMenuItem, + BlockNoteEditor, + createSlashMenu, + 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; + } + + createSlashMenu(editor, (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.items, + slashMenuState.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 039e6939d7..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 = params.referenceRect.y + "px"; - container.style.left = - params.referenceRect.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 2a9387ea0a..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 = params.referenceRect.y + "px"; - container.style.left = params.referenceRect.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 3e1aface51..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 = params.referenceRect.y + "px"; - container.style.left = params.referenceRect.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 4730827626..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 = params.referenceRect.y + "px"; - container.style.left = params.referenceRect.x + "px"; - }, - hide: () => { - container.style.display = "none"; - }, - }; -}; diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index f0025942c2..7a1e4f0ba7 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -4,7 +4,7 @@ import { Node } from "prosemirror-model"; import { Editor as TiptapEditor } from "@tiptap/core/dist/packages/core/src/Editor"; import * as Y from "yjs"; -import { UiFactories, getBlockNoteExtensions } from "./BlockNoteExtensions"; +import { getBlockNoteExtensions } from "./BlockNoteExtensions"; import { insertBlocks, removeBlocks, @@ -40,7 +40,6 @@ import { Selection } from "./extensions/Blocks/api/selectionTypes"; import { getBlockInfoFromPos } from "./extensions/Blocks/helpers/getBlockInfoFromPos"; import { BaseSlashMenuItem, - createSlashMenuExtension, defaultSlashMenuItems, } from "./extensions/SlashMenu"; import { EventEmitter } from "./shared/EventEmitter"; @@ -48,12 +47,6 @@ import { EventEmitter } from "./shared/EventEmitter"; 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? * @@ -188,22 +181,11 @@ export class BlockNoteEditor< const extensions = getBlockNoteExtensions({ editor: this, - uiFactories: newOptions.uiFactories || {}, slashCommands: newOptions.slashCommands || defaultSlashMenuItems, blockSchema: newOptions.blockSchema, collaboration: newOptions.collaboration, }); - extensions.push( - createSlashMenuExtension().configure({ - editor: this, - commands: newOptions.slashCommands, - onUpdate: (data: any) => { - this.emit("slashMenuUpdate", data); - }, - }) - ); - this.schema = newOptions.blockSchema; const tiptapOptions: EditorOptions = { diff --git a/packages/core/src/BlockNoteExtensions.ts b/packages/core/src/BlockNoteExtensions.ts index b71e94ec80..94d5d5ca1a 100644 --- a/packages/core/src/BlockNoteExtensions.ts +++ b/packages/core/src/BlockNoteExtensions.ts @@ -23,12 +23,6 @@ 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 } from "./extensions/SlashMenu"; import { TextAlignmentExtension } from "./extensions/TextAlignment/TextAlignmentExtension"; @@ -36,21 +30,12 @@ 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?: { @@ -96,6 +81,7 @@ export const getBlockNoteExtensions = (opts: { Italic, Strike, Underline, + Link, TextColorMark, TextColorExtension, BackgroundColorMark, @@ -152,43 +138,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/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts b/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts deleted file mode 100644 index fbb0980895..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; -}; - -export type BlockSideMenuDynamicParams = { - block: Block; - - referenceRect: DOMRect; -}; - -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 index 6db0fde3da..8b1a87839b 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts @@ -1,37 +1,37 @@ -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, - }), - ]; - }, - }); +// 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/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index fd0f79727e..b2bb2523a0 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -1,4 +1,3 @@ -import { Editor } from "@tiptap/core"; import { Node } from "prosemirror-model"; import { NodeSelection, Plugin, PluginKey, Selection } from "prosemirror-state"; import * as pv from "prosemirror-view"; @@ -6,22 +5,28 @@ import { EditorView } from "prosemirror-view"; import styles from "../../editor.module.css"; import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; import { SlashMenuPluginKey } from "../SlashMenu/SlashMenuExtension"; -import { - BlockSideMenu, - BlockSideMenuDynamicParams, - BlockSideMenuFactory, - BlockSideMenuStaticParams, -} from "./BlockSideMenuFactoryTypes"; -import { DraggableBlocksOptions } from "./DraggableBlocksExtension"; import { MultipleNodeSelection } from "./MultipleNodeSelection"; import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BlockSchema } from "../Blocks/api/blockTypes"; +import { Block, BlockSchema } from "../Blocks/api/blockTypes"; +import { BaseUiElementState } from "../../shared/EditorElement"; 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 & { + block: Block; + + addBlock: () => void; + + freezeMenu: () => void; + unfreezeMenu: () => void; + + blockDragStart: (event: DragEvent) => void; + blockDragEnd: () => void; +}; + function getDraggableBlockFromCoords( coords: { left: number; top: number }, view: EditorView @@ -224,50 +229,49 @@ 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; + + private sideMenuState?: SideMenuState; + public updateSideMenu: () => void; // When true, the drag handle with be anchored at the same level as root elements // When false, the drag handle with be just to the left of the element + // TODO: Is there any case where we want this to be false? horizontalPosAnchoredAtRoot: boolean; - horizontalPosAnchor: number; - blockMenu: BlockSideMenu; - hoveredBlock: HTMLElement | undefined; // Used to check if currently dragged content comes from this editor instance. isDragging = false; - menuOpen = false; + menuFrozen = false; - constructor({ - tiptapEditor, - editor, - blockMenuFactory, - horizontalPosAnchoredAtRoot, - }: BlockMenuViewProps) { + constructor( + editor: BlockNoteEditor, + updateSideMenu: (sideMenu: SideMenuState) => void + ) { this.editor = editor; - this.ttEditor = tiptapEditor; - this.horizontalPosAnchoredAtRoot = horizontalPosAnchoredAtRoot; + this.horizontalPosAnchoredAtRoot = true; this.horizontalPosAnchor = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.editor._tiptapEditor.view.dom.firstChild! as HTMLElement ).getBoundingClientRect().x; - this.blockMenu = blockMenuFactory(this.getStaticParams()); + this.updateSideMenu = () => { + if (!this.sideMenuState) { + throw new Error("Attempting to update uninitialized side menu"); + } + + updateSideMenu(this.sideMenuState); + }; document.body.addEventListener("drop", this.onDrop, true); document.body.addEventListener("dragover", this.onDragOver); - this.ttEditor.view.dom.addEventListener("dragstart", this.onDragStart); + this.editor._tiptapEditor.view.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); @@ -297,7 +301,7 @@ export class BlockMenuView { if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.ttEditor.view.posAtCoords({ + let pos = this.editor._tiptapEditor.view.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -307,7 +311,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.editor._tiptapEditor.view.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -315,7 +319,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.editor._tiptapEditor.view.dom.dispatchEvent(evt); } }; @@ -328,7 +332,7 @@ export class BlockMenuView { if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.ttEditor.view.posAtCoords({ + let pos = this.editor._tiptapEditor.view.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -336,7 +340,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.editor._tiptapEditor.view.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -344,30 +348,32 @@ export class BlockMenuView { evt.preventDefault = () => event.preventDefault(); evt.synthetic = true; // prevent recursion // console.log("dispatch fake dragover"); - this.ttEditor.view.dom.dispatchEvent(evt); + this.editor._tiptapEditor.view.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.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; + onMouseDown = (_event: MouseEvent) => { + // TODO: Fix + return; + // if (this.blockMenu.element?.contains(event.target as HTMLElement)) { + // return; + // } + // + // if (this.sideMenuState?.show) { + // this.sideMenuState.show = false; + // this.updateSideMenu(); + // } + // + // this.menuFrozen = false; }; onMouseMove = (event: MouseEvent) => { @@ -380,18 +386,20 @@ 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.editor._tiptapEditor.view.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(); + this.editor._tiptapEditor.view.dom.getBoundingClientRect(); const cursorWithinEditor = event.clientX >= editorOuterBoundingBox.left && event.clientX <= editorOuterBoundingBox.right && event.clientY >= editorOuterBoundingBox.top && event.clientY <= editorOuterBoundingBox.bottom; + const editorWrapper = this.editor._tiptapEditor.view.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 ( @@ -401,15 +409,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(); } return; @@ -422,13 +429,16 @@ 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.editor._tiptapEditor.view + ); // 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(); } return; @@ -436,11 +446,14 @@ 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 ) { - return; + if (this.sideMenuState?.show) { + this.sideMenuState.show = true; + this.updateSideMenu(); + } } this.hoveredBlock = block.node; @@ -454,37 +467,83 @@ export class BlockMenuView { // Shows or updates elements. if (this.editor.isEditable) { - if (!this.menuOpen) { - this.menuOpen = true; - this.blockMenu.render(this.getDynamicParams(), true); + const blockContentBoundingBox = blockContent.getBoundingClientRect(); + + if (!this.sideMenuState) { + 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")! + )!, + addBlock: this.addBlock, + blockDragStart: (event: DragEvent) => { + // Sets isDragging when dragging blocks. + this.isDragging = true; + dragStart(event, this.editor._tiptapEditor.view); + }, + blockDragEnd: () => unsetDragImage(), + freezeMenu: () => { + this.menuFrozen = true; + }, + unfreezeMenu: () => { + this.menuFrozen = false; + }, + }; } else { - this.blockMenu.render(this.getDynamicParams(), false); + this.sideMenuState.show = true; + this.sideMenuState.referencePos = new DOMRect( + this.horizontalPosAnchoredAtRoot + ? this.horizontalPosAnchor + : blockContentBoundingBox.x, + blockContentBoundingBox.y, + blockContentBoundingBox.width, + blockContentBoundingBox.height + ); + this.sideMenuState.block = this.editor.getBlock( + this.hoveredBlock!.getAttribute("data-id")! + )!; } + + this.updateSideMenu(); } }; onScroll = () => { - // Editor itself may have padding or other styling which affects size/position, so we get the boundingRect of - // the first child (i.e. the blockGroup that wraps all blocks in the editor) for a more accurate bounding box. - const editorBoundingBox = ( - this.ttEditor.view.dom.firstChild! as HTMLElement - ).getBoundingClientRect(); - - this.horizontalPosAnchor = editorBoundingBox.x; + if (this.sideMenuState?.show) { + const blockContent = this.hoveredBlock!.firstChild as HTMLElement; + const blockContentBoundingBox = blockContent.getBoundingClientRect(); - if (this.menuOpen) { - this.blockMenu.render(this.getDynamicParams(), false); + this.sideMenuState.referencePos = new DOMRect( + this.horizontalPosAnchoredAtRoot + ? this.horizontalPosAnchor + : blockContentBoundingBox.x, + blockContentBoundingBox.y, + blockContentBoundingBox.width, + blockContentBoundingBox.height + ); + this.updateSideMenu(); } }; destroy() { - if (this.menuOpen) { - this.menuOpen = false; - this.blockMenu.hide(); + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(); } document.body.removeEventListener("mousemove", this.onMouseMove); document.body.removeEventListener("dragover", this.onDragOver); - this.ttEditor.view.dom.removeEventListener("dragstart", this.onDragStart); + this.editor._tiptapEditor.view.dom.removeEventListener( + "dragstart", + this.onDragStart + ); document.body.removeEventListener("drop", this.onDrop); document.body.removeEventListener("mousedown", this.onMouseDown); document.removeEventListener("scroll", this.onScroll); @@ -492,14 +551,17 @@ export class BlockMenuView { } addBlock() { - this.menuOpen = false; + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(); + } + 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.editor._tiptapEditor.view.posAtCoords({ left: blockContentBoundingBox.left + blockContentBoundingBox.width / 2, top: blockContentBoundingBox.top + blockContentBoundingBox.height / 2, }); @@ -507,7 +569,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; } @@ -519,75 +584,38 @@ 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, { - // TODO import suggestion plugin key - activate: true, - type: "drag", - }) + this.editor._tiptapEditor.view.focus(); + this.editor._tiptapEditor.view.dispatch( + this.editor._tiptapEditor.view.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; - }, - }; - } - - getDynamicParams(): BlockSideMenuDynamicParams { - const blockContent = this.hoveredBlock!.firstChild! as HTMLElement; - const blockContentBoundingBox = blockContent.getBoundingClientRect(); - - return { - block: this.editor.getBlock(this.hoveredBlock!.getAttribute("data-id")!)!, - referenceRect: new DOMRect( - this.horizontalPosAnchoredAtRoot - ? this.horizontalPosAnchor - : blockContentBoundingBox.x, - blockContentBoundingBox.y, - blockContentBoundingBox.width, - blockContentBoundingBox.height - ), - }; - } } -export const createDraggableBlocksPlugin = ( - options: DraggableBlocksOptions +export const createSideMenu = ( + editor: BlockNoteEditor, + updateSideMenu: (sideMenuState: SideMenuState) => void ) => { - return new Plugin({ - key: new PluginKey("DraggableBlocksPlugin"), - view: () => - new BlockMenuView({ - tiptapEditor: options.tiptapEditor, - editor: options.editor, - blockMenuFactory: options.blockSideMenuFactory, - horizontalPosAnchoredAtRoot: true, - }), - }); + editor._tiptapEditor.registerPlugin( + new Plugin({ + key: new PluginKey("DraggableBlocksPlugin"), + view: () => new BlockMenuView(editor, updateSideMenu), + }) + ); }; diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts index a7389c4c8b..e1ef9db496 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts @@ -1,37 +1,37 @@ -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"), - }), - ]; - }, - }); +// 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 f424508038..0000000000 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarFactoryTypes.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { EditorElement, ElementFactory } from "../../shared/EditorElement"; -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BlockSchema } from "../Blocks/api/blockTypes"; - -export type FormattingToolbarStaticParams = { - editor: BlockNoteEditor; -}; - -export type FormattingToolbarDynamicParams = { - referenceRect: DOMRect; -}; - -export type FormattingToolbar = EditorElement< - FormattingToolbarDynamicParams ->; -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 2ee29815a6..e35d092d58 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -6,42 +6,20 @@ import { } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; -import { BlockNoteEditor, BlockSchema } from "../.."; -import { - FormattingToolbar, - FormattingToolbarDynamicParams, - 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; -} +import { BaseUiElementState, BlockNoteEditor, BlockSchema } from "../.."; -export type FormattingToolbarViewProps = - FormattingToolbarPluginProps & { - view: EditorView; - }; +export type FormattingToolbarState = BaseUiElementState; export class FormattingToolbarView { public editor: BlockNoteEditor; private ttEditor: Editor; - public view: EditorView; - public formattingToolbar: FormattingToolbar; + private formattingToolbarState?: FormattingToolbarState; + public updateFormattingToolbar: () => void; public preventHide = false; - public preventShow = false; - - public toolbarIsOpen = false; - public prevWasEditable: boolean | null = null; public shouldShow: (props: { @@ -62,17 +40,26 @@ export class FormattingToolbarView { return !(!view.hasFocus() || empty || isEmptyTextBlock); }; - constructor({ - editor, - tiptapEditor, - formattingToolbarFactory, - view, - }: FormattingToolbarViewProps) { - this.editor = editor; - this.ttEditor = tiptapEditor; + constructor( + editor: BlockNoteEditor, + view: EditorView, + updateFormattingToolbar: ( + formattingToolbarState: FormattingToolbarState + ) => void + ) { this.view = view; + this.editor = editor; + this.ttEditor = editor._tiptapEditor; - this.formattingToolbar = formattingToolbarFactory(this.getStaticParams()); + this.updateFormattingToolbar = () => { + if (!this.formattingToolbarState) { + throw new Error( + "Attempting to update uninitialized formatting toolbar" + ); + } + + updateFormattingToolbar(this.formattingToolbarState); + }; this.view.dom.addEventListener("mousedown", this.viewMousedownHandler); this.view.dom.addEventListener("mouseup", this.viewMouseupHandler); @@ -93,9 +80,12 @@ export class FormattingToolbarView { setTimeout(() => this.update(this.ttEditor.view)); }; + // For dragging the whole editor. dragstartHandler = () => { - this.formattingToolbar.hide(); - this.toolbarIsOpen = false; + if (this.formattingToolbarState?.show) { + this.formattingToolbarState.show = false; + this.updateFormattingToolbar(); + } }; focusHandler = () => { @@ -110,28 +100,31 @@ export class FormattingToolbarView { return; } + const editorWrapper = this.ttEditor.view.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.toolbarIsOpen) { - this.formattingToolbar.render(this.getDynamicParams(), false); + if (this.formattingToolbarState?.show) { + this.formattingToolbarState.referencePos = this.getSelectionBoundingBox(); + this.updateFormattingToolbar?.(); } }; @@ -163,37 +156,36 @@ 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(this.getDynamicParams(), true); - this.toolbarIsOpen = true; + if (!this.formattingToolbarState) { + this.formattingToolbarState = { + show: true, + referencePos: this.getSelectionBoundingBox(), + }; + } else { + this.formattingToolbarState.show = true; + this.formattingToolbarState.referencePos = + this.getSelectionBoundingBox(); + } - return; - } + this.updateFormattingToolbar(); - // Checks if menu should be updated. - if ( - this.toolbarIsOpen && - !this.preventShow && - (shouldShow || this.preventHide) - ) { - this.formattingToolbar.render(this.getDynamicParams(), 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; } @@ -229,25 +221,19 @@ export class FormattingToolbarView { return posToDOMRect(this.ttEditor.view, from, to); } - - getStaticParams(): FormattingToolbarStaticParams { - return { - editor: this.editor, - }; - } - - getDynamicParams(): FormattingToolbarDynamicParams { - return { - referenceRect: this.getSelectionBoundingBox(), - }; - } } -export const createFormattingToolbarPlugin = ( - options: FormattingToolbarPluginProps +export const createFormattingToolbar = ( + editor: BlockNoteEditor, + updateFormattingToolbar: ( + formattingToolbarState: FormattingToolbarState + ) => void ) => { - return new Plugin({ - key: new PluginKey("FormattingToolbarPlugin"), - view: (view) => new FormattingToolbarView({ view, ...options }), - }); + editor._tiptapEditor.registerPlugin( + new Plugin({ + key: new PluginKey("FormattingToolbarPlugin"), + view: (view) => + new FormattingToolbarView(editor, view, updateFormattingToolbar), + }) + ); }; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts index e61cc46dfd..0c08cce099 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts @@ -1,28 +1,28 @@ -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; +// 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 6002c848fd..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; -}; - -export type HyperlinkToolbarDynamicParams = { - url: string; - text: string; - - referenceRect: DOMRect; -}; - -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 d93e333a83..8431a73a86 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -1,27 +1,26 @@ -import { Editor, getMarkRange, posToDOMRect, Range } from "@tiptap/core"; +import { getMarkRange, posToDOMRect, Range } from "@tiptap/core"; 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 { BaseUiElementState } from "../../shared/EditorElement"; +import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { BlockSchema } from "../Blocks/api/blockTypes"; + +export type HyperlinkToolbarState = BaseUiElementState & { + editHyperlink: (url: string, text: string) => void; + deleteHyperlink: () => void; -export type HyperlinkToolbarViewProps = { - editor: Editor; - hyperlinkToolbarFactory: HyperlinkToolbarFactory; + toolbarMouseEnter: () => void; + toolbarMouseLeave: () => void; + + url: string; + text: string; }; -class HyperlinkToolbarView { - editor: Editor; +class HyperlinkToolbarView { + editor: BlockNoteEditor; - hyperlinkToolbar: HyperlinkToolbar; + private hyperlinkToolbarState?: HyperlinkToolbarState; + public updateHyperlinkToolbar: () => void; menuUpdateTimer: NodeJS.Timeout | undefined; startMenuUpdateTimer: () => void; @@ -36,10 +35,21 @@ class HyperlinkToolbarView { hyperlinkMark: Mark | undefined; hyperlinkMarkRange: Range | undefined; - constructor({ editor, hyperlinkToolbarFactory }: HyperlinkToolbarViewProps) { + constructor( + editor: BlockNoteEditor, + updateHyperlinkToolbar: ( + hyperlinkToolbarState: HyperlinkToolbarState + ) => void + ) { this.editor = editor; - this.hyperlinkToolbar = hyperlinkToolbarFactory(this.getStaticParams()); + this.updateHyperlinkToolbar = () => { + if (!this.hyperlinkToolbarState) { + throw new Error("Attempting to update uninitialized hyperlink toolbar"); + } + + updateHyperlinkToolbar(this.hyperlinkToolbarState); + }; this.startMenuUpdateTimer = () => { this.menuUpdateTimer = setTimeout(() => { @@ -56,7 +66,10 @@ class HyperlinkToolbarView { return false; }; - this.editor.view.dom.addEventListener("mouseover", this.mouseOverHandler); + this.editor._tiptapEditor.view.dom.addEventListener( + "mouseover", + this.mouseOverHandler + ); document.addEventListener("click", this.clickHandler, true); document.addEventListener("scroll", this.scrollHandler); } @@ -76,14 +89,16 @@ class HyperlinkToolbarView { // mouseHoveredHyperlinkMarkRange. const hoveredHyperlinkElement = event.target; const posInHoveredHyperlinkMark = - this.editor.view.posAtDOM(hoveredHyperlinkElement, 0) + 1; - const resolvedPosInHoveredHyperlinkMark = this.editor.state.doc.resolve( - posInHoveredHyperlinkMark - ); + this.editor._tiptapEditor.view.posAtDOM(hoveredHyperlinkElement, 0) + 1; + const resolvedPosInHoveredHyperlinkMark = + this.editor._tiptapEditor.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.editor._tiptapEditor.schema.mark("link").type.name + ) { this.mouseHoveredHyperlinkMark = mark; this.mouseHoveredHyperlinkMarkRange = getMarkRange( @@ -103,31 +118,80 @@ class HyperlinkToolbarView { }; clickHandler = (event: MouseEvent) => { + const editorWrapper = this.editor._tiptapEditor.view.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.relatedTarget as Node) || + editorWrapper.contains(event.relatedTarget as Node) + ) ) { - this.hyperlinkToolbar.hide(); + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.show = false; + this.updateHyperlinkToolbar(); + } } }; scrollHandler = () => { if (this.hyperlinkMark !== undefined) { - this.hyperlinkToolbar.render(this.getDynamicParams(), false); + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.referencePos = posToDOMRect( + this.editor._tiptapEditor.view, + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ); + this.updateHyperlinkToolbar(); + } } }; + editHyperlink(url: string, text: string) { + const tr = this.editor._tiptapEditor.view.state.tr.insertText( + text, + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ); + tr.addMark( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.from + text.length, + this.editor._tiptapEditor.schema.mark("link", { href: url }) + ); + this.editor._tiptapEditor.view.dispatch(tr); + this.editor._tiptapEditor.view.focus(); + + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.show = false; + this.updateHyperlinkToolbar(); + } + } + + deleteHyperlink() { + this.editor._tiptapEditor.view.dispatch( + this.editor._tiptapEditor.view.state.tr + .removeMark( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to, + this.hyperlinkMark!.type + ) + .setMeta("preventAutolink", true) + ); + this.editor._tiptapEditor.view.focus(); + + if (this.hyperlinkToolbarState?.show) { + this.hyperlinkToolbarState.show = false; + this.updateHyperlinkToolbar(); + } + } + update() { - if (!this.editor.view.hasFocus()) { + if (!this.editor._tiptapEditor.view.hasFocus()) { return; } @@ -144,15 +208,19 @@ 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.editor._tiptapEditor.state.selection.empty) { + const marksAtPos = + this.editor._tiptapEditor.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.editor._tiptapEditor.schema.mark("link").type.name + ) { this.keyboardHoveredHyperlinkMark = mark; this.keyboardHoveredHyperlinkMarkRange = getMarkRange( - this.editor.state.selection.$from, + this.editor._tiptapEditor.state.selection.$from, mark.type, mark.attrs ) || undefined; @@ -174,116 +242,73 @@ 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 + if (!this.hyperlinkToolbarState) { + this.hyperlinkToolbarState = { + show: true, + referencePos: posToDOMRect( + this.editor._tiptapEditor.view, + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ), + url: this.hyperlinkMark!.attrs.href, + text: this.editor._tiptapEditor.view.state.doc.textBetween( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ), + editHyperlink: this.editHyperlink, + deleteHyperlink: this.deleteHyperlink, + toolbarMouseEnter: this.stopMenuUpdateTimer, + toolbarMouseLeave: this.startMenuUpdateTimer, + }; + } else { + this.hyperlinkToolbarState.show = true; + this.hyperlinkToolbarState.referencePos = posToDOMRect( + this.editor._tiptapEditor.view, + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to ); - - return; + this.hyperlinkToolbarState.url = this.hyperlinkMark!.attrs.href; + this.hyperlinkToolbarState.text = + this.editor._tiptapEditor.view.state.doc.textBetween( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ); } - - // Updates menu. - this.hyperlinkToolbar.render(this.getDynamicParams(), false); + 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( + this.editor._tiptapEditor.view.dom.removeEventListener( "mouseover", this.mouseOverHandler ); document.removeEventListener("scroll", this.scrollHandler); } - - 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(); - }, - 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(); - }, - }; - } - - getDynamicParams(): HyperlinkToolbarDynamicParams { - return { - url: this.hyperlinkMark!.attrs.href, - text: this.editor.view.state.doc.textBetween( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ), - referenceRect: posToDOMRect( - this.editor.view, - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ), - }; - } } -export const createHyperlinkToolbarPlugin = ( - editor: Editor, - options: HyperlinkToolbarPluginProps +export const createHyperlinkToolbar = ( + editor: BlockNoteEditor, + updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void ) => { - return new Plugin({ - key: PLUGIN_KEY, - view: () => - new HyperlinkToolbarView({ - editor: editor, - hyperlinkToolbarFactory: options.hyperlinkToolbarFactory, - }), - }); + editor._tiptapEditor.registerPlugin( + new Plugin({ + key: new PluginKey("HyperlinkToolbarPlugin"), + view: () => new HyperlinkToolbarView(editor, updateHyperlinkToolbar), + }) + ); }; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts b/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts index a8f2d9c3f4..086650db91 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts @@ -1,52 +1,52 @@ -import { Extension } from "@tiptap/core"; -import { PluginKey } from "prosemirror-state"; -import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { createSuggestionPlugin } from "../../shared/plugins/suggestion/SuggestionPlugin"; -import { BlockSchema } from "../Blocks/api/blockTypes"; -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; - -export type SlashMenuOptions = { - editor: BlockNoteEditor | undefined; - commands: BaseSlashMenuItem[] | undefined; - onUpdate: any; //SuggestionsMenuFactory | undefined; -}; - -export const SlashMenuPluginKey = new PluginKey("suggestions-slash-commands"); - -export const createSlashMenuExtension = () => - Extension.create>({ - name: "slash-command", - - addOptions() { - return { - editor: undefined, - commands: undefined, - onUpdate: undefined, - }; - }, - - addProseMirrorPlugins() { - if (!this.options.onUpdate || !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: "/", - onUpdate: this.options.onUpdate!, - items: (query) => { - return commands.filter((cmd: BaseSlashMenuItem) => - cmd.match(query) - ); - }, - onSelectItem: ({ item, editor }) => { - item.execute(editor); - }, - }), - ]; - }, - }); +// import { Extension } from "@tiptap/core"; +// import { PluginKey } from "prosemirror-state"; +// import { BlockNoteEditor } from "../../BlockNoteEditor"; +// import { createSuggestionPlugin } from "../../shared/plugins/suggestion/SuggestionPlugin"; +// import { BlockSchema } from "../Blocks/api/blockTypes"; +// import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; +// +// export type SlashMenuOptions = { +// editor: BlockNoteEditor | undefined; +// commands: BaseSlashMenuItem[] | undefined; +// onUpdate: any; //SuggestionsMenuFactory | undefined; +// }; +// +// export const SlashMenuPluginKey = new PluginKey("suggestions-slash-commands"); +// +// export const createSlashMenuExtension = () => +// Extension.create>({ +// name: "slash-command", +// +// addOptions() { +// return { +// editor: undefined, +// commands: undefined, +// onUpdate: undefined, +// }; +// }, +// +// addProseMirrorPlugins() { +// if (!this.options.onUpdate || !this.options.commands) { +// throw new Error("required args not defined for SlashMenuExtension"); +// } +// +// const commands = this.options.commands; +// +// return [ +// createSuggestionPlugin, BSchema>( +// "SlashMenuPlugin", +// "/", +// this.options.editor!, +// this.options.onUpdate!, +// ({ item, editor }) => { +// item.execute(editor); +// }, +// (query) => { +// return commands.filter((cmd: BaseSlashMenuItem) => +// cmd.match(query) +// ); +// } +// ), +// ]; +// }, +// }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 551885e440..0a71b8ada7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,18 +1,20 @@ export * from "./BlockNoteEditor"; export * from "./BlockNoteExtensions"; + export * from "./extensions/Blocks/api/block"; export * from "./extensions/Blocks/api/blockTypes"; export * from "./extensions/Blocks/api/defaultBlocks"; export * from "./extensions/Blocks/api/inlineContentTypes"; export * from "./extensions/Blocks/api/serialization"; + +export * from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; +export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; +export * from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; +export * from "./shared/plugins/suggestion/SuggestionPlugin"; +export * from "./shared/EditorElement"; + export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; -export * from "./extensions/DraggableBlocks/BlockSideMenuFactoryTypes"; -export * from "./extensions/FormattingToolbar/FormattingToolbarFactoryTypes"; -export { createFormattingToolbarPlugin } from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; -export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes"; + export * from "./extensions/SlashMenu/BaseSlashMenuItem"; export { defaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; -export * from "./shared/EditorElement"; export type { SuggestionItem } from "./shared/plugins/suggestion/SuggestionItem"; -export { createSuggestionPlugin } from "./shared/plugins/suggestion/SuggestionPlugin"; -export * from "./shared/plugins/suggestion/SuggestionsMenuFactoryTypes"; diff --git a/packages/core/src/shared/EditorElement.ts b/packages/core/src/shared/EditorElement.ts index d085d32f0c..a3f6599f87 100644 --- a/packages/core/src/shared/EditorElement.ts +++ b/packages/core/src/shared/EditorElement.ts @@ -1,16 +1,4 @@ -export type RequiredStaticParams = Record; -export type RequiredDynamicParams = Record & { - referenceRect: DOMRect; +export type BaseUiElementState = { + show: boolean; + referencePos: DOMRect; }; - -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/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 6f46aa9114..18a8c09a5b 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -1,93 +1,23 @@ -import { Editor, Range } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; import { 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; - - onUpdate: any; - - /** - * 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, +import { BaseUiElementState } from "../../EditorElement"; +import { + BaseSlashMenuItem, + defaultSlashMenuItems, +} from "../../../extensions/SlashMenu"; +import { DefaultBlockSchema } from "../../../extensions/Blocks/api/defaultBlocks"; +import { ReactSlashMenuItem } from "@blocknote/react"; + +export type SuggestionsMenuState = + BaseUiElementState & { + items: T[]; + itemCallback: (item: T) => void; + keyboardHoveredItemIndex: number; }; -} - -type SuggestionPluginViewOptions< - T extends SuggestionItem, - BSchema extends BlockSchema -> = { - editor: BlockNoteEditor; - pluginKey: PluginKey; - onSelectItem: (props: { item: T; editor: BlockNoteEditor }) => void; - onUpdate: any; -}; class SuggestionPluginView< T extends SuggestionItem, @@ -96,22 +26,35 @@ class SuggestionPluginView< editor: BlockNoteEditor; pluginKey: PluginKey; - onUpdate: any; + private suggestionsMenuState?: SuggestionsMenuState; + public updateSuggestionsMenu: () => void; pluginState: SuggestionPluginState; itemCallback: (item: T) => void; - constructor({ - editor, - pluginKey, - onSelectItem: selectItemCallback = () => {}, - onUpdate, - }: SuggestionPluginViewOptions) { + constructor( + editor: BlockNoteEditor, + pluginKey: PluginKey, + onSelectItem: (props: { + item: T; + editor: BlockNoteEditor; + }) => void = () => {}, + updateSuggestionsMenu: ( + suggestionsMenuState: SuggestionsMenuState + ) => void = () => {} + ) { this.editor = editor; this.pluginKey = pluginKey; - this.onUpdate = onUpdate; this.pluginState = getDefaultPluginState(); + this.updateSuggestionsMenu = () => { + if (!this.suggestionsMenuState) { + throw new Error("Attempting to update uninitialized suggestions menu"); + } + + updateSuggestionsMenu(this.suggestionsMenuState); + }; + this.itemCallback = (item: T) => { editor._tiptapEditor .chain() @@ -124,7 +67,7 @@ class SuggestionPluginView< }) .run(); - selectItemCallback({ + onSelectItem({ item: item, editor: editor, }); @@ -136,8 +79,13 @@ class SuggestionPluginView< } handleScroll = () => { - if (this.pluginKey.getState(this.editor._tiptapEditor.state).active) { - // this.suggestionsMenu.render(this.getDynamicParams(), false); + if (this.suggestionsMenuState?.show) { + const decorationNode = document.querySelector( + `[data-decoration-id="${this.pluginState.decorationId}"]` + ); + this.suggestionsMenuState.referencePos = + decorationNode!.getBoundingClientRect(); + this.updateSuggestionsMenu(); } }; @@ -160,51 +108,71 @@ class SuggestionPluginView< this.pluginState = stopped ? prev : next; if (stopped || !this.editor.isEditable) { - this.params.active = false; - this.onUpdate(this.params); - // this.suggestionsMenu.hide(); - // Listener stops focus moving to the menu on click. - // this.suggestionsMenu.element!.removeEventListener("mousedown", (event) => - // event.preventDefault() - // ); + this.suggestionsMenuState!.show = false; + this.updateSuggestionsMenu(); } + const decorationNode = document.querySelector( + `[data-decoration-id="${this.pluginState.decorationId}"]` + ); + if (changed) { - this.updateActiveParams(); - this.onUpdate(this.params); - // this.suggestionsMenu.render(this.getDynamicParams(), false); + this.suggestionsMenuState!.referencePos = + decorationNode!.getBoundingClientRect(); + this.suggestionsMenuState!.items = this.pluginState.items; + this.suggestionsMenuState!.keyboardHoveredItemIndex = + this.pluginState.keyboardHoveredItemIndex!; + this.updateSuggestionsMenu(); } if (started && this.editor.isEditable) { - // this.suggestionsMenu.render(this.getDynamicParams(), true); - this.updateActiveParams(); - this.onUpdate(this.params); - // Listener stops focus moving to the menu on click. - // this.suggestionsMenu.element!.addEventListener("mousedown", (event) => - // event.preventDefault() - // ); + this.suggestionsMenuState = { + show: true, + referencePos: decorationNode!.getBoundingClientRect(), + items: this.pluginState.items, + itemCallback: (item: T) => this.itemCallback(item), + keyboardHoveredItemIndex: this.pluginState.keyboardHoveredItemIndex!, + }; + this.updateSuggestionsMenu(); } } destroy() { document.removeEventListener("scroll", this.handleScroll); } +} + +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; +}; - private params: any = { +function getDefaultPluginState< + T extends SuggestionItem +>(): SuggestionPluginState { + return { active: false, - itemCallback: (item: T) => this.itemCallback(item), + triggerCharacter: undefined, + queryStartPos: undefined, + items: [] as T[], + keyboardHoveredItemIndex: undefined, + notFoundCount: 0, + decorationId: undefined, }; - - updateActiveParams(): any { - const decorationNode = document.querySelector( - `[data-decoration-id="${this.pluginState.decorationId}"]` - ); - this.params.active = true; - this.params.items = this.pluginState.items; - this.params.keyboardHoveredItemIndex = - this.pluginState.keyboardHoveredItemIndex!; - this.params.referenceRect = decorationNode!.getBoundingClientRect(); - } } /** @@ -216,26 +184,30 @@ 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< T extends SuggestionItem, BSchema extends BlockSchema ->({ - pluginKey, - editor, - defaultTriggerCharacter, - onUpdate, - onSelectItem: selectItemCallback = () => {}, - items = () => [], -}: SuggestionPluginOptions) { +>( + pluginName: string, + defaultTriggerCharacter: string, + editor: BlockNoteEditor, + updateSuggestionsMenu: ( + suggestionsMenuState: SuggestionsMenuState + ) => void, + onSelectItem: (props: { + item: T; + editor: BlockNoteEditor; + }) => void = () => {}, + items: (query: string) => T[] = () => [] +) { // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); } + const pluginKey = new PluginKey(pluginName); + const deactivate = (view: EditorView) => { view.dispatch(view.state.tr.setMeta(pluginKey, { deactivate: true })); }; @@ -245,18 +217,15 @@ export function createSuggestionPlugin< key: pluginKey, view: (view: EditorView) => - new SuggestionPluginView({ - editor: editor, - pluginKey: pluginKey, - onSelectItem: (props: { - item: T; - editor: BlockNoteEditor; - }) => { + new SuggestionPluginView( + editor, + pluginKey, + (props: { item: T; editor: BlockNoteEditor }) => { deactivate(view); - selectItemCallback(props); + onSelectItem(props); }, - onUpdate, - }), + updateSuggestionsMenu + ), state: { // Initialize the plugin's internal state. @@ -418,7 +387,7 @@ export function createSuggestionPlugin< }) .run(); - selectItemCallback({ + onSelectItem({ item: items[keyboardHoveredItemIndex], editor: editor, }); @@ -484,3 +453,27 @@ export function createSuggestionPlugin< }, }); } + +export const createSlashMenu = ( + editor: BlockNoteEditor, + updateSlashMenu: ( + slashMenuState: SuggestionsMenuState> + ) => void +) => { + editor._tiptapEditor.registerPlugin( + createSuggestionPlugin< + BaseSlashMenuItem, + DefaultBlockSchema + >( + "SlashMenuPlugin", + "/", + editor, + (slashMenuState) => updateSlashMenu(slashMenuState), + ({ item, editor }) => item.execute(editor), + (query) => + defaultSlashMenuItems.filter( + (cmd: BaseSlashMenuItem) => cmd.match(query) + ) + ) + ); +}; 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 faa59326c3..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; -}; - -export type SuggestionsMenuDynamicParams = { - items: T[]; - keyboardHoveredItemIndex: number; - - referenceRect: DOMRect; -}; - -export type SuggestionsMenu = EditorElement< - SuggestionsMenuDynamicParams ->; -export type SuggestionsMenuFactory = ElementFactory< - SuggestionsMenuStaticParams, - SuggestionsMenuDynamicParams ->; diff --git a/packages/react/src/BlockNoteTheme.ts b/packages/react/src/BlockNoteTheme.ts index 2d941f3a38..e840718141 100644 --- a/packages/react/src/BlockNoteTheme.ts +++ b/packages/react/src/BlockNoteTheme.ts @@ -268,6 +268,7 @@ export const getBlockNoteTheme = ( SlashMenu: { styles: () => ({ root: { + position: "relative", ".mantine-Menu-item": { // Icon ".mantine-Menu-itemIcon": { diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index 666bd29e8a..ad482fa659 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -1,21 +1,22 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { EditorContent } from "@tiptap/react"; import { FormattingToolbar } from "./FormattingToolbar/components/FormattingToolbar"; -import { SlashMenu2 } from "./SlashMenu/components/SlashMenu"; -// import { BlockNoteTheme } from "./BlockNoteTheme"; -// import { MantineProvider } from "@mantine/core"; +import { SlashMenu } from "./SlashMenu/components/SlashMenu"; +import { HyperlinkToolbar } from "./HyperlinkToolbar/components/HyperlinkToolbar"; +import { SideMenu } from "./BlockSideMenu/components/BlockSideMenu"; +import { getBlockNoteTheme } from "./BlockNoteTheme"; +import { MantineProvider } from "@mantine/core"; export function BlockNoteView(props: { - editor: BlockNoteEditor | null; + editor: BlockNoteEditor; }) { return ( - // TODO: Should we wrap editor in MantineProvider? Otherwise we have to duplicate color hex values. - // - <> + - - - // + + + + ); } diff --git a/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx b/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx index 6d8b608a5a..072df14e76 100644 --- a/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx +++ b/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx @@ -1,49 +1,49 @@ -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, - }, - }, - ], - }, - }); -}; +// import { FC } from "react"; +// import { +// BlockSchema, +// BlockSideMenuDynamicParams, +// BlockSideMenuStaticParams, +// } from "@blocknote/core"; +// import { MantineThemeOverride } from "@mantine/core"; +// import { ReactElementFactory } from "../ElementFactory/components/ReactElementFactory"; +// import { SideMenu 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 index 1f5555bab6..b6177ca826 100644 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx @@ -1,24 +1,20 @@ -import { Block, BlockNoteEditor, BlockSchema } from "@blocknote/core"; -import { ActionIcon, Group, Menu } from "@mantine/core"; -import { FC, useEffect, useRef, useState } from "react"; +import { + BlockNoteEditor, + BlockSchema, + createSideMenu, + SideMenuState, +} from "@blocknote/core"; +import { ActionIcon, Menu } from "@mantine/core"; +import { useCallback, 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"; +import Tippy from "@tippyjs/react"; -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 +export const BlockSideMenuOld = ( + props: Omit, "referencePos"> & { + editor: BlockNoteEditor; + } ) => { const [dragHandleMenuOpened, setDragHandleMenuOpened] = useState(false); @@ -45,10 +41,10 @@ export const BlockSideMenu = ( props.unfreezeMenu(); }; - const DragHandleMenu = props.dragHandleMenu || DefaultDragHandleMenu; + const DragHandleMenu = DefaultDragHandleMenu; return ( - +
{ ( closeMenu={closeMenu} /> - +
+ ); +}; + +export const SideMenu = (props: { + editor: BlockNoteEditor; +}) => { + const [state, setState] = useState< + Omit, "referencePos"> | undefined + >(); + // Since we're using Tippy, we don't want to trigger re-renders when only the + // reference position changes. So we store it in a ref instead of state. + const referenceClientRect = useRef(); + + useEffect(() => { + createSideMenu(props.editor, ({ referencePos, ...state }) => { + setState(state); + referenceClientRect.current = referencePos; + }); + }, [props.editor]); + + const getReferenceClientRect = useCallback( + () => referenceClientRect.current!, + [referenceClientRect] + ); + + return ( + } + getReferenceClientRect={ + referenceClientRect.current && getReferenceClientRect + } + interactive={true} + visible={state?.show || false} + 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/FormattingToolbar/FormattingToolbarFactory.tsx b/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx index bb9c521fb3..40979fa233 100644 --- a/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx +++ b/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx @@ -1,28 +1,28 @@ -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", - }); -}; +// 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/FormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx index 21cd753de5..cf3606c324 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx @@ -1,13 +1,11 @@ import { BlockNoteEditor, BlockSchema, - createFormattingToolbarPlugin, + createFormattingToolbar, + FormattingToolbarState, } from "@blocknote/core"; -import { PluginKey } from "prosemirror-state"; -import { useEffect, useRef, useState } from "react"; -import { getBlockNoteTheme } from "../../BlockNoteTheme"; -import { EditorElementComponentWrapper } from "../../ElementFactory/components/EditorElementComponentWrapper"; +import { useCallback, useEffect, useRef, useState } from "react"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ColorStyleButton } from "./DefaultButtons/ColorStyleButton"; import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; @@ -18,6 +16,7 @@ import { import { TextAlignButton } from "./DefaultButtons/TextAlignButton"; import { ToggledStyleButton } from "./DefaultButtons/ToggledStyleButton"; import { BlockTypeDropdown } from "./DefaultDropdowns/BlockTypeDropdown"; +import Tippy from "@tippyjs/react"; export const FormattingToolbarOld = (props: { editor: BlockNoteEditor; @@ -48,58 +47,36 @@ export const FormattingToolbarOld = (props: { export const FormattingToolbar = (props: { editor: BlockNoteEditor; }) => { - const [params, setParams] = useState(); - const [isHidden, setIsHidden] = useState(true); + const [state, setState] = useState< + Omit | undefined + >(); + // Since we're using Tippy, we don't want to trigger re-renders when only the + // reference position changes. So we store it in a ref instead of state. + const referenceClientRect = useRef(); - const elementRef = useRef(null); useEffect(() => { - if (!elementRef.current || !props.editor) { - return; - } - - if (props.editor._tiptapEditor.isDestroyed) { - return; - } - - const pluginKey = new PluginKey("FormattingToolbarPlugin2"); - - const plugin = createFormattingToolbarPlugin({ - tiptapEditor: props.editor._tiptapEditor, - editor: props.editor, - formattingToolbarFactory: () => ({ - element: elementRef.current!, - render: (params, isHidden) => { - setParams(params); - setIsHidden(false); - }, - hide: () => { - setIsHidden(true); - }, - }), - pluginKey, + createFormattingToolbar(props.editor, ({ referencePos, ...state }) => { + setState(state); + referenceClientRect.current = referencePos; }); + }, [props.editor]); + + const getReferenceClientRect = useCallback( + () => referenceClientRect.current!, + [referenceClientRect] + ); - props.editor._tiptapEditor.registerPlugin(plugin); - return () => props.editor._tiptapEditor.unregisterPlugin(pluginKey); - }, [props.editor, elementRef.current]); - console.log("FormattingToolbar", params, isHidden); return ( -
- {elementRef.current && props.editor && ( - - )} -
+ } + getReferenceClientRect={ + referenceClientRect.current && getReferenceClientRect + } + interactive={true} + visible={state?.show || false} + animation={"fade"} + placement={"top-start"} + /> ); }; diff --git a/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx b/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx index 5bf7e0ad27..c335a19277 100644 --- a/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx +++ b/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx @@ -1,20 +1,20 @@ -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", - }); +// 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/HyperlinkToolbar.tsx index f2ce16b66b..635ca32f1b 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx @@ -1,8 +1,15 @@ -import { useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; +import { + BlockNoteEditor, + BlockSchema, + createHyperlinkToolbar, + HyperlinkToolbarState, +} from "@blocknote/core"; +import Tippy from "@tippyjs/react"; // import rootStyles from "../../../root.module.css"; export type HyperlinkToolbarProps = { @@ -16,7 +23,9 @@ export type HyperlinkToolbarProps = { * Main menu component for the hyperlink extension. * Renders a toolbar that appears on hyperlink hover. */ -export const HyperlinkToolbar = (props: HyperlinkToolbarProps) => { +export const HyperlinkToolbarOld = ( + props: Omit +) => { const [isEditing, setIsEditing] = useState(false); if (isEditing) { @@ -54,3 +63,41 @@ export const HyperlinkToolbar = (props: HyperlinkToolbarProps) => { ); }; + +export const HyperlinkToolbar = (props: { + editor: BlockNoteEditor; +}) => { + const [state, setState] = useState< + Omit | undefined + >(); + // Since we're using Tippy, we don't want to trigger re-renders when only the + // reference position changes. So we store it in a ref instead of state. + const referenceClientRect = useRef(); + + useEffect(() => { + createHyperlinkToolbar(props.editor, ({ referencePos, ...state }) => { + setState(state); + referenceClientRect.current = referencePos; + }); + }, [props.editor]); + + const getReferenceClientRect = useCallback( + () => referenceClientRect.current!, + [referenceClientRect] + ); + + return ( + } + getReferenceClientRect={ + referenceClientRect.current && getReferenceClientRect + } + interactive={true} + visible={state?.show || false} + animation={"fade"} + placement={"top-start"} + /> + ); +}; diff --git a/packages/react/src/SlashMenu/SlashMenuFactory.tsx b/packages/react/src/SlashMenu/SlashMenuFactory.tsx index 3eda458e7d..ff53d2f39e 100644 --- a/packages/react/src/SlashMenu/SlashMenuFactory.tsx +++ b/packages/react/src/SlashMenu/SlashMenuFactory.tsx @@ -1,22 +1,22 @@ -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", - }); +// 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/SlashMenu.tsx index 1782f8404a..4eee59d4cd 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -1,11 +1,16 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { Menu, createStyles } from "@mantine/core"; import * as _ from "lodash"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { SlashMenuItem } from "./SlashMenuItem"; - import Tippy from "@tippyjs/react"; +import { + createSuggestionPlugin, + DefaultBlockSchema, + SuggestionsMenuState, +} from "@blocknote/core"; +import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; export type SlashMenuProps = { items: ReactSlashMenuItem[]; @@ -13,8 +18,11 @@ export type SlashMenuProps = { itemCallback: (item: ReactSlashMenuItem) => void; }; -export function SlashMenu( - props: SlashMenuProps +export function SlashMenuOld( + props: Omit< + SuggestionsMenuState>, + "referencePos" + > ) { const { classes } = createStyles({ root: {} })(undefined, { name: "SlashMenu", @@ -67,105 +75,68 @@ export function SlashMenu( ); } -export const SlashMenu2 = (props: { +// TODO: This whole React/Base item design sucks with the new architecture. +const createSlashMenu = ( + editor: BlockNoteEditor, + updateSlashMenu: ( + slashMenuState: SuggestionsMenuState> + ) => void +) => { + editor._tiptapEditor.registerPlugin( + createSuggestionPlugin< + ReactSlashMenuItem, + DefaultBlockSchema + >( + "SlashMenuPlugin", + "/", + editor, + (slashMenuState) => updateSlashMenu(slashMenuState), + ({ item, editor }) => item.execute(editor), + (query) => + defaultReactSlashMenuItems.filter( + (cmd: ReactSlashMenuItem) => cmd.match(query) + ) + ) + ); +}; + +export const SlashMenu = (props: { editor: BlockNoteEditor; }) => { - const [params, setParams] = useState(); + const [state, setState] = useState< + | Omit< + SuggestionsMenuState>, + "referencePos" + > + | undefined + >(); + // Since we're using Tippy, we don't want to trigger re-renders when only the + // reference position changes. So we store it in a ref instead of state. + const referenceClientRect = useRef(); useEffect(() => { - if (!props.editor) { - return; - } - const cb = (params: any) => { - setParams({ ...params }); - }; - props.editor.on("slashMenuUpdate", cb); - return () => { - props.editor.off("slashMenuUpdate", cb); - }; + createSlashMenu(props.editor as any, ({ referencePos, ...state }) => { + setState(state); + referenceClientRect.current = referencePos; + }); }, [props.editor]); - // This commented out part can be removed, - // but it shows the original way according to tiptap examples where they make the components instantiate - // the plugin. We now do this in BlockNoteEditor by default, making the code in the component more concise - - // useEffect(() => { - // if (!elementRef.current || !props.editor) { - // return; - // } - - // if (props.editor._tiptapEditor.isDestroyed) { - // return; - // } - - // const pluginKey = new PluginKey("SlashMenu2"); - - // const plugin = createSuggestionPlugin, BSchema>({ - // pluginKey, - // editor: props.editor!, - // defaultTriggerCharacter: "/", - // suggestionsMenuFactory: () => ({ - // element: elementRef.current!, - // render: (params, isHidden) => { - // console.log("params", params.referenceRect); - // setParams(params); - // setIsHidden(false); - // }, - // hide: () => { - // setIsHidden(true); - // }, - // }), - // items: (query) => { - // return defaultSlashMenuItems.filter((cmd: BaseSlashMenuItem) => - // cmd.match(query) - // ); - // }, - // onSelectItem: ({ item, editor }) => { - // item.execute(editor); - // }, - // }); - - // props.editor._tiptapEditor.registerPlugin(plugin); - // return () => props.editor._tiptapEditor.unregisterPlugin(pluginKey); - // }, [props.editor, elementRef.current]); - const getReferenceClientRect = useCallback( - () => params.referenceRect, - [params] + () => referenceClientRect.current!, + [referenceClientRect] ); - console.log("slashmenu render"); - if (!props.editor || !params) { - return null; - } return ( -
{ - // prevent blur - e.preventDefault(); - e.stopPropagation(); - }}> - } - getReferenceClientRect={getReferenceClientRect} - interactive={true} - visible={params.active} - popperOptions={{ - // if the window height is too small, prevent the menu from causing - // the body to be scrollable - modifiers: [ - { - name: "preventOverflow", - options: { - altAxis: true, - }, - }, - ], - }} - animation="fade" - placement="bottom-start"> -
-
-
+ } + getReferenceClientRect={ + referenceClientRect.current && getReferenceClientRect + } + interactive={true} + visible={state?.show || false} + animation={"fade"} + placement={"bottom-start"} + /> ); }; diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index e11f9a22c7..12a5174762 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -24,6 +24,53 @@ function useForceUpdate() { return () => setValue((value) => value + 1); } +function initEditor( + options: Partial< + BlockNoteEditorOptions & { + customElements: CustomElements; + } + > = {} +) { + // 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, + }; + + if (newOptions.customElements && newOptions.uiFactories) { + console.warn( + "BlockNote editor initialized with both `customElements` and `uiFactories` options, prioritizing `uiFactories`." + ); + } + + let uiFactories = { + formattingToolbarFactory: undefined, + hyperlinkToolbarFactory: createReactHyperlinkToolbarFactory( + getBlockNoteTheme(newOptions.theme === "dark") + ), + slashMenuFactory: undefined, + 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> + ); + + return instance; +} + /** * Main hook for importing a BlockNote editor into a React project */ @@ -35,66 +82,68 @@ export const useBlockNote = ( > = {}, 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, - }; - - if (newOptions.customElements && newOptions.uiFactories) { - console.warn( - "BlockNote editor initialized with both `customElements` and `uiFactories` options, prioritizing `uiFactories`." - ); - } - - let uiFactories = { - formattingToolbarFactory: undefined, - hyperlinkToolbarFactory: createReactHyperlinkToolbarFactory( - getBlockNoteTheme(newOptions.theme === "dark") - ), - slashMenuFactory: undefined, - 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(); - // } - // }); - // }); - // }); + // const [editor, setEditor] = useState>( + // initEditor(options) + // ); + // const forceUpdate = useForceUpdate(); - return () => { - instance._tiptapEditor.destroy(); - isMounted = false; - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, deps); + // 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, + // }; + // + // if (newOptions.customElements && newOptions.uiFactories) { + // console.warn( + // "BlockNote editor initialized with both `customElements` and `uiFactories` options, prioritizing `uiFactories`." + // ); + // } + // + // let uiFactories = { + // formattingToolbarFactory: undefined, + // hyperlinkToolbarFactory: createReactHyperlinkToolbarFactory( + // getBlockNoteTheme(newOptions.theme === "dark") + // ), + // slashMenuFactory: undefined, + // 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; + return initEditor(options); }; From 784bdc0966ebb07f59886ddeb5a87b21ceacd0ce Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 14:49:41 +0200 Subject: [PATCH 04/42] Exported plugin keys & cleaned up slash menu plugin --- examples/vanilla/src/ui/addSlashMenu.ts | 56 +++++++++++-------- .../DraggableBlocks/DraggableBlocksPlugin.ts | 7 ++- .../FormattingToolbarPlugin.ts | 5 +- .../HyperlinkToolbarPlugin.ts | 5 +- .../Placeholder/PlaceholderExtension.ts | 4 +- .../extensions/SlashMenu/SlashMenuPlugin.ts | 34 +++++++++++ .../core/src/extensions/SlashMenu/index.ts | 4 +- packages/core/src/index.ts | 1 + .../plugins/suggestion/SuggestionPlugin.ts | 34 +---------- .../src/SlashMenu/components/SlashMenu.tsx | 48 +++++----------- 10 files changed, 97 insertions(+), 101 deletions(-) create mode 100644 packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts diff --git a/examples/vanilla/src/ui/addSlashMenu.ts b/examples/vanilla/src/ui/addSlashMenu.ts index 62b837b189..cdf9b33014 100644 --- a/examples/vanilla/src/ui/addSlashMenu.ts +++ b/examples/vanilla/src/ui/addSlashMenu.ts @@ -2,6 +2,7 @@ import { BaseSlashMenuItem, BlockNoteEditor, createSlashMenu, + defaultSlashMenuItems, DefaultBlockSchema, } from "@blocknote/core"; import { createButton } from "./util"; @@ -29,32 +30,39 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { return domItems; } - createSlashMenu(editor, (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"; + createSlashMenu>( + editor, + (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); - } + document.getElementById("root")!.appendChild(element); + } - if (slashMenuState.show) { - updateItems( - slashMenuState.items, - slashMenuState.itemCallback, - slashMenuState.keyboardHoveredItemIndex - ); + if (slashMenuState.show) { + updateItems( + slashMenuState.items, + slashMenuState.itemCallback, + slashMenuState.keyboardHoveredItemIndex + ); - element.style.display = "block"; + 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"; - } - }); + element.style.top = slashMenuState.referencePos.top + "px"; + element.style.left = + slashMenuState.referencePos.x - element.offsetWidth + "px"; + } else { + element.style.display = "none"; + } + }, + (query) => + defaultSlashMenuItems.filter( + (cmd: BaseSlashMenuItem) => cmd.match(query) + ) + ); }; diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index b2bb2523a0..901aaf7039 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -4,11 +4,11 @@ import * as pv from "prosemirror-view"; import { EditorView } from "prosemirror-view"; import styles from "../../editor.module.css"; import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; -import { SlashMenuPluginKey } from "../SlashMenu/SlashMenuExtension"; import { MultipleNodeSelection } from "./MultipleNodeSelection"; import { BlockNoteEditor } from "../../BlockNoteEditor"; import { Block, BlockSchema } from "../Blocks/api/blockTypes"; import { BaseUiElementState } from "../../shared/EditorElement"; +import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; const serializeForClipboard = (pv as any).__serializeForClipboard; // code based on https://github.com/ueberdosis/tiptap/issues/323#issuecomment-506637799 @@ -599,7 +599,7 @@ export class BlockMenuView { this.editor._tiptapEditor.view.dispatch( this.editor._tiptapEditor.view.state.tr .scrollIntoView() - .setMeta(SlashMenuPluginKey, { + .setMeta(slashMenuPluginKey, { // TODO import suggestion plugin key activate: true, type: "drag", @@ -608,13 +608,14 @@ export class BlockMenuView { } } +export const sideMenuPluginKey = new PluginKey("SideMenuPlugin"); export const createSideMenu = ( editor: BlockNoteEditor, updateSideMenu: (sideMenuState: SideMenuState) => void ) => { editor._tiptapEditor.registerPlugin( new Plugin({ - key: new PluginKey("DraggableBlocksPlugin"), + key: sideMenuPluginKey, view: () => new BlockMenuView(editor, updateSideMenu), }) ); diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index e35d092d58..70ee3cb56f 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -223,6 +223,9 @@ export class FormattingToolbarView { } } +export const formattingToolbarPluginKey = new PluginKey( + "FormattingToolbarPlugin" +); export const createFormattingToolbar = ( editor: BlockNoteEditor, updateFormattingToolbar: ( @@ -231,7 +234,7 @@ export const createFormattingToolbar = ( ) => { editor._tiptapEditor.registerPlugin( new Plugin({ - key: new PluginKey("FormattingToolbarPlugin"), + key: formattingToolbarPluginKey, view: (view) => new FormattingToolbarView(editor, view, updateFormattingToolbar), }) diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index 8431a73a86..a50b2ab363 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -301,13 +301,16 @@ class HyperlinkToolbarView { } } +export const hyperlinkToolbarPluginKey = new PluginKey( + "HyperlinkToolbarPlugin" +); export const createHyperlinkToolbar = ( editor: BlockNoteEditor, updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void ) => { editor._tiptapEditor.registerPlugin( new Plugin({ - key: new PluginKey("HyperlinkToolbarPlugin"), + key: hyperlinkToolbarPluginKey, view: () => new HyperlinkToolbarView(editor, updateHyperlinkToolbar), }) ); 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/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts new file mode 100644 index 0000000000..5c5fffc2a4 --- /dev/null +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -0,0 +1,34 @@ +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; +import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; +import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { + createSuggestionPlugin, + SuggestionsMenuState, +} from "../../shared/plugins/suggestion/SuggestionPlugin"; +import { PluginKey } from "prosemirror-state"; + +export const slashMenuPluginKey = new PluginKey("SlashMenuPlugin"); +export const createSlashMenu = < + SlashMenuItem extends BaseSlashMenuItem +>( + editor: BlockNoteEditor, + updateSlashMenu: ( + slashMenuState: SuggestionsMenuState + ) => void, + items: (query: string) => SlashMenuItem[] +) => { + editor._tiptapEditor.registerPlugin( + createSuggestionPlugin( + slashMenuPluginKey, + "/", + editor, + (slashMenuState) => updateSlashMenu(slashMenuState), + ({ item, editor }) => item.execute(editor), + items + // (query) => + // defaultSlashMenuItems.filter( + // (cmd: SlashMenuItem) => cmd.match(query) + // ) + ) + ); +}; diff --git a/packages/core/src/extensions/SlashMenu/index.ts b/packages/core/src/extensions/SlashMenu/index.ts index 3fae65095c..c7de75fc48 100644 --- a/packages/core/src/extensions/SlashMenu/index.ts +++ b/packages/core/src/extensions/SlashMenu/index.ts @@ -1,5 +1,5 @@ import { defaultSlashMenuItems } from "./defaultSlashMenuItems"; -import { createSlashMenuExtension } from "./SlashMenuExtension"; +// import { createSlashMenuExtension } from "./SlashMenuExtension"; import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; -export { defaultSlashMenuItems, BaseSlashMenuItem, createSlashMenuExtension }; +export { defaultSlashMenuItems, BaseSlashMenuItem }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 0a71b8ada7..4f63f83581 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -11,6 +11,7 @@ export * from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; export * from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; export * from "./shared/plugins/suggestion/SuggestionPlugin"; +export * from "./extensions/SlashMenu/SlashMenuPlugin"; export * from "./shared/EditorElement"; export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 18a8c09a5b..7563dddbf0 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -5,12 +5,6 @@ import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; import { SuggestionItem } from "./SuggestionItem"; import { BaseUiElementState } from "../../EditorElement"; -import { - BaseSlashMenuItem, - defaultSlashMenuItems, -} from "../../../extensions/SlashMenu"; -import { DefaultBlockSchema } from "../../../extensions/Blocks/api/defaultBlocks"; -import { ReactSlashMenuItem } from "@blocknote/react"; export type SuggestionsMenuState = BaseUiElementState & { @@ -189,7 +183,7 @@ export function createSuggestionPlugin< T extends SuggestionItem, BSchema extends BlockSchema >( - pluginName: string, + pluginKey: PluginKey, defaultTriggerCharacter: string, editor: BlockNoteEditor, updateSuggestionsMenu: ( @@ -206,8 +200,6 @@ export function createSuggestionPlugin< throw new Error("'char' should be a single character"); } - const pluginKey = new PluginKey(pluginName); - const deactivate = (view: EditorView) => { view.dispatch(view.state.tr.setMeta(pluginKey, { deactivate: true })); }; @@ -453,27 +445,3 @@ export function createSuggestionPlugin< }, }); } - -export const createSlashMenu = ( - editor: BlockNoteEditor, - updateSlashMenu: ( - slashMenuState: SuggestionsMenuState> - ) => void -) => { - editor._tiptapEditor.registerPlugin( - createSuggestionPlugin< - BaseSlashMenuItem, - DefaultBlockSchema - >( - "SlashMenuPlugin", - "/", - editor, - (slashMenuState) => updateSlashMenu(slashMenuState), - ({ item, editor }) => item.execute(editor), - (query) => - defaultSlashMenuItems.filter( - (cmd: BaseSlashMenuItem) => cmd.match(query) - ) - ) - ); -}; diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index 4eee59d4cd..5836a9cbe6 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -1,15 +1,11 @@ -import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { BlockNoteEditor, BlockSchema, createSlashMenu } from "@blocknote/core"; import { Menu, createStyles } from "@mantine/core"; import * as _ from "lodash"; import { useCallback, useEffect, useRef, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { SlashMenuItem } from "./SlashMenuItem"; import Tippy from "@tippyjs/react"; -import { - createSuggestionPlugin, - DefaultBlockSchema, - SuggestionsMenuState, -} from "@blocknote/core"; +import { DefaultBlockSchema, SuggestionsMenuState } from "@blocknote/core"; import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; export type SlashMenuProps = { @@ -75,31 +71,6 @@ export function SlashMenuOld( ); } -// TODO: This whole React/Base item design sucks with the new architecture. -const createSlashMenu = ( - editor: BlockNoteEditor, - updateSlashMenu: ( - slashMenuState: SuggestionsMenuState> - ) => void -) => { - editor._tiptapEditor.registerPlugin( - createSuggestionPlugin< - ReactSlashMenuItem, - DefaultBlockSchema - >( - "SlashMenuPlugin", - "/", - editor, - (slashMenuState) => updateSlashMenu(slashMenuState), - ({ item, editor }) => item.execute(editor), - (query) => - defaultReactSlashMenuItems.filter( - (cmd: ReactSlashMenuItem) => cmd.match(query) - ) - ) - ); -}; - export const SlashMenu = (props: { editor: BlockNoteEditor; }) => { @@ -115,10 +86,17 @@ export const SlashMenu = (props: { const referenceClientRect = useRef(); useEffect(() => { - createSlashMenu(props.editor as any, ({ referencePos, ...state }) => { - setState(state); - referenceClientRect.current = referencePos; - }); + createSlashMenu>( + props.editor as any, + ({ referencePos, ...state }) => { + setState(state); + referenceClientRect.current = referencePos; + }, + (query) => + defaultReactSlashMenuItems.filter( + (cmd: ReactSlashMenuItem) => cmd.match(query) + ) + ); }, [props.editor]); const getReferenceClientRect = useCallback( From 8237395bf3809127690651451d8a6b64c2bea895 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 14:49:57 +0200 Subject: [PATCH 05/42] Removed redundant type --- .../src/HyperlinkToolbar/components/HyperlinkToolbar.tsx | 7 ------- 1 file changed, 7 deletions(-) diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx index 635ca32f1b..1dbf618c13 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx @@ -12,13 +12,6 @@ import { import Tippy from "@tippyjs/react"; // import rootStyles from "../../../root.module.css"; -export type HyperlinkToolbarProps = { - url: string; - text: string; - editHyperlink: (url: string, text: string) => void; - deleteHyperlink: () => void; -}; - /** * Main menu component for the hyperlink extension. * Renders a toolbar that appears on hyperlink hover. From 3accd8c0ba17aed663054d9e17bfe8033889be04 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 14:52:29 +0200 Subject: [PATCH 06/42] Commented out old factory & component wrapper --- .../EditorElementComponentWrapper.tsx | 138 +++++++++--------- .../components/ReactElementFactory.tsx | 136 ++++++++--------- 2 files changed, 137 insertions(+), 137 deletions(-) diff --git a/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx b/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx index b1c54830f8..946f2380a1 100644 --- a/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx +++ b/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx @@ -1,69 +1,69 @@ -import { RequiredDynamicParams } from "@blocknote/core"; -import { MantineProvider, MantineThemeOverride } from "@mantine/core"; -import Tippy, { TippyProps } from "@tippyjs/react"; -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 Record, - 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 getReferenceClientRect = useCallback( - () => props.dynamicParams!.referenceRect, - [props.dynamicParams] - ); - - const onShow = useCallback(() => { - setContentCleared(false); - // document.body.appendChild(props.rootElement); - }, [props.rootElement]); - - const onHidden = useCallback(() => { - // props.rootElement.remove(); - setContentCleared(true); - }, [props.rootElement]); - - return ( - - - ) : undefined - } - getReferenceClientRect={ - !contentCleared ? getReferenceClientRect : undefined - } - interactive={true} - onShow={onShow} - onHidden={onHidden} - visible={props.isOpen} - {...props.tippyProps} - /> - - ); -} +// import { RequiredDynamicParams } from "@blocknote/core"; +// import { MantineProvider, MantineThemeOverride } from "@mantine/core"; +// import Tippy, { TippyProps } from "@tippyjs/react"; +// 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 Record, +// 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 getReferenceClientRect = useCallback( +// () => props.dynamicParams!.referenceRect, +// [props.dynamicParams] +// ); +// +// const onShow = useCallback(() => { +// setContentCleared(false); +// // document.body.appendChild(props.rootElement); +// }, [props.rootElement]); +// +// const onHidden = useCallback(() => { +// // props.rootElement.remove(); +// setContentCleared(true); +// }, [props.rootElement]); +// +// return ( +// +// +// ) : undefined +// } +// getReferenceClientRect={ +// !contentCleared ? getReferenceClientRect : undefined +// } +// 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 4e21b1e1ef..1c01554bfa 100644 --- a/packages/react/src/ElementFactory/components/ReactElementFactory.tsx +++ b/packages/react/src/ElementFactory/components/ReactElementFactory.tsx @@ -1,68 +1,68 @@ -import { FC } from "react"; -import { TippyProps } from "@tippyjs/react"; -import { createRoot } from "react-dom/client"; -import { EditorElement, RequiredDynamicParams } 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 Record, - 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. If we were to pass in undefined instead, the element would be immediately cleared, not - // leaving time for the fade out animation to complete. - let prevDynamicParams: ElementDynamicParams | undefined = undefined; - - return { - element: rootElement, - render: (dynamicParams: ElementDynamicParams, _isHidden: boolean) => { - prevDynamicParams = dynamicParams; - - root.render( - - ); - }, - hide: () => { - root.render( - - ); - }, - }; -}; +// import { FC } from "react"; +// import { TippyProps } from "@tippyjs/react"; +// import { createRoot } from "react-dom/client"; +// import { EditorElement, RequiredDynamicParams } 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 Record, +// 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. If we were to pass in undefined instead, the element would be immediately cleared, not +// // leaving time for the fade out animation to complete. +// let prevDynamicParams: ElementDynamicParams | undefined = undefined; +// +// return { +// element: rootElement, +// render: (dynamicParams: ElementDynamicParams, _isHidden: boolean) => { +// prevDynamicParams = dynamicParams; +// +// root.render( +// +// ); +// }, +// hide: () => { +// root.render( +// +// ); +// }, +// }; +// }; From 1c251a3740299130583b357072577f1de31e376f Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 14:59:34 +0200 Subject: [PATCH 07/42] Removed old files & fixed build --- .../DraggableBlocksExtension.ts | 37 ---------- .../FormattingToolbarExtension.ts | 37 ---------- .../HyperlinkToolbar/HyperlinkMark.ts | 28 -------- .../SlashMenu/SlashMenuExtension.ts | 52 -------------- .../BlockSideMenu/BlockSideMenuFactory.tsx | 49 ------------- .../EditorElementComponentWrapper.tsx | 69 ------------------- .../components/ReactElementFactory.tsx | 68 ------------------ .../FormattingToolbarFactory.tsx | 28 -------- .../HyperlinkToolbarFactory.tsx | 20 ------ .../react/src/SlashMenu/SlashMenuFactory.tsx | 22 ------ packages/react/src/hooks/useBlockNote.ts | 35 ++-------- packages/react/src/index.ts | 4 -- 12 files changed, 7 insertions(+), 442 deletions(-) delete mode 100644 packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts delete mode 100644 packages/core/src/extensions/FormattingToolbar/FormattingToolbarExtension.ts delete mode 100644 packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts delete mode 100644 packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts delete mode 100644 packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx delete mode 100644 packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx delete mode 100644 packages/react/src/ElementFactory/components/ReactElementFactory.tsx delete mode 100644 packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx delete mode 100644 packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx delete mode 100644 packages/react/src/SlashMenu/SlashMenuFactory.tsx diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksExtension.ts deleted file mode 100644 index 8b1a87839b..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 e1ef9db496..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/HyperlinkToolbar/HyperlinkMark.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkMark.ts deleted file mode 100644 index 0c08cce099..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/SlashMenu/SlashMenuExtension.ts b/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts deleted file mode 100644 index 086650db91..0000000000 --- a/packages/core/src/extensions/SlashMenu/SlashMenuExtension.ts +++ /dev/null @@ -1,52 +0,0 @@ -// import { Extension } from "@tiptap/core"; -// import { PluginKey } from "prosemirror-state"; -// import { BlockNoteEditor } from "../../BlockNoteEditor"; -// import { createSuggestionPlugin } from "../../shared/plugins/suggestion/SuggestionPlugin"; -// import { BlockSchema } from "../Blocks/api/blockTypes"; -// import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; -// -// export type SlashMenuOptions = { -// editor: BlockNoteEditor | undefined; -// commands: BaseSlashMenuItem[] | undefined; -// onUpdate: any; //SuggestionsMenuFactory | undefined; -// }; -// -// export const SlashMenuPluginKey = new PluginKey("suggestions-slash-commands"); -// -// export const createSlashMenuExtension = () => -// Extension.create>({ -// name: "slash-command", -// -// addOptions() { -// return { -// editor: undefined, -// commands: undefined, -// onUpdate: undefined, -// }; -// }, -// -// addProseMirrorPlugins() { -// if (!this.options.onUpdate || !this.options.commands) { -// throw new Error("required args not defined for SlashMenuExtension"); -// } -// -// const commands = this.options.commands; -// -// return [ -// createSuggestionPlugin, BSchema>( -// "SlashMenuPlugin", -// "/", -// this.options.editor!, -// this.options.onUpdate!, -// ({ item, editor }) => { -// item.execute(editor); -// }, -// (query) => { -// return commands.filter((cmd: BaseSlashMenuItem) => -// cmd.match(query) -// ); -// } -// ), -// ]; -// }, -// }); diff --git a/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx b/packages/react/src/BlockSideMenu/BlockSideMenuFactory.tsx deleted file mode 100644 index 072df14e76..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 { SideMenu 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/ElementFactory/components/EditorElementComponentWrapper.tsx b/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx deleted file mode 100644 index 946f2380a1..0000000000 --- a/packages/react/src/ElementFactory/components/EditorElementComponentWrapper.tsx +++ /dev/null @@ -1,69 +0,0 @@ -// import { RequiredDynamicParams } from "@blocknote/core"; -// import { MantineProvider, MantineThemeOverride } from "@mantine/core"; -// import Tippy, { TippyProps } from "@tippyjs/react"; -// 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 Record, -// 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 getReferenceClientRect = useCallback( -// () => props.dynamicParams!.referenceRect, -// [props.dynamicParams] -// ); -// -// const onShow = useCallback(() => { -// setContentCleared(false); -// // document.body.appendChild(props.rootElement); -// }, [props.rootElement]); -// -// const onHidden = useCallback(() => { -// // props.rootElement.remove(); -// setContentCleared(true); -// }, [props.rootElement]); -// -// return ( -// -// -// ) : undefined -// } -// getReferenceClientRect={ -// !contentCleared ? getReferenceClientRect : undefined -// } -// 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 deleted file mode 100644 index 1c01554bfa..0000000000 --- a/packages/react/src/ElementFactory/components/ReactElementFactory.tsx +++ /dev/null @@ -1,68 +0,0 @@ -// import { FC } from "react"; -// import { TippyProps } from "@tippyjs/react"; -// import { createRoot } from "react-dom/client"; -// import { EditorElement, RequiredDynamicParams } 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 Record, -// 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. If we were to pass in undefined instead, the element would be immediately cleared, not -// // leaving time for the fade out animation to complete. -// let prevDynamicParams: ElementDynamicParams | undefined = undefined; -// -// return { -// element: rootElement, -// render: (dynamicParams: ElementDynamicParams, _isHidden: boolean) => { -// prevDynamicParams = dynamicParams; -// -// root.render( -// -// ); -// }, -// hide: () => { -// root.render( -// -// ); -// }, -// }; -// }; diff --git a/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx b/packages/react/src/FormattingToolbar/FormattingToolbarFactory.tsx deleted file mode 100644 index 40979fa233..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/HyperlinkToolbar/HyperlinkToolbarFactory.tsx b/packages/react/src/HyperlinkToolbar/HyperlinkToolbarFactory.tsx deleted file mode 100644 index c335a19277..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/SlashMenu/SlashMenuFactory.tsx b/packages/react/src/SlashMenu/SlashMenuFactory.tsx deleted file mode 100644 index ff53d2f39e..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/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 12a5174762..abbc1e7ea5 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -4,11 +4,8 @@ import { BlockSchema, DefaultBlockSchema, } from "@blocknote/core"; -import { DependencyList, FC, useEffect, useState } from "react"; -import { getBlockNoteTheme } from "../BlockNoteTheme"; -import { createReactBlockSideMenuFactory } from "../BlockSideMenu/BlockSideMenuFactory"; +import { DependencyList, FC } from "react"; import { DragHandleMenuProps } from "../BlockSideMenu/components/DragHandleMenu"; -import { createReactHyperlinkToolbarFactory } from "../HyperlinkToolbar/HyperlinkToolbarFactory"; import { defaultReactSlashMenuItems } from "../SlashMenu/defaultReactSlashMenuItems"; //based on https://github.com/ueberdosis/tiptap/blob/main/packages/react/src/useEditor.ts @@ -18,11 +15,11 @@ type CustomElements = Partial<{ dragHandleMenu: FC>; }>; -function useForceUpdate() { - const [, setValue] = useState(0); - - return () => setValue((value) => value + 1); -} +// function useForceUpdate() { +// const [, setValue] = useState(0); +// +// return () => setValue((value) => value + 1); +// } function initEditor( options: Partial< @@ -45,24 +42,6 @@ function initEditor( ); } - let uiFactories = { - formattingToolbarFactory: undefined, - hyperlinkToolbarFactory: createReactHyperlinkToolbarFactory( - getBlockNoteTheme(newOptions.theme === "dark") - ), - slashMenuFactory: undefined, - 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> @@ -80,7 +59,7 @@ export const useBlockNote = ( customElements: CustomElements; } > = {}, - deps: DependencyList = [] + _deps: DependencyList = [] ) => { // const [editor, setEditor] = useState>( // initEditor(options) diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 88fa18eee0..02a122f441 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -1,11 +1,9 @@ // TODO: review directories export * from "./BlockNoteView"; -export * from "./BlockSideMenu/BlockSideMenuFactory"; export * from "./BlockSideMenu/components/DefaultButtons/BlockColorsButton"; export * from "./BlockSideMenu/components/DefaultButtons/RemoveBlockButton"; export * from "./BlockSideMenu/components/DragHandleMenu"; export * from "./BlockSideMenu/components/DragHandleMenuItem"; -export * from "./FormattingToolbar/FormattingToolbarFactory"; export * from "./FormattingToolbar/components/DefaultButtons/ColorStyleButton"; export * from "./FormattingToolbar/components/DefaultButtons/CreateLinkButton"; export * from "./FormattingToolbar/components/DefaultButtons/NestBlockButtons"; @@ -13,13 +11,11 @@ export * from "./FormattingToolbar/components/DefaultButtons/TextAlignButton"; export * from "./FormattingToolbar/components/DefaultButtons/ToggledStyleButton"; export * from "./FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown"; export * from "./FormattingToolbar/components/FormattingToolbar"; -export * from "./HyperlinkToolbar/HyperlinkToolbarFactory"; export * from "./ReactBlockSpec"; export * from "./SharedComponents/Toolbar/components/Toolbar"; export * from "./SharedComponents/Toolbar/components/ToolbarButton"; export * from "./SharedComponents/Toolbar/components/ToolbarDropdown"; export * from "./SlashMenu/ReactSlashMenuItem"; -export * from "./SlashMenu/SlashMenuFactory"; export * from "./SlashMenu/components/SlashMenu"; export * from "./SlashMenu/defaultReactSlashMenuItems"; export * from "./hooks/useBlockNote"; From c7f26e7f512cd9d2c37a582a3d1407c6441a2ddc Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 15:06:54 +0200 Subject: [PATCH 08/42] Small cleanup --- packages/core/src/BlockNoteEditor.ts | 6 +- .../extensions/SlashMenu/SlashMenuPlugin.ts | 4 -- .../core/src/extensions/SlashMenu/index.ts | 1 - packages/core/src/shared/EventEmitter.ts | 62 ------------------- .../plugins/suggestion/SuggestionPlugin.ts | 2 - .../components/BlockSideMenu.tsx | 6 +- 6 files changed, 4 insertions(+), 77 deletions(-) delete mode 100644 packages/core/src/shared/EventEmitter.ts diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 7a1e4f0ba7..bad71a1f5b 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -42,7 +42,6 @@ import { BaseSlashMenuItem, defaultSlashMenuItems, } from "./extensions/SlashMenu"; -import { EventEmitter } from "./shared/EventEmitter"; export type BlockNoteEditorOptions = { // TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them. @@ -141,9 +140,7 @@ const blockNoteTipTapOptions = { enableCoreExtensions: false, }; -export class BlockNoteEditor< - BSchema extends BlockSchema = DefaultBlockSchema -> extends EventEmitter { +export class BlockNoteEditor { public readonly _tiptapEditor: TiptapEditor & { contentComponent: any }; public blockCache = new WeakMap>(); public readonly schema: BSchema; @@ -163,7 +160,6 @@ export class BlockNoteEditor< constructor( private readonly options: Partial> = {} ) { - super(); // apply defaults const newOptions: Omit & { defaultStyles: boolean; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index 5c5fffc2a4..f8644e145c 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -25,10 +25,6 @@ export const createSlashMenu = < (slashMenuState) => updateSlashMenu(slashMenuState), ({ item, editor }) => item.execute(editor), items - // (query) => - // defaultSlashMenuItems.filter( - // (cmd: SlashMenuItem) => cmd.match(query) - // ) ) ); }; diff --git a/packages/core/src/extensions/SlashMenu/index.ts b/packages/core/src/extensions/SlashMenu/index.ts index c7de75fc48..3fb14694c5 100644 --- a/packages/core/src/extensions/SlashMenu/index.ts +++ b/packages/core/src/extensions/SlashMenu/index.ts @@ -1,5 +1,4 @@ import { defaultSlashMenuItems } from "./defaultSlashMenuItems"; -// import { createSlashMenuExtension } from "./SlashMenuExtension"; import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; export { defaultSlashMenuItems, BaseSlashMenuItem }; diff --git a/packages/core/src/shared/EventEmitter.ts b/packages/core/src/shared/EventEmitter.ts deleted file mode 100644 index 674ed14e9f..0000000000 --- a/packages/core/src/shared/EventEmitter.ts +++ /dev/null @@ -1,62 +0,0 @@ -//from tiptap. Could also use a package like nanoevents - -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 - ): this { - if (!this.callbacks[event]) { - this.callbacks[event] = []; - } - - this.callbacks[event].push(fn); - - return this; - } - - protected emit>( - event: EventName, - ...args: CallbackType - ): this { - const callbacks = this.callbacks[event]; - - if (callbacks) { - callbacks.forEach((callback) => callback.apply(this, args)); - } - - return this; - } - - public off>( - event: EventName, - fn?: CallbackFunction - ): this { - const callbacks = this.callbacks[event]; - - if (callbacks) { - if (fn) { - this.callbacks[event] = callbacks.filter((callback) => callback !== fn); - } else { - delete this.callbacks[event]; - } - } - - return this; - } - - protected removeAllListeners(): void { - this.callbacks = {}; - } -} diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 7563dddbf0..20a5b18780 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -67,8 +67,6 @@ class SuggestionPluginView< }); }; - // this.suggestionsMenu = suggestionsMenuFactory(this.getStaticParams()); - document.addEventListener("scroll", this.handleScroll); } diff --git a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx index b6177ca826..de5643a45c 100644 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx @@ -4,7 +4,7 @@ import { createSideMenu, SideMenuState, } from "@blocknote/core"; -import { ActionIcon, Menu } from "@mantine/core"; +import { ActionIcon, Group, Menu } from "@mantine/core"; import { useCallback, useEffect, useRef, useState } from "react"; import { AiOutlinePlus } from "react-icons/ai"; import { MdDragIndicator } from "react-icons/md"; @@ -44,7 +44,7 @@ export const BlockSideMenuOld = ( const DragHandleMenu = DefaultDragHandleMenu; return ( -
+ { ( closeMenu={closeMenu} /> -
+
); }; From 251fc94f2d6d2464000dee7000f4767df9f7f43e Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 16:10:28 +0200 Subject: [PATCH 09/42] Fixed some bugs in the slash and side menus --- .../DraggableBlocks/DraggableBlocksPlugin.ts | 17 ++++++++--------- .../BlockSideMenu/components/BlockSideMenu.tsx | 10 ++-------- .../src/SlashMenu/components/SlashMenu.tsx | 10 +++------- 3 files changed, 13 insertions(+), 24 deletions(-) diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index 901aaf7039..11be9040d2 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -363,17 +363,16 @@ export class BlockMenuView { onMouseDown = (_event: MouseEvent) => { // TODO: Fix - return; // if (this.blockMenu.element?.contains(event.target as HTMLElement)) { // return; // } - // - // if (this.sideMenuState?.show) { - // this.sideMenuState.show = false; - // this.updateSideMenu(); - // } - // - // this.menuFrozen = false; + + if (this.sideMenuState?.show) { + this.sideMenuState.show = false; + this.updateSideMenu(); + } + + this.menuFrozen = false; }; onMouseMove = (event: MouseEvent) => { @@ -483,7 +482,7 @@ export class BlockMenuView { block: this.editor.getBlock( this.hoveredBlock!.getAttribute("data-id")! )!, - addBlock: this.addBlock, + addBlock: () => this.addBlock(), blockDragStart: (event: DragEvent) => { // Sets isDragging when dragging blocks. this.isDragging = true; diff --git a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx index de5643a45c..c390b0b82e 100644 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx @@ -16,8 +16,6 @@ export const BlockSideMenuOld = ( editor: BlockNoteEditor; } ) => { - const [dragHandleMenuOpened, setDragHandleMenuOpened] = useState(false); - const dragHandleRef = useRef(null); useEffect(() => { @@ -37,7 +35,6 @@ export const BlockSideMenuOld = ( }, [props.blockDragEnd, props.blockDragStart]); const closeMenu = () => { - setDragHandleMenuOpened(false); props.unfreezeMenu(); }; @@ -55,14 +52,11 @@ export const BlockSideMenuOld = ( /> } - +
{ - setDragHandleMenuOpened(true); - props.freezeMenu(); - }} + onClick={() => props.freezeMenu()} size={24} data-test={"dragHandle"}> {} diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index 5836a9cbe6..4ef239f9a3 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -8,12 +8,6 @@ import Tippy from "@tippyjs/react"; import { DefaultBlockSchema, SuggestionsMenuState } from "@blocknote/core"; import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; -export type SlashMenuProps = { - items: ReactSlashMenuItem[]; - keyboardHoveredItemIndex: number; - itemCallback: (item: ReactSlashMenuItem) => void; -}; - export function SlashMenuOld( props: Omit< SuggestionsMenuState>, @@ -60,7 +54,9 @@ export function SlashMenuOld( defaultOpened={true} trigger={"hover"} closeDelay={10000000}> - + event.preventDefault()} + className={classes.root}> {renderedItems.length > 0 ? ( renderedItems ) : ( From 7c2cc058fcf8bc13bca76c7631c0910be347c8b4 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 16:30:30 +0200 Subject: [PATCH 10/42] Made menu & toolbar plugins load with the highest priority instead of the lowest --- .../DraggableBlocks/DraggableBlocksPlugin.ts | 6 +- .../FormattingToolbarPlugin.ts | 6 +- .../HyperlinkToolbarPlugin.ts | 6 +- .../extensions/SlashMenu/SlashMenuPlugin.ts | 16 +- .../plugins/suggestion/SuggestionPlugin.ts | 450 +++++++++--------- 5 files changed, 252 insertions(+), 232 deletions(-) diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index 11be9040d2..409c444b10 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -616,6 +616,10 @@ export const createSideMenu = ( new Plugin({ key: sideMenuPluginKey, view: () => new BlockMenuView(editor, updateSideMenu), - }) + }), + (sideMenuPlugin, plugins) => { + plugins.unshift(sideMenuPlugin); + return plugins; + } ); }; diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 70ee3cb56f..58a89bb68e 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -237,6 +237,10 @@ export const createFormattingToolbar = ( key: formattingToolbarPluginKey, view: (view) => new FormattingToolbarView(editor, view, updateFormattingToolbar), - }) + }), + (formattingToolbarPlugin, plugins) => { + plugins.unshift(formattingToolbarPlugin); + return plugins; + } ); }; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index a50b2ab363..61e3170856 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -312,6 +312,10 @@ export const createHyperlinkToolbar = ( new Plugin({ key: hyperlinkToolbarPluginKey, view: () => new HyperlinkToolbarView(editor, updateHyperlinkToolbar), - }) + }), + (hyperlinkToolbarPlugin, plugins) => { + plugins.unshift(hyperlinkToolbarPlugin); + return plugins; + } ); }; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index f8644e145c..04f12f1571 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -17,14 +17,12 @@ export const createSlashMenu = < ) => void, items: (query: string) => SlashMenuItem[] ) => { - editor._tiptapEditor.registerPlugin( - createSuggestionPlugin( - slashMenuPluginKey, - "/", - editor, - (slashMenuState) => updateSlashMenu(slashMenuState), - ({ item, editor }) => item.execute(editor), - items - ) + createSuggestionPlugin( + slashMenuPluginKey, + "/", + editor, + (slashMenuState) => updateSlashMenu(slashMenuState), + ({ item, editor }) => item.execute(editor), + items ); }; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 20a5b18780..96efeb7eca 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -203,243 +203,253 @@ export function createSuggestionPlugin< }; // Plugin key is passed in as a parameter, so it can be exported and used in the DraggableBlocksPlugin. - return new Plugin({ - key: pluginKey, - - view: (view: EditorView) => - new SuggestionPluginView( - editor, - pluginKey, - (props: { item: T; editor: BlockNoteEditor }) => { - deactivate(view); - onSelectItem(props); + editor._tiptapEditor.registerPlugin( + new Plugin({ + key: pluginKey, + + view: (view: EditorView) => + new SuggestionPluginView( + editor, + pluginKey, + (props: { item: T; editor: BlockNoteEditor }) => { + deactivate(view); + onSelectItem(props); + }, + updateSuggestionsMenu + ), + + state: { + // Initialize the plugin's internal state. + init(): SuggestionPluginState { + return getDefaultPluginState(); }, - updateSuggestionsMenu - ), - 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)}`, + }; + } - // 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) - ); - - // 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) + // 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 + ) ); - } - - // 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) + ); + } + + // 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(); } - next.keyboardHoveredItemIndex = newIndex; - } + // 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; + } + + next.keyboardHoveredItemIndex = newIndex; + } - return next; + 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; + } + + // 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(); - return true; - } + 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(); - - onSelectItem({ - item: items[keyboardHoveredItemIndex], - editor: editor, - }); - - return true; - } - - // Closes the menu. - if (event.key === "Escape") { + // Hides menu in cases where mouse click does not cause an editor state change. + handleClick(view) { 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, + } + ), + ]); + }, }, - }, - }); + }), + (suggestionPlugin, plugins) => { + plugins.unshift(suggestionPlugin); + return plugins; + } + ); } From fb37efad20c600f48817d7c420e5814f1def35ed Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 17:01:48 +0200 Subject: [PATCH 11/42] Disabled strict mode --- examples/editor/src/main.tsx | 6 +----- packages/react/src/SlashMenu/components/SlashMenu.tsx | 1 + 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/examples/editor/src/main.tsx b/examples/editor/src/main.tsx index 5c948c1c61..9497403d49 100644 --- a/examples/editor/src/main.tsx +++ b/examples/editor/src/main.tsx @@ -6,10 +6,6 @@ import "./index.css"; window.React = React; const root = createRoot(document.getElementById("root")!); -root.render( - - - -); +root.render(); // root.render(); diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index 4ef239f9a3..c34235c1ba 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -55,6 +55,7 @@ export function SlashMenuOld( trigger={"hover"} closeDelay={10000000}> event.preventDefault()} className={classes.root}> {renderedItems.length > 0 ? ( From f2ed0f3d2772a7badd9fb034e28e6f25c378f459 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 10 Jul 2023 17:36:21 +0200 Subject: [PATCH 12/42] Fixed a bug which caused plugin views to be created multiple times --- .../DraggableBlocks/DraggableBlocksPlugin.ts | 33 ++++++++++--------- .../FormattingToolbarPlugin.ts | 12 +++++-- .../HyperlinkToolbarPlugin.ts | 10 +++++- .../plugins/suggestion/SuggestionPlugin.ts | 26 ++++++++------- 4 files changed, 52 insertions(+), 29 deletions(-) diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index 409c444b10..81fc435ce2 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -229,7 +229,7 @@ function dragStart(e: DragEvent, view: EditorView) { } } -export class BlockMenuView { +export class SideMenuView { editor: BlockNoteEditor; private sideMenuState?: SideMenuState; @@ -366,16 +366,18 @@ export class BlockMenuView { // if (this.blockMenu.element?.contains(event.target as HTMLElement)) { // return; // } - - if (this.sideMenuState?.show) { - this.sideMenuState.show = false; - this.updateSideMenu(); - } - - this.menuFrozen = false; + // + // if (this.sideMenuState?.show) { + // this.sideMenuState.show = false; + // this.updateSideMenu(); + // } + // + // this.menuFrozen = false; }; onMouseMove = (event: MouseEvent) => { + console.log(this.menuFrozen); + console.log(this.sideMenuState); if (this.menuFrozen) { return; } @@ -489,12 +491,8 @@ export class BlockMenuView { dragStart(event, this.editor._tiptapEditor.view); }, blockDragEnd: () => unsetDragImage(), - freezeMenu: () => { - this.menuFrozen = true; - }, - unfreezeMenu: () => { - this.menuFrozen = false; - }, + freezeMenu: () => (this.menuFrozen = true), + unfreezeMenu: () => (this.menuFrozen = false), }; } else { this.sideMenuState.show = true; @@ -612,10 +610,15 @@ export const createSideMenu = ( editor: BlockNoteEditor, updateSideMenu: (sideMenuState: SideMenuState) => void ) => { + // TODO: Add a way to unregister the plugin. + const sideMenuView = new SideMenuView(editor, updateSideMenu); + // For some reason, each time `registerPlugin` is called, the previous plugins + // which were added are either added again, or `view` is called again, + // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: sideMenuPluginKey, - view: () => new BlockMenuView(editor, updateSideMenu), + view: () => sideMenuView, }), (sideMenuPlugin, plugins) => { plugins.unshift(sideMenuPlugin); diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 58a89bb68e..8a536c8eec 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -232,11 +232,19 @@ export const createFormattingToolbar = ( formattingToolbarState: FormattingToolbarState ) => void ) => { + // TODO: Add a way to unregister the plugin. + const formattingToolbarView = new FormattingToolbarView( + editor, + editor._tiptapEditor.view, + updateFormattingToolbar + ); + // For some reason, each time `registerPlugin` is called, the previous plugins + // which were added are either added again, or `view` is called again, + // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: formattingToolbarPluginKey, - view: (view) => - new FormattingToolbarView(editor, view, updateFormattingToolbar), + view: () => formattingToolbarView, }), (formattingToolbarPlugin, plugins) => { plugins.unshift(formattingToolbarPlugin); diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index 61e3170856..934a8c903b 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -308,10 +308,18 @@ export const createHyperlinkToolbar = ( editor: BlockNoteEditor, updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void ) => { + // TODO: Add a way to unregister the plugin. + const hyperlinkToolbarView = new HyperlinkToolbarView( + editor, + updateHyperlinkToolbar + ); + // For some reason, each time `registerPlugin` is called, the previous plugins + // which were added are either added again, or `view` is called again, + // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: hyperlinkToolbarPluginKey, - view: () => new HyperlinkToolbarView(editor, updateHyperlinkToolbar), + view: () => hyperlinkToolbarView, }), (hyperlinkToolbarPlugin, plugins) => { plugins.unshift(hyperlinkToolbarPlugin); diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 96efeb7eca..f1b074d44b 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -193,6 +193,7 @@ export function createSuggestionPlugin< }) => void = () => {}, items: (query: string) => T[] = () => [] ) { + // TODO: Add a way to unregister the plugin. // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); @@ -202,21 +203,24 @@ export function createSuggestionPlugin< 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. + const suggestionPluginView = new SuggestionPluginView( + editor, + pluginKey, + (props: { item: T; editor: BlockNoteEditor }) => { + deactivate(editor._tiptapEditor.view); + onSelectItem(props); + }, + updateSuggestionsMenu + ); + + // For some reason, each time `registerPlugin` is called, the previous plugins + // which were added are either added again, or `view` is called again, + // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: pluginKey, - view: (view: EditorView) => - new SuggestionPluginView( - editor, - pluginKey, - (props: { item: T; editor: BlockNoteEditor }) => { - deactivate(view); - onSelectItem(props); - }, - updateSuggestionsMenu - ), + view: () => suggestionPluginView, state: { // Initialize the plugin's internal state. From ca32ce3715017ff7894463386e73f0ba235e9a28 Mon Sep 17 00:00:00 2001 From: Yousef Date: Tue, 11 Jul 2023 13:42:10 +0200 Subject: [PATCH 13/42] several fixes for react rearchitecture (#272) --- examples/editor/src/main.tsx | 8 +- .../DraggableBlocks/DraggableBlocksPlugin.ts | 48 +++++----- .../FormattingToolbarPlugin.ts | 20 ++-- .../HyperlinkToolbarPlugin.ts | 14 +-- .../extensions/SlashMenu/SlashMenuPlugin.ts | 7 +- .../plugins/suggestion/SuggestionPlugin.ts | 27 +++--- packages/react/src/BlockNoteView.tsx | 20 ++-- .../components/BlockSideMenu.tsx | 94 ++++++++++--------- .../components/FormattingToolbar.tsx | 43 ++++----- .../components/HyperlinkToolbar.tsx | 44 ++++----- .../Toolbar/components/ToolbarDropdown.tsx | 4 +- .../src/SlashMenu/components/SlashMenu.tsx | 56 +++++------ packages/website/partykitserver.ts | 2 +- 13 files changed, 192 insertions(+), 195 deletions(-) diff --git a/examples/editor/src/main.tsx b/examples/editor/src/main.tsx index 9497403d49..0808f1a4d8 100644 --- a/examples/editor/src/main.tsx +++ b/examples/editor/src/main.tsx @@ -6,6 +6,8 @@ import "./index.css"; window.React = React; const root = createRoot(document.getElementById("root")!); -root.render(); - -// root.render(); +root.render( + + + +); diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index 81fc435ce2..6beed395a8 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -1,20 +1,23 @@ +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 styles from "../../editor.module.css"; -import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; -import { MultipleNodeSelection } from "./MultipleNodeSelection"; import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { Block, BlockSchema } from "../Blocks/api/blockTypes"; +import styles from "../../editor.module.css"; import { BaseUiElementState } from "../../shared/EditorElement"; +import { Block, BlockSchema } from "../Blocks/api/blockTypes"; +import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; +import { MultipleNodeSelection } from "./MultipleNodeSelection"; const serializeForClipboard = (pv as any).__serializeForClipboard; // code based on https://github.com/ueberdosis/tiptap/issues/323#issuecomment-506637799 let dragImageElement: Element | undefined; +// TODO: I think freezeMenu, unfreezeMenu, blockDragStart, blockDragEnd are not "state", but +// but actions that should be for example returned from createSideMenu export type SideMenuState = BaseUiElementState & { block: Block; @@ -229,9 +232,8 @@ function dragStart(e: DragEvent, view: EditorView) { } } -export class SideMenuView { +export class SideMenuView implements PluginView { editor: BlockNoteEditor; - private sideMenuState?: SideMenuState; public updateSideMenu: () => void; @@ -357,7 +359,6 @@ export class SideMenuView { this.sideMenuState.show = false; this.updateSideMenu(); } - this.menuFrozen = false; }; @@ -376,8 +377,6 @@ export class SideMenuView { }; onMouseMove = (event: MouseEvent) => { - console.log(this.menuFrozen); - console.log(this.sideMenuState); if (this.menuFrozen) { return; } @@ -430,11 +429,12 @@ export class SideMenuView { left: editorBoundingBox.left + editorBoundingBox.width / 2, // take middle of editor top: event.clientY, }; + const block = getDraggableBlockFromCoords( coords, this.editor._tiptapEditor.view ); - + console.log(block); // Closes the menu if the mouse cursor is beyond the editor vertically. if (!block || !this.editor.isEditable) { if (this.sideMenuState?.show) { @@ -451,6 +451,7 @@ export class SideMenuView { this.hoveredBlock?.hasAttribute("data-id") && this.hoveredBlock?.getAttribute("data-id") === block.id ) { + // TODO: this doesn't seem right if (this.sideMenuState?.show) { this.sideMenuState.show = true; this.updateSideMenu(); @@ -491,8 +492,12 @@ export class SideMenuView { dragStart(event, this.editor._tiptapEditor.view); }, blockDragEnd: () => unsetDragImage(), - freezeMenu: () => (this.menuFrozen = true), - unfreezeMenu: () => (this.menuFrozen = false), + freezeMenu: () => { + this.menuFrozen = true; + }, + unfreezeMenu: () => { + this.menuFrozen = false; + }, }; } else { this.sideMenuState.show = true; @@ -535,16 +540,19 @@ export class SideMenuView { this.sideMenuState.show = false; this.updateSideMenu(); } - document.body.removeEventListener("mousemove", this.onMouseMove); + // (remove this comment): + // the event listeners weren't detached properly because the parameters didn't match + // the params passed to addEventListener. + document.body.removeEventListener("mousemove", this.onMouseMove, true); document.body.removeEventListener("dragover", this.onDragOver); this.editor._tiptapEditor.view.dom.removeEventListener( "dragstart", this.onDragStart ); - document.body.removeEventListener("drop", this.onDrop); - document.body.removeEventListener("mousedown", this.onMouseDown); + document.body.removeEventListener("drop", this.onDrop, true); + document.body.removeEventListener("mousedown", this.onMouseDown, true); document.removeEventListener("scroll", this.onScroll); - document.body.removeEventListener("keydown", this.onKeyDown); + document.body.removeEventListener("keydown", this.onKeyDown, true); } addBlock() { @@ -610,19 +618,15 @@ export const createSideMenu = ( editor: BlockNoteEditor, updateSideMenu: (sideMenuState: SideMenuState) => void ) => { - // TODO: Add a way to unregister the plugin. - const sideMenuView = new SideMenuView(editor, updateSideMenu); - // For some reason, each time `registerPlugin` is called, the previous plugins - // which were added are either added again, or `view` is called again, - // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: sideMenuPluginKey, - view: () => sideMenuView, + view: () => new SideMenuView(editor, updateSideMenu), }), (sideMenuPlugin, plugins) => { plugins.unshift(sideMenuPlugin); return plugins; } ); + return () => editor._tiptapEditor.unregisterPlugin(sideMenuPluginKey); }; diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 8a536c8eec..8b456a4ecb 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -124,7 +124,7 @@ export class FormattingToolbarView { scrollHandler = () => { if (this.formattingToolbarState?.show) { this.formattingToolbarState.referencePos = this.getSelectionBoundingBox(); - this.updateFormattingToolbar?.(); + this.updateFormattingToolbar(); } }; @@ -232,23 +232,21 @@ export const createFormattingToolbar = ( formattingToolbarState: FormattingToolbarState ) => void ) => { - // TODO: Add a way to unregister the plugin. - const formattingToolbarView = new FormattingToolbarView( - editor, - editor._tiptapEditor.view, - updateFormattingToolbar - ); - // For some reason, each time `registerPlugin` is called, the previous plugins - // which were added are either added again, or `view` is called again, - // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: formattingToolbarPluginKey, - view: () => formattingToolbarView, + view: () => + new FormattingToolbarView( + editor, + editor._tiptapEditor.view, + updateFormattingToolbar + ), }), (formattingToolbarPlugin, plugins) => { plugins.unshift(formattingToolbarPlugin); return plugins; } ); + return () => + editor._tiptapEditor.unregisterPlugin(formattingToolbarPluginKey); }; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index 934a8c903b..ae40246b03 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -1,8 +1,8 @@ import { getMarkRange, posToDOMRect, Range } from "@tiptap/core"; import { Mark } from "prosemirror-model"; import { Plugin, PluginKey } from "prosemirror-state"; -import { BaseUiElementState } from "../../shared/EditorElement"; import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { BaseUiElementState } from "../../shared/EditorElement"; import { BlockSchema } from "../Blocks/api/blockTypes"; export type HyperlinkToolbarState = BaseUiElementState & { @@ -298,6 +298,7 @@ class HyperlinkToolbarView { this.mouseOverHandler ); document.removeEventListener("scroll", this.scrollHandler); + document.removeEventListener("click", this.clickHandler, true); } } @@ -308,22 +309,15 @@ export const createHyperlinkToolbar = ( editor: BlockNoteEditor, updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void ) => { - // TODO: Add a way to unregister the plugin. - const hyperlinkToolbarView = new HyperlinkToolbarView( - editor, - updateHyperlinkToolbar - ); - // For some reason, each time `registerPlugin` is called, the previous plugins - // which were added are either added again, or `view` is called again, - // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: hyperlinkToolbarPluginKey, - view: () => hyperlinkToolbarView, + view: () => new HyperlinkToolbarView(editor, updateHyperlinkToolbar), }), (hyperlinkToolbarPlugin, plugins) => { plugins.unshift(hyperlinkToolbarPlugin); return plugins; } ); + return () => editor._tiptapEditor.unregisterPlugin(hyperlinkToolbarPluginKey); }; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index 04f12f1571..6c964f9433 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -1,11 +1,11 @@ -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; -import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; +import { PluginKey } from "prosemirror-state"; import { BlockNoteEditor } from "../../BlockNoteEditor"; import { createSuggestionPlugin, SuggestionsMenuState, } from "../../shared/plugins/suggestion/SuggestionPlugin"; -import { PluginKey } from "prosemirror-state"; +import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; export const slashMenuPluginKey = new PluginKey("SlashMenuPlugin"); export const createSlashMenu = < @@ -25,4 +25,5 @@ export const createSlashMenu = < ({ item, editor }) => item.execute(editor), items ); + return () => editor._tiptapEditor.unregisterPlugin(slashMenuPluginKey); }; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index f1b074d44b..9e34dd1df7 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -3,8 +3,8 @@ import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; -import { SuggestionItem } from "./SuggestionItem"; import { BaseUiElementState } from "../../EditorElement"; +import { SuggestionItem } from "./SuggestionItem"; export type SuggestionsMenuState = BaseUiElementState & { @@ -193,7 +193,6 @@ export function createSuggestionPlugin< }) => void = () => {}, items: (query: string) => T[] = () => [] ) { - // TODO: Add a way to unregister the plugin. // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); @@ -203,24 +202,20 @@ export function createSuggestionPlugin< view.dispatch(view.state.tr.setMeta(pluginKey, { deactivate: true })); }; - const suggestionPluginView = new SuggestionPluginView( - editor, - pluginKey, - (props: { item: T; editor: BlockNoteEditor }) => { - deactivate(editor._tiptapEditor.view); - onSelectItem(props); - }, - updateSuggestionsMenu - ); - - // For some reason, each time `registerPlugin` is called, the previous plugins - // which were added are either added again, or `view` is called again, - // resulting in duplicate views. This seems like a bug in TipTap? editor._tiptapEditor.registerPlugin( new Plugin({ key: pluginKey, - view: () => suggestionPluginView, + view: () => + new SuggestionPluginView( + editor, + pluginKey, + (props: { item: T; editor: BlockNoteEditor }) => { + deactivate(editor._tiptapEditor.view); + onSelectItem(props); + }, + updateSuggestionsMenu + ), state: { // Initialize the plugin's internal state. diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index ad482fa659..b8932b33ef 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -1,22 +1,24 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; +import { getBlockNoteTheme } from "./BlockNoteTheme"; +import { SideMenu } from "./BlockSideMenu/components/BlockSideMenu"; import { FormattingToolbar } from "./FormattingToolbar/components/FormattingToolbar"; -import { SlashMenu } from "./SlashMenu/components/SlashMenu"; import { HyperlinkToolbar } from "./HyperlinkToolbar/components/HyperlinkToolbar"; -import { SideMenu } from "./BlockSideMenu/components/BlockSideMenu"; -import { getBlockNoteTheme } from "./BlockNoteTheme"; -import { MantineProvider } from "@mantine/core"; +import { SlashMenu } from "./SlashMenu/components/SlashMenu"; export function BlockNoteView(props: { editor: BlockNoteEditor; }) { return ( - - - - - + + + + + + + ); } diff --git a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx index c390b0b82e..be61ea5b4a 100644 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx @@ -5,11 +5,11 @@ import { SideMenuState, } from "@blocknote/core"; import { ActionIcon, Group, Menu } from "@mantine/core"; -import { useCallback, useEffect, useRef, useState } from "react"; +import Tippy from "@tippyjs/react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { AiOutlinePlus } from "react-icons/ai"; import { MdDragIndicator } from "react-icons/md"; import { DefaultDragHandleMenu } from "./DefaultDragHandleMenu"; -import Tippy from "@tippyjs/react"; export const BlockSideMenuOld = ( props: Omit, "referencePos"> & { @@ -35,7 +35,8 @@ export const BlockSideMenuOld = ( }, [props.blockDragEnd, props.blockDragStart]); const closeMenu = () => { - props.unfreezeMenu(); + // TODO: I don't think this is needed / used? + // props.unfreezeMenu(); }; const DragHandleMenu = DefaultDragHandleMenu; @@ -52,13 +53,15 @@ export const BlockSideMenuOld = ( /> } - + props.freezeMenu()} + onClose={() => props.unfreezeMenu()} + width={100} + position={"left"}>
- props.freezeMenu()} - size={24} - data-test={"dragHandle"}> + {}
@@ -76,54 +79,57 @@ export const BlockSideMenuOld = ( export const SideMenu = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState< - Omit, "referencePos"> | undefined - >(); - // Since we're using Tippy, we don't want to trigger re-renders when only the - // reference position changes. So we store it in a ref instead of state. - const referenceClientRect = useRef(); + const [state, setState] = useState>(); useEffect(() => { - createSideMenu(props.editor, ({ referencePos, ...state }) => { - setState(state); - referenceClientRect.current = referencePos; + return createSideMenu(props.editor, (state) => { + setState({ ...state }); }); }, [props.editor]); - const getReferenceClientRect = useCallback( - () => referenceClientRect.current!, - [referenceClientRect] - ); + const getReferenceClientRect = useMemo(() => { + // TODO: test + console.log( + "new reference pos, this should only be triggered when hovering a new block" + ); + if (!state?.referencePos) { + return undefined; + } + return () => state.referencePos; + }, [state?.referencePos]); return ( below + moved to + // appendTo={props.editor._tiptapEditor.view.dom.parentElement!} content={} - getReferenceClientRect={ - referenceClientRect.current && getReferenceClientRect - } + getReferenceClientRect={getReferenceClientRect} interactive={true} visible={state?.show || false} animation={"fade"} - offset={[0, 0]} + offset={offset} placement={"left"} - popperOptions={{ - modifiers: [ - { - name: "flip", - options: { - fallbackPlacements: [], - }, - }, - { - name: "preventOverflow", - options: { - mainAxis: false, - altAxis: false, - }, - }, - ], - }} - /> + popperOptions={popperOptions}> +
+ ); }; + +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/FormattingToolbar/components/FormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx index cf3606c324..4047bb134b 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx @@ -1,11 +1,12 @@ import { BlockNoteEditor, BlockSchema, - createFormattingToolbar, FormattingToolbarState, + createFormattingToolbar, } from "@blocknote/core"; -import { useCallback, useEffect, useRef, useState } from "react"; +import Tippy from "@tippyjs/react"; +import { useEffect, useMemo, useState } from "react"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ColorStyleButton } from "./DefaultButtons/ColorStyleButton"; import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; @@ -16,7 +17,6 @@ import { import { TextAlignButton } from "./DefaultButtons/TextAlignButton"; import { ToggledStyleButton } from "./DefaultButtons/ToggledStyleButton"; import { BlockTypeDropdown } from "./DefaultDropdowns/BlockTypeDropdown"; -import Tippy from "@tippyjs/react"; export const FormattingToolbarOld = (props: { editor: BlockNoteEditor; @@ -47,36 +47,33 @@ export const FormattingToolbarOld = (props: { export const FormattingToolbar = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState< - Omit | undefined - >(); - // Since we're using Tippy, we don't want to trigger re-renders when only the - // reference position changes. So we store it in a ref instead of state. - const referenceClientRect = useRef(); - + const [state, setState] = useState(); useEffect(() => { - createFormattingToolbar(props.editor, ({ referencePos, ...state }) => { - setState(state); - referenceClientRect.current = referencePos; + return createFormattingToolbar(props.editor, (state) => { + setState({ ...state }); }); }, [props.editor]); - const getReferenceClientRect = useCallback( - () => referenceClientRect.current!, - [referenceClientRect] - ); + const getReferenceClientRect = useMemo(() => { + // TODO: test + console.log( + "new reference pos TOOLBAR, this should only be triggered when selection changes" + ); + if (!state?.referencePos) { + return undefined; + } + return () => state.referencePos; + }, [state?.referencePos]); return ( } - getReferenceClientRect={ - referenceClientRect.current && getReferenceClientRect - } + getReferenceClientRect={getReferenceClientRect} interactive={true} visible={state?.show || false} animation={"fade"} - placement={"top-start"} - /> + placement={"top-start"}> +
+ ); }; diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx index 1dbf618c13..89e6b61e68 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx @@ -1,15 +1,15 @@ -import { useCallback, useEffect, useRef, useState } from "react"; -import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; -import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; -import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; -import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; import { BlockNoteEditor, BlockSchema, - createHyperlinkToolbar, HyperlinkToolbarState, + createHyperlinkToolbar, } from "@blocknote/core"; import Tippy from "@tippyjs/react"; +import { useEffect, useMemo, useState } from "react"; +import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; +import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; +import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; +import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; // import rootStyles from "../../../root.module.css"; /** @@ -60,37 +60,33 @@ export const HyperlinkToolbarOld = ( export const HyperlinkToolbar = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState< - Omit | undefined - >(); - // Since we're using Tippy, we don't want to trigger re-renders when only the - // reference position changes. So we store it in a ref instead of state. - const referenceClientRect = useRef(); + const [state, setState] = useState(); useEffect(() => { - createHyperlinkToolbar(props.editor, ({ referencePos, ...state }) => { + return createHyperlinkToolbar(props.editor, ({ ...state }) => { setState(state); - referenceClientRect.current = referencePos; }); }, [props.editor]); - const getReferenceClientRect = useCallback( - () => referenceClientRect.current!, - [referenceClientRect] - ); + const getReferenceClientRect = useMemo(() => { + // TODO: test and remove + console.log("new reference pos for HYPERLINKTOOLBAR"); + if (!state?.referencePos) { + return undefined; + } + return () => state.referencePos; + }, [state?.referencePos]); return ( } - getReferenceClientRect={ - referenceClientRect.current && getReferenceClientRect - } + getReferenceClientRect={getReferenceClientRect} interactive={true} visible={state?.show || false} animation={"fade"} - placement={"top-start"} - /> + placement={"top-start"}> +
+ ); }; diff --git a/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx b/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx index 9e8e5ff474..f10591db8c 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; diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index c34235c1ba..65638b4224 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -1,12 +1,17 @@ -import { BlockNoteEditor, BlockSchema, createSlashMenu } from "@blocknote/core"; +import { + BlockNoteEditor, + BlockSchema, + DefaultBlockSchema, + SuggestionsMenuState, + createSlashMenu, +} from "@blocknote/core"; import { Menu, createStyles } from "@mantine/core"; +import Tippy from "@tippyjs/react"; import * as _ from "lodash"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; -import { SlashMenuItem } from "./SlashMenuItem"; -import Tippy from "@tippyjs/react"; -import { DefaultBlockSchema, SuggestionsMenuState } from "@blocknote/core"; import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; +import { SlashMenuItem } from "./SlashMenuItem"; export function SlashMenuOld( props: Omit< @@ -71,23 +76,14 @@ export function SlashMenuOld( export const SlashMenu = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState< - | Omit< - SuggestionsMenuState>, - "referencePos" - > - | undefined - >(); - // Since we're using Tippy, we don't want to trigger re-renders when only the - // reference position changes. So we store it in a ref instead of state. - const referenceClientRect = useRef(); + const [state, setState] = + useState>>(); useEffect(() => { - createSlashMenu>( + return createSlashMenu>( props.editor as any, - ({ referencePos, ...state }) => { + ({ ...state }) => { setState(state); - referenceClientRect.current = referencePos; }, (query) => defaultReactSlashMenuItems.filter( @@ -96,22 +92,26 @@ export const SlashMenu = (props: { ); }, [props.editor]); - const getReferenceClientRect = useCallback( - () => referenceClientRect.current!, - [referenceClientRect] - ); + const getReferenceClientRect = useMemo(() => { + // TODO: test and remove + console.log( + "new reference pos for SLASHMENU, this should only be triggered when slashmenu position changes" + ); + if (!state?.referencePos) { + return undefined; + } + return () => state.referencePos; + }, [state?.referencePos]); return ( } - getReferenceClientRect={ - referenceClientRect.current && getReferenceClientRect - } + getReferenceClientRect={getReferenceClientRect} interactive={true} visible={state?.show || false} animation={"fade"} - placement={"bottom-start"} - /> + placement={"bottom-start"}> +
+ ); }; 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; From 52d26cd84e2d65676d21c9b548aa9bc57ade9a69 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 12 Jul 2023 19:18:37 +0200 Subject: [PATCH 14/42] Major cleanup for menus & toolbars --- packages/core/src/BlockNoteEditor.ts | 8 ++ .../DraggableBlocks/DraggableBlocksPlugin.ts | 107 +++++++++--------- .../FormattingToolbarPlugin.ts | 47 +++++--- .../HyperlinkToolbarPlugin.ts | 86 +++++++------- .../extensions/SlashMenu/SlashMenuPlugin.ts | 6 +- packages/core/src/index.ts | 2 +- ...EditorElement.ts => BaseUiElementTypes.ts} | 4 + .../plugins/suggestion/SuggestionPlugin.ts | 69 ++++++++--- packages/react/src/BlockNoteView.tsx | 3 +- .../components/BlockSideMenu.tsx | 83 ++++++++------ .../DefaultButtons/BlockColorsButton.tsx | 1 - .../DefaultButtons/RemoveBlockButton.tsx | 1 - .../components/DragHandleMenu.tsx | 1 - .../components/DragHandleMenuItem.tsx | 19 +--- .../DefaultButtons/ColorStyleButton.tsx | 37 ++++-- .../DefaultButtons/CreateLinkButton.tsx | 23 +++- .../DefaultButtons/NestBlockButtons.tsx | 28 ++++- .../DefaultButtons/TextAlignButton.tsx | 26 ++++- .../DefaultButtons/ToggledStyleButton.tsx | 11 +- .../DefaultDropdowns/BlockTypeDropdown.tsx | 15 ++- .../components/FormattingToolbar.tsx | 41 ++++--- .../components/HyperlinkToolbar.tsx | 83 ++++++++++---- .../Toolbar/components/Toolbar.tsx | 20 +++- .../Toolbar/components/ToolbarDropdown.tsx | 6 +- .../src/SlashMenu/components/SlashMenu.tsx | 73 +++++++++--- packages/react/src/hooks/useBlockNote.ts | 6 - .../react/src/hooks/useEditorContentChange.ts | 15 +++ packages/react/src/index.ts | 2 + 28 files changed, 547 insertions(+), 276 deletions(-) rename packages/core/src/shared/{EditorElement.ts => BaseUiElementTypes.ts} (54%) create mode 100644 packages/react/src/hooks/useEditorContentChange.ts diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index bad71a1f5b..c19b0fbe0e 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -324,6 +324,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/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index 6beed395a8..c39b45a961 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -5,7 +5,10 @@ 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/EditorElement"; +import { + BaseUiElementCallbacks, + BaseUiElementState, +} from "../../shared/BaseUiElementTypes"; import { Block, BlockSchema } from "../Blocks/api/blockTypes"; import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; @@ -16,20 +19,27 @@ const serializeForClipboard = (pv as any).__serializeForClipboard; let dragImageElement: Element | undefined; -// TODO: I think freezeMenu, unfreezeMenu, blockDragStart, blockDragEnd are not "state", but -// but actions that should be for example returned from createSideMenu -export type SideMenuState = BaseUiElementState & { - block: Block; - +export type SideMenuCallbacks = BaseUiElementCallbacks & { + // If the block is empty, opens the slash menu. If the block has content, + // creates a new block below and opens the slash menu in it. addBlock: () => void; + // Freezes/unfreezes the side menu. When frozen, the side menu will stay + // attached to the same block regardless of which block is hovered by the + // mouse cursor. freezeMenu: () => void; unfreezeMenu: () => void; + // Handles drag & drop events for blocks. blockDragStart: (event: DragEvent) => void; blockDragEnd: () => void; }; +export type SideMenuState = BaseUiElementState & { + // The block that the side menu is attached to. + block: Block; +}; + function getDraggableBlockFromCoords( coords: { left: number; top: number }, view: EditorView @@ -234,6 +244,7 @@ function dragStart(e: DragEvent, view: EditorView) { export class SideMenuView implements PluginView { editor: BlockNoteEditor; + private sideMenuState?: SideMenuState; public updateSideMenu: () => void; @@ -252,7 +263,7 @@ export class SideMenuView implements PluginView { constructor( editor: BlockNoteEditor, - updateSideMenu: (sideMenu: SideMenuState) => void + updateSideMenu: (sideMenuState: SideMenuState) => void ) { this.editor = editor; this.horizontalPosAnchoredAtRoot = true; @@ -434,7 +445,7 @@ export class SideMenuView implements PluginView { coords, this.editor._tiptapEditor.view ); - console.log(block); + // Closes the menu if the mouse cursor is beyond the editor vertically. if (!block || !this.editor.isEditable) { if (this.sideMenuState?.show) { @@ -451,11 +462,7 @@ export class SideMenuView implements PluginView { this.hoveredBlock?.hasAttribute("data-id") && this.hoveredBlock?.getAttribute("data-id") === block.id ) { - // TODO: this doesn't seem right - if (this.sideMenuState?.show) { - this.sideMenuState.show = true; - this.updateSideMenu(); - } + return; } this.hoveredBlock = block.node; @@ -471,48 +478,20 @@ export class SideMenuView implements PluginView { if (this.editor.isEditable) { const blockContentBoundingBox = blockContent.getBoundingClientRect(); - if (!this.sideMenuState) { - 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")! - )!, - addBlock: () => this.addBlock(), - blockDragStart: (event: DragEvent) => { - // Sets isDragging when dragging blocks. - this.isDragging = true; - dragStart(event, this.editor._tiptapEditor.view); - }, - blockDragEnd: () => unsetDragImage(), - freezeMenu: () => { - this.menuFrozen = true; - }, - unfreezeMenu: () => { - this.menuFrozen = false; - }, - }; - } else { - this.sideMenuState.show = true; - this.sideMenuState.referencePos = new DOMRect( + this.sideMenuState = { + show: true, + referencePos: new DOMRect( this.horizontalPosAnchoredAtRoot ? this.horizontalPosAnchor : blockContentBoundingBox.x, blockContentBoundingBox.y, blockContentBoundingBox.width, blockContentBoundingBox.height - ); - this.sideMenuState.block = this.editor.getBlock( + ), + block: this.editor.getBlock( this.hoveredBlock!.getAttribute("data-id")! - )!; - } + )!, + }; this.updateSideMenu(); } @@ -614,19 +593,41 @@ export class SideMenuView implements PluginView { } export const sideMenuPluginKey = new PluginKey("SideMenuPlugin"); -export const createSideMenu = ( +export function createSideMenu( editor: BlockNoteEditor, updateSideMenu: (sideMenuState: SideMenuState) => void -) => { +): SideMenuCallbacks { + let sideMenuView: SideMenuView; + editor._tiptapEditor.registerPlugin( new Plugin({ key: sideMenuPluginKey, - view: () => new SideMenuView(editor, updateSideMenu), + view: () => { + if (sideMenuView) { + sideMenuView.destroy(); + } + + sideMenuView = new SideMenuView(editor, updateSideMenu); + return sideMenuView; + }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (sideMenuPlugin, plugins) => { plugins.unshift(sideMenuPlugin); return plugins; } ); - return () => editor._tiptapEditor.unregisterPlugin(sideMenuPluginKey); -}; + + return { + addBlock: () => sideMenuView.addBlock(), + blockDragStart: (event: DragEvent) => { + sideMenuView.isDragging = true; + dragStart(event, sideMenuView.editor._tiptapEditor.view); + }, + blockDragEnd: () => unsetDragImage(), + freezeMenu: () => (sideMenuView.menuFrozen = true), + unfreezeMenu: () => (sideMenuView.menuFrozen = false), + destroy: () => editor._tiptapEditor.unregisterPlugin(sideMenuPluginKey), + }; +} diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 8b456a4ecb..861cd30b28 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -6,7 +6,14 @@ import { } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; -import { BaseUiElementState, BlockNoteEditor, BlockSchema } from "../.."; +import { + BaseUiElementCallbacks, + BaseUiElementState, + BlockNoteEditor, + BlockSchema, +} from "../.."; + +export type FormattingToolbarCallbacks = BaseUiElementCallbacks; export type FormattingToolbarState = BaseUiElementState; @@ -162,16 +169,10 @@ export class FormattingToolbarView { !this.preventShow && (shouldShow || this.preventHide) ) { - if (!this.formattingToolbarState) { - this.formattingToolbarState = { - show: true, - referencePos: this.getSelectionBoundingBox(), - }; - } else { - this.formattingToolbarState.show = true; - this.formattingToolbarState.referencePos = - this.getSelectionBoundingBox(); - } + this.formattingToolbarState = { + show: true, + referencePos: this.getSelectionBoundingBox(), + }; this.updateFormattingToolbar(); @@ -231,22 +232,34 @@ export const createFormattingToolbar = ( updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState ) => void -) => { +): FormattingToolbarCallbacks => { + let formattingToolbarView: FormattingToolbarView; + editor._tiptapEditor.registerPlugin( new Plugin({ key: formattingToolbarPluginKey, - view: () => - new FormattingToolbarView( + view: () => { + if (formattingToolbarView) { + formattingToolbarView.destroy(); + } + + formattingToolbarView = new FormattingToolbarView( editor, editor._tiptapEditor.view, updateFormattingToolbar - ), + ); + return formattingToolbarView; + }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (formattingToolbarPlugin, plugins) => { plugins.unshift(formattingToolbarPlugin); return plugins; } ); - return () => - editor._tiptapEditor.unregisterPlugin(formattingToolbarPluginKey); + return { + destroy: () => + editor._tiptapEditor.unregisterPlugin(formattingToolbarPluginKey), + }; }; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index ae40246b03..a6fdca70ea 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -2,16 +2,28 @@ import { getMarkRange, posToDOMRect, Range } from "@tiptap/core"; import { Mark } from "prosemirror-model"; import { Plugin, PluginKey } from "prosemirror-state"; import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BaseUiElementState } from "../../shared/EditorElement"; +import { + BaseUiElementCallbacks, + BaseUiElementState, +} from "../../shared/BaseUiElementTypes"; import { BlockSchema } from "../Blocks/api/blockTypes"; -export type HyperlinkToolbarState = BaseUiElementState & { +export type HyperlinkToolbarCallbacks = BaseUiElementCallbacks & { + // Updates or deletes the hovered hyperlink. editHyperlink: (url: string, text: string) => void; deleteHyperlink: () => void; - toolbarMouseEnter: () => void; - toolbarMouseLeave: () => void; + // When hovering on/off hyperlinks using the mouse cursor, the hyperlink + // toolbar will open & close with a delay. These functions start & stop the + // delay timer, and should be used for when the mouse cursor enters & exits + // the hyperlink toolbar. + startHideTimer: () => void; + stopHideTimer: () => void; +}; +export type HyperlinkToolbarState = BaseUiElementState & { + // The hovered hyperlink's URL, and the text it's displayed with in the + // editor. url: string; text: string; }; @@ -128,8 +140,8 @@ class HyperlinkToolbarView { event.target && // The clicked element is not the editor. !( - editorWrapper === (event.relatedTarget as Node) || - editorWrapper.contains(event.relatedTarget as Node) + editorWrapper === (event.target as Node) || + editorWrapper.contains(event.target as Node) ) ) { if (this.hyperlinkToolbarState?.show) { @@ -242,38 +254,19 @@ class HyperlinkToolbarView { } if (this.hyperlinkMark && this.editor.isEditable) { - if (!this.hyperlinkToolbarState) { - this.hyperlinkToolbarState = { - show: true, - referencePos: posToDOMRect( - this.editor._tiptapEditor.view, - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ), - url: this.hyperlinkMark!.attrs.href, - text: this.editor._tiptapEditor.view.state.doc.textBetween( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ), - editHyperlink: this.editHyperlink, - deleteHyperlink: this.deleteHyperlink, - toolbarMouseEnter: this.stopMenuUpdateTimer, - toolbarMouseLeave: this.startMenuUpdateTimer, - }; - } else { - this.hyperlinkToolbarState.show = true; - this.hyperlinkToolbarState.referencePos = posToDOMRect( + this.hyperlinkToolbarState = { + show: true, + referencePos: posToDOMRect( this.editor._tiptapEditor.view, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to - ); - this.hyperlinkToolbarState.url = this.hyperlinkMark!.attrs.href; - this.hyperlinkToolbarState.text = - this.editor._tiptapEditor.view.state.doc.textBetween( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ); - } + ), + url: this.hyperlinkMark!.attrs.href, + text: this.editor._tiptapEditor.view.state.doc.textBetween( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ), + }; this.updateHyperlinkToolbar(); return; @@ -308,16 +301,33 @@ export const hyperlinkToolbarPluginKey = new PluginKey( export const createHyperlinkToolbar = ( editor: BlockNoteEditor, updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void -) => { +): HyperlinkToolbarCallbacks => { + let hyperlinkToolbarView: HyperlinkToolbarView; + editor._tiptapEditor.registerPlugin( new Plugin({ key: hyperlinkToolbarPluginKey, - view: () => new HyperlinkToolbarView(editor, updateHyperlinkToolbar), + view: () => { + hyperlinkToolbarView = new HyperlinkToolbarView( + editor, + updateHyperlinkToolbar + ); + return hyperlinkToolbarView; + }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (hyperlinkToolbarPlugin, plugins) => { plugins.unshift(hyperlinkToolbarPlugin); return plugins; } ); - return () => editor._tiptapEditor.unregisterPlugin(hyperlinkToolbarPluginKey); + return { + editHyperlink: (url, text) => hyperlinkToolbarView.editHyperlink(url, text), + deleteHyperlink: () => hyperlinkToolbarView.deleteHyperlink(), + startHideTimer: () => hyperlinkToolbarView.startMenuUpdateTimer(), + stopHideTimer: () => hyperlinkToolbarView.stopMenuUpdateTimer(), + destroy: () => + editor._tiptapEditor.unregisterPlugin(hyperlinkToolbarPluginKey), + }; }; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index 6c964f9433..789177ef2f 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -3,6 +3,7 @@ import { BlockNoteEditor } from "../../BlockNoteEditor"; import { createSuggestionPlugin, SuggestionsMenuState, + SuggestionsPluginCallbacks, } from "../../shared/plugins/suggestion/SuggestionPlugin"; import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; @@ -16,8 +17,8 @@ export const createSlashMenu = < slashMenuState: SuggestionsMenuState ) => void, items: (query: string) => SlashMenuItem[] -) => { - createSuggestionPlugin( +): SuggestionsPluginCallbacks => { + return createSuggestionPlugin( slashMenuPluginKey, "/", editor, @@ -25,5 +26,4 @@ export const createSlashMenu = < ({ item, editor }) => item.execute(editor), items ); - return () => editor._tiptapEditor.unregisterPlugin(slashMenuPluginKey); }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4f63f83581..9ece264c0a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -12,7 +12,7 @@ export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; export * from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; export * from "./shared/plugins/suggestion/SuggestionPlugin"; export * from "./extensions/SlashMenu/SlashMenuPlugin"; -export * from "./shared/EditorElement"; +export * from "./shared/BaseUiElementTypes"; export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; diff --git a/packages/core/src/shared/EditorElement.ts b/packages/core/src/shared/BaseUiElementTypes.ts similarity index 54% rename from packages/core/src/shared/EditorElement.ts rename to packages/core/src/shared/BaseUiElementTypes.ts index a3f6599f87..4ca4cc9f4c 100644 --- a/packages/core/src/shared/EditorElement.ts +++ b/packages/core/src/shared/BaseUiElementTypes.ts @@ -1,3 +1,7 @@ +export type BaseUiElementCallbacks = { + destroy: () => void; +}; + export type BaseUiElementState = { show: boolean; referencePos: DOMRect; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 9e34dd1df7..e2c0f47da5 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -3,13 +3,23 @@ import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; -import { BaseUiElementState } from "../../EditorElement"; +import { + BaseUiElementCallbacks, + BaseUiElementState, +} from "../../BaseUiElementTypes"; import { SuggestionItem } from "./SuggestionItem"; +export type SuggestionsPluginCallbacks = + BaseUiElementCallbacks & { + // The function to execute when selecting a suggested item. + itemCallback: (item: T) => void; + }; + export type SuggestionsMenuState = BaseUiElementState & { + // The suggested items to display. items: T[]; - itemCallback: (item: T) => void; + // The index of the suggested item that's currently hovered by the keyboard. keyboardHoveredItemIndex: number; }; @@ -102,29 +112,22 @@ class SuggestionPluginView< if (stopped || !this.editor.isEditable) { this.suggestionsMenuState!.show = false; this.updateSuggestionsMenu(); + + return; } const decorationNode = document.querySelector( `[data-decoration-id="${this.pluginState.decorationId}"]` ); - if (changed) { - this.suggestionsMenuState!.referencePos = - decorationNode!.getBoundingClientRect(); - this.suggestionsMenuState!.items = this.pluginState.items; - this.suggestionsMenuState!.keyboardHoveredItemIndex = - this.pluginState.keyboardHoveredItemIndex!; - this.updateSuggestionsMenu(); - } - - if (started && this.editor.isEditable) { + if (this.editor.isEditable) { this.suggestionsMenuState = { show: true, referencePos: decorationNode!.getBoundingClientRect(), items: this.pluginState.items, - itemCallback: (item: T) => this.itemCallback(item), keyboardHoveredItemIndex: this.pluginState.keyboardHoveredItemIndex!, }; + this.updateSuggestionsMenu(); } } @@ -192,12 +195,14 @@ export function createSuggestionPlugin< editor: BlockNoteEditor; }) => void = () => {}, items: (query: string) => T[] = () => [] -) { +): SuggestionsPluginCallbacks { // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); } + let suggestionsPluginView: SuggestionPluginView; + const deactivate = (view: EditorView) => { view.dispatch(view.state.tr.setMeta(pluginKey, { deactivate: true })); }; @@ -206,8 +211,8 @@ export function createSuggestionPlugin< new Plugin({ key: pluginKey, - view: () => - new SuggestionPluginView( + view: () => { + suggestionsPluginView = new SuggestionPluginView( editor, pluginKey, (props: { item: T; editor: BlockNoteEditor }) => { @@ -215,7 +220,9 @@ export function createSuggestionPlugin< onSelectItem(props); }, updateSuggestionsMenu - ), + ); + return suggestionsPluginView; + }, state: { // Initialize the plugin's internal state. @@ -295,7 +302,8 @@ export function createSuggestionPlugin< return getDefaultPluginState(); } - // Updates keyboardHoveredItemIndex if necessary. + // 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 @@ -311,6 +319,8 @@ export function createSuggestionPlugin< } next.keyboardHoveredItemIndex = newIndex; + } else if (oldState.selection.from !== newState.selection.from) { + next.keyboardHoveredItemIndex = 0; } return next; @@ -446,9 +456,32 @@ export function createSuggestionPlugin< }, }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (suggestionPlugin, plugins) => { plugins.unshift(suggestionPlugin); return plugins; } ); + + return { + destroy: () => editor._tiptapEditor.unregisterPlugin(pluginKey), + itemCallback: (item: T) => { + editor._tiptapEditor + .chain() + .focus() + .deleteRange({ + from: + suggestionsPluginView.pluginState.queryStartPos! - + suggestionsPluginView.pluginState.triggerCharacter!.length, + to: editor._tiptapEditor.state.selection.from, + }) + .run(); + + onSelectItem({ + item: item, + editor: editor, + }); + }, + }; } diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index b8932b33ef..c094ff0bd8 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -12,11 +12,10 @@ export function BlockNoteView(props: { }) { return ( - + - diff --git a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx index be61ea5b4a..c93e7a274c 100644 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx @@ -1,7 +1,11 @@ import { + BaseUiElementCallbacks, + BaseUiElementState, + Block, BlockNoteEditor, BlockSchema, createSideMenu, + SideMenuCallbacks, SideMenuState, } from "@blocknote/core"; import { ActionIcon, Group, Menu } from "@mantine/core"; @@ -12,9 +16,10 @@ import { MdDragIndicator } from "react-icons/md"; import { DefaultDragHandleMenu } from "./DefaultDragHandleMenu"; export const BlockSideMenuOld = ( - props: Omit, "referencePos"> & { - editor: BlockNoteEditor; - } + props: Omit & + Omit, keyof BaseUiElementState> & { + editor: BlockNoteEditor; + } ) => { const dragHandleRef = useRef(null); @@ -34,29 +39,17 @@ export const BlockSideMenuOld = ( return; }, [props.blockDragEnd, props.blockDragStart]); - const closeMenu = () => { - // TODO: I don't think this is needed / used? - // props.unfreezeMenu(); - }; - const DragHandleMenu = DefaultDragHandleMenu; return ( - { - { - props.addBlock(); - }} - /> - } + props.freezeMenu()} - onClose={() => props.unfreezeMenu()} + onOpen={props.freezeMenu} + onClose={props.unfreezeMenu} width={100} position={"left"}> @@ -66,11 +59,7 @@ export const BlockSideMenuOld = (
- +
); @@ -79,33 +68,57 @@ export const BlockSideMenuOld = ( export const SideMenu = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState>(); + const [show, setShow] = useState(false); + const [block, setBlock] = useState>(); + + const referencePos = useRef(); + const callbacks = useRef(); useEffect(() => { - return createSideMenu(props.editor, (state) => { - setState({ ...state }); + callbacks.current = createSideMenu(props.editor, (sideMenuState) => { + setShow(sideMenuState.show); + setBlock(sideMenuState.block); + + referencePos.current = sideMenuState.referencePos; }); + + return callbacks.current!.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test - console.log( - "new reference pos, this should only be triggered when hovering a new block" - ); - if (!state?.referencePos) { + if (!referencePos.current) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + + return () => referencePos.current!; + }, [referencePos.current]); + + const sideMenu = useMemo(() => { + if (!block || !callbacks.current) { + return null; + } + + return ( + + ); + }, [block, props.editor]); return ( below + moved to // appendTo={props.editor._tiptapEditor.view.dom.parentElement!} - content={} + content={sideMenu} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + visible={show} animation={"fade"} offset={offset} placement={"left"} diff --git a/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx b/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx index 3fc435b275..651c6fd365 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx +++ b/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx @@ -38,7 +38,6 @@ export const BlockColorsButton = ( return ( diff --git a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx b/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx index 70d9cd60ab..bbd5e2331c 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx +++ b/packages/react/src/BlockSideMenu/components/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/DragHandleMenu.tsx b/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx index 816f3ed344..6da4a84590 100644 --- a/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx @@ -5,7 +5,6 @@ import { Block, BlockSchema, BlockNoteEditor } from "@blocknote/core"; export type DragHandleMenuProps = { editor: BlockNoteEditor; block: Block; - closeMenu: () => void; }; export const DragHandleMenu = (props: { children: ReactNode }) => { diff --git a/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx b/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx index f8ce980238..e5da796147 100644 --- a/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx +++ b/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx @@ -1,18 +1,9 @@ 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} - ; +export const DragHandleMenuItem = ( + props: PolymorphicComponentProps<"button"> +) => { + const { children, ...remainingProps } = props; + return {children}; }; 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..6e9210f03f 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 { useEditorContentChange } from "../../../hooks/useEditorContentChange"; export const CreateLinkButton = (props: { editor: BlockNoteEditor; }) => { + const [url, setUrl] = useState( + props.editor.getSelectedLinkUrl() || "" + ); + const [text, setText] = useState( + props.editor.getSelectedText() || "" + ); + + useEditorContentChange(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); + } + }); + const show = useMemo(() => { const selection = props.editor.getSelection(); @@ -77,10 +96,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..618f367cc5 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx @@ -9,6 +9,8 @@ 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"; const shortcuts: Record = { bold: "Mod+B", @@ -30,6 +32,13 @@ 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()); + }); const toggleStyle = (style: ToggledStyle) => { props.editor.focus(); @@ -39,7 +48,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/FormattingToolbar.tsx index 4047bb134b..0baf0b17f3 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx @@ -1,12 +1,13 @@ import { BlockNoteEditor, BlockSchema, - FormattingToolbarState, createFormattingToolbar, + FormattingToolbarCallbacks, } from "@blocknote/core"; import Tippy from "@tippyjs/react"; -import { useEffect, useMemo, useState } from "react"; +import { sticky } from "tippy.js"; +import { useEffect, useMemo, useRef, useState } from "react"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ColorStyleButton } from "./DefaultButtons/ColorStyleButton"; import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; @@ -47,32 +48,42 @@ export const FormattingToolbarOld = (props: { export const FormattingToolbar = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState(); + const [show, setShow] = useState(false); + + const referencePos = useRef(); + const callbacks = useRef(); + useEffect(() => { - return createFormattingToolbar(props.editor, (state) => { - setState({ ...state }); + callbacks.current = createFormattingToolbar(props.editor, (state) => { + setShow(state.show); + + referencePos.current = state.referencePos; }); + + return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test - console.log( - "new reference pos TOOLBAR, this should only be triggered when selection changes" - ); - if (!state?.referencePos) { + if (!referencePos) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + return () => referencePos.current!; + }, [referencePos.current]); + + const formattingToolbar = useMemo(() => { + return ; + }, [props.editor]); return ( } + content={formattingToolbar} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + visible={show} animation={"fade"} - placement={"top-start"}> + placement={"top-start"} + sticky={true} + plugins={[sticky]}>
); diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx index 89e6b61e68..e87aa092ec 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx @@ -3,9 +3,12 @@ import { BlockSchema, HyperlinkToolbarState, createHyperlinkToolbar, + HyperlinkToolbarCallbacks, + BaseUiElementState, + BaseUiElementCallbacks, } from "@blocknote/core"; import Tippy from "@tippyjs/react"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; @@ -17,26 +20,32 @@ import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlink * Renders a toolbar that appears on hyperlink hover. */ export const HyperlinkToolbarOld = ( - props: Omit + props: Omit & + Omit & { + isEditing: boolean; + setIsEditing: (isEditing: boolean) => void; + } ) => { - const [isEditing, setIsEditing] = useState(false); - - if (isEditing) { + if (props.isEditing) { return ( props.editHyperlink(url, text)} /> ); } return ( - + event.preventDefault()} + onMouseEnter={props.stopHideTimer} + onMouseLeave={props.startHideTimer}> setIsEditing(true)}> + onClick={() => props.setIsEditing(true)}> Edit Link (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState(); + const [show, setShow] = useState(false); + const [url, setUrl] = useState(); + const [text, setText] = useState(); + + const [isEditing, setIsEditing] = useState(false); + + const referencePos = useRef(); + const callbacks = useRef(); useEffect(() => { - return createHyperlinkToolbar(props.editor, ({ ...state }) => { - setState(state); - }); + callbacks.current = createHyperlinkToolbar( + props.editor, + (hyperlinkToolbarState) => { + setShow(hyperlinkToolbarState.show); + setUrl(hyperlinkToolbarState.url); + setText(hyperlinkToolbarState.text); + + referencePos.current = hyperlinkToolbarState.referencePos; + } + ); + + return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test and remove - console.log("new reference pos for HYPERLINKTOOLBAR"); - if (!state?.referencePos) { + if (!referencePos.current) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + + return () => referencePos.current!; + }, [referencePos.current]); + + const hyperlinkToolbar = useMemo(() => { + if (!url || !text || !callbacks.current) { + return null; + } + + return ( + + ); + }, [isEditing, text, url]); return ( } + onHidden={() => setIsEditing(false)} + content={hyperlinkToolbar} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + 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 f10591db8c..8d7a6ca02d 100644 --- a/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx +++ b/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx @@ -27,7 +27,11 @@ export function ToolbarDropdown(props: ToolbarDropdownProps) { return ( - + {props.items.map((item) => ( diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index 65638b4224..23fd40c6e8 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -4,20 +4,27 @@ import { DefaultBlockSchema, SuggestionsMenuState, createSlashMenu, + SuggestionsPluginCallbacks, + BaseUiElementState, + BaseUiElementCallbacks, } from "@blocknote/core"; import { Menu, createStyles } from "@mantine/core"; import Tippy from "@tippyjs/react"; import * as _ from "lodash"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; import { SlashMenuItem } from "./SlashMenuItem"; export function SlashMenuOld( props: Omit< - SuggestionsMenuState>, - "referencePos" - > + SuggestionsPluginCallbacks>, + keyof BaseUiElementCallbacks + > & + Omit< + SuggestionsMenuState>, + keyof BaseUiElementState + > ) { const { classes } = createStyles({ root: {} })(undefined, { name: "SlashMenu", @@ -76,39 +83,69 @@ export function SlashMenuOld( export const SlashMenu = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = - useState>>(); + const [show, setShow] = useState(false); + const [items, setItems] = + useState[]>(); + const [keyboardHoveredItemIndex, setKeyboardHoveredItemIndex] = + useState(); + + const referencePos = useRef(); + const callbacks = + useRef< + SuggestionsPluginCallbacks> + >(); useEffect(() => { - return createSlashMenu>( + callbacks.current = createSlashMenu>( props.editor as any, - ({ ...state }) => { - setState(state); + (slashMenuState) => { + setShow(slashMenuState.show); + setItems(slashMenuState.items); + setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); + + referencePos.current = slashMenuState.referencePos; }, (query) => defaultReactSlashMenuItems.filter( (cmd: ReactSlashMenuItem) => cmd.match(query) ) ); + + return callbacks.current!.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test and remove - console.log( - "new reference pos for SLASHMENU, this should only be triggered when slashmenu position changes" - ); - if (!state?.referencePos) { + if (!referencePos.current) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + + return () => referencePos.current!; + }, [referencePos.current]); + + const slashMenu = useMemo(() => { + if ( + !items || + keyboardHoveredItemIndex === undefined || + !callbacks.current + ) { + return null; + } + + return ( + callbacks.current!.itemCallback(item)} + keyboardHoveredItemIndex={keyboardHoveredItemIndex!} + /> + ); + }, [items, keyboardHoveredItemIndex]); return ( } + content={slashMenu} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + visible={show} animation={"fade"} placement={"bottom-start"}>
diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index abbc1e7ea5..439f013b4e 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -36,12 +36,6 @@ function initEditor( ...options, }; - if (newOptions.customElements && newOptions.uiFactories) { - console.warn( - "BlockNote editor initialized with both `customElements` and `uiFactories` options, prioritizing `uiFactories`." - ); - } - console.log("create new blocknote instance"); const instance = new BlockNoteEditor( newOptions as Partial> 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/index.ts b/packages/react/src/index.ts index 02a122f441..a2d9167f33 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -20,3 +20,5 @@ export * from "./SlashMenu/components/SlashMenu"; export * from "./SlashMenu/defaultReactSlashMenuItems"; export * from "./hooks/useBlockNote"; export * from "./hooks/useEditorForceUpdate"; +export * from "./hooks/useEditorContentChange"; +export * from "./hooks/useEditorSelectionChange"; From 5547704b2c890287ba5bceffa5faf7aa42547a6b Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 12 Jul 2023 19:18:37 +0200 Subject: [PATCH 15/42] Major cleanup for menus & toolbars --- packages/core/src/BlockNoteEditor.ts | 8 ++ .../DraggableBlocks/DraggableBlocksPlugin.ts | 107 +++++++++--------- .../FormattingToolbarPlugin.ts | 47 +++++--- .../HyperlinkToolbarPlugin.ts | 86 +++++++------- .../extensions/SlashMenu/SlashMenuPlugin.ts | 6 +- packages/core/src/index.ts | 2 +- ...EditorElement.ts => BaseUiElementTypes.ts} | 4 + .../plugins/suggestion/SuggestionPlugin.ts | 69 ++++++++--- packages/react/src/BlockNoteView.tsx | 3 +- .../components/BlockSideMenu.tsx | 83 ++++++++------ .../DefaultButtons/BlockColorsButton.tsx | 1 - .../DefaultButtons/RemoveBlockButton.tsx | 1 - .../components/DragHandleMenu.tsx | 1 - .../components/DragHandleMenuItem.tsx | 19 +--- .../DefaultButtons/ColorStyleButton.tsx | 37 ++++-- .../DefaultButtons/CreateLinkButton.tsx | 23 +++- .../DefaultButtons/NestBlockButtons.tsx | 28 ++++- .../DefaultButtons/TextAlignButton.tsx | 26 ++++- .../DefaultButtons/ToggledStyleButton.tsx | 11 +- .../DefaultDropdowns/BlockTypeDropdown.tsx | 15 ++- .../components/FormattingToolbar.tsx | 41 ++++--- .../components/HyperlinkToolbar.tsx | 83 ++++++++++---- .../Toolbar/components/Toolbar.tsx | 20 +++- .../Toolbar/components/ToolbarDropdown.tsx | 6 +- .../src/SlashMenu/components/SlashMenu.tsx | 73 +++++++++--- packages/react/src/hooks/useBlockNote.ts | 6 - .../react/src/hooks/useEditorContentChange.ts | 15 +++ .../src/hooks/useEditorSelectionChange.ts | 15 +++ packages/react/src/index.ts | 2 + 29 files changed, 562 insertions(+), 276 deletions(-) rename packages/core/src/shared/{EditorElement.ts => BaseUiElementTypes.ts} (54%) create mode 100644 packages/react/src/hooks/useEditorContentChange.ts create mode 100644 packages/react/src/hooks/useEditorSelectionChange.ts diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index bad71a1f5b..c19b0fbe0e 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -324,6 +324,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/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index 6beed395a8..c39b45a961 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -5,7 +5,10 @@ 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/EditorElement"; +import { + BaseUiElementCallbacks, + BaseUiElementState, +} from "../../shared/BaseUiElementTypes"; import { Block, BlockSchema } from "../Blocks/api/blockTypes"; import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; @@ -16,20 +19,27 @@ const serializeForClipboard = (pv as any).__serializeForClipboard; let dragImageElement: Element | undefined; -// TODO: I think freezeMenu, unfreezeMenu, blockDragStart, blockDragEnd are not "state", but -// but actions that should be for example returned from createSideMenu -export type SideMenuState = BaseUiElementState & { - block: Block; - +export type SideMenuCallbacks = BaseUiElementCallbacks & { + // If the block is empty, opens the slash menu. If the block has content, + // creates a new block below and opens the slash menu in it. addBlock: () => void; + // Freezes/unfreezes the side menu. When frozen, the side menu will stay + // attached to the same block regardless of which block is hovered by the + // mouse cursor. freezeMenu: () => void; unfreezeMenu: () => void; + // Handles drag & drop events for blocks. blockDragStart: (event: DragEvent) => void; blockDragEnd: () => void; }; +export type SideMenuState = BaseUiElementState & { + // The block that the side menu is attached to. + block: Block; +}; + function getDraggableBlockFromCoords( coords: { left: number; top: number }, view: EditorView @@ -234,6 +244,7 @@ function dragStart(e: DragEvent, view: EditorView) { export class SideMenuView implements PluginView { editor: BlockNoteEditor; + private sideMenuState?: SideMenuState; public updateSideMenu: () => void; @@ -252,7 +263,7 @@ export class SideMenuView implements PluginView { constructor( editor: BlockNoteEditor, - updateSideMenu: (sideMenu: SideMenuState) => void + updateSideMenu: (sideMenuState: SideMenuState) => void ) { this.editor = editor; this.horizontalPosAnchoredAtRoot = true; @@ -434,7 +445,7 @@ export class SideMenuView implements PluginView { coords, this.editor._tiptapEditor.view ); - console.log(block); + // Closes the menu if the mouse cursor is beyond the editor vertically. if (!block || !this.editor.isEditable) { if (this.sideMenuState?.show) { @@ -451,11 +462,7 @@ export class SideMenuView implements PluginView { this.hoveredBlock?.hasAttribute("data-id") && this.hoveredBlock?.getAttribute("data-id") === block.id ) { - // TODO: this doesn't seem right - if (this.sideMenuState?.show) { - this.sideMenuState.show = true; - this.updateSideMenu(); - } + return; } this.hoveredBlock = block.node; @@ -471,48 +478,20 @@ export class SideMenuView implements PluginView { if (this.editor.isEditable) { const blockContentBoundingBox = blockContent.getBoundingClientRect(); - if (!this.sideMenuState) { - 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")! - )!, - addBlock: () => this.addBlock(), - blockDragStart: (event: DragEvent) => { - // Sets isDragging when dragging blocks. - this.isDragging = true; - dragStart(event, this.editor._tiptapEditor.view); - }, - blockDragEnd: () => unsetDragImage(), - freezeMenu: () => { - this.menuFrozen = true; - }, - unfreezeMenu: () => { - this.menuFrozen = false; - }, - }; - } else { - this.sideMenuState.show = true; - this.sideMenuState.referencePos = new DOMRect( + this.sideMenuState = { + show: true, + referencePos: new DOMRect( this.horizontalPosAnchoredAtRoot ? this.horizontalPosAnchor : blockContentBoundingBox.x, blockContentBoundingBox.y, blockContentBoundingBox.width, blockContentBoundingBox.height - ); - this.sideMenuState.block = this.editor.getBlock( + ), + block: this.editor.getBlock( this.hoveredBlock!.getAttribute("data-id")! - )!; - } + )!, + }; this.updateSideMenu(); } @@ -614,19 +593,41 @@ export class SideMenuView implements PluginView { } export const sideMenuPluginKey = new PluginKey("SideMenuPlugin"); -export const createSideMenu = ( +export function createSideMenu( editor: BlockNoteEditor, updateSideMenu: (sideMenuState: SideMenuState) => void -) => { +): SideMenuCallbacks { + let sideMenuView: SideMenuView; + editor._tiptapEditor.registerPlugin( new Plugin({ key: sideMenuPluginKey, - view: () => new SideMenuView(editor, updateSideMenu), + view: () => { + if (sideMenuView) { + sideMenuView.destroy(); + } + + sideMenuView = new SideMenuView(editor, updateSideMenu); + return sideMenuView; + }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (sideMenuPlugin, plugins) => { plugins.unshift(sideMenuPlugin); return plugins; } ); - return () => editor._tiptapEditor.unregisterPlugin(sideMenuPluginKey); -}; + + return { + addBlock: () => sideMenuView.addBlock(), + blockDragStart: (event: DragEvent) => { + sideMenuView.isDragging = true; + dragStart(event, sideMenuView.editor._tiptapEditor.view); + }, + blockDragEnd: () => unsetDragImage(), + freezeMenu: () => (sideMenuView.menuFrozen = true), + unfreezeMenu: () => (sideMenuView.menuFrozen = false), + destroy: () => editor._tiptapEditor.unregisterPlugin(sideMenuPluginKey), + }; +} diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 8b456a4ecb..861cd30b28 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -6,7 +6,14 @@ import { } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; -import { BaseUiElementState, BlockNoteEditor, BlockSchema } from "../.."; +import { + BaseUiElementCallbacks, + BaseUiElementState, + BlockNoteEditor, + BlockSchema, +} from "../.."; + +export type FormattingToolbarCallbacks = BaseUiElementCallbacks; export type FormattingToolbarState = BaseUiElementState; @@ -162,16 +169,10 @@ export class FormattingToolbarView { !this.preventShow && (shouldShow || this.preventHide) ) { - if (!this.formattingToolbarState) { - this.formattingToolbarState = { - show: true, - referencePos: this.getSelectionBoundingBox(), - }; - } else { - this.formattingToolbarState.show = true; - this.formattingToolbarState.referencePos = - this.getSelectionBoundingBox(); - } + this.formattingToolbarState = { + show: true, + referencePos: this.getSelectionBoundingBox(), + }; this.updateFormattingToolbar(); @@ -231,22 +232,34 @@ export const createFormattingToolbar = ( updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState ) => void -) => { +): FormattingToolbarCallbacks => { + let formattingToolbarView: FormattingToolbarView; + editor._tiptapEditor.registerPlugin( new Plugin({ key: formattingToolbarPluginKey, - view: () => - new FormattingToolbarView( + view: () => { + if (formattingToolbarView) { + formattingToolbarView.destroy(); + } + + formattingToolbarView = new FormattingToolbarView( editor, editor._tiptapEditor.view, updateFormattingToolbar - ), + ); + return formattingToolbarView; + }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (formattingToolbarPlugin, plugins) => { plugins.unshift(formattingToolbarPlugin); return plugins; } ); - return () => - editor._tiptapEditor.unregisterPlugin(formattingToolbarPluginKey); + return { + destroy: () => + editor._tiptapEditor.unregisterPlugin(formattingToolbarPluginKey), + }; }; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index ae40246b03..a6fdca70ea 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -2,16 +2,28 @@ import { getMarkRange, posToDOMRect, Range } from "@tiptap/core"; import { Mark } from "prosemirror-model"; import { Plugin, PluginKey } from "prosemirror-state"; import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { BaseUiElementState } from "../../shared/EditorElement"; +import { + BaseUiElementCallbacks, + BaseUiElementState, +} from "../../shared/BaseUiElementTypes"; import { BlockSchema } from "../Blocks/api/blockTypes"; -export type HyperlinkToolbarState = BaseUiElementState & { +export type HyperlinkToolbarCallbacks = BaseUiElementCallbacks & { + // Updates or deletes the hovered hyperlink. editHyperlink: (url: string, text: string) => void; deleteHyperlink: () => void; - toolbarMouseEnter: () => void; - toolbarMouseLeave: () => void; + // When hovering on/off hyperlinks using the mouse cursor, the hyperlink + // toolbar will open & close with a delay. These functions start & stop the + // delay timer, and should be used for when the mouse cursor enters & exits + // the hyperlink toolbar. + startHideTimer: () => void; + stopHideTimer: () => void; +}; +export type HyperlinkToolbarState = BaseUiElementState & { + // The hovered hyperlink's URL, and the text it's displayed with in the + // editor. url: string; text: string; }; @@ -128,8 +140,8 @@ class HyperlinkToolbarView { event.target && // The clicked element is not the editor. !( - editorWrapper === (event.relatedTarget as Node) || - editorWrapper.contains(event.relatedTarget as Node) + editorWrapper === (event.target as Node) || + editorWrapper.contains(event.target as Node) ) ) { if (this.hyperlinkToolbarState?.show) { @@ -242,38 +254,19 @@ class HyperlinkToolbarView { } if (this.hyperlinkMark && this.editor.isEditable) { - if (!this.hyperlinkToolbarState) { - this.hyperlinkToolbarState = { - show: true, - referencePos: posToDOMRect( - this.editor._tiptapEditor.view, - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ), - url: this.hyperlinkMark!.attrs.href, - text: this.editor._tiptapEditor.view.state.doc.textBetween( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ), - editHyperlink: this.editHyperlink, - deleteHyperlink: this.deleteHyperlink, - toolbarMouseEnter: this.stopMenuUpdateTimer, - toolbarMouseLeave: this.startMenuUpdateTimer, - }; - } else { - this.hyperlinkToolbarState.show = true; - this.hyperlinkToolbarState.referencePos = posToDOMRect( + this.hyperlinkToolbarState = { + show: true, + referencePos: posToDOMRect( this.editor._tiptapEditor.view, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to - ); - this.hyperlinkToolbarState.url = this.hyperlinkMark!.attrs.href; - this.hyperlinkToolbarState.text = - this.editor._tiptapEditor.view.state.doc.textBetween( - this.hyperlinkMarkRange!.from, - this.hyperlinkMarkRange!.to - ); - } + ), + url: this.hyperlinkMark!.attrs.href, + text: this.editor._tiptapEditor.view.state.doc.textBetween( + this.hyperlinkMarkRange!.from, + this.hyperlinkMarkRange!.to + ), + }; this.updateHyperlinkToolbar(); return; @@ -308,16 +301,33 @@ export const hyperlinkToolbarPluginKey = new PluginKey( export const createHyperlinkToolbar = ( editor: BlockNoteEditor, updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void -) => { +): HyperlinkToolbarCallbacks => { + let hyperlinkToolbarView: HyperlinkToolbarView; + editor._tiptapEditor.registerPlugin( new Plugin({ key: hyperlinkToolbarPluginKey, - view: () => new HyperlinkToolbarView(editor, updateHyperlinkToolbar), + view: () => { + hyperlinkToolbarView = new HyperlinkToolbarView( + editor, + updateHyperlinkToolbar + ); + return hyperlinkToolbarView; + }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (hyperlinkToolbarPlugin, plugins) => { plugins.unshift(hyperlinkToolbarPlugin); return plugins; } ); - return () => editor._tiptapEditor.unregisterPlugin(hyperlinkToolbarPluginKey); + return { + editHyperlink: (url, text) => hyperlinkToolbarView.editHyperlink(url, text), + deleteHyperlink: () => hyperlinkToolbarView.deleteHyperlink(), + startHideTimer: () => hyperlinkToolbarView.startMenuUpdateTimer(), + stopHideTimer: () => hyperlinkToolbarView.stopMenuUpdateTimer(), + destroy: () => + editor._tiptapEditor.unregisterPlugin(hyperlinkToolbarPluginKey), + }; }; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index 6c964f9433..789177ef2f 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -3,6 +3,7 @@ import { BlockNoteEditor } from "../../BlockNoteEditor"; import { createSuggestionPlugin, SuggestionsMenuState, + SuggestionsPluginCallbacks, } from "../../shared/plugins/suggestion/SuggestionPlugin"; import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; @@ -16,8 +17,8 @@ export const createSlashMenu = < slashMenuState: SuggestionsMenuState ) => void, items: (query: string) => SlashMenuItem[] -) => { - createSuggestionPlugin( +): SuggestionsPluginCallbacks => { + return createSuggestionPlugin( slashMenuPluginKey, "/", editor, @@ -25,5 +26,4 @@ export const createSlashMenu = < ({ item, editor }) => item.execute(editor), items ); - return () => editor._tiptapEditor.unregisterPlugin(slashMenuPluginKey); }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4f63f83581..9ece264c0a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -12,7 +12,7 @@ export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; export * from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; export * from "./shared/plugins/suggestion/SuggestionPlugin"; export * from "./extensions/SlashMenu/SlashMenuPlugin"; -export * from "./shared/EditorElement"; +export * from "./shared/BaseUiElementTypes"; export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; diff --git a/packages/core/src/shared/EditorElement.ts b/packages/core/src/shared/BaseUiElementTypes.ts similarity index 54% rename from packages/core/src/shared/EditorElement.ts rename to packages/core/src/shared/BaseUiElementTypes.ts index a3f6599f87..4ca4cc9f4c 100644 --- a/packages/core/src/shared/EditorElement.ts +++ b/packages/core/src/shared/BaseUiElementTypes.ts @@ -1,3 +1,7 @@ +export type BaseUiElementCallbacks = { + destroy: () => void; +}; + export type BaseUiElementState = { show: boolean; referencePos: DOMRect; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 9e34dd1df7..e2c0f47da5 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -3,13 +3,23 @@ import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; -import { BaseUiElementState } from "../../EditorElement"; +import { + BaseUiElementCallbacks, + BaseUiElementState, +} from "../../BaseUiElementTypes"; import { SuggestionItem } from "./SuggestionItem"; +export type SuggestionsPluginCallbacks = + BaseUiElementCallbacks & { + // The function to execute when selecting a suggested item. + itemCallback: (item: T) => void; + }; + export type SuggestionsMenuState = BaseUiElementState & { + // The suggested items to display. items: T[]; - itemCallback: (item: T) => void; + // The index of the suggested item that's currently hovered by the keyboard. keyboardHoveredItemIndex: number; }; @@ -102,29 +112,22 @@ class SuggestionPluginView< if (stopped || !this.editor.isEditable) { this.suggestionsMenuState!.show = false; this.updateSuggestionsMenu(); + + return; } const decorationNode = document.querySelector( `[data-decoration-id="${this.pluginState.decorationId}"]` ); - if (changed) { - this.suggestionsMenuState!.referencePos = - decorationNode!.getBoundingClientRect(); - this.suggestionsMenuState!.items = this.pluginState.items; - this.suggestionsMenuState!.keyboardHoveredItemIndex = - this.pluginState.keyboardHoveredItemIndex!; - this.updateSuggestionsMenu(); - } - - if (started && this.editor.isEditable) { + if (this.editor.isEditable) { this.suggestionsMenuState = { show: true, referencePos: decorationNode!.getBoundingClientRect(), items: this.pluginState.items, - itemCallback: (item: T) => this.itemCallback(item), keyboardHoveredItemIndex: this.pluginState.keyboardHoveredItemIndex!, }; + this.updateSuggestionsMenu(); } } @@ -192,12 +195,14 @@ export function createSuggestionPlugin< editor: BlockNoteEditor; }) => void = () => {}, items: (query: string) => T[] = () => [] -) { +): SuggestionsPluginCallbacks { // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); } + let suggestionsPluginView: SuggestionPluginView; + const deactivate = (view: EditorView) => { view.dispatch(view.state.tr.setMeta(pluginKey, { deactivate: true })); }; @@ -206,8 +211,8 @@ export function createSuggestionPlugin< new Plugin({ key: pluginKey, - view: () => - new SuggestionPluginView( + view: () => { + suggestionsPluginView = new SuggestionPluginView( editor, pluginKey, (props: { item: T; editor: BlockNoteEditor }) => { @@ -215,7 +220,9 @@ export function createSuggestionPlugin< onSelectItem(props); }, updateSuggestionsMenu - ), + ); + return suggestionsPluginView; + }, state: { // Initialize the plugin's internal state. @@ -295,7 +302,8 @@ export function createSuggestionPlugin< return getDefaultPluginState(); } - // Updates keyboardHoveredItemIndex if necessary. + // 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 @@ -311,6 +319,8 @@ export function createSuggestionPlugin< } next.keyboardHoveredItemIndex = newIndex; + } else if (oldState.selection.from !== newState.selection.from) { + next.keyboardHoveredItemIndex = 0; } return next; @@ -446,9 +456,32 @@ export function createSuggestionPlugin< }, }, }), + // Ensures the plugin is loaded at the highest priority so that things like + // keyboard handlers work. (suggestionPlugin, plugins) => { plugins.unshift(suggestionPlugin); return plugins; } ); + + return { + destroy: () => editor._tiptapEditor.unregisterPlugin(pluginKey), + itemCallback: (item: T) => { + editor._tiptapEditor + .chain() + .focus() + .deleteRange({ + from: + suggestionsPluginView.pluginState.queryStartPos! - + suggestionsPluginView.pluginState.triggerCharacter!.length, + to: editor._tiptapEditor.state.selection.from, + }) + .run(); + + onSelectItem({ + item: item, + editor: editor, + }); + }, + }; } diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index b8932b33ef..c094ff0bd8 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -12,11 +12,10 @@ export function BlockNoteView(props: { }) { return ( - + - diff --git a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx index be61ea5b4a..c93e7a274c 100644 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx @@ -1,7 +1,11 @@ import { + BaseUiElementCallbacks, + BaseUiElementState, + Block, BlockNoteEditor, BlockSchema, createSideMenu, + SideMenuCallbacks, SideMenuState, } from "@blocknote/core"; import { ActionIcon, Group, Menu } from "@mantine/core"; @@ -12,9 +16,10 @@ import { MdDragIndicator } from "react-icons/md"; import { DefaultDragHandleMenu } from "./DefaultDragHandleMenu"; export const BlockSideMenuOld = ( - props: Omit, "referencePos"> & { - editor: BlockNoteEditor; - } + props: Omit & + Omit, keyof BaseUiElementState> & { + editor: BlockNoteEditor; + } ) => { const dragHandleRef = useRef(null); @@ -34,29 +39,17 @@ export const BlockSideMenuOld = ( return; }, [props.blockDragEnd, props.blockDragStart]); - const closeMenu = () => { - // TODO: I don't think this is needed / used? - // props.unfreezeMenu(); - }; - const DragHandleMenu = DefaultDragHandleMenu; return ( - { - { - props.addBlock(); - }} - /> - } + props.freezeMenu()} - onClose={() => props.unfreezeMenu()} + onOpen={props.freezeMenu} + onClose={props.unfreezeMenu} width={100} position={"left"}> @@ -66,11 +59,7 @@ export const BlockSideMenuOld = (
- +
); @@ -79,33 +68,57 @@ export const BlockSideMenuOld = ( export const SideMenu = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState>(); + const [show, setShow] = useState(false); + const [block, setBlock] = useState>(); + + const referencePos = useRef(); + const callbacks = useRef(); useEffect(() => { - return createSideMenu(props.editor, (state) => { - setState({ ...state }); + callbacks.current = createSideMenu(props.editor, (sideMenuState) => { + setShow(sideMenuState.show); + setBlock(sideMenuState.block); + + referencePos.current = sideMenuState.referencePos; }); + + return callbacks.current!.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test - console.log( - "new reference pos, this should only be triggered when hovering a new block" - ); - if (!state?.referencePos) { + if (!referencePos.current) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + + return () => referencePos.current!; + }, [referencePos.current]); + + const sideMenu = useMemo(() => { + if (!block || !callbacks.current) { + return null; + } + + return ( + + ); + }, [block, props.editor]); return ( below + moved to // appendTo={props.editor._tiptapEditor.view.dom.parentElement!} - content={} + content={sideMenu} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + visible={show} animation={"fade"} offset={offset} placement={"left"} diff --git a/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx b/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx index 3fc435b275..651c6fd365 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx +++ b/packages/react/src/BlockSideMenu/components/DefaultButtons/BlockColorsButton.tsx @@ -38,7 +38,6 @@ export const BlockColorsButton = ( return ( diff --git a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx b/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx index 70d9cd60ab..bbd5e2331c 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx +++ b/packages/react/src/BlockSideMenu/components/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/DragHandleMenu.tsx b/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx index 816f3ed344..6da4a84590 100644 --- a/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx +++ b/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx @@ -5,7 +5,6 @@ import { Block, BlockSchema, BlockNoteEditor } from "@blocknote/core"; export type DragHandleMenuProps = { editor: BlockNoteEditor; block: Block; - closeMenu: () => void; }; export const DragHandleMenu = (props: { children: ReactNode }) => { diff --git a/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx b/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx index f8ce980238..e5da796147 100644 --- a/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx +++ b/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx @@ -1,18 +1,9 @@ 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} - ; +export const DragHandleMenuItem = ( + props: PolymorphicComponentProps<"button"> +) => { + const { children, ...remainingProps } = props; + return {children}; }; 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..6e9210f03f 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 { useEditorContentChange } from "../../../hooks/useEditorContentChange"; export const CreateLinkButton = (props: { editor: BlockNoteEditor; }) => { + const [url, setUrl] = useState( + props.editor.getSelectedLinkUrl() || "" + ); + const [text, setText] = useState( + props.editor.getSelectedText() || "" + ); + + useEditorContentChange(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); + } + }); + const show = useMemo(() => { const selection = props.editor.getSelection(); @@ -77,10 +96,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..618f367cc5 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx @@ -9,6 +9,8 @@ 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"; const shortcuts: Record = { bold: "Mod+B", @@ -30,6 +32,13 @@ 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()); + }); const toggleStyle = (style: ToggledStyle) => { props.editor.focus(); @@ -39,7 +48,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/FormattingToolbar.tsx index 4047bb134b..0baf0b17f3 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx @@ -1,12 +1,13 @@ import { BlockNoteEditor, BlockSchema, - FormattingToolbarState, createFormattingToolbar, + FormattingToolbarCallbacks, } from "@blocknote/core"; import Tippy from "@tippyjs/react"; -import { useEffect, useMemo, useState } from "react"; +import { sticky } from "tippy.js"; +import { useEffect, useMemo, useRef, useState } from "react"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ColorStyleButton } from "./DefaultButtons/ColorStyleButton"; import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; @@ -47,32 +48,42 @@ export const FormattingToolbarOld = (props: { export const FormattingToolbar = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState(); + const [show, setShow] = useState(false); + + const referencePos = useRef(); + const callbacks = useRef(); + useEffect(() => { - return createFormattingToolbar(props.editor, (state) => { - setState({ ...state }); + callbacks.current = createFormattingToolbar(props.editor, (state) => { + setShow(state.show); + + referencePos.current = state.referencePos; }); + + return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test - console.log( - "new reference pos TOOLBAR, this should only be triggered when selection changes" - ); - if (!state?.referencePos) { + if (!referencePos) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + return () => referencePos.current!; + }, [referencePos.current]); + + const formattingToolbar = useMemo(() => { + return ; + }, [props.editor]); return ( } + content={formattingToolbar} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + visible={show} animation={"fade"} - placement={"top-start"}> + placement={"top-start"} + sticky={true} + plugins={[sticky]}>
); diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx index 89e6b61e68..e87aa092ec 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx @@ -3,9 +3,12 @@ import { BlockSchema, HyperlinkToolbarState, createHyperlinkToolbar, + HyperlinkToolbarCallbacks, + BaseUiElementState, + BaseUiElementCallbacks, } from "@blocknote/core"; import Tippy from "@tippyjs/react"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; @@ -17,26 +20,32 @@ import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlink * Renders a toolbar that appears on hyperlink hover. */ export const HyperlinkToolbarOld = ( - props: Omit + props: Omit & + Omit & { + isEditing: boolean; + setIsEditing: (isEditing: boolean) => void; + } ) => { - const [isEditing, setIsEditing] = useState(false); - - if (isEditing) { + if (props.isEditing) { return ( props.editHyperlink(url, text)} /> ); } return ( - + event.preventDefault()} + onMouseEnter={props.stopHideTimer} + onMouseLeave={props.startHideTimer}> setIsEditing(true)}> + onClick={() => props.setIsEditing(true)}> Edit Link (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = useState(); + const [show, setShow] = useState(false); + const [url, setUrl] = useState(); + const [text, setText] = useState(); + + const [isEditing, setIsEditing] = useState(false); + + const referencePos = useRef(); + const callbacks = useRef(); useEffect(() => { - return createHyperlinkToolbar(props.editor, ({ ...state }) => { - setState(state); - }); + callbacks.current = createHyperlinkToolbar( + props.editor, + (hyperlinkToolbarState) => { + setShow(hyperlinkToolbarState.show); + setUrl(hyperlinkToolbarState.url); + setText(hyperlinkToolbarState.text); + + referencePos.current = hyperlinkToolbarState.referencePos; + } + ); + + return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test and remove - console.log("new reference pos for HYPERLINKTOOLBAR"); - if (!state?.referencePos) { + if (!referencePos.current) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + + return () => referencePos.current!; + }, [referencePos.current]); + + const hyperlinkToolbar = useMemo(() => { + if (!url || !text || !callbacks.current) { + return null; + } + + return ( + + ); + }, [isEditing, text, url]); return ( } + onHidden={() => setIsEditing(false)} + content={hyperlinkToolbar} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + 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 f10591db8c..8d7a6ca02d 100644 --- a/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx +++ b/packages/react/src/SharedComponents/Toolbar/components/ToolbarDropdown.tsx @@ -27,7 +27,11 @@ export function ToolbarDropdown(props: ToolbarDropdownProps) { return ( - + {props.items.map((item) => ( diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenu.tsx index 65638b4224..23fd40c6e8 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenu.tsx @@ -4,20 +4,27 @@ import { DefaultBlockSchema, SuggestionsMenuState, createSlashMenu, + SuggestionsPluginCallbacks, + BaseUiElementState, + BaseUiElementCallbacks, } from "@blocknote/core"; import { Menu, createStyles } from "@mantine/core"; import Tippy from "@tippyjs/react"; import * as _ from "lodash"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; import { SlashMenuItem } from "./SlashMenuItem"; export function SlashMenuOld( props: Omit< - SuggestionsMenuState>, - "referencePos" - > + SuggestionsPluginCallbacks>, + keyof BaseUiElementCallbacks + > & + Omit< + SuggestionsMenuState>, + keyof BaseUiElementState + > ) { const { classes } = createStyles({ root: {} })(undefined, { name: "SlashMenu", @@ -76,39 +83,69 @@ export function SlashMenuOld( export const SlashMenu = (props: { editor: BlockNoteEditor; }) => { - const [state, setState] = - useState>>(); + const [show, setShow] = useState(false); + const [items, setItems] = + useState[]>(); + const [keyboardHoveredItemIndex, setKeyboardHoveredItemIndex] = + useState(); + + const referencePos = useRef(); + const callbacks = + useRef< + SuggestionsPluginCallbacks> + >(); useEffect(() => { - return createSlashMenu>( + callbacks.current = createSlashMenu>( props.editor as any, - ({ ...state }) => { - setState(state); + (slashMenuState) => { + setShow(slashMenuState.show); + setItems(slashMenuState.items); + setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); + + referencePos.current = slashMenuState.referencePos; }, (query) => defaultReactSlashMenuItems.filter( (cmd: ReactSlashMenuItem) => cmd.match(query) ) ); + + return callbacks.current!.destroy; }, [props.editor]); const getReferenceClientRect = useMemo(() => { - // TODO: test and remove - console.log( - "new reference pos for SLASHMENU, this should only be triggered when slashmenu position changes" - ); - if (!state?.referencePos) { + if (!referencePos.current) { return undefined; } - return () => state.referencePos; - }, [state?.referencePos]); + + return () => referencePos.current!; + }, [referencePos.current]); + + const slashMenu = useMemo(() => { + if ( + !items || + keyboardHoveredItemIndex === undefined || + !callbacks.current + ) { + return null; + } + + return ( + callbacks.current!.itemCallback(item)} + keyboardHoveredItemIndex={keyboardHoveredItemIndex!} + /> + ); + }, [items, keyboardHoveredItemIndex]); return ( } + content={slashMenu} getReferenceClientRect={getReferenceClientRect} interactive={true} - visible={state?.show || false} + visible={show} animation={"fade"} placement={"bottom-start"}>
diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index abbc1e7ea5..439f013b4e 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -36,12 +36,6 @@ function initEditor( ...options, }; - if (newOptions.customElements && newOptions.uiFactories) { - console.warn( - "BlockNote editor initialized with both `customElements` and `uiFactories` options, prioritizing `uiFactories`." - ); - } - console.log("create new blocknote instance"); const instance = new BlockNoteEditor( newOptions as Partial> 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 02a122f441..a2d9167f33 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -20,3 +20,5 @@ export * from "./SlashMenu/components/SlashMenu"; export * from "./SlashMenu/defaultReactSlashMenuItems"; export * from "./hooks/useBlockNote"; export * from "./hooks/useEditorForceUpdate"; +export * from "./hooks/useEditorContentChange"; +export * from "./hooks/useEditorSelectionChange"; From c2c9a943864c8611958b9481b7b976b056942ece Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 12 Jul 2023 20:16:51 +0200 Subject: [PATCH 16/42] Cleaned up `useBlockNote`, menu & toolbar components --- packages/react/src/BlockNoteView.tsx | 16 +-- .../components/DefaultFormattingToolbar.tsx | 38 ++++++ .../components/FormattingToolbar.tsx | 90 -------------- .../components/FormattingToolbarWrapper.tsx | 55 +++++++++ .../components/DefaultHyperlinkToolbar.tsx | 58 +++++++++ ...oolbar.tsx => HyperlinkToolbarWrapper.tsx} | 67 +--------- .../DefaultButtons/BlockColorsButton.tsx | 4 +- .../DefaultButtons/RemoveBlockButton.tsx | 4 +- .../SideMenu/components/DefaultSideMenu.tsx | 64 ++++++++++ .../DragHandleMenu}/DefaultDragHandleMenu.tsx | 4 +- .../DragHandleMenu}/DragHandleMenu.tsx | 0 .../DragHandleMenu}/DragHandleMenuItem.tsx | 0 .../components/SideMenuWrapper.tsx} | 65 +--------- .../SlashMenu/components/DefaultSlashMenu.tsx | 76 ++++++++++++ .../{SlashMenu.tsx => SlashMenuWrapper.tsx} | 80 +----------- packages/react/src/hooks/useBlockNote.ts | 114 ++---------------- packages/react/src/index.ts | 12 +- 17 files changed, 336 insertions(+), 411 deletions(-) create mode 100644 packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx delete mode 100644 packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx create mode 100644 packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx create mode 100644 packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx rename packages/react/src/HyperlinkToolbar/components/{HyperlinkToolbar.tsx => HyperlinkToolbarWrapper.tsx} (50%) rename packages/react/src/{BlockSideMenu => SideMenu}/components/DefaultButtons/BlockColorsButton.tsx (94%) rename packages/react/src/{BlockSideMenu => SideMenu}/components/DefaultButtons/RemoveBlockButton.tsx (71%) create mode 100644 packages/react/src/SideMenu/components/DefaultSideMenu.tsx rename packages/react/src/{BlockSideMenu/components => SideMenu/components/DragHandleMenu}/DefaultDragHandleMenu.tsx (73%) rename packages/react/src/{BlockSideMenu/components => SideMenu/components/DragHandleMenu}/DragHandleMenu.tsx (100%) rename packages/react/src/{BlockSideMenu/components => SideMenu/components/DragHandleMenu}/DragHandleMenuItem.tsx (100%) rename packages/react/src/{BlockSideMenu/components/BlockSideMenu.tsx => SideMenu/components/SideMenuWrapper.tsx} (53%) create mode 100644 packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx rename packages/react/src/SlashMenu/components/{SlashMenu.tsx => SlashMenuWrapper.tsx} (51%) diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index c094ff0bd8..f416e14cbf 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -2,10 +2,10 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; import { getBlockNoteTheme } from "./BlockNoteTheme"; -import { SideMenu } from "./BlockSideMenu/components/BlockSideMenu"; -import { FormattingToolbar } from "./FormattingToolbar/components/FormattingToolbar"; -import { HyperlinkToolbar } from "./HyperlinkToolbar/components/HyperlinkToolbar"; -import { SlashMenu } from "./SlashMenu/components/SlashMenu"; +import { SideMenuWrapper } from "./SideMenu/components/SideMenuWrapper"; +import { FormattingToolbarWrapper } from "./FormattingToolbar/components/FormattingToolbarWrapper"; +import { HyperlinkToolbarWrapper } from "./HyperlinkToolbar/components/HyperlinkToolbarWrapper"; +import { SlashMenuWrapper } from "./SlashMenu/components/SlashMenuWrapper"; export function BlockNoteView(props: { editor: BlockNoteEditor; @@ -13,10 +13,10 @@ export function BlockNoteView(props: { return ( - - - - + + + + ); diff --git a/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx new file mode 100644 index 0000000000..d1358c82f5 --- /dev/null +++ b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx @@ -0,0 +1,38 @@ +import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; + +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 { + NestBlockButton, + UnnestBlockButton, +} from "./DefaultButtons/NestBlockButtons"; +import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; + +export const DefaultFormattingToolbar = (props: { + editor: BlockNoteEditor; +}) => { + return ( + + + + + + + + + + + + + + + + + + + + ); +}; diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx deleted file mode 100644 index 0baf0b17f3..0000000000 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbar.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import { - BlockNoteEditor, - BlockSchema, - createFormattingToolbar, - FormattingToolbarCallbacks, -} from "@blocknote/core"; - -import Tippy from "@tippyjs/react"; -import { sticky } from "tippy.js"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; -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"; - -export const FormattingToolbarOld = (props: { - editor: BlockNoteEditor; -}) => { - return ( - - - - - - - - - - - - - - - - - - - - ); -}; - -export const FormattingToolbar = (props: { - editor: BlockNoteEditor; -}) => { - const [show, setShow] = useState(false); - - const referencePos = useRef(); - const callbacks = useRef(); - - useEffect(() => { - callbacks.current = createFormattingToolbar(props.editor, (state) => { - setShow(state.show); - - referencePos.current = state.referencePos; - }); - - return callbacks.current.destroy; - }, [props.editor]); - - const getReferenceClientRect = useMemo(() => { - if (!referencePos) { - return undefined; - } - return () => referencePos.current!; - }, [referencePos.current]); - - const formattingToolbar = useMemo(() => { - return ; - }, [props.editor]); - - return ( - -
- - ); -}; diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx new file mode 100644 index 0000000000..2eaf519cbc --- /dev/null +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx @@ -0,0 +1,55 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import Tippy from "@tippyjs/react"; +import { sticky } from "tippy.js"; +import { + BlockNoteEditor, + BlockSchema, + createFormattingToolbar, + FormattingToolbarCallbacks, +} from "@blocknote/core"; + +import { DefaultFormattingToolbar } from "./DefaultFormattingToolbar"; + +export const FormattingToolbarWrapper = (props: { + editor: BlockNoteEditor; +}) => { + const [show, setShow] = useState(false); + + const referencePos = useRef(); + const callbacks = useRef(); + + useEffect(() => { + callbacks.current = createFormattingToolbar(props.editor, (state) => { + setShow(state.show); + + referencePos.current = state.referencePos; + }); + + return callbacks.current.destroy; + }, [props.editor]); + + const getReferenceClientRect = useMemo(() => { + if (!referencePos) { + return undefined; + } + return () => referencePos.current!; + }, [referencePos.current]); + + const formattingToolbar = useMemo(() => { + return ; + }, [props.editor]); + + return ( + +
+ + ); +}; diff --git a/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx new file mode 100644 index 0000000000..9841600a3c --- /dev/null +++ b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx @@ -0,0 +1,58 @@ +import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; +import { + BaseUiElementCallbacks, + BaseUiElementState, + HyperlinkToolbarCallbacks, + HyperlinkToolbarState, +} from "@blocknote/core"; + +import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; +import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; +import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; + +export const DefaultHyperlinkToolbar = ( + props: Omit & + Omit & { + isEditing: boolean; + setIsEditing: (isEditing: boolean) => void; + } +) => { + if (props.isEditing) { + return ( + props.editHyperlink(url, text)} + /> + ); + } + + return ( + event.preventDefault()} + onMouseEnter={props.stopHideTimer} + onMouseLeave={props.startHideTimer}> + props.setIsEditing(true)}> + Edit Link + + { + window.open(props.url, "_blank"); + }} + icon={RiExternalLinkFill} + /> + + + ); +}; diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarWrapper.tsx similarity index 50% rename from packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx rename to packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarWrapper.tsx index e87aa092ec..56e72a2116 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarWrapper.tsx @@ -1,72 +1,15 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import Tippy from "@tippyjs/react"; import { BlockNoteEditor, BlockSchema, - HyperlinkToolbarState, createHyperlinkToolbar, HyperlinkToolbarCallbacks, - BaseUiElementState, - BaseUiElementCallbacks, } from "@blocknote/core"; -import Tippy from "@tippyjs/react"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; -import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; -import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; -import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; -// import rootStyles from "../../../root.module.css"; - -/** - * Main menu component for the hyperlink extension. - * Renders a toolbar that appears on hyperlink hover. - */ -export const HyperlinkToolbarOld = ( - props: Omit & - Omit & { - isEditing: boolean; - setIsEditing: (isEditing: boolean) => void; - } -) => { - if (props.isEditing) { - return ( - props.editHyperlink(url, text)} - /> - ); - } - return ( - event.preventDefault()} - onMouseEnter={props.stopHideTimer} - onMouseLeave={props.startHideTimer}> - props.setIsEditing(true)}> - Edit Link - - { - window.open(props.url, "_blank"); - }} - icon={RiExternalLinkFill} - /> - - - ); -}; +import { DefaultHyperlinkToolbar } from "./DefaultHyperlinkToolbar"; -export const HyperlinkToolbar = (props: { +export const HyperlinkToolbarWrapper = (props: { editor: BlockNoteEditor; }) => { const [show, setShow] = useState(false); @@ -107,7 +50,7 @@ export const HyperlinkToolbar = (props: { } return ( - ( diff --git a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx b/packages/react/src/SideMenu/components/DefaultButtons/RemoveBlockButton.tsx similarity index 71% rename from packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx rename to packages/react/src/SideMenu/components/DefaultButtons/RemoveBlockButton.tsx index bbd5e2331c..dd44bf569e 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultButtons/RemoveBlockButton.tsx +++ b/packages/react/src/SideMenu/components/DefaultButtons/RemoveBlockButton.tsx @@ -1,8 +1,8 @@ import { ReactNode } from "react"; import { BlockSchema } from "@blocknote/core"; -import { DragHandleMenuProps } from "../DragHandleMenu"; -import { DragHandleMenuItem } from "../DragHandleMenuItem"; +import { DragHandleMenuProps } from "../DragHandleMenu/DragHandleMenu"; +import { DragHandleMenuItem } from "../DragHandleMenu/DragHandleMenuItem"; export const RemoveBlockButton = ( props: DragHandleMenuProps & { children: ReactNode } diff --git a/packages/react/src/SideMenu/components/DefaultSideMenu.tsx b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx new file mode 100644 index 0000000000..63589d600a --- /dev/null +++ b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx @@ -0,0 +1,64 @@ +import { useEffect, useRef } from "react"; +import { ActionIcon, Group, Menu } from "@mantine/core"; +import { AiOutlinePlus } from "react-icons/ai"; +import { MdDragIndicator } from "react-icons/md"; +import { + BaseUiElementCallbacks, + BaseUiElementState, + BlockNoteEditor, + BlockSchema, + SideMenuCallbacks, + SideMenuState, +} from "@blocknote/core"; + +import { DefaultDragHandleMenu } from "./DragHandleMenu/DefaultDragHandleMenu"; + +export const DefaultSideMenu = ( + props: Omit & + Omit, keyof BaseUiElementState> & { + editor: BlockNoteEditor; + } +) => { + 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 DragHandleMenu = DefaultDragHandleMenu; + + return ( + + + + + + +
+ + {} + +
+
+ +
+
+ ); +}; diff --git a/packages/react/src/BlockSideMenu/components/DefaultDragHandleMenu.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx similarity index 73% rename from packages/react/src/BlockSideMenu/components/DefaultDragHandleMenu.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx index 0f8ffa3b1a..33c9287e65 100644 --- a/packages/react/src/BlockSideMenu/components/DefaultDragHandleMenu.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx @@ -1,6 +1,6 @@ import { DragHandleMenu, DragHandleMenuProps } from "./DragHandleMenu"; -import { RemoveBlockButton } from "./DefaultButtons/RemoveBlockButton"; -import { BlockColorsButton } from "./DefaultButtons/BlockColorsButton"; +import { RemoveBlockButton } from "../DefaultButtons/RemoveBlockButton"; +import { BlockColorsButton } from "../DefaultButtons/BlockColorsButton"; import { BlockSchema } from "@blocknote/core"; export const DefaultDragHandleMenu = ( diff --git a/packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx similarity index 100% rename from packages/react/src/BlockSideMenu/components/DragHandleMenu.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx diff --git a/packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenuItem.tsx similarity index 100% rename from packages/react/src/BlockSideMenu/components/DragHandleMenuItem.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenuItem.tsx diff --git a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx b/packages/react/src/SideMenu/components/SideMenuWrapper.tsx similarity index 53% rename from packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx rename to packages/react/src/SideMenu/components/SideMenuWrapper.tsx index c93e7a274c..b1352c5d2e 100644 --- a/packages/react/src/BlockSideMenu/components/BlockSideMenu.tsx +++ b/packages/react/src/SideMenu/components/SideMenuWrapper.tsx @@ -1,71 +1,16 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import Tippy from "@tippyjs/react"; import { - BaseUiElementCallbacks, - BaseUiElementState, Block, BlockNoteEditor, BlockSchema, createSideMenu, SideMenuCallbacks, - SideMenuState, } from "@blocknote/core"; -import { ActionIcon, Group, Menu } from "@mantine/core"; -import Tippy from "@tippyjs/react"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { AiOutlinePlus } from "react-icons/ai"; -import { MdDragIndicator } from "react-icons/md"; -import { DefaultDragHandleMenu } from "./DefaultDragHandleMenu"; - -export const BlockSideMenuOld = ( - props: Omit & - Omit, keyof BaseUiElementState> & { - editor: BlockNoteEditor; - } -) => { - 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 DragHandleMenu = DefaultDragHandleMenu; - - return ( - - - - - - -
- - {} - -
-
- -
-
- ); -}; +import { DefaultSideMenu } from "./DefaultSideMenu"; -export const SideMenu = (props: { +export const SideMenuWrapper = (props: { editor: BlockNoteEditor; }) => { const [show, setShow] = useState(false); @@ -99,7 +44,7 @@ export const SideMenu = (props: { } return ( - >, + keyof BaseUiElementCallbacks + > & + Omit< + SuggestionsMenuState>, + keyof BaseUiElementState + > +) { + const { classes } = createStyles({ root: {} })(undefined, { + name: "SlashMenu", + }); + const renderedItems: any[] = []; + let index = 0; + + const groups = _.groupBy(props.items, (i) => i.group); + + _.forEach(groups, (el) => { + renderedItems.push( + {el[0].group} + ); + + for (const item of el) { + renderedItems.push( + props.itemCallback(item)} + /> + ); + index++; + } + }); + + return ( + + event.preventDefault()} + className={classes.root}> + {renderedItems.length > 0 ? ( + renderedItems + ) : ( + No match found + )} + + + ); +} diff --git a/packages/react/src/SlashMenu/components/SlashMenu.tsx b/packages/react/src/SlashMenu/components/SlashMenuWrapper.tsx similarity index 51% rename from packages/react/src/SlashMenu/components/SlashMenu.tsx rename to packages/react/src/SlashMenu/components/SlashMenuWrapper.tsx index 23fd40c6e8..8a2a249be8 100644 --- a/packages/react/src/SlashMenu/components/SlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuWrapper.tsx @@ -1,86 +1,18 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import Tippy from "@tippyjs/react"; import { BlockNoteEditor, BlockSchema, DefaultBlockSchema, - SuggestionsMenuState, createSlashMenu, SuggestionsPluginCallbacks, - BaseUiElementState, - BaseUiElementCallbacks, } from "@blocknote/core"; -import { Menu, createStyles } from "@mantine/core"; -import Tippy from "@tippyjs/react"; -import * as _ from "lodash"; -import { useEffect, useMemo, useRef, useState } from "react"; + import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; -import { SlashMenuItem } from "./SlashMenuItem"; - -export function SlashMenuOld( - props: Omit< - SuggestionsPluginCallbacks>, - keyof BaseUiElementCallbacks - > & - Omit< - SuggestionsMenuState>, - keyof BaseUiElementState - > -) { - const { classes } = createStyles({ root: {} })(undefined, { - name: "SlashMenu", - }); - const renderedItems: any[] = []; - let index = 0; - - const groups = _.groupBy(props.items, (i) => i.group); - - _.forEach(groups, (el) => { - renderedItems.push( - {el[0].group} - ); - - for (const item of el) { - renderedItems.push( - props.itemCallback(item)} - /> - ); - index++; - } - }); - - return ( - - event.preventDefault()} - className={classes.root}> - {renderedItems.length > 0 ? ( - renderedItems - ) : ( - No match found - )} - - - ); -} +import { DefaultSlashMenu } from "./DefaultSlashMenu"; -export const SlashMenu = (props: { +export const SlashMenuWrapper = (props: { editor: BlockNoteEditor; }) => { const [show, setShow] = useState(false); @@ -132,7 +64,7 @@ export const SlashMenu = (props: { } return ( - callbacks.current!.itemCallback(item)} keyboardHoveredItemIndex={keyboardHoveredItemIndex!} diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 439f013b4e..bb3c7556f0 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -4,119 +4,23 @@ import { BlockSchema, DefaultBlockSchema, } from "@blocknote/core"; -import { DependencyList, FC } from "react"; -import { DragHandleMenuProps } from "../BlockSideMenu/components/DragHandleMenu"; +import { DependencyList } from "react"; import { defaultReactSlashMenuItems } from "../SlashMenu/defaultReactSlashMenuItems"; -//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); -// } - -function initEditor( - options: Partial< - BlockNoteEditorOptions & { - customElements: CustomElements; - } - > = {} -) { - // 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. +/** + * Main hook for importing a BlockNote editor into a React project + */ +export const useBlockNote = ( + options: Partial> = {}, + _deps: DependencyList = [] +) => { let newOptions: Record = { slashCommands: defaultReactSlashMenuItems, ...options, }; console.log("create new blocknote instance"); - const instance = new BlockNoteEditor( + return new BlockNoteEditor( newOptions as Partial> ); - - return instance; -} - -/** - * Main hook for importing a BlockNote editor into a React project - */ -export const useBlockNote = ( - options: Partial< - BlockNoteEditorOptions & { - customElements: CustomElements; - } - > = {}, - _deps: DependencyList = [] -) => { - // const [editor, setEditor] = useState>( - // initEditor(options) - // ); - // 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, - // }; - // - // if (newOptions.customElements && newOptions.uiFactories) { - // console.warn( - // "BlockNote editor initialized with both `customElements` and `uiFactories` options, prioritizing `uiFactories`." - // ); - // } - // - // let uiFactories = { - // formattingToolbarFactory: undefined, - // hyperlinkToolbarFactory: createReactHyperlinkToolbarFactory( - // getBlockNoteTheme(newOptions.theme === "dark") - // ), - // slashMenuFactory: undefined, - // 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 initEditor(options); }; diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index a2d9167f33..42e7cf75f2 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -1,22 +1,22 @@ // TODO: review directories export * from "./BlockNoteView"; -export * from "./BlockSideMenu/components/DefaultButtons/BlockColorsButton"; -export * from "./BlockSideMenu/components/DefaultButtons/RemoveBlockButton"; -export * from "./BlockSideMenu/components/DragHandleMenu"; -export * from "./BlockSideMenu/components/DragHandleMenuItem"; +export * from "./SideMenu/components/DefaultButtons/BlockColorsButton"; +export * from "./SideMenu/components/DefaultButtons/RemoveBlockButton"; +export * from "./SideMenu/components/DragHandleMenu/DragHandleMenu"; +export * from "./SideMenu/components/DragHandleMenu/DragHandleMenuItem"; export * from "./FormattingToolbar/components/DefaultButtons/ColorStyleButton"; 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 "./FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown"; -export * from "./FormattingToolbar/components/FormattingToolbar"; +export * from "./FormattingToolbar/components/FormattingToolbarWrapper"; export * from "./ReactBlockSpec"; export * from "./SharedComponents/Toolbar/components/Toolbar"; export * from "./SharedComponents/Toolbar/components/ToolbarButton"; export * from "./SharedComponents/Toolbar/components/ToolbarDropdown"; export * from "./SlashMenu/ReactSlashMenuItem"; -export * from "./SlashMenu/components/SlashMenu"; +export * from "./SlashMenu/components/SlashMenuWrapper"; export * from "./SlashMenu/defaultReactSlashMenuItems"; export * from "./hooks/useBlockNote"; export * from "./hooks/useEditorForceUpdate"; From 827e7e4c5e9b84cac3e286269ec4fd5a812b67c9 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Thu, 13 Jul 2023 16:44:05 +0200 Subject: [PATCH 17/42] Changed menu & toolbar APIs to work with the new rendering architecture --- examples/editor/src/App.tsx | 47 ++++++++++++++++++- .../vanilla/src/ui/addHyperlinkToolbar.ts | 6 +-- examples/vanilla/src/ui/addSideMenu.ts | 8 ++-- examples/vanilla/src/ui/addSlashMenu.ts | 11 ++--- .../extensions/SlashMenu/SlashMenuPlugin.ts | 4 +- .../plugins/suggestion/SuggestionPlugin.ts | 4 +- packages/react/src/BlockNoteView.tsx | 16 +++++-- .../DefaultButtons/CreateLinkButton.tsx | 4 +- .../components/DefaultFormattingToolbar.tsx | 9 ++-- .../components/FormattingToolbarWrapper.tsx | 17 +++++-- .../components/EditHyperlinkMenu.tsx | 27 ++++++----- .../components/DefaultHyperlinkToolbar.tsx | 27 +++++------ .../components/HyperlinkToolbarWrapper.tsx | 28 +++++++---- .../DefaultButtons/BlockColorsButton.tsx | 3 +- .../SideMenu/components/DefaultSideMenu.tsx | 22 ++++----- .../DragHandleMenu/DefaultDragHandleMenu.tsx | 3 +- .../DragHandleMenu/DragHandleMenu.tsx | 2 +- .../SideMenu/components/SideMenuWrapper.tsx | 24 ++++++++-- .../SlashMenu/components/DefaultSlashMenu.tsx | 30 ++++-------- .../SlashMenu/components/SlashMenuWrapper.tsx | 41 ++++++++++------ packages/react/src/index.ts | 35 ++++++++++---- 21 files changed, 226 insertions(+), 142 deletions(-) diff --git a/examples/editor/src/App.tsx b/examples/editor/src/App.tsx index 55ce63eb93..a56ae5c7c0 100644 --- a/examples/editor/src/App.tsx +++ b/examples/editor/src/App.tsx @@ -1,6 +1,17 @@ // import logo from './logo.svg' import "@blocknote/core/style.css"; -import { BlockNoteView, useBlockNote } from "@blocknote/react"; +import { + BlockNoteView, + FormattingToolbarWrapper, + SlashMenuWrapper, + SideMenuWrapper, + HyperlinkToolbarWrapper, + useBlockNote, + defaultReactSlashMenuItems, + DefaultSideMenu, + DragHandleMenuItem, + DragHandleMenu, +} from "@blocknote/react"; import styles from "./App.module.css"; type WindowWithProseMirror = Window & typeof globalThis & { ProseMirror: any }; @@ -20,7 +31,39 @@ function App() { // Give tests a way to get prosemirror instance (window as WindowWithProseMirror).ProseMirror = editor?._tiptapEditor; - return ; + return ( + +
Formatting Toolbar
} + /> +
Hyperlink Toolbar
} + /> +
Slash Menu
} + slashMenuItems={defaultReactSlashMenuItems.filter((item) => + item.name.includes("Heading") + )} + /> +
Side Menu
} /> + {/* (*/} + {/* (*/} + {/* */} + {/* Item*/} + {/* */} + {/* )}*/} + {/* />*/} + {/* )}*/} + {/*/>*/} +
+ ); } export default App; diff --git a/examples/vanilla/src/ui/addHyperlinkToolbar.ts b/examples/vanilla/src/ui/addHyperlinkToolbar.ts index 51b07f1740..a55e12021b 100644 --- a/examples/vanilla/src/ui/addHyperlinkToolbar.ts +++ b/examples/vanilla/src/ui/addHyperlinkToolbar.ts @@ -4,7 +4,7 @@ import { createButton } from "./util"; export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { let element: HTMLElement; - createHyperlinkToolbar(editor, (hyperlinkToolbarState) => { + const callbacks = createHyperlinkToolbar(editor, (hyperlinkToolbarState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -17,13 +17,13 @@ export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { const editBtn = createButton("edit", () => { const newUrl = prompt("new url") || url; - hyperlinkToolbarState.editHyperlink(newUrl, text); + callbacks.editHyperlink(newUrl, text); }); element.appendChild(editBtn); const removeBtn = createButton("remove", () => { - hyperlinkToolbarState.deleteHyperlink(); + callbacks.deleteHyperlink(); }); element.appendChild(editBtn); diff --git a/examples/vanilla/src/ui/addSideMenu.ts b/examples/vanilla/src/ui/addSideMenu.ts index 7f3e2589f2..d6717d6667 100644 --- a/examples/vanilla/src/ui/addSideMenu.ts +++ b/examples/vanilla/src/ui/addSideMenu.ts @@ -4,7 +4,7 @@ import { createButton } from "./util"; export const addSideMenu = (editor: BlockNoteEditor) => { let element: HTMLElement; - createSideMenu(editor, (sideMenuState) => { + const callbacks = createSideMenu(editor, (sideMenuState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -12,7 +12,7 @@ export const addSideMenu = (editor: BlockNoteEditor) => { element.style.padding = "10px"; element.style.opacity = "0.8"; const addBtn = createButton("+", () => { - sideMenuState.addBlock(); + callbacks.addBlock(); }); element.appendChild(addBtn); @@ -20,8 +20,8 @@ export const addSideMenu = (editor: BlockNoteEditor) => { // TODO: render a submenu with a delete option that calls "props.deleteBlock" }); - dragBtn.addEventListener("dragstart", sideMenuState.blockDragStart); - dragBtn.addEventListener("dragend", sideMenuState.blockDragEnd); + dragBtn.addEventListener("dragstart", callbacks.blockDragStart); + dragBtn.addEventListener("dragend", callbacks.blockDragEnd); dragBtn.draggable = true; element.style.display = "none"; element.appendChild(dragBtn); diff --git a/examples/vanilla/src/ui/addSlashMenu.ts b/examples/vanilla/src/ui/addSlashMenu.ts index cdf9b33014..6b8e32de8b 100644 --- a/examples/vanilla/src/ui/addSlashMenu.ts +++ b/examples/vanilla/src/ui/addSlashMenu.ts @@ -30,7 +30,7 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { return domItems; } - createSlashMenu>( + const callbacks = createSlashMenu>( editor, (slashMenuState) => { if (!element) { @@ -46,8 +46,8 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { if (slashMenuState.show) { updateItems( - slashMenuState.items, - slashMenuState.itemCallback, + slashMenuState.filteredItems, + callbacks.itemCallback, slashMenuState.keyboardHoveredItemIndex ); @@ -60,9 +60,6 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { element.style.display = "none"; } }, - (query) => - defaultSlashMenuItems.filter( - (cmd: BaseSlashMenuItem) => cmd.match(query) - ) + defaultSlashMenuItems ); }; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index 789177ef2f..fb692729b3 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -16,7 +16,7 @@ export const createSlashMenu = < updateSlashMenu: ( slashMenuState: SuggestionsMenuState ) => void, - items: (query: string) => SlashMenuItem[] + items: SlashMenuItem[] ): SuggestionsPluginCallbacks => { return createSuggestionPlugin( slashMenuPluginKey, @@ -24,6 +24,6 @@ export const createSlashMenu = < editor, (slashMenuState) => updateSlashMenu(slashMenuState), ({ item, editor }) => item.execute(editor), - items + (query) => items.filter((item: SlashMenuItem) => item.match(query)) ); }; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index e2c0f47da5..a82b4021df 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -18,7 +18,7 @@ export type SuggestionsPluginCallbacks = export type SuggestionsMenuState = BaseUiElementState & { // The suggested items to display. - items: T[]; + filteredItems: T[]; // The index of the suggested item that's currently hovered by the keyboard. keyboardHoveredItemIndex: number; }; @@ -124,7 +124,7 @@ class SuggestionPluginView< this.suggestionsMenuState = { show: true, referencePos: decorationNode!.getBoundingClientRect(), - items: this.pluginState.items, + filteredItems: this.pluginState.items, keyboardHoveredItemIndex: this.pluginState.keyboardHoveredItemIndex!, }; diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index f416e14cbf..ab6b047353 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -2,21 +2,27 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; import { getBlockNoteTheme } from "./BlockNoteTheme"; -import { SideMenuWrapper } from "./SideMenu/components/SideMenuWrapper"; +import { ReactNode } from "react"; import { FormattingToolbarWrapper } from "./FormattingToolbar/components/FormattingToolbarWrapper"; import { HyperlinkToolbarWrapper } from "./HyperlinkToolbar/components/HyperlinkToolbarWrapper"; import { SlashMenuWrapper } from "./SlashMenu/components/SlashMenuWrapper"; +import { SideMenuWrapper } from "./SideMenu/components/SideMenuWrapper"; export function BlockNoteView(props: { editor: BlockNoteEditor; + children?: ReactNode; }) { return ( - - - - + {props.children || ( + <> + + + + + + )} ); diff --git a/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx b/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx index 6e9210f03f..465c89ab7d 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/CreateLinkButton.tsx @@ -3,7 +3,7 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { RiLink } from "react-icons/ri"; import LinkToolbarButton from "../LinkToolbarButton"; import { formatKeyboardShortcut } from "../../../utils"; -import { useEditorContentChange } from "../../../hooks/useEditorContentChange"; +import { useEditorSelectionChange } from "../../../hooks/useEditorSelectionChange"; export const CreateLinkButton = (props: { editor: BlockNoteEditor; @@ -15,7 +15,7 @@ export const CreateLinkButton = (props: { props.editor.getSelectedText() || "" ); - useEditorContentChange(props.editor, () => { + useEditorSelectionChange(props.editor, () => { setText(props.editor.getSelectedText() || ""); setUrl(props.editor.getSelectedLinkUrl() || ""); }); diff --git a/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx index d1358c82f5..0495efa955 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx @@ -1,5 +1,6 @@ -import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; +import { BlockSchema } from "@blocknote/core"; +import { FormattingToolbarProps } from "./FormattingToolbarWrapper"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { BlockTypeDropdown } from "./DefaultDropdowns/BlockTypeDropdown"; import { ToggledStyleButton } from "./DefaultButtons/ToggledStyleButton"; @@ -11,9 +12,9 @@ import { } from "./DefaultButtons/NestBlockButtons"; import { CreateLinkButton } from "./DefaultButtons/CreateLinkButton"; -export const DefaultFormattingToolbar = (props: { - editor: BlockNoteEditor; -}) => { +export const DefaultFormattingToolbar = ( + props: FormattingToolbarProps +) => { return ( diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx index 2eaf519cbc..4a328dc8af 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from "react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; import Tippy from "@tippyjs/react"; import { sticky } from "tippy.js"; import { @@ -10,8 +10,12 @@ import { import { DefaultFormattingToolbar } from "./DefaultFormattingToolbar"; +export type FormattingToolbarProps = { + editor: BlockNoteEditor; +}; export const FormattingToolbarWrapper = (props: { editor: BlockNoteEditor; + formattingToolbar?: FC>; }) => { const [show, setShow] = useState(false); @@ -35,13 +39,16 @@ export const FormattingToolbarWrapper = (props: { return () => referencePos.current!; }, [referencePos.current]); - const formattingToolbar = useMemo(() => { - return ; - }, [props.editor]); + const formattingToolbarElement = useMemo(() => { + const FormattingToolbar = + props.formattingToolbar || DefaultFormattingToolbar; + + return ; + }, [props.editor, props.formattingToolbar]); return ( ((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/components/DefaultHyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx index 9841600a3c..72fdc8e038 100644 --- a/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx @@ -1,28 +1,23 @@ +import { useState } from "react"; import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; -import { - BaseUiElementCallbacks, - BaseUiElementState, - HyperlinkToolbarCallbacks, - HyperlinkToolbarState, -} from "@blocknote/core"; -import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; +import { HyperlinkToolbarProps } from "./HyperlinkToolbarWrapper"; + import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; +import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlinkMenu"; + +export const DefaultHyperlinkToolbar = (props: HyperlinkToolbarProps) => { + const [isEditing, setIsEditing] = useState(false); -export const DefaultHyperlinkToolbar = ( - props: Omit & - Omit & { - isEditing: boolean; - setIsEditing: (isEditing: boolean) => void; - } -) => { - if (props.isEditing) { + if (isEditing) { return ( props.editHyperlink(url, text)} + // TODO: Better way of waiting for fade out + onBlur={() => setTimeout(() => setIsEditing(false), 500)} /> ); } @@ -36,7 +31,7 @@ export const DefaultHyperlinkToolbar = ( props.setIsEditing(true)}> + onClick={() => setIsEditing(true)}> Edit Link & + Omit; + export const HyperlinkToolbarWrapper = (props: { editor: BlockNoteEditor; + hyperlinkToolbar?: FC; }) => { const [show, setShow] = useState(false); const [url, setUrl] = useState(); const [text, setText] = useState(); - const [isEditing, setIsEditing] = useState(false); - const referencePos = useRef(); const callbacks = useRef(); @@ -44,29 +52,29 @@ export const HyperlinkToolbarWrapper = (props: { return () => referencePos.current!; }, [referencePos.current]); - const hyperlinkToolbar = useMemo(() => { + const hyperlinkToolbarElement = useMemo(() => { if (!url || !text || !callbacks.current) { return null; } + const HyperlinkToolbar = props.hyperlinkToolbar || DefaultHyperlinkToolbar; + return ( - ); - }, [isEditing, text, url]); + }, [props.hyperlinkToolbar, text, url]); return ( setIsEditing(false)} - content={hyperlinkToolbar} + // onHidden={() => setIsEditing(false)} + content={hyperlinkToolbarElement} getReferenceClientRect={getReferenceClientRect} interactive={true} visible={show} diff --git a/packages/react/src/SideMenu/components/DefaultButtons/BlockColorsButton.tsx b/packages/react/src/SideMenu/components/DefaultButtons/BlockColorsButton.tsx index 019f35122f..c366bbec8d 100644 --- a/packages/react/src/SideMenu/components/DefaultButtons/BlockColorsButton.tsx +++ b/packages/react/src/SideMenu/components/DefaultButtons/BlockColorsButton.tsx @@ -1,7 +1,8 @@ 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/DragHandleMenu"; import { DragHandleMenuItem } from "../DragHandleMenu/DragHandleMenuItem"; import { ColorPicker } from "../../../SharedComponents/ColorPicker/components/ColorPicker"; diff --git a/packages/react/src/SideMenu/components/DefaultSideMenu.tsx b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx index 63589d600a..0609181a64 100644 --- a/packages/react/src/SideMenu/components/DefaultSideMenu.tsx +++ b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx @@ -1,23 +1,17 @@ -import { useEffect, useRef } from "react"; +import { FC, useEffect, useRef } from "react"; import { ActionIcon, Group, Menu } from "@mantine/core"; import { AiOutlinePlus } from "react-icons/ai"; import { MdDragIndicator } from "react-icons/md"; -import { - BaseUiElementCallbacks, - BaseUiElementState, - BlockNoteEditor, - BlockSchema, - SideMenuCallbacks, - SideMenuState, -} from "@blocknote/core"; +import { BlockSchema } from "@blocknote/core"; +import { SideMenuProps } from "./SideMenuWrapper"; +import { DragHandleMenuProps } from "./DragHandleMenu/DragHandleMenu"; import { DefaultDragHandleMenu } from "./DragHandleMenu/DefaultDragHandleMenu"; export const DefaultSideMenu = ( - props: Omit & - Omit, keyof BaseUiElementState> & { - editor: BlockNoteEditor; - } + props: SideMenuProps & { + dragHandleMenu?: FC>; + } ) => { const dragHandleRef = useRef(null); @@ -37,7 +31,7 @@ export const DefaultSideMenu = ( return; }, [props.blockDragEnd, props.blockDragStart]); - const DragHandleMenu = DefaultDragHandleMenu; + const DragHandleMenu = props.dragHandleMenu || DefaultDragHandleMenu; return ( diff --git a/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx index 33c9287e65..7759e9dd70 100644 --- a/packages/react/src/SideMenu/components/DragHandleMenu/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/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx index 6da4a84590..1062799004 100644 --- a/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DragHandleMenu.tsx @@ -1,6 +1,6 @@ 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; diff --git a/packages/react/src/SideMenu/components/SideMenuWrapper.tsx b/packages/react/src/SideMenu/components/SideMenuWrapper.tsx index b1352c5d2e..a1f19405db 100644 --- a/packages/react/src/SideMenu/components/SideMenuWrapper.tsx +++ b/packages/react/src/SideMenu/components/SideMenuWrapper.tsx @@ -1,17 +1,29 @@ -import { useEffect, useMemo, useRef, useState } from "react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; import Tippy from "@tippyjs/react"; import { + BaseUiElementCallbacks, + BaseUiElementState, Block, BlockNoteEditor, BlockSchema, createSideMenu, SideMenuCallbacks, + SideMenuState, } from "@blocknote/core"; import { DefaultSideMenu } from "./DefaultSideMenu"; +export type SideMenuProps = Omit< + SideMenuCallbacks, + keyof BaseUiElementCallbacks +> & + Omit, keyof BaseUiElementState> & { + editor: BlockNoteEditor; + }; + export const SideMenuWrapper = (props: { editor: BlockNoteEditor; + sideMenu?: FC>; }) => { const [show, setShow] = useState(false); const [block, setBlock] = useState>(); @@ -38,13 +50,15 @@ export const SideMenuWrapper = (props: { return () => referencePos.current!; }, [referencePos.current]); - const sideMenu = useMemo(() => { + const sideMenuElement = useMemo(() => { if (!block || !callbacks.current) { return null; } + const SideMenu = props.sideMenu || DefaultSideMenu; + return ( - (props: { unfreezeMenu={callbacks.current.unfreezeMenu} /> ); - }, [block, props.editor]); + }, [block, props.editor, props.sideMenu]); return ( below + moved to // appendTo={props.editor._tiptapEditor.view.dom.parentElement!} - content={sideMenu} + content={sideMenuElement} getReferenceClientRect={getReferenceClientRect} interactive={true} visible={show} diff --git a/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx b/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx index 9b3e177eef..bb5ad65c39 100644 --- a/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx @@ -1,40 +1,26 @@ import { createStyles, Menu } from "@mantine/core"; import * as _ from "lodash"; -import { - BaseUiElementCallbacks, - BaseUiElementState, - DefaultBlockSchema, - SuggestionsMenuState, - SuggestionsPluginCallbacks, -} from "@blocknote/core"; -import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { SlashMenuItem } from "./SlashMenuItem"; +import { SlashMenuProps } from "./SlashMenuWrapper"; -export function DefaultSlashMenu( - props: Omit< - SuggestionsPluginCallbacks>, - keyof BaseUiElementCallbacks - > & - Omit< - SuggestionsMenuState>, - keyof BaseUiElementState - > -) { +export function DefaultSlashMenu(props: SlashMenuProps) { const { classes } = createStyles({ root: {} })(undefined, { name: "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( >, + keyof BaseUiElementCallbacks +> & + Omit< + SuggestionsMenuState>, + keyof BaseUiElementState + >; + export const SlashMenuWrapper = (props: { editor: BlockNoteEditor; + slashMenuItems?: ReactSlashMenuItem[]; + slashMenu?: FC; }) => { const [show, setShow] = useState(false); - const [items, setItems] = + const [filteredItems, setFilteredItems] = useState[]>(); const [keyboardHoveredItemIndex, setKeyboardHoveredItemIndex] = useState(); @@ -32,19 +46,16 @@ export const SlashMenuWrapper = (props: { props.editor as any, (slashMenuState) => { setShow(slashMenuState.show); - setItems(slashMenuState.items); + setFilteredItems(slashMenuState.filteredItems); setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); referencePos.current = slashMenuState.referencePos; }, - (query) => - defaultReactSlashMenuItems.filter( - (cmd: ReactSlashMenuItem) => cmd.match(query) - ) + props.slashMenuItems || defaultReactSlashMenuItems ); return callbacks.current!.destroy; - }, [props.editor]); + }, [props.editor, props.slashMenuItems]); const getReferenceClientRect = useMemo(() => { if (!referencePos.current) { @@ -54,27 +65,29 @@ export const SlashMenuWrapper = (props: { return () => referencePos.current!; }, [referencePos.current]); - const slashMenu = useMemo(() => { + const slashMenuElement = useMemo(() => { if ( - !items || + !filteredItems || keyboardHoveredItemIndex === undefined || !callbacks.current ) { return null; } + const SlashMenu = props.slashMenu || DefaultSlashMenu; + return ( - callbacks.current!.itemCallback(item)} keyboardHoveredItemIndex={keyboardHoveredItemIndex!} /> ); - }, [items, keyboardHoveredItemIndex]); + }, [filteredItems, keyboardHoveredItemIndex, props.slashMenu]); return ( Date: Tue, 25 Jul 2023 16:53:00 +0200 Subject: [PATCH 18/42] Numerous changes: - Menu extensions are now initialized on editor creation and expose listeners - Cleaned up slash menu item creation and typing - Fixed drag & drop causing errors when calling `getBlockInfoFromPos` --- .../vanilla/src/ui/addFormattingToolbar.ts | 4 +- .../vanilla/src/ui/addHyperlinkToolbar.ts | 4 +- examples/vanilla/src/ui/addSideMenu.ts | 4 +- examples/vanilla/src/ui/addSlashMenu.ts | 54 ++-- packages/core/src/BlockNoteEditor.ts | 244 +++++++++++++++++- .../Blocks/helpers/getBlockInfoFromPos.ts | 6 + .../DraggableBlocks/DraggableBlocksPlugin.ts | 115 ++++----- .../FormattingToolbarPlugin.ts | 59 ++--- .../HyperlinkToolbarPlugin.ts | 94 +++---- .../extensions/SlashMenu/BaseSlashMenuItem.ts | 44 ++-- .../extensions/SlashMenu/SlashMenuPlugin.ts | 34 ++- .../SlashMenu/defaultSlashMenuItems.ts | 122 +++++++++ .../SlashMenu/defaultSlashMenuItems.tsx | 195 -------------- .../core/src/extensions/SlashMenu/index.ts | 4 - packages/core/src/index.ts | 2 +- .../plugins/suggestion/SuggestionItem.ts | 10 +- .../plugins/suggestion/SuggestionPlugin.ts | 90 +++---- packages/react/src/BlockNoteView.tsx | 21 +- .../components/DefaultFormattingToolbar.tsx | 2 +- ...er.tsx => FormattingToolbarPositioner.tsx} | 13 +- .../components/DefaultHyperlinkToolbar.tsx | 15 +- ...per.tsx => HyperlinkToolbarPositioner.tsx} | 12 +- .../SideMenu/components/DefaultSideMenu.tsx | 2 +- ...MenuWrapper.tsx => SideMenuPositioner.tsx} | 13 +- .../SlashMenu/components/DefaultSlashMenu.tsx | 7 +- ...enuWrapper.tsx => SlashMenuPositioner.tsx} | 48 ++-- .../SlashMenu/defaultReactSlashMenuItems.tsx | 27 +- packages/react/src/hooks/useBlockNote.ts | 18 +- packages/react/src/index.ts | 8 +- 29 files changed, 707 insertions(+), 564 deletions(-) create mode 100644 packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts delete mode 100644 packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.tsx delete mode 100644 packages/core/src/extensions/SlashMenu/index.ts rename packages/react/src/FormattingToolbar/components/{FormattingToolbarWrapper.tsx => FormattingToolbarPositioner.tsx} (85%) rename packages/react/src/HyperlinkToolbar/components/{HyperlinkToolbarWrapper.tsx => HyperlinkToolbarPositioner.tsx} (90%) rename packages/react/src/SideMenu/components/{SideMenuWrapper.tsx => SideMenuPositioner.tsx} (85%) rename packages/react/src/SlashMenu/components/{SlashMenuWrapper.tsx => SlashMenuPositioner.tsx} (58%) diff --git a/examples/vanilla/src/ui/addFormattingToolbar.ts b/examples/vanilla/src/ui/addFormattingToolbar.ts index c8d36d18ef..c2d95b8e81 100644 --- a/examples/vanilla/src/ui/addFormattingToolbar.ts +++ b/examples/vanilla/src/ui/addFormattingToolbar.ts @@ -1,11 +1,11 @@ -import { BlockNoteEditor, createFormattingToolbar } from "@blocknote/core"; +import { BlockNoteEditor } from "@blocknote/core"; import { createButton } from "./util"; export const addFormattingToolbar = (editor: BlockNoteEditor) => { let element: HTMLElement; let boldBtn: HTMLAnchorElement; - createFormattingToolbar(editor, (formattingToolbarState) => { + editor.createFormattingToolbar((formattingToolbarState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; diff --git a/examples/vanilla/src/ui/addHyperlinkToolbar.ts b/examples/vanilla/src/ui/addHyperlinkToolbar.ts index a55e12021b..bf2fd299bb 100644 --- a/examples/vanilla/src/ui/addHyperlinkToolbar.ts +++ b/examples/vanilla/src/ui/addHyperlinkToolbar.ts @@ -1,10 +1,10 @@ -import { BlockNoteEditor, createHyperlinkToolbar } from "@blocknote/core"; +import { BlockNoteEditor } from "@blocknote/core"; import { createButton } from "./util"; export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { let element: HTMLElement; - const callbacks = createHyperlinkToolbar(editor, (hyperlinkToolbarState) => { + const callbacks = editor.createHyperlinkToolbar((hyperlinkToolbarState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; diff --git a/examples/vanilla/src/ui/addSideMenu.ts b/examples/vanilla/src/ui/addSideMenu.ts index d6717d6667..cc4f829553 100644 --- a/examples/vanilla/src/ui/addSideMenu.ts +++ b/examples/vanilla/src/ui/addSideMenu.ts @@ -1,10 +1,10 @@ -import { BlockNoteEditor, createSideMenu } from "@blocknote/core"; +import { BlockNoteEditor } from "@blocknote/core"; import { createButton } from "./util"; export const addSideMenu = (editor: BlockNoteEditor) => { let element: HTMLElement; - const callbacks = createSideMenu(editor, (sideMenuState) => { + const callbacks = editor.createSideMenu((sideMenuState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; diff --git a/examples/vanilla/src/ui/addSlashMenu.ts b/examples/vanilla/src/ui/addSlashMenu.ts index 6b8e32de8b..25ff74a057 100644 --- a/examples/vanilla/src/ui/addSlashMenu.ts +++ b/examples/vanilla/src/ui/addSlashMenu.ts @@ -1,8 +1,6 @@ import { BaseSlashMenuItem, BlockNoteEditor, - createSlashMenu, - defaultSlashMenuItems, DefaultBlockSchema, } from "@blocknote/core"; import { createButton } from "./util"; @@ -30,36 +28,32 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { return domItems; } - const callbacks = createSlashMenu>( - editor, - (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"; + const callbacks = editor.createSlashMenu((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); - } + document.getElementById("root")!.appendChild(element); + } - if (slashMenuState.show) { - updateItems( - slashMenuState.filteredItems, - callbacks.itemCallback, - slashMenuState.keyboardHoveredItemIndex - ); + if (slashMenuState.show) { + updateItems( + slashMenuState.filteredItems, + callbacks.itemCallback, + slashMenuState.keyboardHoveredItemIndex + ); - element.style.display = "block"; + 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"; - } - }, - defaultSlashMenuItems - ); + element.style.top = slashMenuState.referencePos.top + "px"; + element.style.left = + slashMenuState.referencePos.x - element.offsetWidth + "px"; + } else { + element.style.display = "none"; + } + }); }; diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index c19b0fbe0e..10c9cc06f0 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -1,4 +1,4 @@ -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"; @@ -39,9 +39,27 @@ import { import { Selection } from "./extensions/Blocks/api/selectionTypes"; import { getBlockInfoFromPos } from "./extensions/Blocks/helpers/getBlockInfoFromPos"; import { - BaseSlashMenuItem, - defaultSlashMenuItems, -} from "./extensions/SlashMenu"; + setupFormattingToolbar, + FormattingToolbarState, + FormattingToolbarCallbacks, +} from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; +import { + HyperlinkToolbarCallbacks, + HyperlinkToolbarState, + setupHyperlinkToolbar, +} from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; +import { + SuggestionsMenuCallbacks, + SuggestionsMenuState, +} from "./shared/plugins/suggestion/SuggestionPlugin"; +import { setupSlashMenu } from "./extensions/SlashMenu/SlashMenuPlugin"; +import { + setupSideMenu, + SideMenuCallbacks, + SideMenuState, +} from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; +import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; +import { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; export type BlockNoteEditorOptions = { // TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them. @@ -157,6 +175,82 @@ export class BlockNoteEditor { this._tiptapEditor.view.focus(); } + private uiElementCallbacks: { + formattingToolbar: FormattingToolbarCallbacks; + hyperlinkToolbar: HyperlinkToolbarCallbacks; + slashMenu: SuggestionsMenuCallbacks>; + sideMenu: SideMenuCallbacks; + }; + + private uiElementListeners: Partial<{ + formattingToolbar: (formattingToolbarState: FormattingToolbarState) => void; + hyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void; + slashMenu: ( + slashMenuState: SuggestionsMenuState> + ) => void; + sideMenu: (sideMenuState: SideMenuState) => void; + }> = {}; + + public createFormattingToolbar = ( + updateFormattingToolbar: ( + formattingToolbarState: FormattingToolbarState + ) => void + ) => { + if ("formattingToolbar" in this.uiElementListeners) { + throw Error( + "You have already created a Formatting Toolbar. You can only create a single Formatting Toolbar per BlockNote editor instance." + ); + } + + this.uiElementListeners.formattingToolbar = updateFormattingToolbar; + + return this.uiElementCallbacks.formattingToolbar; + }; + + public createHyperlinkToolbar = ( + updateHyperlinkToolbar: ( + hyperlinkToolbarState: HyperlinkToolbarState + ) => void + ) => { + if ("hyperlinkToolbar" in this.uiElementListeners) { + throw Error( + "You have already created a Hyperlink Toolbar. You can only create a single Hyperlink Toolbar per BlockNote editor instance." + ); + } + + this.uiElementListeners.hyperlinkToolbar = updateHyperlinkToolbar; + + return this.uiElementCallbacks.hyperlinkToolbar; + }; + + public createSlashMenu = >( + updateSlashMenu: (slashMenuState: SuggestionsMenuState) => void + ) => { + if ("slashMenu" in this.uiElementListeners) { + throw Error( + "You have already created a Slash Menu. You can only create a single Slash Menu per BlockNote editor instance." + ); + } + + this.uiElementListeners.slashMenu = updateSlashMenu as any; + + return this.uiElementCallbacks.slashMenu; + }; + + public createSideMenu = ( + updateSideMenu: (sideMenuState: SideMenuState) => void + ) => { + if ("sideMenu" in this.uiElementListeners) { + throw Error( + "You have already created a Side Menu. You can only create a single Side Menu per BlockNote editor instance." + ); + } + + this.uiElementListeners.sideMenu = updateSideMenu; + + return this.uiElementCallbacks.sideMenu; + }; + constructor( private readonly options: Partial> = {} ) { @@ -175,15 +269,145 @@ export class BlockNoteEditor { ...options, }; + const editor = this; + const extensions = getBlockNoteExtensions({ editor: this, - slashCommands: newOptions.slashCommands || defaultSlashMenuItems, + slashCommands: + newOptions.slashCommands || + getDefaultSlashMenuItems(newOptions.blockSchema), blockSchema: newOptions.blockSchema, collaboration: newOptions.collaboration, }); this.schema = newOptions.blockSchema; + let formattingToolbarCallbacks: FormattingToolbarCallbacks; + const formattingToolbarExtension = Extension.create({ + name: "FormattingToolbarExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupFormattingToolbar( + editor, + this.editor, + (formattingToolbarState) => { + const formattingToolbarListener = + editor.uiElementListeners.formattingToolbar; + + if (!formattingToolbarListener) { + return; + } + + formattingToolbarListener(formattingToolbarState); + } + ); + + formattingToolbarCallbacks = { + destroy: () => delete editor.uiElementListeners.formattingToolbar, + ...callbacks, + }; + + return [plugin]; + }, + }); + + extensions.push(formattingToolbarExtension); + + let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks; + const hyperlinkToolbarExtension = Extension.create({ + name: "HyperlinkToolbarExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupHyperlinkToolbar( + editor, + this.editor, + (hyperlinkToolbarState) => { + const hyperlinkToolbarListener = + editor.uiElementListeners.hyperlinkToolbar; + + if (!hyperlinkToolbarListener) { + return; + } + + hyperlinkToolbarListener(hyperlinkToolbarState); + } + ); + + hyperlinkToolbarCallbacks = { + destroy: () => delete editor.uiElementListeners.hyperlinkToolbar, + ...callbacks, + }; + + return [plugin]; + }, + }); + + extensions.push(hyperlinkToolbarExtension); + + let slashMenuCallbacks: SuggestionsMenuCallbacks< + BaseSlashMenuItem + >; + const slashMenuExtension = Extension.create({ + name: "SlashMenuExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupSlashMenu( + editor, + this.editor, + (slashMenuState) => { + const slashMenuListener = editor.uiElementListeners.slashMenu; + + if (!slashMenuListener) { + return; + } + + slashMenuListener(slashMenuState as any); + }, + newOptions.slashCommands || + getDefaultSlashMenuItems(newOptions.blockSchema) + ); + + slashMenuCallbacks = { + destroy: () => delete editor.uiElementListeners.slashMenu, + ...callbacks, + }; + + return [plugin]; + }, + }); + + extensions.push(slashMenuExtension); + + let sideMenuCallbacks: SideMenuCallbacks; + const sideMenuExtension = Extension.create({ + name: "SideMenuExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupSideMenu( + editor, + this.editor, + (sideMenuState) => { + const sideMenuListener = editor.uiElementListeners.sideMenu; + + if (!sideMenuListener) { + return; + } + + sideMenuListener(sideMenuState as any); + } + ); + + sideMenuCallbacks = { + destroy: () => delete editor.uiElementListeners.sideMenu, + ...callbacks, + }; + + return [plugin]; + }, + }); + + extensions.push(sideMenuExtension); + 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. @@ -195,6 +419,7 @@ export class BlockNoteEditor { ...blockNoteTipTapOptions, ...newOptions._tiptapOptions, onCreate: () => { + console.log("create"); newOptions.onEditorReady?.(this); newOptions.initialContent && this.replaceBlocks(this.topLevelBlocks, newOptions.initialContent); @@ -231,6 +456,15 @@ export class BlockNoteEditor { this._tiptapEditor = new Editor(tiptapOptions) as Editor & { contentComponent: any; }; + + // These need to be assigned after the TipTap editor is created as they are + // initialized in a plugin, which is only loaded on editor creation. + this.uiElementCallbacks = { + formattingToolbar: formattingToolbarCallbacks!, + hyperlinkToolbar: hyperlinkToolbarCallbacks!, + slashMenu: slashMenuCallbacks!, + sideMenu: sideMenuCallbacks!, + }; } /** 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/DraggableBlocksPlugin.ts b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts index c39b45a961..6ad785e420 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts @@ -13,6 +13,7 @@ import { Block, BlockSchema } from "../Blocks/api/blockTypes"; import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; import { MultipleNodeSelection } from "./MultipleNodeSelection"; +import { Editor } from "@tiptap/core"; const serializeForClipboard = (pv as any).__serializeForClipboard; // code based on https://github.com/ueberdosis/tiptap/issues/323#issuecomment-506637799 @@ -244,6 +245,7 @@ function dragStart(e: DragEvent, view: EditorView) { export class SideMenuView implements PluginView { editor: BlockNoteEditor; + ttEditor: Editor; private sideMenuState?: SideMenuState; public updateSideMenu: () => void; @@ -263,12 +265,15 @@ export class SideMenuView implements PluginView { constructor( editor: BlockNoteEditor, + tiptapEditor: Editor, updateSideMenu: (sideMenuState: SideMenuState) => void ) { this.editor = editor; + this.ttEditor = tiptapEditor; + this.horizontalPosAnchoredAtRoot = true; this.horizontalPosAnchor = ( - this.editor._tiptapEditor.view.dom.firstChild! as HTMLElement + this.ttEditor.view.dom.firstChild! as HTMLElement ).getBoundingClientRect().x; this.updateSideMenu = () => { @@ -281,10 +286,7 @@ export class SideMenuView implements PluginView { document.body.addEventListener("drop", this.onDrop, true); document.body.addEventListener("dragover", this.onDragOver); - this.editor._tiptapEditor.view.dom.addEventListener( - "dragstart", - this.onDragStart - ); + this.ttEditor.view.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); @@ -311,10 +313,13 @@ export class SideMenuView implements PluginView { * when dragging / dropping to the side of the editor */ onDrop = (event: DragEvent) => { + this.ttEditor.commands.blur(); + if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.editor._tiptapEditor.view.posAtCoords({ + + let pos = this.ttEditor.view.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -324,7 +329,7 @@ export class SideMenuView implements PluginView { if (!pos || pos.inside === -1) { const evt = new Event("drop", event) as any; const editorBoundingBox = ( - this.editor._tiptapEditor.view.dom.firstChild! as HTMLElement + this.ttEditor.view.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -332,7 +337,7 @@ export class SideMenuView implements PluginView { evt.preventDefault = () => event.preventDefault(); evt.synthetic = true; // prevent recursion // console.log("dispatch fake drop"); - this.editor._tiptapEditor.view.dom.dispatchEvent(evt); + this.ttEditor.view.dom.dispatchEvent(evt); } }; @@ -345,7 +350,7 @@ export class SideMenuView implements PluginView { if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.editor._tiptapEditor.view.posAtCoords({ + let pos = this.ttEditor.view.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -353,7 +358,7 @@ export class SideMenuView implements PluginView { if (!pos || pos.inside === -1) { const evt = new Event("dragover", event) as any; const editorBoundingBox = ( - this.editor._tiptapEditor.view.dom.firstChild! as HTMLElement + this.ttEditor.view.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -361,7 +366,7 @@ export class SideMenuView implements PluginView { evt.preventDefault = () => event.preventDefault(); evt.synthetic = true; // prevent recursion // console.log("dispatch fake dragover"); - this.editor._tiptapEditor.view.dom.dispatchEvent(evt); + this.ttEditor.view.dom.dispatchEvent(evt); } }; @@ -397,19 +402,19 @@ export class SideMenuView implements PluginView { // blockGroup that wraps all blocks in the editor) for more accurate side // menu placement. const editorBoundingBox = ( - this.editor._tiptapEditor.view.dom.firstChild! as HTMLElement + this.ttEditor.view.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.editor._tiptapEditor.view.dom.getBoundingClientRect(); + this.ttEditor.view.dom.getBoundingClientRect(); const cursorWithinEditor = event.clientX >= editorOuterBoundingBox.left && event.clientX <= editorOuterBoundingBox.right && event.clientY >= editorOuterBoundingBox.top && event.clientY <= editorOuterBoundingBox.bottom; - const editorWrapper = this.editor._tiptapEditor.view.dom.parentElement!; + const editorWrapper = this.ttEditor.view.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. @@ -441,10 +446,7 @@ export class SideMenuView implements PluginView { top: event.clientY, }; - const block = getDraggableBlockFromCoords( - coords, - this.editor._tiptapEditor.view - ); + const block = getDraggableBlockFromCoords(coords, this.ttEditor.view); // Closes the menu if the mouse cursor is beyond the editor vertically. if (!block || !this.editor.isEditable) { @@ -524,10 +526,7 @@ export class SideMenuView implements PluginView { // the params passed to addEventListener. document.body.removeEventListener("mousemove", this.onMouseMove, true); document.body.removeEventListener("dragover", this.onDragOver); - this.editor._tiptapEditor.view.dom.removeEventListener( - "dragstart", - this.onDragStart - ); + this.ttEditor.view.dom.removeEventListener("dragstart", this.onDragStart); document.body.removeEventListener("drop", this.onDrop, true); document.body.removeEventListener("mousedown", this.onMouseDown, true); document.removeEventListener("scroll", this.onScroll); @@ -545,7 +544,7 @@ export class SideMenuView implements PluginView { const blockContent = this.hoveredBlock!.firstChild! as HTMLElement; const blockContentBoundingBox = blockContent.getBoundingClientRect(); - const pos = this.editor._tiptapEditor.view.posAtCoords({ + const pos = this.ttEditor.view.posAtCoords({ left: blockContentBoundingBox.left + blockContentBoundingBox.width / 2, top: blockContentBoundingBox.top + blockContentBoundingBox.height / 2, }); @@ -553,10 +552,7 @@ export class SideMenuView implements PluginView { return; } - const blockInfo = getBlockInfoFromPos( - this.editor._tiptapEditor.state.doc, - pos.pos - ); + const blockInfo = getBlockInfoFromPos(this.ttEditor.state.doc, pos.pos); if (blockInfo === undefined) { return; } @@ -568,66 +564,57 @@ export class SideMenuView implements PluginView { const newBlockInsertionPos = endPos + 1; const newBlockContentPos = newBlockInsertionPos + 2; - this.editor._tiptapEditor + this.ttEditor .chain() .BNCreateBlock(newBlockInsertionPos) .BNUpdateBlock(newBlockContentPos, { type: "paragraph", props: {} }) .setTextSelection(newBlockContentPos) .run(); } else { - this.editor._tiptapEditor.commands.setTextSelection(endPos); + this.ttEditor.commands.setTextSelection(endPos); } // Focuses and activates the suggestion menu. - this.editor._tiptapEditor.view.focus(); - this.editor._tiptapEditor.view.dispatch( - this.editor._tiptapEditor.view.state.tr - .scrollIntoView() - .setMeta(slashMenuPluginKey, { - // TODO import suggestion plugin key - activate: true, - type: "drag", - }) + this.ttEditor.view.focus(); + this.ttEditor.view.dispatch( + this.ttEditor.view.state.tr.scrollIntoView().setMeta(slashMenuPluginKey, { + // TODO import suggestion plugin key + activate: true, + type: "drag", + }) ); } } export const sideMenuPluginKey = new PluginKey("SideMenuPlugin"); -export function createSideMenu( + +export function setupSideMenu( editor: BlockNoteEditor, + tiptapEditor: Editor, updateSideMenu: (sideMenuState: SideMenuState) => void -): SideMenuCallbacks { +): { + plugin: Plugin; + callbacks: Omit; +} { let sideMenuView: SideMenuView; - editor._tiptapEditor.registerPlugin( - new Plugin({ + return { + plugin: new Plugin({ key: sideMenuPluginKey, view: () => { - if (sideMenuView) { - sideMenuView.destroy(); - } - - sideMenuView = new SideMenuView(editor, updateSideMenu); + sideMenuView = new SideMenuView(editor, tiptapEditor, updateSideMenu); return sideMenuView; }, }), - // Ensures the plugin is loaded at the highest priority so that things like - // keyboard handlers work. - (sideMenuPlugin, plugins) => { - plugins.unshift(sideMenuPlugin); - return plugins; - } - ); - - return { - addBlock: () => sideMenuView.addBlock(), - blockDragStart: (event: DragEvent) => { - sideMenuView.isDragging = true; - dragStart(event, sideMenuView.editor._tiptapEditor.view); + callbacks: { + addBlock: () => sideMenuView.addBlock(), + blockDragStart: (event: DragEvent) => { + sideMenuView.isDragging = true; + dragStart(event, sideMenuView.ttEditor.view); + }, + blockDragEnd: () => unsetDragImage(), + freezeMenu: () => (sideMenuView.menuFrozen = true), + unfreezeMenu: () => (sideMenuView.menuFrozen = false), }, - blockDragEnd: () => unsetDragImage(), - freezeMenu: () => (sideMenuView.menuFrozen = true), - unfreezeMenu: () => (sideMenuView.menuFrozen = false), - destroy: () => editor._tiptapEditor.unregisterPlugin(sideMenuPluginKey), }; } diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 861cd30b28..4c65d8224a 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -20,7 +20,6 @@ export type FormattingToolbarState = BaseUiElementState; export class FormattingToolbarView { public editor: BlockNoteEditor; private ttEditor: Editor; - public view: EditorView; private formattingToolbarState?: FormattingToolbarState; public updateFormattingToolbar: () => void; @@ -49,14 +48,13 @@ export class FormattingToolbarView { constructor( editor: BlockNoteEditor, - view: EditorView, + tipTapEditor: Editor, updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState ) => void ) { - this.view = view; this.editor = editor; - this.ttEditor = editor._tiptapEditor; + this.ttEditor = tipTapEditor; this.updateFormattingToolbar = () => { if (!this.formattingToolbarState) { @@ -68,9 +66,12 @@ export class FormattingToolbarView { updateFormattingToolbar(this.formattingToolbarState); }; - this.view.dom.addEventListener("mousedown", this.viewMousedownHandler); - this.view.dom.addEventListener("mouseup", this.viewMouseupHandler); - this.view.dom.addEventListener("dragstart", this.dragstartHandler); + this.ttEditor.view.dom.addEventListener( + "mousedown", + this.viewMousedownHandler + ); + this.ttEditor.view.dom.addEventListener("mouseup", this.viewMouseupHandler); + this.ttEditor.view.dom.addEventListener("dragstart", this.dragstartHandler); this.ttEditor.on("focus", this.focusHandler); this.ttEditor.on("blur", this.blurHandler); @@ -193,9 +194,18 @@ export class FormattingToolbarView { } destroy() { - this.view.dom.removeEventListener("mousedown", this.viewMousedownHandler); - this.view.dom.removeEventListener("mouseup", this.viewMouseupHandler); - this.view.dom.removeEventListener("dragstart", this.dragstartHandler); + this.ttEditor.view.dom.removeEventListener( + "mousedown", + this.viewMousedownHandler + ); + this.ttEditor.view.dom.removeEventListener( + "mouseup", + this.viewMouseupHandler + ); + this.ttEditor.view.dom.removeEventListener( + "dragstart", + this.dragstartHandler + ); this.ttEditor.off("focus", this.focusHandler); this.ttEditor.off("blur", this.blurHandler); @@ -227,39 +237,30 @@ export class FormattingToolbarView { export const formattingToolbarPluginKey = new PluginKey( "FormattingToolbarPlugin" ); -export const createFormattingToolbar = ( +export const setupFormattingToolbar = ( editor: BlockNoteEditor, + tiptapEditor: Editor, updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState ) => void -): FormattingToolbarCallbacks => { +): { + plugin: Plugin; + callbacks: Omit; +} => { let formattingToolbarView: FormattingToolbarView; - editor._tiptapEditor.registerPlugin( - new Plugin({ + return { + plugin: new Plugin({ key: formattingToolbarPluginKey, view: () => { - if (formattingToolbarView) { - formattingToolbarView.destroy(); - } - formattingToolbarView = new FormattingToolbarView( editor, - editor._tiptapEditor.view, + tiptapEditor, updateFormattingToolbar ); return formattingToolbarView; }, }), - // Ensures the plugin is loaded at the highest priority so that things like - // keyboard handlers work. - (formattingToolbarPlugin, plugins) => { - plugins.unshift(formattingToolbarPlugin); - return plugins; - } - ); - return { - destroy: () => - editor._tiptapEditor.unregisterPlugin(formattingToolbarPluginKey), + callbacks: {}, }; }; diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index a6fdca70ea..6731e60453 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -1,4 +1,4 @@ -import { getMarkRange, posToDOMRect, Range } from "@tiptap/core"; +import { Editor, getMarkRange, posToDOMRect, Range } from "@tiptap/core"; import { Mark } from "prosemirror-model"; import { Plugin, PluginKey } from "prosemirror-state"; import { BlockNoteEditor } from "../../BlockNoteEditor"; @@ -30,6 +30,7 @@ export type HyperlinkToolbarState = BaseUiElementState & { class HyperlinkToolbarView { editor: BlockNoteEditor; + ttEditor: Editor; private hyperlinkToolbarState?: HyperlinkToolbarState; public updateHyperlinkToolbar: () => void; @@ -49,11 +50,13 @@ class HyperlinkToolbarView { constructor( editor: BlockNoteEditor, + tiptapEditor: Editor, updateHyperlinkToolbar: ( hyperlinkToolbarState: HyperlinkToolbarState ) => void ) { this.editor = editor; + this.ttEditor = tiptapEditor; this.updateHyperlinkToolbar = () => { if (!this.hyperlinkToolbarState) { @@ -78,10 +81,7 @@ class HyperlinkToolbarView { return false; }; - this.editor._tiptapEditor.view.dom.addEventListener( - "mouseover", - this.mouseOverHandler - ); + this.ttEditor.view.dom.addEventListener("mouseover", this.mouseOverHandler); document.addEventListener("click", this.clickHandler, true); document.addEventListener("scroll", this.scrollHandler); } @@ -101,16 +101,14 @@ class HyperlinkToolbarView { // mouseHoveredHyperlinkMarkRange. const hoveredHyperlinkElement = event.target; const posInHoveredHyperlinkMark = - this.editor._tiptapEditor.view.posAtDOM(hoveredHyperlinkElement, 0) + 1; - const resolvedPosInHoveredHyperlinkMark = - this.editor._tiptapEditor.state.doc.resolve(posInHoveredHyperlinkMark); + this.ttEditor.view.posAtDOM(hoveredHyperlinkElement, 0) + 1; + const resolvedPosInHoveredHyperlinkMark = this.ttEditor.state.doc.resolve( + posInHoveredHyperlinkMark + ); const marksAtPos = resolvedPosInHoveredHyperlinkMark.marks(); for (const mark of marksAtPos) { - if ( - mark.type.name === - this.editor._tiptapEditor.schema.mark("link").type.name - ) { + if (mark.type.name === this.ttEditor.schema.mark("link").type.name) { this.mouseHoveredHyperlinkMark = mark; this.mouseHoveredHyperlinkMarkRange = getMarkRange( @@ -130,7 +128,7 @@ class HyperlinkToolbarView { }; clickHandler = (event: MouseEvent) => { - const editorWrapper = this.editor._tiptapEditor.view.dom.parentElement!; + const editorWrapper = this.ttEditor.view.dom.parentElement!; if ( // Toolbar is open. @@ -155,7 +153,7 @@ class HyperlinkToolbarView { if (this.hyperlinkMark !== undefined) { if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.referencePos = posToDOMRect( - this.editor._tiptapEditor.view, + this.ttEditor.view, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ); @@ -165,7 +163,7 @@ class HyperlinkToolbarView { }; editHyperlink(url: string, text: string) { - const tr = this.editor._tiptapEditor.view.state.tr.insertText( + const tr = this.ttEditor.view.state.tr.insertText( text, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to @@ -173,10 +171,10 @@ class HyperlinkToolbarView { tr.addMark( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.from + text.length, - this.editor._tiptapEditor.schema.mark("link", { href: url }) + this.ttEditor.schema.mark("link", { href: url }) ); - this.editor._tiptapEditor.view.dispatch(tr); - this.editor._tiptapEditor.view.focus(); + this.ttEditor.view.dispatch(tr); + this.ttEditor.view.focus(); if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.show = false; @@ -185,8 +183,8 @@ class HyperlinkToolbarView { } deleteHyperlink() { - this.editor._tiptapEditor.view.dispatch( - this.editor._tiptapEditor.view.state.tr + this.ttEditor.view.dispatch( + this.ttEditor.view.state.tr .removeMark( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to, @@ -194,7 +192,7 @@ class HyperlinkToolbarView { ) .setMeta("preventAutolink", true) ); - this.editor._tiptapEditor.view.focus(); + this.ttEditor.view.focus(); if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.show = false; @@ -203,7 +201,7 @@ class HyperlinkToolbarView { } update() { - if (!this.editor._tiptapEditor.view.hasFocus()) { + if (!this.ttEditor.view.hasFocus()) { return; } @@ -220,19 +218,15 @@ class HyperlinkToolbarView { // Finds link mark at the editor selection's position to update keyboardHoveredHyperlinkMark and // keyboardHoveredHyperlinkMarkRange. - if (this.editor._tiptapEditor.state.selection.empty) { - const marksAtPos = - this.editor._tiptapEditor.state.selection.$from.marks(); + if (this.ttEditor.state.selection.empty) { + const marksAtPos = this.ttEditor.state.selection.$from.marks(); for (const mark of marksAtPos) { - if ( - mark.type.name === - this.editor._tiptapEditor.schema.mark("link").type.name - ) { + if (mark.type.name === this.ttEditor.schema.mark("link").type.name) { this.keyboardHoveredHyperlinkMark = mark; this.keyboardHoveredHyperlinkMarkRange = getMarkRange( - this.editor._tiptapEditor.state.selection.$from, + this.ttEditor.state.selection.$from, mark.type, mark.attrs ) || undefined; @@ -257,12 +251,12 @@ class HyperlinkToolbarView { this.hyperlinkToolbarState = { show: true, referencePos: posToDOMRect( - this.editor._tiptapEditor.view, + this.ttEditor.view, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ), url: this.hyperlinkMark!.attrs.href, - text: this.editor._tiptapEditor.view.state.doc.textBetween( + text: this.ttEditor.view.state.doc.textBetween( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ), @@ -286,7 +280,7 @@ class HyperlinkToolbarView { } destroy() { - this.editor._tiptapEditor.view.dom.removeEventListener( + this.ttEditor.view.dom.removeEventListener( "mouseover", this.mouseOverHandler ); @@ -298,36 +292,34 @@ class HyperlinkToolbarView { export const hyperlinkToolbarPluginKey = new PluginKey( "HyperlinkToolbarPlugin" ); -export const createHyperlinkToolbar = ( +export const setupHyperlinkToolbar = ( editor: BlockNoteEditor, + tiptapEditor: Editor, updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void -): HyperlinkToolbarCallbacks => { +): { + plugin: Plugin; + callbacks: Omit; +} => { let hyperlinkToolbarView: HyperlinkToolbarView; - editor._tiptapEditor.registerPlugin( - new Plugin({ + return { + plugin: new Plugin({ key: hyperlinkToolbarPluginKey, view: () => { hyperlinkToolbarView = new HyperlinkToolbarView( editor, + tiptapEditor, updateHyperlinkToolbar ); return hyperlinkToolbarView; }, }), - // Ensures the plugin is loaded at the highest priority so that things like - // keyboard handlers work. - (hyperlinkToolbarPlugin, plugins) => { - plugins.unshift(hyperlinkToolbarPlugin); - return plugins; - } - ); - return { - editHyperlink: (url, text) => hyperlinkToolbarView.editHyperlink(url, text), - deleteHyperlink: () => hyperlinkToolbarView.deleteHyperlink(), - startHideTimer: () => hyperlinkToolbarView.startMenuUpdateTimer(), - stopHideTimer: () => hyperlinkToolbarView.stopMenuUpdateTimer(), - destroy: () => - editor._tiptapEditor.unregisterPlugin(hyperlinkToolbarPluginKey), + callbacks: { + editHyperlink: (url, text) => + hyperlinkToolbarView.editHyperlink(url, text), + deleteHyperlink: () => hyperlinkToolbarView.deleteHyperlink(), + startHideTimer: () => hyperlinkToolbarView.startMenuUpdateTimer(), + stopHideTimer: () => hyperlinkToolbarView.stopMenuUpdateTimer(), + }, }; }; diff --git a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts index 355cc0b1f6..aeef81aa78 100644 --- a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts +++ b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts @@ -2,33 +2,27 @@ import { SuggestionItem } from "../../shared/plugins/suggestion/SuggestionItem"; import { BlockNoteEditor } from "../../BlockNoteEditor"; import { BlockSchema } from "../Blocks/api/blockTypes"; -/** - * 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 => { +export type BaseSlashMenuItem = SuggestionItem & { + execute: (editor: BlockNoteEditor) => void; + aliases: string[]; +}; + +export function createBaseSlashMenuItem( + name: string, + execute: (editor: BlockNoteEditor) => void, + aliases: string[] = [] +): BaseSlashMenuItem { + return { + name, + execute, + aliases, + match: (query: string): boolean => { return ( - this.name.toLowerCase().startsWith(query.toLowerCase()) || - this.aliases.filter((alias) => + name.toLowerCase().startsWith(query.toLowerCase()) || + aliases.filter((alias) => alias.toLowerCase().startsWith(query.toLowerCase()) ).length !== 0 ); - }); - } + }, + }; } diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index fb692729b3..ddd6c39194 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -1,29 +1,37 @@ -import { PluginKey } from "prosemirror-state"; +import { Plugin, PluginKey } from "prosemirror-state"; import { BlockNoteEditor } from "../../BlockNoteEditor"; import { - createSuggestionPlugin, + setupSuggestionsMenu, SuggestionsMenuState, - SuggestionsPluginCallbacks, + SuggestionsMenuCallbacks, } from "../../shared/plugins/suggestion/SuggestionPlugin"; -import { DefaultBlockSchema } from "../Blocks/api/defaultBlocks"; import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; +import { Editor } from "@tiptap/core"; +import { BlockSchema } from "../Blocks/api/blockTypes"; export const slashMenuPluginKey = new PluginKey("SlashMenuPlugin"); -export const createSlashMenu = < - SlashMenuItem extends BaseSlashMenuItem +export const setupSlashMenu = < + BSchema extends BlockSchema, + SlashMenuItem extends BaseSlashMenuItem >( - editor: BlockNoteEditor, + editor: BlockNoteEditor, + tiptapEditor: Editor, updateSlashMenu: ( slashMenuState: SuggestionsMenuState ) => void, items: SlashMenuItem[] -): SuggestionsPluginCallbacks => { - return createSuggestionPlugin( +): { + plugin: Plugin; + callbacks: Omit, "destroy">; +} => { + return setupSuggestionsMenu( + editor, + tiptapEditor, + updateSlashMenu, + slashMenuPluginKey, "/", - editor, - (slashMenuState) => updateSlashMenu(slashMenuState), - ({ item, editor }) => item.execute(editor), - (query) => items.filter((item: SlashMenuItem) => item.match(query)) + (query) => items.filter((item: SlashMenuItem) => item.match(query)), + ({ item, editor }) => item.execute(editor) ); }; diff --git a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts new file mode 100644 index 0000000000..0a79603c6c --- /dev/null +++ b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts @@ -0,0 +1,122 @@ +import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { BlockSchema, PartialBlock } from "../Blocks/api/blockTypes"; +import { + BaseSlashMenuItem, + createBaseSlashMenuItem, +} 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!); + } +} + +export const getDefaultSlashMenuItems = ( + schema: BSchema +) => { + const slashMenuItems: BaseSlashMenuItem[] = []; + + if ("heading" in schema && "level" in schema.heading.propSchema) { + if (schema.heading.propSchema.level.values?.includes("1")) { + slashMenuItems.push( + // Command for creating a level 1 heading + createBaseSlashMenuItem( + "Heading", + (editor) => + insertOrUpdateBlock(editor, { + type: "heading", + props: { level: "1" }, + } as PartialBlock), + ["h", "heading1", "h1"] + ) + ); + } + + if (schema.heading.propSchema.level.values?.includes("2")) { + slashMenuItems.push( + // Command for creating a level 2 heading + createBaseSlashMenuItem( + "Heading 2", + (editor) => + insertOrUpdateBlock(editor, { + type: "heading", + props: { level: "2" }, + } as PartialBlock), + ["h2", "heading2", "subheading"] + ) + ); + } + + if (schema.heading.propSchema.level.values?.includes("3")) { + slashMenuItems.push( + // Command for creating a level 3 heading + createBaseSlashMenuItem( + "Heading 3", + (editor) => + insertOrUpdateBlock(editor, { + type: "heading", + props: { level: "3" }, + } as PartialBlock), + ["h3", "heading3", "subheading"] + ) + ); + } + } + + if ("bulletListItem" in schema) { + slashMenuItems.push( + // Command for creating a bullet list item + createBaseSlashMenuItem( + "Bullet List", + (editor) => + insertOrUpdateBlock(editor, { + type: "bulletListItem", + } as PartialBlock), + ["ul", "list", "bulletlist", "bullet list"] + ) + ); + } + + if ("numberedListItem" in schema) { + slashMenuItems.push( + // Command for creating a numbered list item + createBaseSlashMenuItem( + "Numbered List", + (editor) => + insertOrUpdateBlock(editor, { + type: "numberedListItem", + } as PartialBlock), + ["li", "list", "numberedlist", "numbered list"] + ) + ); + } + + if ("paragraph" in schema) { + slashMenuItems.push( + // Command for creating a paragraph + createBaseSlashMenuItem( + "Paragraph", + (editor) => + insertOrUpdateBlock(editor, { + type: "paragraph", + } as PartialBlock), + ["p"] + ) + ); + } + + 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 3fb14694c5..0000000000 --- a/packages/core/src/extensions/SlashMenu/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { defaultSlashMenuItems } from "./defaultSlashMenuItems"; -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; - -export { defaultSlashMenuItems, BaseSlashMenuItem }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 9ece264c0a..7ecea91239 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -17,5 +17,5 @@ export * from "./shared/BaseUiElementTypes"; export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; export * from "./extensions/SlashMenu/BaseSlashMenuItem"; -export { defaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; +export { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; export type { SuggestionItem } from "./shared/plugins/suggestion/SuggestionItem"; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts b/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts index 7fe85af195..6b0eb26ec6 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts @@ -1,6 +1,4 @@ -/** - * 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; + match: (query: string) => boolean; +}; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index a82b4021df..fa0c8ae053 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -8,8 +8,9 @@ import { BaseUiElementState, } from "../../BaseUiElementTypes"; import { SuggestionItem } from "./SuggestionItem"; +import { Editor } from "@tiptap/core"; -export type SuggestionsPluginCallbacks = +export type SuggestionsMenuCallbacks = BaseUiElementCallbacks & { // The function to execute when selecting a suggested item. itemCallback: (item: T) => void; @@ -23,11 +24,12 @@ export type SuggestionsMenuState = keyboardHoveredItemIndex: number; }; -class SuggestionPluginView< +class SuggestionsMenuView< T extends SuggestionItem, BSchema extends BlockSchema > { editor: BlockNoteEditor; + ttEditor: Editor; pluginKey: PluginKey; private suggestionsMenuState?: SuggestionsMenuState; @@ -38,6 +40,7 @@ class SuggestionPluginView< constructor( editor: BlockNoteEditor, + tiptapEditor: Editor, pluginKey: PluginKey, onSelectItem: (props: { item: T; @@ -48,6 +51,7 @@ class SuggestionPluginView< ) => void = () => {} ) { this.editor = editor; + this.ttEditor = tiptapEditor; this.pluginKey = pluginKey; this.pluginState = getDefaultPluginState(); @@ -60,14 +64,14 @@ class SuggestionPluginView< }; this.itemCallback = (item: T) => { - editor._tiptapEditor + this.ttEditor .chain() .focus() .deleteRange({ from: this.pluginState.queryStartPos! - this.pluginState.triggerCharacter!.length, - to: editor._tiptapEditor.state.selection.from, + to: this.ttEditor.state.selection.from, }) .run(); @@ -180,43 +184,49 @@ function getDefaultPluginState< * - This version hides some unnecessary complexity from the user of the plugin. * - This version handles key events differently */ -export function createSuggestionPlugin< +export const setupSuggestionsMenu = < T extends SuggestionItem, BSchema extends BlockSchema >( - pluginKey: PluginKey, - defaultTriggerCharacter: string, editor: BlockNoteEditor, + tiptapEditor: Editor, updateSuggestionsMenu: ( suggestionsMenuState: SuggestionsMenuState ) => void, + + pluginKey: PluginKey, + defaultTriggerCharacter: string, + items: (query: string) => T[] = () => [], onSelectItem: (props: { item: T; editor: BlockNoteEditor; - }) => void = () => {}, - items: (query: string) => T[] = () => [] -): SuggestionsPluginCallbacks { + }) => void = () => {} +): { + plugin: Plugin; + callbacks: Omit, "destroy">; +} => { // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); } - let suggestionsPluginView: SuggestionPluginView; + let suggestionsPluginView: SuggestionsMenuView; const deactivate = (view: EditorView) => { view.dispatch(view.state.tr.setMeta(pluginKey, { deactivate: true })); }; - editor._tiptapEditor.registerPlugin( - new Plugin({ + return { + plugin: new Plugin({ key: pluginKey, view: () => { - suggestionsPluginView = new SuggestionPluginView( + suggestionsPluginView = new SuggestionsMenuView( editor, + tiptapEditor, pluginKey, (props: { item: T; editor: BlockNoteEditor }) => { - deactivate(editor._tiptapEditor.view); + deactivate(tiptapEditor.view); onSelectItem(props); }, updateSuggestionsMenu @@ -382,12 +392,12 @@ export function createSuggestionPlugin< // Selects an item and closes the menu. if (event.key === "Enter") { deactivate(view); - editor._tiptapEditor + tiptapEditor .chain() .focus() .deleteRange({ from: queryStartPos! - triggerCharacter!.length, - to: editor._tiptapEditor.state.selection.from, + to: tiptapEditor.state.selection.from, }) .run(); @@ -456,32 +466,24 @@ export function createSuggestionPlugin< }, }, }), - // Ensures the plugin is loaded at the highest priority so that things like - // keyboard handlers work. - (suggestionPlugin, plugins) => { - plugins.unshift(suggestionPlugin); - return plugins; - } - ); - - return { - destroy: () => editor._tiptapEditor.unregisterPlugin(pluginKey), - itemCallback: (item: T) => { - editor._tiptapEditor - .chain() - .focus() - .deleteRange({ - from: - suggestionsPluginView.pluginState.queryStartPos! - - suggestionsPluginView.pluginState.triggerCharacter!.length, - to: editor._tiptapEditor.state.selection.from, - }) - .run(); - - onSelectItem({ - item: item, - editor: editor, - }); + callbacks: { + itemCallback: (item: T) => { + tiptapEditor + .chain() + .focus() + .deleteRange({ + from: + suggestionsPluginView.pluginState.queryStartPos! - + suggestionsPluginView.pluginState.triggerCharacter!.length, + to: tiptapEditor.state.selection.from, + }) + .run(); + + onSelectItem({ + item: item, + editor: editor, + }); + }, }, }; -} +}; diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index ab6b047353..b282621572 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -3,10 +3,10 @@ import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; import { getBlockNoteTheme } from "./BlockNoteTheme"; import { ReactNode } from "react"; -import { FormattingToolbarWrapper } from "./FormattingToolbar/components/FormattingToolbarWrapper"; -import { HyperlinkToolbarWrapper } from "./HyperlinkToolbar/components/HyperlinkToolbarWrapper"; -import { SlashMenuWrapper } from "./SlashMenu/components/SlashMenuWrapper"; -import { SideMenuWrapper } from "./SideMenu/components/SideMenuWrapper"; +import { FormattingToolbarPositioner } from "./FormattingToolbar/components/FormattingToolbarPositioner"; +import { HyperlinkToolbarPositioner } from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; +import { SlashMenuPositioner } from "./SlashMenu/components/SlashMenuPositioner"; +import { SideMenuPositioner } from "./SideMenu/components/SideMenuPositioner"; export function BlockNoteView(props: { editor: BlockNoteEditor; @@ -14,13 +14,16 @@ export function BlockNoteView(props: { }) { return ( - + {props.children || ( <> - - - - + + + + )} diff --git a/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx index 0495efa955..17591e17c6 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultFormattingToolbar.tsx @@ -1,6 +1,6 @@ import { BlockSchema } from "@blocknote/core"; -import { FormattingToolbarProps } from "./FormattingToolbarWrapper"; +import { FormattingToolbarProps } from "./FormattingToolbarPositioner"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { BlockTypeDropdown } from "./DefaultDropdowns/BlockTypeDropdown"; import { ToggledStyleButton } from "./DefaultButtons/ToggledStyleButton"; diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx similarity index 85% rename from packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx rename to packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 4a328dc8af..7caef35d9a 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarWrapper.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -4,7 +4,6 @@ import { sticky } from "tippy.js"; import { BlockNoteEditor, BlockSchema, - createFormattingToolbar, FormattingToolbarCallbacks, } from "@blocknote/core"; @@ -13,7 +12,9 @@ import { DefaultFormattingToolbar } from "./DefaultFormattingToolbar"; export type FormattingToolbarProps = { editor: BlockNoteEditor; }; -export const FormattingToolbarWrapper = (props: { +export const FormattingToolbarPositioner = < + BSchema extends BlockSchema +>(props: { editor: BlockNoteEditor; formattingToolbar?: FC>; }) => { @@ -23,7 +24,7 @@ export const FormattingToolbarWrapper = (props: { const callbacks = useRef(); useEffect(() => { - callbacks.current = createFormattingToolbar(props.editor, (state) => { + callbacks.current = props.editor.createFormattingToolbar((state) => { setShow(state.show); referencePos.current = state.referencePos; @@ -48,6 +49,7 @@ export const FormattingToolbarWrapper = (props: { return ( (props: { animation={"fade"} placement={"top-start"} sticky={true} - plugins={[sticky]}> -
- + plugins={[sticky]} + /> ); }; diff --git a/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx index 72fdc8e038..89b8b4cb82 100644 --- a/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx @@ -1,7 +1,7 @@ -import { useState } from "react"; +import { useRef, useState } from "react"; import { RiExternalLinkFill, RiLinkUnlink } from "react-icons/ri"; -import { HyperlinkToolbarProps } from "./HyperlinkToolbarWrapper"; +import { HyperlinkToolbarProps } from "./HyperlinkToolbarPositioner"; import { Toolbar } from "../../SharedComponents/Toolbar/components/Toolbar"; import { ToolbarButton } from "../../SharedComponents/Toolbar/components/ToolbarButton"; @@ -9,6 +9,7 @@ import { EditHyperlinkMenu } from "../EditHyperlinkMenu/components/EditHyperlink export const DefaultHyperlinkToolbar = (props: HyperlinkToolbarProps) => { const [isEditing, setIsEditing] = useState(false); + const editMenuRef = useRef(null); if (isEditing) { return ( @@ -17,7 +18,15 @@ export const DefaultHyperlinkToolbar = (props: HyperlinkToolbarProps) => { text={props.text} update={(url, text) => props.editHyperlink(url, text)} // TODO: Better way of waiting for fade out - onBlur={() => setTimeout(() => setIsEditing(false), 500)} + onBlur={(event) => + setTimeout(() => { + if (editMenuRef.current?.contains(event.relatedTarget)) { + return; + } + setIsEditing(false); + }, 500) + } + ref={editMenuRef} /> ); } diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarWrapper.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx similarity index 90% rename from packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarWrapper.tsx rename to packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx index f74a8e1b4e..34208796f5 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarWrapper.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx @@ -5,7 +5,6 @@ import { BaseUiElementState, BlockNoteEditor, BlockSchema, - createHyperlinkToolbar, HyperlinkToolbarCallbacks, HyperlinkToolbarState, } from "@blocknote/core"; @@ -18,7 +17,7 @@ export type HyperlinkToolbarProps = Omit< > & Omit; -export const HyperlinkToolbarWrapper = (props: { +export const HyperlinkToolbarPositioner = (props: { editor: BlockNoteEditor; hyperlinkToolbar?: FC; }) => { @@ -30,8 +29,7 @@ export const HyperlinkToolbarWrapper = (props: { const callbacks = useRef(); useEffect(() => { - callbacks.current = createHyperlinkToolbar( - props.editor, + callbacks.current = props.editor.createHyperlinkToolbar( (hyperlinkToolbarState) => { setShow(hyperlinkToolbarState.show); setUrl(hyperlinkToolbarState.url); @@ -73,14 +71,14 @@ export const HyperlinkToolbarWrapper = (props: { return ( setIsEditing(false)} content={hyperlinkToolbarElement} getReferenceClientRect={getReferenceClientRect} interactive={true} visible={show} animation={"fade"} - placement={"top-start"}> -
- + placement={"top-start"} + /> ); }; diff --git a/packages/react/src/SideMenu/components/DefaultSideMenu.tsx b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx index 0609181a64..8b5901df44 100644 --- a/packages/react/src/SideMenu/components/DefaultSideMenu.tsx +++ b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx @@ -4,7 +4,7 @@ import { AiOutlinePlus } from "react-icons/ai"; import { MdDragIndicator } from "react-icons/md"; import { BlockSchema } from "@blocknote/core"; -import { SideMenuProps } from "./SideMenuWrapper"; +import { SideMenuProps } from "./SideMenuPositioner"; import { DragHandleMenuProps } from "./DragHandleMenu/DragHandleMenu"; import { DefaultDragHandleMenu } from "./DragHandleMenu/DefaultDragHandleMenu"; diff --git a/packages/react/src/SideMenu/components/SideMenuWrapper.tsx b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx similarity index 85% rename from packages/react/src/SideMenu/components/SideMenuWrapper.tsx rename to packages/react/src/SideMenu/components/SideMenuPositioner.tsx index a1f19405db..40bc6fe38d 100644 --- a/packages/react/src/SideMenu/components/SideMenuWrapper.tsx +++ b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx @@ -6,7 +6,6 @@ import { Block, BlockNoteEditor, BlockSchema, - createSideMenu, SideMenuCallbacks, SideMenuState, } from "@blocknote/core"; @@ -21,7 +20,7 @@ export type SideMenuProps = Omit< editor: BlockNoteEditor; }; -export const SideMenuWrapper = (props: { +export const SideMenuPositioner = (props: { editor: BlockNoteEditor; sideMenu?: FC>; }) => { @@ -32,7 +31,7 @@ export const SideMenuWrapper = (props: { const callbacks = useRef(); useEffect(() => { - callbacks.current = createSideMenu(props.editor, (sideMenuState) => { + callbacks.current = props.editor.createSideMenu((sideMenuState) => { setShow(sideMenuState.show); setBlock(sideMenuState.block); @@ -72,8 +71,7 @@ export const SideMenuWrapper = (props: { return ( below + moved to - // appendTo={props.editor._tiptapEditor.view.dom.parentElement!} + appendTo={props.editor.domElement.parentElement!} content={sideMenuElement} getReferenceClientRect={getReferenceClientRect} interactive={true} @@ -81,9 +79,8 @@ export const SideMenuWrapper = (props: { animation={"fade"} offset={offset} placement={"left"} - popperOptions={popperOptions}> -
- + popperOptions={popperOptions} + /> ); }; diff --git a/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx b/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx index bb5ad65c39..382b6c8964 100644 --- a/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx +++ b/packages/react/src/SlashMenu/components/DefaultSlashMenu.tsx @@ -2,9 +2,12 @@ import { createStyles, Menu } from "@mantine/core"; import * as _ from "lodash"; import { SlashMenuItem } from "./SlashMenuItem"; -import { SlashMenuProps } from "./SlashMenuWrapper"; +import { SlashMenuProps } from "./SlashMenuPositioner"; +import { BlockSchema } from "@blocknote/core"; -export function DefaultSlashMenu(props: SlashMenuProps) { +export function DefaultSlashMenu( + props: SlashMenuProps +) { const { classes } = createStyles({ root: {} })(undefined, { name: "SlashMenu", }); diff --git a/packages/react/src/SlashMenu/components/SlashMenuWrapper.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx similarity index 58% rename from packages/react/src/SlashMenu/components/SlashMenuWrapper.tsx rename to packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx index 63e149fedd..7ea826de3a 100644 --- a/packages/react/src/SlashMenu/components/SlashMenuWrapper.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -3,59 +3,51 @@ import Tippy from "@tippyjs/react"; import { BlockNoteEditor, BlockSchema, - DefaultBlockSchema, - createSlashMenu, - SuggestionsPluginCallbacks, BaseUiElementCallbacks, SuggestionsMenuState, BaseUiElementState, + SuggestionsMenuCallbacks, } from "@blocknote/core"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; -import { defaultReactSlashMenuItems } from "../defaultReactSlashMenuItems"; import { DefaultSlashMenu } from "./DefaultSlashMenu"; -export type SlashMenuProps = Omit< - SuggestionsPluginCallbacks>, +export type SlashMenuProps = Omit< + SuggestionsMenuCallbacks>, keyof BaseUiElementCallbacks > & Omit< - SuggestionsMenuState>, + SuggestionsMenuState>, keyof BaseUiElementState >; -export const SlashMenuWrapper = (props: { +export const SlashMenuPositioner = (props: { editor: BlockNoteEditor; - slashMenuItems?: ReactSlashMenuItem[]; - slashMenu?: FC; + slashMenu?: FC>; }) => { const [show, setShow] = useState(false); const [filteredItems, setFilteredItems] = - useState[]>(); + useState[]>(); const [keyboardHoveredItemIndex, setKeyboardHoveredItemIndex] = useState(); const referencePos = useRef(); const callbacks = - useRef< - SuggestionsPluginCallbacks> - >(); + useRef>>(); useEffect(() => { - callbacks.current = createSlashMenu>( - props.editor as any, - (slashMenuState) => { - setShow(slashMenuState.show); - setFilteredItems(slashMenuState.filteredItems); - setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); + callbacks.current = props.editor.createSlashMenu((slashMenuState) => { + setShow(slashMenuState.show); + setFilteredItems( + slashMenuState.filteredItems as ReactSlashMenuItem[] + ); + setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); - referencePos.current = slashMenuState.referencePos; - }, - props.slashMenuItems || defaultReactSlashMenuItems - ); + referencePos.current = slashMenuState.referencePos; + }) as SuggestionsMenuCallbacks>; return callbacks.current!.destroy; - }, [props.editor, props.slashMenuItems]); + }, [props.editor]); const getReferenceClientRect = useMemo(() => { if (!referencePos.current) { @@ -87,13 +79,13 @@ export const SlashMenuWrapper = (props: { return ( -
- + placement={"bottom-start"} + /> ); }; diff --git a/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx b/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx index 740265e12d..2cc868d9e1 100644 --- a/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx +++ b/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx @@ -1,7 +1,8 @@ import { BaseSlashMenuItem, + BlockSchema, DefaultBlockSchema, - defaultSlashMenuItems, + getDefaultSlashMenuItems, } from "@blocknote/core"; import { RiH1, @@ -13,6 +14,7 @@ import { } from "react-icons/ri"; import { formatKeyboardShortcut } from "../utils"; import { ReactSlashMenuItem } from "./ReactSlashMenuItem"; + const extraFields: Record< string, Omit< @@ -58,15 +60,14 @@ 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( + schema: 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 bb3c7556f0..beeada5248 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -2,10 +2,11 @@ import { BlockNoteEditor, BlockNoteEditorOptions, BlockSchema, + defaultBlockSchema, DefaultBlockSchema, } from "@blocknote/core"; import { DependencyList } from "react"; -import { defaultReactSlashMenuItems } from "../SlashMenu/defaultReactSlashMenuItems"; +import { getDefaultReactSlashMenuItems } from "../SlashMenu/defaultReactSlashMenuItems"; /** * Main hook for importing a BlockNote editor into a React project @@ -14,13 +15,12 @@ export const useBlockNote = ( options: Partial> = {}, _deps: DependencyList = [] ) => { - let newOptions: Record = { - slashCommands: defaultReactSlashMenuItems, - ...options, - }; - console.log("create new blocknote instance"); - return new BlockNoteEditor( - newOptions as Partial> - ); + + return new BlockNoteEditor({ + slashCommands: getDefaultReactSlashMenuItems( + options.blockSchema || defaultBlockSchema + ), + ...options, + }); }; diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index efb3440845..6289d21d58 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -1,7 +1,7 @@ // TODO: review directories export * from "./BlockNoteView"; -export * from "./FormattingToolbar/components/FormattingToolbarWrapper"; +export * from "./FormattingToolbar/components/FormattingToolbarPositioner"; export * from "./FormattingToolbar/components/DefaultFormattingToolbar"; export * from "./FormattingToolbar/components/DefaultDropdowns/BlockTypeDropdown"; export * from "./FormattingToolbar/components/DefaultButtons/ColorStyleButton"; @@ -10,9 +10,9 @@ export * from "./FormattingToolbar/components/DefaultButtons/NestBlockButtons"; export * from "./FormattingToolbar/components/DefaultButtons/TextAlignButton"; export * from "./FormattingToolbar/components/DefaultButtons/ToggledStyleButton"; -export * from "./HyperlinkToolbar/components/HyperlinkToolbarWrapper"; +export * from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; -export * from "./SideMenu/components/SideMenuWrapper"; +export * from "./SideMenu/components/SideMenuPositioner"; export * from "./SideMenu/components/DefaultSideMenu"; export * from "./SideMenu/components/DragHandleMenu/DragHandleMenu"; @@ -21,7 +21,7 @@ export * from "./SideMenu/components/DragHandleMenu/DragHandleMenuItem"; export * from "./SideMenu/components/DefaultButtons/BlockColorsButton"; export * from "./SideMenu/components/DefaultButtons/RemoveBlockButton"; -export * from "./SlashMenu/components/SlashMenuWrapper"; +export * from "./SlashMenu/components/SlashMenuPositioner"; export * from "./SlashMenu/components/DefaultSlashMenu"; export * from "./SlashMenu/components/SlashMenuItem"; export * from "./SlashMenu/ReactSlashMenuItem"; From 1efce16bdb19e0cec48c491ebd62f6753dcb5921 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 25 Jul 2023 19:25:19 +0200 Subject: [PATCH 19/42] Fixed menus being initialized early --- examples/editor/src/App.tsx | 36 ++++++-------- packages/core/src/BlockNoteEditor.ts | 14 ++++++ packages/core/src/BlockNoteExtensions.ts | 2 +- packages/react/src/BlockNoteView.tsx | 39 +++++++++++---- .../react/src/SlashMenu/ReactSlashMenuItem.ts | 48 +++++++++++++------ .../dragdropnested-chromium-linux.json | 6 +-- .../dragdropnested-webkit-linux.json | 6 +-- .../dragdropsingle-chromium-linux.json | 2 +- .../dragdropsingle-webkit-linux.json | 2 +- 9 files changed, 101 insertions(+), 54 deletions(-) diff --git a/examples/editor/src/App.tsx b/examples/editor/src/App.tsx index a56ae5c7c0..00d96815f9 100644 --- a/examples/editor/src/App.tsx +++ b/examples/editor/src/App.tsx @@ -2,15 +2,11 @@ import "@blocknote/core/style.css"; import { BlockNoteView, - FormattingToolbarWrapper, - SlashMenuWrapper, - SideMenuWrapper, - HyperlinkToolbarWrapper, useBlockNote, - defaultReactSlashMenuItems, - DefaultSideMenu, - DragHandleMenuItem, - DragHandleMenu, + FormattingToolbarPositioner, + HyperlinkToolbarPositioner, + SlashMenuPositioner, + SideMenuPositioner, } from "@blocknote/react"; import styles from "./App.module.css"; @@ -31,24 +27,20 @@ function App() { // Give tests a way to get prosemirror instance (window as WindowWithProseMirror).ProseMirror = editor?._tiptapEditor; + // Use mock ID if tests are running. + if ((window as any).__TEST_OPTIONS === undefined) { + // (window as any).__TEST_OPTIONS = {}; + } + return ( -
Formatting Toolbar
} - /> -
Hyperlink Toolbar
} - /> -
Slash Menu
} - slashMenuItems={defaultReactSlashMenuItems.filter((item) => - item.name.includes("Heading") - )} + // formattingToolbar={() =>
Formatting Toolbar
} /> -
Side Menu
} /> + + + {/* (*/} diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 10c9cc06f0..b79018bab6 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -162,6 +162,7 @@ export class BlockNoteEditor { public readonly _tiptapEditor: TiptapEditor & { contentComponent: any }; public blockCache = new WeakMap>(); public readonly schema: BSchema; + public ready = false; public get domElement() { return this._tiptapEditor.view.dom as HTMLDivElement; @@ -423,11 +424,24 @@ export class BlockNoteEditor { newOptions.onEditorReady?.(this); newOptions.initialContent && this.replaceBlocks(this.topLevelBlocks, newOptions.initialContent); + this.ready = true; }, onUpdate: () => { + // This seems to be necessary due to a bug in TipTap: + // https://github.com/ueberdosis/tiptap/issues/2583 + if (!this.ready) { + return; + } + newOptions.onEditorContentChange?.(this); }, onSelectionUpdate: () => { + // This seems to be necessary due to a bug in TipTap: + // https://github.com/ueberdosis/tiptap/issues/2583 + if (!this.ready) { + return; + } + newOptions.onTextCursorPositionChange?.(this); }, editable: options.editable === undefined ? true : options.editable, diff --git a/packages/core/src/BlockNoteExtensions.ts b/packages/core/src/BlockNoteExtensions.ts index 94d5d5ca1a..3a4a23b574 100644 --- a/packages/core/src/BlockNoteExtensions.ts +++ b/packages/core/src/BlockNoteExtensions.ts @@ -24,7 +24,7 @@ import { BlockSchema } from "./extensions/Blocks/api/blockTypes"; import { CustomBlockSerializerExtension } from "./extensions/Blocks/api/serialization"; import blockStyles from "./extensions/Blocks/nodes/Block.module.css"; import { Placeholder } from "./extensions/Placeholder/PlaceholderExtension"; -import { BaseSlashMenuItem } from "./extensions/SlashMenu"; +import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; import { TextAlignmentExtension } from "./extensions/TextAlignment/TextAlignmentExtension"; import { TextColorExtension } from "./extensions/TextColor/TextColorExtension"; import { TextColorMark } from "./extensions/TextColor/TextColorMark"; diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index b282621572..16a1ae3a89 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -2,7 +2,7 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; import { getBlockNoteTheme } from "./BlockNoteTheme"; -import { ReactNode } from "react"; +import { ReactNode, useEffect, useState } from "react"; import { FormattingToolbarPositioner } from "./FormattingToolbar/components/FormattingToolbarPositioner"; import { HyperlinkToolbarPositioner } from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; import { SlashMenuPositioner } from "./SlashMenu/components/SlashMenuPositioner"; @@ -12,20 +12,41 @@ export function BlockNoteView(props: { editor: BlockNoteEditor; children?: ReactNode; }) { + const [ready, setReady] = useState(props.editor.ready); + console.log(props.editor.ready); + + useEffect(() => { + function checkReady() { + if (!props.editor.ready) { + window.setTimeout(checkReady, 100); + } else { + setReady(true); + } + } + checkReady(); + + // TODO: Shouldn't this work with props.editor.ready in deps? It fails in + // tests so it doesn't seem to. + // if (props.editor.ready) { + // setReady(true); + // } + }, []); + return ( - {props.children || ( - <> - - - - - - )} + {ready && + (props.children || ( + <> + + + + + + ))} ); diff --git a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts index 44ff73c2a1..b75506997a 100644 --- a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts +++ b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts @@ -4,18 +4,38 @@ import { BlockSchema, } 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 = + BaseSlashMenuItem & { + group: string; + icon: JSX.Element; + hint?: string; + shortcut?: string; + }; + +export function createReactSlashMenuItem( + name: string, + execute: (editor: BlockNoteEditor) => void, + aliases: string[] = [], + group: string, + icon: JSX.Element, + hint?: string, + shortcut?: string +): ReactSlashMenuItem { + return { + name, + execute, + aliases, + group, + icon, + hint, + shortcut, + match: (query: string): boolean => { + return ( + name.toLowerCase().startsWith(query.toLowerCase()) || + aliases.filter((alias) => + alias.toLowerCase().startsWith(query.toLowerCase()) + ).length !== 0 + ); + }, + }; } 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" }, From 79f617ddb768c7f6cb6ad9c63e068fb892dab73d Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 25 Jul 2023 19:58:01 +0200 Subject: [PATCH 20/42] Fixed some deps --- packages/react/src/BlockNoteView.tsx | 5 ++--- .../components/FormattingToolbarPositioner.tsx | 2 +- .../components/HyperlinkToolbarPositioner.tsx | 2 +- .../react/src/SideMenu/components/SideMenuPositioner.tsx | 2 +- .../react/src/SlashMenu/components/SlashMenuPositioner.tsx | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index 16a1ae3a89..ee6182884a 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -12,8 +12,7 @@ export function BlockNoteView(props: { editor: BlockNoteEditor; children?: ReactNode; }) { - const [ready, setReady] = useState(props.editor.ready); - console.log(props.editor.ready); + const [ready, setReady] = useState(false); useEffect(() => { function checkReady() { @@ -30,7 +29,7 @@ export function BlockNoteView(props: { // if (props.editor.ready) { // setReady(true); // } - }, []); + }, [props.editor.ready]); return ( diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 7caef35d9a..55c60f55ff 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -38,7 +38,7 @@ export const FormattingToolbarPositioner = < return undefined; } return () => referencePos.current!; - }, [referencePos.current]); + }, []); const formattingToolbarElement = useMemo(() => { const FormattingToolbar = diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx index 34208796f5..e2342368a8 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx @@ -48,7 +48,7 @@ export const HyperlinkToolbarPositioner = (props: { } return () => referencePos.current!; - }, [referencePos.current]); + }, []); const hyperlinkToolbarElement = useMemo(() => { if (!url || !text || !callbacks.current) { diff --git a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx index 40bc6fe38d..b7657f07f8 100644 --- a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx +++ b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx @@ -47,7 +47,7 @@ export const SideMenuPositioner = (props: { } return () => referencePos.current!; - }, [referencePos.current]); + }, []); const sideMenuElement = useMemo(() => { if (!block || !callbacks.current) { diff --git a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx index 7ea826de3a..84ce313be1 100644 --- a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -55,7 +55,7 @@ export const SlashMenuPositioner = (props: { } return () => referencePos.current!; - }, [referencePos.current]); + }, []); const slashMenuElement = useMemo(() => { if ( From a3616c3bad86ed3e8dba9829e6b07b9c6fe643aa Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 25 Jul 2023 20:05:04 +0200 Subject: [PATCH 21/42] Reverted some deps --- .../components/FormattingToolbarPositioner.tsx | 2 +- .../HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx | 2 +- packages/react/src/SideMenu/components/SideMenuPositioner.tsx | 2 +- packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 55c60f55ff..7caef35d9a 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -38,7 +38,7 @@ export const FormattingToolbarPositioner = < return undefined; } return () => referencePos.current!; - }, []); + }, [referencePos.current]); const formattingToolbarElement = useMemo(() => { const FormattingToolbar = diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx index e2342368a8..34208796f5 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx @@ -48,7 +48,7 @@ export const HyperlinkToolbarPositioner = (props: { } return () => referencePos.current!; - }, []); + }, [referencePos.current]); const hyperlinkToolbarElement = useMemo(() => { if (!url || !text || !callbacks.current) { diff --git a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx index b7657f07f8..40bc6fe38d 100644 --- a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx +++ b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx @@ -47,7 +47,7 @@ export const SideMenuPositioner = (props: { } return () => referencePos.current!; - }, []); + }, [referencePos.current]); const sideMenuElement = useMemo(() => { if (!block || !callbacks.current) { diff --git a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx index 84ce313be1..7ea826de3a 100644 --- a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -55,7 +55,7 @@ export const SlashMenuPositioner = (props: { } return () => referencePos.current!; - }, []); + }, [referencePos.current]); const slashMenuElement = useMemo(() => { if ( From 7eebdffc857aa5effd6230e1e387cb597eddf5a2 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 26 Jul 2023 16:14:22 +0200 Subject: [PATCH 22/42] Added lint ignore annotations to deps --- .../components/FormattingToolbarPositioner.tsx | 15 +++++++++------ .../components/HyperlinkToolbarPositioner.tsx | 15 +++++++++------ .../SideMenu/components/SideMenuPositioner.tsx | 15 +++++++++------ .../SlashMenu/components/SlashMenuPositioner.tsx | 15 +++++++++------ 4 files changed, 36 insertions(+), 24 deletions(-) diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 7caef35d9a..0b3e71a7e2 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -33,12 +33,15 @@ export const FormattingToolbarPositioner = < return callbacks.current.destroy; }, [props.editor]); - const getReferenceClientRect = useMemo(() => { - if (!referencePos) { - return undefined; - } - return () => referencePos.current!; - }, [referencePos.current]); + const getReferenceClientRect = useMemo( + () => { + if (!referencePos) { + return undefined; + } + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); const formattingToolbarElement = useMemo(() => { const FormattingToolbar = diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx index 34208796f5..8655d8f218 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx @@ -42,13 +42,16 @@ export const HyperlinkToolbarPositioner = (props: { return callbacks.current.destroy; }, [props.editor]); - const getReferenceClientRect = useMemo(() => { - if (!referencePos.current) { - return undefined; - } + const getReferenceClientRect = useMemo( + () => { + if (!referencePos.current) { + return undefined; + } - return () => referencePos.current!; - }, [referencePos.current]); + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); const hyperlinkToolbarElement = useMemo(() => { if (!url || !text || !callbacks.current) { diff --git a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx index 40bc6fe38d..32a851b4e9 100644 --- a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx +++ b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx @@ -41,13 +41,16 @@ export const SideMenuPositioner = (props: { return callbacks.current!.destroy; }, [props.editor]); - const getReferenceClientRect = useMemo(() => { - if (!referencePos.current) { - return undefined; - } + const getReferenceClientRect = useMemo( + () => { + if (!referencePos.current) { + return undefined; + } - return () => referencePos.current!; - }, [referencePos.current]); + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); const sideMenuElement = useMemo(() => { if (!block || !callbacks.current) { diff --git a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx index 7ea826de3a..ec227d2292 100644 --- a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -49,13 +49,16 @@ export const SlashMenuPositioner = (props: { return callbacks.current!.destroy; }, [props.editor]); - const getReferenceClientRect = useMemo(() => { - if (!referencePos.current) { - return undefined; - } + const getReferenceClientRect = useMemo( + () => { + if (!referencePos.current) { + return undefined; + } - return () => referencePos.current!; - }, [referencePos.current]); + return () => referencePos.current!; + }, + [referencePos.current] // eslint-disable-line + ); const slashMenuElement = useMemo(() => { if ( From c48871289f044a4d45b03512a8b3e89f6099d1a4 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 26 Jul 2023 16:46:36 +0200 Subject: [PATCH 23/42] Cleaned up slash menu and suggestion items --- .../extensions/SlashMenu/BaseSlashMenuItem.ts | 20 --- .../extensions/SlashMenu/SlashMenuPlugin.ts | 9 +- .../SlashMenu/defaultSlashMenuItems.ts | 128 ++++++++---------- .../plugins/suggestion/SuggestionItem.ts | 1 - .../react/src/SlashMenu/ReactSlashMenuItem.ts | 34 +---- 5 files changed, 64 insertions(+), 128 deletions(-) diff --git a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts index aeef81aa78..5976ceb52f 100644 --- a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts +++ b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts @@ -6,23 +6,3 @@ export type BaseSlashMenuItem = SuggestionItem & { execute: (editor: BlockNoteEditor) => void; aliases: string[]; }; - -export function createBaseSlashMenuItem( - name: string, - execute: (editor: BlockNoteEditor) => void, - aliases: string[] = [] -): BaseSlashMenuItem { - return { - name, - execute, - aliases, - match: (query: string): boolean => { - return ( - name.toLowerCase().startsWith(query.toLowerCase()) || - aliases.filter((alias) => - alias.toLowerCase().startsWith(query.toLowerCase()) - ).length !== 0 - ); - }, - }; -} diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index ddd6c39194..7af4d3a67a 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -31,7 +31,14 @@ export const setupSlashMenu = < slashMenuPluginKey, "/", - (query) => items.filter((item: SlashMenuItem) => item.match(query)), + (query) => + items.filter( + ({ name, aliases }: SlashMenuItem) => + name.toLowerCase().startsWith(query.toLowerCase()) || + aliases.filter((alias) => + alias.toLowerCase().startsWith(query.toLowerCase()) + ).length !== 0 + ), ({ item, editor }) => item.execute(editor) ); }; diff --git a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts index 0a79603c6c..32138a6b79 100644 --- a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts +++ b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts @@ -1,9 +1,6 @@ import { BlockNoteEditor } from "../../BlockNoteEditor"; import { BlockSchema, PartialBlock } from "../Blocks/api/blockTypes"; -import { - BaseSlashMenuItem, - createBaseSlashMenuItem, -} from "./BaseSlashMenuItem"; +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; function insertOrUpdateBlock( editor: BlockNoteEditor, @@ -30,92 +27,77 @@ export const getDefaultSlashMenuItems = ( 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( - // Command for creating a level 1 heading - createBaseSlashMenuItem( - "Heading", - (editor) => - insertOrUpdateBlock(editor, { - type: "heading", - props: { level: "1" }, - } as PartialBlock), - ["h", "heading1", "h1"] - ) - ); + 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( - // Command for creating a level 2 heading - createBaseSlashMenuItem( - "Heading 2", - (editor) => - insertOrUpdateBlock(editor, { - type: "heading", - props: { level: "2" }, - } as PartialBlock), - ["h2", "heading2", "subheading"] - ) - ); + 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( - // Command for creating a level 3 heading - createBaseSlashMenuItem( - "Heading 3", - (editor) => - insertOrUpdateBlock(editor, { - type: "heading", - props: { level: "3" }, - } as PartialBlock), - ["h3", "heading3", "subheading"] - ) - ); + 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( - // Command for creating a bullet list item - createBaseSlashMenuItem( - "Bullet List", - (editor) => - insertOrUpdateBlock(editor, { - type: "bulletListItem", - } as PartialBlock), - ["ul", "list", "bulletlist", "bullet list"] - ) - ); + 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( - // Command for creating a numbered list item - createBaseSlashMenuItem( - "Numbered List", - (editor) => - insertOrUpdateBlock(editor, { - type: "numberedListItem", - } as PartialBlock), - ["li", "list", "numberedlist", "numbered list"] - ) - ); + 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( - // Command for creating a paragraph - createBaseSlashMenuItem( - "Paragraph", - (editor) => - insertOrUpdateBlock(editor, { - type: "paragraph", - } as PartialBlock), - ["p"] - ) - ); + slashMenuItems.push({ + name: "Paragraph", + aliases: ["p"], + execute: (editor) => + insertOrUpdateBlock(editor, { + type: "paragraph", + } as PartialBlock), + }); } return slashMenuItems; diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts b/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts index 6b0eb26ec6..aebd7be2cd 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionItem.ts @@ -1,4 +1,3 @@ export type SuggestionItem = { name: string; - match: (query: string) => boolean; }; diff --git a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts index b75506997a..96416c7b98 100644 --- a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts +++ b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts @@ -1,8 +1,4 @@ -import { - BaseSlashMenuItem, - BlockNoteEditor, - BlockSchema, -} from "@blocknote/core"; +import { BaseSlashMenuItem, BlockSchema } from "@blocknote/core"; export type ReactSlashMenuItem = BaseSlashMenuItem & { @@ -11,31 +7,3 @@ export type ReactSlashMenuItem = hint?: string; shortcut?: string; }; - -export function createReactSlashMenuItem( - name: string, - execute: (editor: BlockNoteEditor) => void, - aliases: string[] = [], - group: string, - icon: JSX.Element, - hint?: string, - shortcut?: string -): ReactSlashMenuItem { - return { - name, - execute, - aliases, - group, - icon, - hint, - shortcut, - match: (query: string): boolean => { - return ( - name.toLowerCase().startsWith(query.toLowerCase()) || - aliases.filter((alias) => - alias.toLowerCase().startsWith(query.toLowerCase()) - ).length !== 0 - ); - }, - }; -} From 5409f8b9fd0685472bfac527ea085c6eb873d4c5 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 26 Jul 2023 18:32:32 +0200 Subject: [PATCH 24/42] Cleaned up `BlockNoteEditor` --- packages/core/src/BlockNoteEditor.ts | 224 +++++++++++---------------- 1 file changed, 92 insertions(+), 132 deletions(-) diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index abd3e81bd5..56b40d4628 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -59,6 +59,11 @@ import { } from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; import { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; +import { + BaseUiElementCallbacks, + BaseUiElementState, +} from "./shared/BaseUiElementTypes"; +import { Plugin } from "prosemirror-state"; export type BlockNoteEditorOptions = { // TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them. @@ -163,18 +168,6 @@ export class BlockNoteEditor { public readonly schema: BSchema; public ready = false; - public get domElement() { - return this._tiptapEditor.view.dom as HTMLDivElement; - } - - public isFocused() { - return this._tiptapEditor.view.hasFocus(); - } - - public focus() { - this._tiptapEditor.view.focus(); - } - private uiElementCallbacks: { formattingToolbar: FormattingToolbarCallbacks; hyperlinkToolbar: HyperlinkToolbarCallbacks; @@ -191,6 +184,49 @@ export class BlockNoteEditor { sideMenu: (sideMenuState: SideMenuState) => void; }> = {}; + private createUiElementExtension< + State extends BaseUiElementState, + Callbacks extends BaseUiElementCallbacks + >( + elementName: string, + elementSetupFunction: ( + editor: BlockNoteEditor, + tiptapEditor: TiptapEditor + ) => { + plugin: Plugin; + callbacks: Callbacks; + }, + elementListener: ((state: State) => void) | undefined, + elementCallbacks: undefined + ) { + const editor = this; + + return Extension.create({ + name: elementName, + + addProseMirrorPlugins() { + const { plugin, callbacks } = elementSetupFunction( + this, + this._tiptapEditor, + (state) => { + if (!elementListener) { + return; + } + + elementListener(state); + } + ); + + elementCallbacks = { + destroy: () => delete editor.uiElementListeners.formattingToolbar, + ...callbacks, + }; + + return [plugin]; + }, + }); + } + public createFormattingToolbar = ( updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState @@ -269,8 +305,6 @@ export class BlockNoteEditor { ...options, }; - const editor = this; - const extensions = getBlockNoteExtensions({ editor: this, slashCommands: @@ -282,130 +316,44 @@ export class BlockNoteEditor { this.schema = newOptions.blockSchema; - let formattingToolbarCallbacks: FormattingToolbarCallbacks; - const formattingToolbarExtension = Extension.create({ - name: "FormattingToolbarExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupFormattingToolbar( - editor, - this.editor, - (formattingToolbarState) => { - const formattingToolbarListener = - editor.uiElementListeners.formattingToolbar; - - if (!formattingToolbarListener) { - return; - } - - formattingToolbarListener(formattingToolbarState); - } - ); - - formattingToolbarCallbacks = { - destroy: () => delete editor.uiElementListeners.formattingToolbar, - ...callbacks, - }; - - return [plugin]; - }, - }); - + let formattingToolbarCallbacks: FormattingToolbarCallbacks | undefined = + undefined; + const formattingToolbarExtension = this.createUiElementExtension( + "FormattingToolbarExtension", + setupFormattingToolbar, + this.uiElementListeners.formattingToolbar, + formattingToolbarCallbacks + ); extensions.push(formattingToolbarExtension); - let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks; - const hyperlinkToolbarExtension = Extension.create({ - name: "HyperlinkToolbarExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupHyperlinkToolbar( - editor, - this.editor, - (hyperlinkToolbarState) => { - const hyperlinkToolbarListener = - editor.uiElementListeners.hyperlinkToolbar; - - if (!hyperlinkToolbarListener) { - return; - } - - hyperlinkToolbarListener(hyperlinkToolbarState); - } - ); - - hyperlinkToolbarCallbacks = { - destroy: () => delete editor.uiElementListeners.hyperlinkToolbar, - ...callbacks, - }; - - return [plugin]; - }, - }); - + let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks | undefined = + undefined; + const hyperlinkToolbarExtension = this.createUiElementExtension( + "HyperlinkToolbarExtension", + setupHyperlinkToolbar, + this.uiElementListeners.hyperlinkToolbar, + hyperlinkToolbarCallbacks + ); extensions.push(hyperlinkToolbarExtension); - let slashMenuCallbacks: SuggestionsMenuCallbacks< - BaseSlashMenuItem - >; - const slashMenuExtension = Extension.create({ - name: "SlashMenuExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupSlashMenu( - editor, - this.editor, - (slashMenuState) => { - const slashMenuListener = editor.uiElementListeners.slashMenu; - - if (!slashMenuListener) { - return; - } - - slashMenuListener(slashMenuState as any); - }, - newOptions.slashCommands || - getDefaultSlashMenuItems(newOptions.blockSchema) - ); - - slashMenuCallbacks = { - destroy: () => delete editor.uiElementListeners.slashMenu, - ...callbacks, - }; - - return [plugin]; - }, - }); - + let slashMenuCallbacks: + | SuggestionsMenuCallbacks> + | undefined = undefined; + const slashMenuExtension = this.createUiElementExtension( + "SlashMenuExtension", + setupSlashMenu, + this.uiElementListeners.slashMenu, + slashMenuCallbacks + ); extensions.push(slashMenuExtension); - let sideMenuCallbacks: SideMenuCallbacks; - const sideMenuExtension = Extension.create({ - name: "SideMenuExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupSideMenu( - editor, - this.editor, - (sideMenuState) => { - const sideMenuListener = editor.uiElementListeners.sideMenu; - - if (!sideMenuListener) { - return; - } - - sideMenuListener(sideMenuState as any); - } - ); - - sideMenuCallbacks = { - destroy: () => delete editor.uiElementListeners.sideMenu, - ...callbacks, - }; - - return [plugin]; - }, - }); - + let sideMenuCallbacks: SideMenuCallbacks | undefined = undefined; + const sideMenuExtension = this.createUiElementExtension( + "SideMenuExtension", + setupSideMenu, + this.uiElementListeners.sideMenu, + sideMenuCallbacks + ); extensions.push(sideMenuExtension); const tiptapOptions: EditorOptions = { @@ -479,6 +427,18 @@ export class BlockNoteEditor { }; } + 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. From 07a774cef12b031db472c4eeab43975e73d58843 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 26 Jul 2023 18:55:55 +0200 Subject: [PATCH 25/42] Revert "Cleaned up `BlockNoteEditor`" This reverts commit 5409f8b9fd0685472bfac527ea085c6eb873d4c5. --- packages/core/src/BlockNoteEditor.ts | 224 ++++++++++++++++----------- 1 file changed, 132 insertions(+), 92 deletions(-) diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 56b40d4628..abd3e81bd5 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -59,11 +59,6 @@ import { } from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; import { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; -import { - BaseUiElementCallbacks, - BaseUiElementState, -} from "./shared/BaseUiElementTypes"; -import { Plugin } from "prosemirror-state"; export type BlockNoteEditorOptions = { // TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them. @@ -168,6 +163,18 @@ export class BlockNoteEditor { public readonly schema: BSchema; public ready = false; + public get domElement() { + return this._tiptapEditor.view.dom as HTMLDivElement; + } + + public isFocused() { + return this._tiptapEditor.view.hasFocus(); + } + + public focus() { + this._tiptapEditor.view.focus(); + } + private uiElementCallbacks: { formattingToolbar: FormattingToolbarCallbacks; hyperlinkToolbar: HyperlinkToolbarCallbacks; @@ -184,49 +191,6 @@ export class BlockNoteEditor { sideMenu: (sideMenuState: SideMenuState) => void; }> = {}; - private createUiElementExtension< - State extends BaseUiElementState, - Callbacks extends BaseUiElementCallbacks - >( - elementName: string, - elementSetupFunction: ( - editor: BlockNoteEditor, - tiptapEditor: TiptapEditor - ) => { - plugin: Plugin; - callbacks: Callbacks; - }, - elementListener: ((state: State) => void) | undefined, - elementCallbacks: undefined - ) { - const editor = this; - - return Extension.create({ - name: elementName, - - addProseMirrorPlugins() { - const { plugin, callbacks } = elementSetupFunction( - this, - this._tiptapEditor, - (state) => { - if (!elementListener) { - return; - } - - elementListener(state); - } - ); - - elementCallbacks = { - destroy: () => delete editor.uiElementListeners.formattingToolbar, - ...callbacks, - }; - - return [plugin]; - }, - }); - } - public createFormattingToolbar = ( updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState @@ -305,6 +269,8 @@ export class BlockNoteEditor { ...options, }; + const editor = this; + const extensions = getBlockNoteExtensions({ editor: this, slashCommands: @@ -316,44 +282,130 @@ export class BlockNoteEditor { this.schema = newOptions.blockSchema; - let formattingToolbarCallbacks: FormattingToolbarCallbacks | undefined = - undefined; - const formattingToolbarExtension = this.createUiElementExtension( - "FormattingToolbarExtension", - setupFormattingToolbar, - this.uiElementListeners.formattingToolbar, - formattingToolbarCallbacks - ); + let formattingToolbarCallbacks: FormattingToolbarCallbacks; + const formattingToolbarExtension = Extension.create({ + name: "FormattingToolbarExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupFormattingToolbar( + editor, + this.editor, + (formattingToolbarState) => { + const formattingToolbarListener = + editor.uiElementListeners.formattingToolbar; + + if (!formattingToolbarListener) { + return; + } + + formattingToolbarListener(formattingToolbarState); + } + ); + + formattingToolbarCallbacks = { + destroy: () => delete editor.uiElementListeners.formattingToolbar, + ...callbacks, + }; + + return [plugin]; + }, + }); + extensions.push(formattingToolbarExtension); - let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks | undefined = - undefined; - const hyperlinkToolbarExtension = this.createUiElementExtension( - "HyperlinkToolbarExtension", - setupHyperlinkToolbar, - this.uiElementListeners.hyperlinkToolbar, - hyperlinkToolbarCallbacks - ); + let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks; + const hyperlinkToolbarExtension = Extension.create({ + name: "HyperlinkToolbarExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupHyperlinkToolbar( + editor, + this.editor, + (hyperlinkToolbarState) => { + const hyperlinkToolbarListener = + editor.uiElementListeners.hyperlinkToolbar; + + if (!hyperlinkToolbarListener) { + return; + } + + hyperlinkToolbarListener(hyperlinkToolbarState); + } + ); + + hyperlinkToolbarCallbacks = { + destroy: () => delete editor.uiElementListeners.hyperlinkToolbar, + ...callbacks, + }; + + return [plugin]; + }, + }); + extensions.push(hyperlinkToolbarExtension); - let slashMenuCallbacks: - | SuggestionsMenuCallbacks> - | undefined = undefined; - const slashMenuExtension = this.createUiElementExtension( - "SlashMenuExtension", - setupSlashMenu, - this.uiElementListeners.slashMenu, - slashMenuCallbacks - ); + let slashMenuCallbacks: SuggestionsMenuCallbacks< + BaseSlashMenuItem + >; + const slashMenuExtension = Extension.create({ + name: "SlashMenuExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupSlashMenu( + editor, + this.editor, + (slashMenuState) => { + const slashMenuListener = editor.uiElementListeners.slashMenu; + + if (!slashMenuListener) { + return; + } + + slashMenuListener(slashMenuState as any); + }, + newOptions.slashCommands || + getDefaultSlashMenuItems(newOptions.blockSchema) + ); + + slashMenuCallbacks = { + destroy: () => delete editor.uiElementListeners.slashMenu, + ...callbacks, + }; + + return [plugin]; + }, + }); + extensions.push(slashMenuExtension); - let sideMenuCallbacks: SideMenuCallbacks | undefined = undefined; - const sideMenuExtension = this.createUiElementExtension( - "SideMenuExtension", - setupSideMenu, - this.uiElementListeners.sideMenu, - sideMenuCallbacks - ); + let sideMenuCallbacks: SideMenuCallbacks; + const sideMenuExtension = Extension.create({ + name: "SideMenuExtension", + + addProseMirrorPlugins() { + const { plugin, callbacks } = setupSideMenu( + editor, + this.editor, + (sideMenuState) => { + const sideMenuListener = editor.uiElementListeners.sideMenu; + + if (!sideMenuListener) { + return; + } + + sideMenuListener(sideMenuState as any); + } + ); + + sideMenuCallbacks = { + destroy: () => delete editor.uiElementListeners.sideMenu, + ...callbacks, + }; + + return [plugin]; + }, + }); + extensions.push(sideMenuExtension); const tiptapOptions: EditorOptions = { @@ -427,18 +479,6 @@ export class BlockNoteEditor { }; } - 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. From cca7268a9d9ea73b8a501568a9e3525237c439fd Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Wed, 26 Jul 2023 18:58:39 +0200 Subject: [PATCH 26/42] Minor changes --- packages/core/src/BlockNoteEditor.ts | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index abd3e81bd5..4591c64645 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -163,18 +163,6 @@ export class BlockNoteEditor { public readonly schema: BSchema; public ready = false; - public get domElement() { - return this._tiptapEditor.view.dom as HTMLDivElement; - } - - public isFocused() { - return this._tiptapEditor.view.hasFocus(); - } - - public focus() { - this._tiptapEditor.view.focus(); - } - private uiElementCallbacks: { formattingToolbar: FormattingToolbarCallbacks; hyperlinkToolbar: HyperlinkToolbarCallbacks; @@ -310,7 +298,6 @@ export class BlockNoteEditor { return [plugin]; }, }); - extensions.push(formattingToolbarExtension); let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks; @@ -341,7 +328,6 @@ export class BlockNoteEditor { return [plugin]; }, }); - extensions.push(hyperlinkToolbarExtension); let slashMenuCallbacks: SuggestionsMenuCallbacks< @@ -375,7 +361,6 @@ export class BlockNoteEditor { return [plugin]; }, }); - extensions.push(slashMenuExtension); let sideMenuCallbacks: SideMenuCallbacks; @@ -405,7 +390,6 @@ export class BlockNoteEditor { return [plugin]; }, }); - extensions.push(sideMenuExtension); const tiptapOptions: EditorOptions = { @@ -479,6 +463,18 @@ export class BlockNoteEditor { }; } + 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. From 0af18e6362183ca5c89fe99191a52872abd8be23 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Thu, 27 Jul 2023 21:04:23 +0200 Subject: [PATCH 27/42] Minor changes & update to formatting toolbar docs --- .../extensions/SlashMenu/BaseSlashMenuItem.ts | 2 +- .../extensions/SlashMenu/SlashMenuPlugin.ts | 7 +- .../SlashMenu/defaultSlashMenuItems.ts | 7 +- .../FormattingToolbarPositioner.tsx | 7 +- .../components/HyperlinkToolbarPositioner.tsx | 5 +- .../components/SideMenuPositioner.tsx | 27 +- .../components/SlashMenuPositioner.tsx | 20 +- .../SlashMenu/defaultReactSlashMenuItems.tsx | 7 +- .../website/docs/docs/formatting-toolbar.md | 300 +++++++++++++----- packages/website/docs/docs/introduction.md | 2 +- packages/website/docs/docs/quickstart.md | 4 +- packages/website/docs/docs/slash-menu.md | 34 +- 12 files changed, 301 insertions(+), 121 deletions(-) diff --git a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts index 5976ceb52f..d133a62347 100644 --- a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts +++ b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts @@ -4,5 +4,5 @@ import { BlockSchema } from "../Blocks/api/blockTypes"; export type BaseSlashMenuItem = SuggestionItem & { execute: (editor: BlockNoteEditor) => void; - aliases: string[]; + aliases?: string[]; }; diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index 7af4d3a67a..bc6c058b0b 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -35,9 +35,10 @@ export const setupSlashMenu = < items.filter( ({ name, aliases }: SlashMenuItem) => name.toLowerCase().startsWith(query.toLowerCase()) || - aliases.filter((alias) => - alias.toLowerCase().startsWith(query.toLowerCase()) - ).length !== 0 + (aliases && + aliases.filter((alias) => + alias.toLowerCase().startsWith(query.toLowerCase()) + ).length !== 0) ), ({ item, editor }) => item.execute(editor) ); diff --git a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts index 32138a6b79..e6bc7830dd 100644 --- a/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts +++ b/packages/core/src/extensions/SlashMenu/defaultSlashMenuItems.ts @@ -1,6 +1,7 @@ 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, @@ -22,7 +23,11 @@ function insertOrUpdateBlock( } export const getDefaultSlashMenuItems = ( - schema: BSchema + // 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[] = []; diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 0b3e71a7e2..86b14174cd 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -4,16 +4,19 @@ import { sticky } from "tippy.js"; import { BlockNoteEditor, BlockSchema, + DefaultBlockSchema, FormattingToolbarCallbacks, } from "@blocknote/core"; import { DefaultFormattingToolbar } from "./DefaultFormattingToolbar"; -export type FormattingToolbarProps = { +export type FormattingToolbarProps< + BSchema extends BlockSchema = DefaultBlockSchema +> = { editor: BlockNoteEditor; }; export const FormattingToolbarPositioner = < - BSchema extends BlockSchema + BSchema extends BlockSchema = DefaultBlockSchema >(props: { editor: BlockNoteEditor; formattingToolbar?: FC>; diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx index 8655d8f218..1fa0a2d7e5 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx @@ -5,6 +5,7 @@ import { BaseUiElementState, BlockNoteEditor, BlockSchema, + DefaultBlockSchema, HyperlinkToolbarCallbacks, HyperlinkToolbarState, } from "@blocknote/core"; @@ -17,7 +18,9 @@ export type HyperlinkToolbarProps = Omit< > & Omit; -export const HyperlinkToolbarPositioner = (props: { +export const HyperlinkToolbarPositioner = < + BSchema extends BlockSchema = DefaultBlockSchema +>(props: { editor: BlockNoteEditor; hyperlinkToolbar?: FC; }) => { diff --git a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx index 32a851b4e9..1c93852929 100644 --- a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx +++ b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx @@ -6,21 +6,32 @@ import { Block, BlockNoteEditor, BlockSchema, + DefaultBlockSchema, SideMenuCallbacks, SideMenuState, } from "@blocknote/core"; import { DefaultSideMenu } from "./DefaultSideMenu"; -export type SideMenuProps = Omit< - SideMenuCallbacks, - keyof BaseUiElementCallbacks -> & - Omit, keyof BaseUiElementState> & { - editor: BlockNoteEditor; - }; +export type SideMenuProps = + Omit & + Omit, keyof BaseUiElementState> & { + editor: BlockNoteEditor; + }; + +// export type a = { +// callbacks: SideMenuCallbacks; +// state: SideMenuState; +// }; +// +// export type b = { +// callbacks: Omit; +// state: SideMenuState; +// }; -export const SideMenuPositioner = (props: { +export const SideMenuPositioner = < + BSchema extends BlockSchema = DefaultBlockSchema +>(props: { editor: BlockNoteEditor; sideMenu?: FC>; }) => { diff --git a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx index ec227d2292..82a79f2308 100644 --- a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -7,21 +7,25 @@ import { SuggestionsMenuState, BaseUiElementState, SuggestionsMenuCallbacks, + DefaultBlockSchema, } from "@blocknote/core"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { DefaultSlashMenu } from "./DefaultSlashMenu"; -export type SlashMenuProps = Omit< - SuggestionsMenuCallbacks>, - keyof BaseUiElementCallbacks -> & +export type SlashMenuProps = Omit< - SuggestionsMenuState>, - keyof BaseUiElementState - >; + SuggestionsMenuCallbacks>, + keyof BaseUiElementCallbacks + > & + Omit< + SuggestionsMenuState>, + keyof BaseUiElementState + >; -export const SlashMenuPositioner = (props: { +export const SlashMenuPositioner = < + BSchema extends BlockSchema = DefaultBlockSchema +>(props: { editor: BlockNoteEditor; slashMenu?: FC>; }) => { diff --git a/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx b/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx index 2cc868d9e1..3c13b21d61 100644 --- a/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx +++ b/packages/react/src/SlashMenu/defaultReactSlashMenuItems.tsx @@ -1,6 +1,7 @@ import { BaseSlashMenuItem, BlockSchema, + defaultBlockSchema, DefaultBlockSchema, getDefaultSlashMenuItems, } from "@blocknote/core"; @@ -61,7 +62,11 @@ const extraFields: Record< }; export function getDefaultReactSlashMenuItems( - schema: BSchema + // 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); diff --git a/packages/website/docs/docs/formatting-toolbar.md b/packages/website/docs/docs/formatting-toolbar.md index 881ba087f1..e27cb5bef2 100644 --- a/packages/website/docs/docs/formatting-toolbar.md +++ b/packages/website/docs/docs/formatting-toolbar.md @@ -18,9 +18,180 @@ The Formatting Toolbar appears whenever you highlight text in the editor, and is image -## Custom Formatting Toolbar +## Custom Formatting Toolbar Element -You can create a custom Formatting Toolbar using a React component. This component should take the following props: +You can create a custom Formatting Toolbar using a React component. 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) }}", + }); + + // Renders the editor instance. + return ( + + + + + + + ); +} +``` + +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} +``` + +::: + +Let's go over this code, starting with the `CustomFormattingToolbar` component, which is used to render the toolbar and takes the following props: + +```typescript +type FormattingToolbarProps = { + editor: BlockNoteEditor +}; +``` + +`editor:` The BlockNote editor instance to attach the toolbar to. + +```jsx +const CustomFormattingToolbar = (props: FormattingToolbarProps) => { + 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 + + + ); +}; +``` + +The components used to build this custom Formatting Toolbar are pre-made and come with BlockNote. These can be used if you need to change the functionality or layout, but want to keep the default styling. You can find all the pre-made components BlockNote offers in the [Default Items](/docs/formatting-toolbar#default-items) and [Custom Items](/docs/formatting-toolbar#custom-items) subsections. + +However, you could render whatever you like in `CustomFormattingToolbar`, allowing for fully custom designs. + +Also, if you're unsure about what's happening inside `ToolbarButton`'s `onClick` and `isSelected` props, head to [Introduction to Blocks](/docs/blocks), which will guide you through reading & manipulating blocks in the editor using code. + +After creating a custom toolbar and editor instance, we can add it to the editor by rendering it inside `BlockNoteView`: + +```jsx +export default function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({}); + + // Renders the editor instance. + return ( + + + + + + + ); +} +``` + +There's a bit more we have to explain here though. First of all, let's talk about the `FormattingToolbarPositioner` component. Not only can you change what's inside the Formatting Toolbar and how it looks, but also when it's shown/hidden, as well as where it's positioned. + +If you're looking to customize this to create, for example, a static Formatting Toolbar, head to [Custom Formatting Toolbar Positioner](/docs/formatting-toolbar#custom-formatting-toolbar-positioner). If you only want to change the toolbar element itself, you can use the `FormattingToolbarPositioner` to apply the default behaviour. + +TODO: Text below is not final. We should change how we remove & customize the menus & toolbars. Take the scenarios: +- Customizing 1 UI element +- Customizing all UI elements +- Removing 1 UI element +- Removing all UI elements + +By default, if you don't provide any children the `BlockNoteView`, BlockNote uses the default UI. However, if you want to provide a custom Formatting Toolbar, you should also add the default positioners for them (default components are used if custom ones aren't provided), as BlockNote won't render them otherwise. + +This also means you can remove the Formatting Toolbar from the editor by only adding default positioners for all other menus & toolbars in `BlockNoteView`: + +```jsx +return ( + + + + + +); +``` ```typescript type CustomFormattingToolbarProps = { @@ -30,20 +201,58 @@ type CustomFormattingToolbarProps = { const CustomFormattingToolbar = (props: CustomFormattingToolbarProps): JSX.Element => ...; ``` -You can then tell BlockNote to use your custom Formatting Toolbar using -the `customElements` option in `useBlockNote`: +However, this means you also have to handle showing, hiding, and positioning the Formatting Toolbar yourself. While this allows for additional customization, there are a lot of cases where you only want to change the toolbar itself and not have to deal with all of that. Therefore, BlockNote provides a `FormattingToolbarPositioner` component which handles showing, hiding, and positioning for you: -```typescript -const editor = useBlockNote({ - customElements: { - formattingToolbar: CustomFormattingToolbar - }, -}); +```typescript jsx +import { + FormattingToolbarProps, + FormattingToolbarPositioner +} from "@blocknote/react"; + +const FormattingToolbarPositioner = (props: { + editor: BlockNoteEditor, + formattingToolbar?: (props: FormattingToolbarProps) => JSX.Element +}): JSX.Element => { + ... +}, +```` + +You can then tell BlockNote to use your custom Formatting Toolbar by adding it as a child of `BlockNoteView`: + +```jsx +import { BlockNoteEditor } from "@blocknote/core"; +import { + BlockNoteView, + FormattingToolbarProps, + FormattingToolbarPositioner, + useBlockNote +} from "@blocknote/react"; +import "@blocknote/core/style.css"; + +const CustomFormattingToolbar = (props: CustomFormattingToolbarProps) => { + // Define your custom toolbar here component here + ... +}; + +function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({}); + + // Renders the editor instance using a React component. + return ( + + + + ); +} ``` ## Default Items -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: +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 and more - both the toolbar itself and the items in it. Below are all the default components you can use to build your custom toolbar: ```typescript // Toolbar which wraps all the items. @@ -144,71 +353,6 @@ 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) }} -``` - -::: +## Custom Formatting Toolbar Positioner -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 +TODO \ 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/slash-menu.md b/packages/website/docs/docs/slash-menu.md index 272e6c1458..11ede34380 100644 --- a/packages/website/docs/docs/slash-menu.md +++ b/packages/website/docs/docs/slash-menu.md @@ -29,9 +29,10 @@ Which you can use to customize the contents of the Slash Menu. Let's take a look ```typescript type ReactSlashMenuItem = { name: string; - execute: (editor: BlockNoteEditor) => void; - aliases: string[]; group: string; + icon: JSX.Element; + execute: (editor: BlockNoteEditor) => void; + aliases?: string[]; hint?: string; shortcut?: string; }; @@ -39,12 +40,14 @@ type ReactSlashMenuItem = { `name:` The item's name, which is the same string you see displayed in the menu, e.g. "Heading" or "Paragraph". +`group:` The name of the group the item belongs to, e.g. "Headings" or "Basic Blocks". + +`icon:` An element which displays the item's icon. + `execute:` A function that runs when the item is selected. `aliases:` Other names for the item, which as used as shortcuts for search. -`group:` The name of the group the item belongs to, e.g. "Headings" or "Basic Blocks". - `hint:` A short phrase to describe what the item is for, which is displayed below its name. `shortcuts:` A keyboard shortcut which can be used to run the item's `execute` function outside the Slash Menu. @@ -58,13 +61,14 @@ If you want to change, remove & reorder the default items , you first import and ```typescript import { BlockNoteView, - defaultReactSlashMenuItems, + getDefaultReactSlashMenuItems, useBlockNote } from "@blocknote/react"; import "@blocknote/core/style.css"; function App() { - const newSlashMenuItems: ReactSlashMenuItem[] = defaultReactSlashMenuItems; + const newSlashMenuItems: ReactSlashMenuItem[] = + getDefaultReactSlashMenuItems(); // Edit newSlashMenuItems ... @@ -109,20 +113,20 @@ export default function App() { }; // 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." - ); + 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." + }; // 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], + slashCommands: [...getDefaultReactSlashMenuItems(), insertHelloWorldItem], }); // Renders the editor instance. From aaad427e0d9499d5d17842e283f70912d2edca0f Mon Sep 17 00:00:00 2001 From: Yousef Date: Mon, 31 Jul 2023 13:40:28 +0200 Subject: [PATCH 28/42] simplify ui elements (#288) * simplify ui elements * remove unused * fix view * Fixed build * add onUpdate * fix vanilla * fix build * allow props for blocknoteview --------- Co-authored-by: Matthew Lipski --- examples/editor/src/App.tsx | 4 +- .../vanilla/src/ui/addFormattingToolbar.ts | 2 +- .../vanilla/src/ui/addHyperlinkToolbar.ts | 6 +- examples/vanilla/src/ui/addSideMenu.ts | 8 +- examples/vanilla/src/ui/addSlashMenu.ts | 4 +- .../vanilla/src/ui/blockSideMenuFactory.ts | 0 .../src/ui/formattingToolbarFactory.ts | 0 packages/core/src/BlockNoteEditor.ts | 257 +++--------------- packages/core/src/BlockNoteExtensions.ts | 2 - .../BlockSideMenuFactoryTypes.ts | 0 .../FormattingToolbarPlugin.ts | 113 +++----- .../HyperlinkToolbarFactoryTypes.ts | 0 .../HyperlinkToolbarPlugin.ts | 164 +++++------ .../MultipleNodeSelection.ts | 0 .../SideMenuPlugin.ts} | 214 +++++++-------- .../extensions/SlashMenu/SlashMenuPlugin.ts | 74 ++--- packages/core/src/index.ts | 14 +- packages/core/src/shared/EventEmitter.ts | 58 ++++ .../plugins/suggestion/SuggestionPlugin.ts | 98 ++----- packages/react/src/BlockNoteView.tsx | 20 +- .../FormattingToolbarPositioner.tsx | 17 +- .../components/HyperlinkToolbarPositioner.tsx | 31 +-- .../components/SideMenuPositioner.tsx | 52 ++-- .../components/SlashMenuPositioner.tsx | 50 ++-- 24 files changed, 471 insertions(+), 717 deletions(-) delete mode 100644 examples/vanilla/src/ui/blockSideMenuFactory.ts delete mode 100644 examples/vanilla/src/ui/formattingToolbarFactory.ts delete mode 100644 packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts delete mode 100644 packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts rename packages/core/src/extensions/{DraggableBlocks => SideMenu}/MultipleNodeSelection.ts (100%) rename packages/core/src/extensions/{DraggableBlocks/DraggableBlocksPlugin.ts => SideMenu/SideMenuPlugin.ts} (80%) create mode 100644 packages/core/src/shared/EventEmitter.ts diff --git a/examples/editor/src/App.tsx b/examples/editor/src/App.tsx index 00d96815f9..ada4b8c3b9 100644 --- a/examples/editor/src/App.tsx +++ b/examples/editor/src/App.tsx @@ -2,11 +2,11 @@ import "@blocknote/core/style.css"; import { BlockNoteView, - useBlockNote, FormattingToolbarPositioner, HyperlinkToolbarPositioner, - SlashMenuPositioner, SideMenuPositioner, + SlashMenuPositioner, + useBlockNote, } from "@blocknote/react"; import styles from "./App.module.css"; diff --git a/examples/vanilla/src/ui/addFormattingToolbar.ts b/examples/vanilla/src/ui/addFormattingToolbar.ts index c2d95b8e81..bae8673512 100644 --- a/examples/vanilla/src/ui/addFormattingToolbar.ts +++ b/examples/vanilla/src/ui/addFormattingToolbar.ts @@ -5,7 +5,7 @@ export const addFormattingToolbar = (editor: BlockNoteEditor) => { let element: HTMLElement; let boldBtn: HTMLAnchorElement; - editor.createFormattingToolbar((formattingToolbarState) => { + editor.formattingToolbar.onUpdate((formattingToolbarState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; diff --git a/examples/vanilla/src/ui/addHyperlinkToolbar.ts b/examples/vanilla/src/ui/addHyperlinkToolbar.ts index bf2fd299bb..866ba7c24c 100644 --- a/examples/vanilla/src/ui/addHyperlinkToolbar.ts +++ b/examples/vanilla/src/ui/addHyperlinkToolbar.ts @@ -4,7 +4,7 @@ import { createButton } from "./util"; export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { let element: HTMLElement; - const callbacks = editor.createHyperlinkToolbar((hyperlinkToolbarState) => { + editor.hyperlinkToolbar.onUpdate((hyperlinkToolbarState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -17,13 +17,13 @@ export const addHyperlinkToolbar = (editor: BlockNoteEditor) => { const editBtn = createButton("edit", () => { const newUrl = prompt("new url") || url; - callbacks.editHyperlink(newUrl, text); + editor.hyperlinkToolbar.editHyperlink(newUrl, text); }); element.appendChild(editBtn); const removeBtn = createButton("remove", () => { - callbacks.deleteHyperlink(); + editor.hyperlinkToolbar.deleteHyperlink(); }); element.appendChild(editBtn); diff --git a/examples/vanilla/src/ui/addSideMenu.ts b/examples/vanilla/src/ui/addSideMenu.ts index cc4f829553..de277aabcc 100644 --- a/examples/vanilla/src/ui/addSideMenu.ts +++ b/examples/vanilla/src/ui/addSideMenu.ts @@ -4,7 +4,7 @@ import { createButton } from "./util"; export const addSideMenu = (editor: BlockNoteEditor) => { let element: HTMLElement; - const callbacks = editor.createSideMenu((sideMenuState) => { + editor.sideMenu.onUpdate((sideMenuState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -12,7 +12,7 @@ export const addSideMenu = (editor: BlockNoteEditor) => { element.style.padding = "10px"; element.style.opacity = "0.8"; const addBtn = createButton("+", () => { - callbacks.addBlock(); + editor.sideMenu.addBlock(); }); element.appendChild(addBtn); @@ -20,8 +20,8 @@ export const addSideMenu = (editor: BlockNoteEditor) => { // TODO: render a submenu with a delete option that calls "props.deleteBlock" }); - dragBtn.addEventListener("dragstart", callbacks.blockDragStart); - dragBtn.addEventListener("dragend", callbacks.blockDragEnd); + dragBtn.addEventListener("dragstart", editor.sideMenu.blockDragStart); + dragBtn.addEventListener("dragend", editor.sideMenu.blockDragEnd); dragBtn.draggable = true; element.style.display = "none"; element.appendChild(dragBtn); diff --git a/examples/vanilla/src/ui/addSlashMenu.ts b/examples/vanilla/src/ui/addSlashMenu.ts index 25ff74a057..3ecbd7fc46 100644 --- a/examples/vanilla/src/ui/addSlashMenu.ts +++ b/examples/vanilla/src/ui/addSlashMenu.ts @@ -28,7 +28,7 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { return domItems; } - const callbacks = editor.createSlashMenu((slashMenuState) => { + editor.slashMenu.onUpdate((slashMenuState) => { if (!element) { element = document.createElement("div"); element.style.background = "gray"; @@ -43,7 +43,7 @@ export const addSlashMenu = (editor: BlockNoteEditor) => { if (slashMenuState.show) { updateItems( slashMenuState.filteredItems, - callbacks.itemCallback, + editor.slashMenu.itemCallback, slashMenuState.keyboardHoveredItemIndex ); diff --git a/examples/vanilla/src/ui/blockSideMenuFactory.ts b/examples/vanilla/src/ui/blockSideMenuFactory.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/vanilla/src/ui/formattingToolbarFactory.ts b/examples/vanilla/src/ui/formattingToolbarFactory.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 4591c64645..bf954f7776 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -37,27 +37,12 @@ import { } from "./extensions/Blocks/api/inlineContentTypes"; import { Selection } from "./extensions/Blocks/api/selectionTypes"; import { getBlockInfoFromPos } from "./extensions/Blocks/helpers/getBlockInfoFromPos"; -import { - setupFormattingToolbar, - FormattingToolbarState, - FormattingToolbarCallbacks, -} from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; -import { - HyperlinkToolbarCallbacks, - HyperlinkToolbarState, - setupHyperlinkToolbar, -} from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; -import { - SuggestionsMenuCallbacks, - SuggestionsMenuState, -} from "./shared/plugins/suggestion/SuggestionPlugin"; -import { setupSlashMenu } from "./extensions/SlashMenu/SlashMenuPlugin"; -import { - setupSideMenu, - SideMenuCallbacks, - SideMenuState, -} from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; + +import { FormattingToolbarProsemirrorPlugin } from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; +import { HyperlinkToolbarProsemirrorPlugin } from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; +import { SideMenuProsemirrorPlugin } from "./extensions/SideMenu/SideMenuPlugin"; import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; +import { SlashMenuProsemirrorPlugin } from "./extensions/SlashMenu/SlashMenuPlugin"; import { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; export type BlockNoteEditorOptions = { @@ -163,81 +148,10 @@ export class BlockNoteEditor { public readonly schema: BSchema; public ready = false; - private uiElementCallbacks: { - formattingToolbar: FormattingToolbarCallbacks; - hyperlinkToolbar: HyperlinkToolbarCallbacks; - slashMenu: SuggestionsMenuCallbacks>; - sideMenu: SideMenuCallbacks; - }; - - private uiElementListeners: Partial<{ - formattingToolbar: (formattingToolbarState: FormattingToolbarState) => void; - hyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void; - slashMenu: ( - slashMenuState: SuggestionsMenuState> - ) => void; - sideMenu: (sideMenuState: SideMenuState) => void; - }> = {}; - - public createFormattingToolbar = ( - updateFormattingToolbar: ( - formattingToolbarState: FormattingToolbarState - ) => void - ) => { - if ("formattingToolbar" in this.uiElementListeners) { - throw Error( - "You have already created a Formatting Toolbar. You can only create a single Formatting Toolbar per BlockNote editor instance." - ); - } - - this.uiElementListeners.formattingToolbar = updateFormattingToolbar; - - return this.uiElementCallbacks.formattingToolbar; - }; - - public createHyperlinkToolbar = ( - updateHyperlinkToolbar: ( - hyperlinkToolbarState: HyperlinkToolbarState - ) => void - ) => { - if ("hyperlinkToolbar" in this.uiElementListeners) { - throw Error( - "You have already created a Hyperlink Toolbar. You can only create a single Hyperlink Toolbar per BlockNote editor instance." - ); - } - - this.uiElementListeners.hyperlinkToolbar = updateHyperlinkToolbar; - - return this.uiElementCallbacks.hyperlinkToolbar; - }; - - public createSlashMenu = >( - updateSlashMenu: (slashMenuState: SuggestionsMenuState) => void - ) => { - if ("slashMenu" in this.uiElementListeners) { - throw Error( - "You have already created a Slash Menu. You can only create a single Slash Menu per BlockNote editor instance." - ); - } - - this.uiElementListeners.slashMenu = updateSlashMenu as any; - - return this.uiElementCallbacks.slashMenu; - }; - - public createSideMenu = ( - updateSideMenu: (sideMenuState: SideMenuState) => void - ) => { - if ("sideMenu" in this.uiElementListeners) { - throw Error( - "You have already created a Side Menu. You can only create a single Side Menu per BlockNote editor instance." - ); - } - - this.uiElementListeners.sideMenu = updateSideMenu; - - return this.uiElementCallbacks.sideMenu; - }; + public readonly sideMenu: SideMenuProsemirrorPlugin; + public readonly formattingToolbar: FormattingToolbarProsemirrorPlugin; + public readonly slashMenu: SlashMenuProsemirrorPlugin; + public readonly hyperlinkToolbar: HyperlinkToolbarProsemirrorPlugin; constructor( private readonly options: Partial> = {} @@ -257,140 +171,36 @@ export class BlockNoteEditor { ...options, }; - const editor = this; + this.sideMenu = new SideMenuProsemirrorPlugin(this); + this.formattingToolbar = new FormattingToolbarProsemirrorPlugin(this); + this.slashMenu = new SlashMenuProsemirrorPlugin( + this, + newOptions.slashCommands || + getDefaultSlashMenuItems(newOptions.blockSchema) + ); + this.hyperlinkToolbar = new HyperlinkToolbarProsemirrorPlugin(this); const extensions = getBlockNoteExtensions({ editor: this, - slashCommands: - newOptions.slashCommands || - getDefaultSlashMenuItems(newOptions.blockSchema), blockSchema: newOptions.blockSchema, collaboration: newOptions.collaboration, }); - this.schema = newOptions.blockSchema; - - let formattingToolbarCallbacks: FormattingToolbarCallbacks; - const formattingToolbarExtension = Extension.create({ - name: "FormattingToolbarExtension", + const blockNoteUIExtension = Extension.create({ + name: "BlockNoteUIExtension", - addProseMirrorPlugins() { - const { plugin, callbacks } = setupFormattingToolbar( - editor, - this.editor, - (formattingToolbarState) => { - const formattingToolbarListener = - editor.uiElementListeners.formattingToolbar; - - if (!formattingToolbarListener) { - return; - } - - formattingToolbarListener(formattingToolbarState); - } - ); - - formattingToolbarCallbacks = { - destroy: () => delete editor.uiElementListeners.formattingToolbar, - ...callbacks, - }; - - return [plugin]; - }, - }); - extensions.push(formattingToolbarExtension); - - let hyperlinkToolbarCallbacks: HyperlinkToolbarCallbacks; - const hyperlinkToolbarExtension = Extension.create({ - name: "HyperlinkToolbarExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupHyperlinkToolbar( - editor, - this.editor, - (hyperlinkToolbarState) => { - const hyperlinkToolbarListener = - editor.uiElementListeners.hyperlinkToolbar; - - if (!hyperlinkToolbarListener) { - return; - } - - hyperlinkToolbarListener(hyperlinkToolbarState); - } - ); - - hyperlinkToolbarCallbacks = { - destroy: () => delete editor.uiElementListeners.hyperlinkToolbar, - ...callbacks, - }; - - return [plugin]; + addProseMirrorPlugins: () => { + return [ + this.sideMenu.plugin, + this.formattingToolbar.plugin, + this.slashMenu.plugin, + this.hyperlinkToolbar.plugin, + ]; }, }); - extensions.push(hyperlinkToolbarExtension); - - let slashMenuCallbacks: SuggestionsMenuCallbacks< - BaseSlashMenuItem - >; - const slashMenuExtension = Extension.create({ - name: "SlashMenuExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupSlashMenu( - editor, - this.editor, - (slashMenuState) => { - const slashMenuListener = editor.uiElementListeners.slashMenu; - - if (!slashMenuListener) { - return; - } - - slashMenuListener(slashMenuState as any); - }, - newOptions.slashCommands || - getDefaultSlashMenuItems(newOptions.blockSchema) - ); - - slashMenuCallbacks = { - destroy: () => delete editor.uiElementListeners.slashMenu, - ...callbacks, - }; - - return [plugin]; - }, - }); - extensions.push(slashMenuExtension); - - let sideMenuCallbacks: SideMenuCallbacks; - const sideMenuExtension = Extension.create({ - name: "SideMenuExtension", - - addProseMirrorPlugins() { - const { plugin, callbacks } = setupSideMenu( - editor, - this.editor, - (sideMenuState) => { - const sideMenuListener = editor.uiElementListeners.sideMenu; - - if (!sideMenuListener) { - return; - } - - sideMenuListener(sideMenuState as any); - } - ); + extensions.push(blockNoteUIExtension); - sideMenuCallbacks = { - destroy: () => delete editor.uiElementListeners.sideMenu, - ...callbacks, - }; - - return [plugin]; - }, - }); - extensions.push(sideMenuExtension); + this.schema = newOptions.blockSchema; const tiptapOptions: EditorOptions = { // TODO: This approach to setting initial content is "cleaner" but requires the PM editor schema, which is only @@ -452,15 +262,10 @@ export class BlockNoteEditor { this._tiptapEditor = new Editor(tiptapOptions) as Editor & { contentComponent: any; }; + } - // These need to be assigned after the TipTap editor is created as they are - // initialized in a plugin, which is only loaded on editor creation. - this.uiElementCallbacks = { - formattingToolbar: formattingToolbarCallbacks!, - hyperlinkToolbar: hyperlinkToolbarCallbacks!, - slashMenu: slashMenuCallbacks!, - sideMenu: sideMenuCallbacks!, - }; + public get prosemirrorView() { + return this._tiptapEditor.view; } public get domElement() { diff --git a/packages/core/src/BlockNoteExtensions.ts b/packages/core/src/BlockNoteExtensions.ts index 3a4a23b574..9dba2510f2 100644 --- a/packages/core/src/BlockNoteExtensions.ts +++ b/packages/core/src/BlockNoteExtensions.ts @@ -24,7 +24,6 @@ import { BlockSchema } from "./extensions/Blocks/api/blockTypes"; import { CustomBlockSerializerExtension } from "./extensions/Blocks/api/serialization"; import blockStyles from "./extensions/Blocks/nodes/Block.module.css"; import { Placeholder } from "./extensions/Placeholder/PlaceholderExtension"; -import { BaseSlashMenuItem } from "./extensions/SlashMenu/BaseSlashMenuItem"; import { TextAlignmentExtension } from "./extensions/TextAlignment/TextAlignmentExtension"; import { TextColorExtension } from "./extensions/TextColor/TextColorExtension"; import { TextColorMark } from "./extensions/TextColor/TextColorMark"; @@ -36,7 +35,6 @@ import UniqueID from "./extensions/UniqueID/UniqueID"; */ export const getBlockNoteExtensions = (opts: { editor: BlockNoteEditor; - slashCommands: BaseSlashMenuItem[]; // couldn't fix type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771 blockSchema: BSchema; collaboration?: { fragment: Y.XmlFragment; diff --git a/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts b/packages/core/src/extensions/DraggableBlocks/BlockSideMenuFactoryTypes.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts index 4c65d8224a..29d893fccb 100644 --- a/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts +++ b/packages/core/src/extensions/FormattingToolbar/FormattingToolbarPlugin.ts @@ -1,9 +1,4 @@ -import { - Editor, - isNodeSelection, - isTextSelection, - posToDOMRect, -} from "@tiptap/core"; +import { isNodeSelection, isTextSelection, posToDOMRect } from "@tiptap/core"; import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; import { @@ -12,15 +7,13 @@ import { BlockNoteEditor, BlockSchema, } from "../.."; +import { EventEmitter } from "../../shared/EventEmitter"; export type FormattingToolbarCallbacks = BaseUiElementCallbacks; export type FormattingToolbarState = BaseUiElementState; export class FormattingToolbarView { - public editor: BlockNoteEditor; - private ttEditor: Editor; - private formattingToolbarState?: FormattingToolbarState; public updateFormattingToolbar: () => void; @@ -47,15 +40,12 @@ export class FormattingToolbarView { }; constructor( - editor: BlockNoteEditor, - tipTapEditor: Editor, + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, updateFormattingToolbar: ( formattingToolbarState: FormattingToolbarState ) => void ) { - this.editor = editor; - this.ttEditor = tipTapEditor; - this.updateFormattingToolbar = () => { if (!this.formattingToolbarState) { throw new Error( @@ -66,15 +56,12 @@ export class FormattingToolbarView { updateFormattingToolbar(this.formattingToolbarState); }; - this.ttEditor.view.dom.addEventListener( - "mousedown", - this.viewMousedownHandler - ); - this.ttEditor.view.dom.addEventListener("mouseup", this.viewMouseupHandler); - this.ttEditor.view.dom.addEventListener("dragstart", this.dragstartHandler); + pmView.dom.addEventListener("mousedown", this.viewMousedownHandler); + pmView.dom.addEventListener("mouseup", this.viewMouseupHandler); + pmView.dom.addEventListener("dragstart", this.dragstartHandler); - this.ttEditor.on("focus", this.focusHandler); - this.ttEditor.on("blur", this.blurHandler); + pmView.dom.addEventListener("focus", this.focusHandler); + pmView.dom.addEventListener("blur", this.blurHandler); document.addEventListener("scroll", this.scrollHandler); } @@ -85,7 +72,7 @@ export class FormattingToolbarView { viewMouseupHandler = () => { this.preventShow = false; - setTimeout(() => this.update(this.ttEditor.view)); + setTimeout(() => this.update(this.pmView)); }; // For dragging the whole editor. @@ -98,17 +85,17 @@ export class FormattingToolbarView { focusHandler = () => { // we use `setTimeout` to make sure `selection` is already updated - setTimeout(() => this.update(this.ttEditor.view)); + setTimeout(() => this.update(this.pmView)); }; - blurHandler = ({ event }: { event: FocusEvent }) => { + blurHandler = (event: FocusEvent) => { if (this.preventHide) { this.preventHide = false; return; } - const editorWrapper = this.ttEditor.view.dom.parentElement!; + const editorWrapper = this.pmView.dom.parentElement!; // Checks if the focus is moving to an element outside the editor. If it is, // the toolbar is hidden. @@ -194,27 +181,18 @@ export class FormattingToolbarView { } destroy() { - this.ttEditor.view.dom.removeEventListener( - "mousedown", - this.viewMousedownHandler - ); - this.ttEditor.view.dom.removeEventListener( - "mouseup", - this.viewMouseupHandler - ); - this.ttEditor.view.dom.removeEventListener( - "dragstart", - this.dragstartHandler - ); - - this.ttEditor.off("focus", this.focusHandler); - this.ttEditor.off("blur", this.blurHandler); + this.pmView.dom.removeEventListener("mousedown", this.viewMousedownHandler); + this.pmView.dom.removeEventListener("mouseup", this.viewMouseupHandler); + this.pmView.dom.removeEventListener("dragstart", this.dragstartHandler); + + this.pmView.dom.removeEventListener("focus", this.focusHandler); + this.pmView.dom.removeEventListener("blur", this.blurHandler); document.removeEventListener("scroll", this.scrollHandler); } getSelectionBoundingBox() { - const { state } = this.ttEditor.view; + const { state } = this.pmView; const { selection } = state; // support for CellSelections @@ -223,44 +201,41 @@ export class FormattingToolbarView { const to = Math.max(...ranges.map((range) => range.$to.pos)); if (isNodeSelection(selection)) { - const node = this.ttEditor.view.nodeDOM(from) as HTMLElement; + const node = this.pmView.nodeDOM(from) as HTMLElement; if (node) { return node.getBoundingClientRect(); } } - return posToDOMRect(this.ttEditor.view, from, to); + return posToDOMRect(this.pmView, from, to); } } export const formattingToolbarPluginKey = new PluginKey( "FormattingToolbarPlugin" ); -export const setupFormattingToolbar = ( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateFormattingToolbar: ( - formattingToolbarState: FormattingToolbarState - ) => void -): { - plugin: Plugin; - callbacks: Omit; -} => { - let formattingToolbarView: FormattingToolbarView; - - return { - plugin: new Plugin({ + +export class FormattingToolbarProsemirrorPlugin< + BSchema extends BlockSchema +> extends EventEmitter { + private view: FormattingToolbarView | undefined; + public readonly plugin: Plugin; + + constructor(editor: BlockNoteEditor) { + super(); + this.plugin = new Plugin({ key: formattingToolbarPluginKey, - view: () => { - formattingToolbarView = new FormattingToolbarView( - editor, - tiptapEditor, - updateFormattingToolbar - ); - return formattingToolbarView; + view: (editorView) => { + this.view = new FormattingToolbarView(editor, editorView, (state) => { + this.emit("update", state); + }); + return this.view; }, - }), - callbacks: {}, - }; -}; + }); + } + + public onUpdate(callback: (state: FormattingToolbarState) => void) { + return this.on("update", callback); + } +} diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarFactoryTypes.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts index 6731e60453..65ae274279 100644 --- a/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts +++ b/packages/core/src/extensions/HyperlinkToolbar/HyperlinkToolbarPlugin.ts @@ -1,26 +1,12 @@ -import { Editor, getMarkRange, posToDOMRect, Range } from "@tiptap/core"; +import { getMarkRange, posToDOMRect, Range } from "@tiptap/core"; +import { EditorView } from "@tiptap/pm/view"; import { Mark } from "prosemirror-model"; import { Plugin, PluginKey } from "prosemirror-state"; import { BlockNoteEditor } from "../../BlockNoteEditor"; -import { - BaseUiElementCallbacks, - BaseUiElementState, -} from "../../shared/BaseUiElementTypes"; +import { BaseUiElementState } from "../../shared/BaseUiElementTypes"; +import { EventEmitter } from "../../shared/EventEmitter"; import { BlockSchema } from "../Blocks/api/blockTypes"; -export type HyperlinkToolbarCallbacks = BaseUiElementCallbacks & { - // Updates or deletes the hovered hyperlink. - editHyperlink: (url: string, text: string) => void; - deleteHyperlink: () => void; - - // When hovering on/off hyperlinks using the mouse cursor, the hyperlink - // toolbar will open & close with a delay. These functions start & stop the - // delay timer, and should be used for when the mouse cursor enters & exits - // the hyperlink toolbar. - startHideTimer: () => void; - stopHideTimer: () => void; -}; - export type HyperlinkToolbarState = BaseUiElementState & { // The hovered hyperlink's URL, and the text it's displayed with in the // editor. @@ -29,9 +15,6 @@ export type HyperlinkToolbarState = BaseUiElementState & { }; class HyperlinkToolbarView { - editor: BlockNoteEditor; - ttEditor: Editor; - private hyperlinkToolbarState?: HyperlinkToolbarState; public updateHyperlinkToolbar: () => void; @@ -49,15 +32,12 @@ class HyperlinkToolbarView { hyperlinkMarkRange: Range | undefined; constructor( - editor: BlockNoteEditor, - tiptapEditor: Editor, + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, updateHyperlinkToolbar: ( hyperlinkToolbarState: HyperlinkToolbarState ) => void ) { - this.editor = editor; - this.ttEditor = tiptapEditor; - this.updateHyperlinkToolbar = () => { if (!this.hyperlinkToolbarState) { throw new Error("Attempting to update uninitialized hyperlink toolbar"); @@ -81,7 +61,7 @@ class HyperlinkToolbarView { return false; }; - this.ttEditor.view.dom.addEventListener("mouseover", this.mouseOverHandler); + this.pmView.dom.addEventListener("mouseover", this.mouseOverHandler); document.addEventListener("click", this.clickHandler, true); document.addEventListener("scroll", this.scrollHandler); } @@ -101,14 +81,16 @@ class HyperlinkToolbarView { // mouseHoveredHyperlinkMarkRange. const hoveredHyperlinkElement = event.target; const posInHoveredHyperlinkMark = - this.ttEditor.view.posAtDOM(hoveredHyperlinkElement, 0) + 1; - const resolvedPosInHoveredHyperlinkMark = this.ttEditor.state.doc.resolve( + this.pmView.posAtDOM(hoveredHyperlinkElement, 0) + 1; + const resolvedPosInHoveredHyperlinkMark = this.pmView.state.doc.resolve( posInHoveredHyperlinkMark ); const marksAtPos = resolvedPosInHoveredHyperlinkMark.marks(); for (const mark of marksAtPos) { - if (mark.type.name === this.ttEditor.schema.mark("link").type.name) { + if ( + mark.type.name === this.pmView.state.schema.mark("link").type.name + ) { this.mouseHoveredHyperlinkMark = mark; this.mouseHoveredHyperlinkMarkRange = getMarkRange( @@ -128,7 +110,7 @@ class HyperlinkToolbarView { }; clickHandler = (event: MouseEvent) => { - const editorWrapper = this.ttEditor.view.dom.parentElement!; + const editorWrapper = this.pmView.dom.parentElement!; if ( // Toolbar is open. @@ -153,7 +135,7 @@ class HyperlinkToolbarView { if (this.hyperlinkMark !== undefined) { if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.referencePos = posToDOMRect( - this.ttEditor.view, + this.pmView, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ); @@ -163,7 +145,7 @@ class HyperlinkToolbarView { }; editHyperlink(url: string, text: string) { - const tr = this.ttEditor.view.state.tr.insertText( + const tr = this.pmView.state.tr.insertText( text, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to @@ -171,10 +153,10 @@ class HyperlinkToolbarView { tr.addMark( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.from + text.length, - this.ttEditor.schema.mark("link", { href: url }) + this.pmView.state.schema.mark("link", { href: url }) ); - this.ttEditor.view.dispatch(tr); - this.ttEditor.view.focus(); + this.pmView.dispatch(tr); + this.pmView.focus(); if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.show = false; @@ -183,8 +165,8 @@ class HyperlinkToolbarView { } deleteHyperlink() { - this.ttEditor.view.dispatch( - this.ttEditor.view.state.tr + this.pmView.dispatch( + this.pmView.state.tr .removeMark( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to, @@ -192,7 +174,7 @@ class HyperlinkToolbarView { ) .setMeta("preventAutolink", true) ); - this.ttEditor.view.focus(); + this.pmView.focus(); if (this.hyperlinkToolbarState?.show) { this.hyperlinkToolbarState.show = false; @@ -201,7 +183,7 @@ class HyperlinkToolbarView { } update() { - if (!this.ttEditor.view.hasFocus()) { + if (!this.pmView.hasFocus()) { return; } @@ -218,15 +200,17 @@ class HyperlinkToolbarView { // Finds link mark at the editor selection's position to update keyboardHoveredHyperlinkMark and // keyboardHoveredHyperlinkMarkRange. - if (this.ttEditor.state.selection.empty) { - const marksAtPos = this.ttEditor.state.selection.$from.marks(); + if (this.pmView.state.selection.empty) { + const marksAtPos = this.pmView.state.selection.$from.marks(); for (const mark of marksAtPos) { - if (mark.type.name === this.ttEditor.schema.mark("link").type.name) { + if ( + mark.type.name === this.pmView.state.schema.mark("link").type.name + ) { this.keyboardHoveredHyperlinkMark = mark; this.keyboardHoveredHyperlinkMarkRange = getMarkRange( - this.ttEditor.state.selection.$from, + this.pmView.state.selection.$from, mark.type, mark.attrs ) || undefined; @@ -251,12 +235,12 @@ class HyperlinkToolbarView { this.hyperlinkToolbarState = { show: true, referencePos: posToDOMRect( - this.ttEditor.view, + this.pmView, this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ), url: this.hyperlinkMark!.attrs.href, - text: this.ttEditor.view.state.doc.textBetween( + text: this.pmView.state.doc.textBetween( this.hyperlinkMarkRange!.from, this.hyperlinkMarkRange!.to ), @@ -280,10 +264,7 @@ class HyperlinkToolbarView { } destroy() { - this.ttEditor.view.dom.removeEventListener( - "mouseover", - this.mouseOverHandler - ); + this.pmView.dom.removeEventListener("mouseover", this.mouseOverHandler); document.removeEventListener("scroll", this.scrollHandler); document.removeEventListener("click", this.clickHandler, true); } @@ -292,34 +273,61 @@ class HyperlinkToolbarView { export const hyperlinkToolbarPluginKey = new PluginKey( "HyperlinkToolbarPlugin" ); -export const setupHyperlinkToolbar = ( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateHyperlinkToolbar: (hyperlinkToolbarState: HyperlinkToolbarState) => void -): { - plugin: Plugin; - callbacks: Omit; -} => { - let hyperlinkToolbarView: HyperlinkToolbarView; - - return { - plugin: new Plugin({ + +export class HyperlinkToolbarProsemirrorPlugin< + BSchema extends BlockSchema +> extends EventEmitter { + private view: HyperlinkToolbarView | undefined; + public readonly plugin: Plugin; + + constructor(editor: BlockNoteEditor) { + super(); + this.plugin = new Plugin({ key: hyperlinkToolbarPluginKey, - view: () => { - hyperlinkToolbarView = new HyperlinkToolbarView( - editor, - tiptapEditor, - updateHyperlinkToolbar - ); - return hyperlinkToolbarView; + view: (editorView) => { + this.view = new HyperlinkToolbarView(editor, editorView, (state) => { + this.emit("update", state); + }); + return this.view; }, - }), - callbacks: { - editHyperlink: (url, text) => - hyperlinkToolbarView.editHyperlink(url, text), - deleteHyperlink: () => hyperlinkToolbarView.deleteHyperlink(), - startHideTimer: () => hyperlinkToolbarView.startMenuUpdateTimer(), - stopHideTimer: () => hyperlinkToolbarView.stopMenuUpdateTimer(), - }, + }); + } + + public onUpdate(callback: (state: HyperlinkToolbarState) => void) { + return this.on("update", callback); + } + + /** + * Edit the currently hovered hyperlink. + */ + public editHyperlink = (url: string, text: string) => { + this.view!.editHyperlink(url, text); }; -}; + + /** + * Delete the currently hovered hyperlink. + */ + public deleteHyperlink = () => { + this.view!.deleteHyperlink(); + }; + + /** + * When hovering on/off hyperlinks using the mouse cursor, the hyperlink + * toolbar will open & close with a delay. + * + * This function starts the delay timer, and should be used for when the mouse cursor enters the hyperlink toolbar. + */ + public startHideTimer = () => { + this.view!.startMenuUpdateTimer(); + }; + + /** + * When hovering on/off hyperlinks using the mouse cursor, the hyperlink + * toolbar will open & close with a delay. + * + * This function stops the delay timer, and should be used for when the mouse cursor exits the hyperlink toolbar. + */ + public stopHideTimer = () => { + this.view!.stopMenuUpdateTimer(); + }; +} diff --git a/packages/core/src/extensions/DraggableBlocks/MultipleNodeSelection.ts b/packages/core/src/extensions/SideMenu/MultipleNodeSelection.ts similarity index 100% rename from packages/core/src/extensions/DraggableBlocks/MultipleNodeSelection.ts rename to packages/core/src/extensions/SideMenu/MultipleNodeSelection.ts diff --git a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts b/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts similarity index 80% rename from packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts rename to packages/core/src/extensions/SideMenu/SideMenuPlugin.ts index 74014f7ba8..63e5aa1bd6 100644 --- a/packages/core/src/extensions/DraggableBlocks/DraggableBlocksPlugin.ts +++ b/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts @@ -5,37 +5,18 @@ import * as pv from "prosemirror-view"; import { EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../BlockNoteEditor"; import styles from "../../editor.module.css"; -import { - BaseUiElementCallbacks, - BaseUiElementState, -} from "../../shared/BaseUiElementTypes"; +import { BaseUiElementState } from "../../shared/BaseUiElementTypes"; +import { EventEmitter } from "../../shared/EventEmitter"; import { Block, BlockSchema } from "../Blocks/api/blockTypes"; import { getBlockInfoFromPos } from "../Blocks/helpers/getBlockInfoFromPos"; import { slashMenuPluginKey } from "../SlashMenu/SlashMenuPlugin"; import { MultipleNodeSelection } from "./MultipleNodeSelection"; -import { Editor } from "@tiptap/core"; const serializeForClipboard = (pv as any).__serializeForClipboard; // code based on https://github.com/ueberdosis/tiptap/issues/323#issuecomment-506637799 let dragImageElement: Element | undefined; -export type SideMenuCallbacks = BaseUiElementCallbacks & { - // If the block is empty, opens the slash menu. If the block has content, - // creates a new block below and opens the slash menu in it. - addBlock: () => void; - - // Freezes/unfreezes the side menu. When frozen, the side menu will stay - // attached to the same block regardless of which block is hovered by the - // mouse cursor. - freezeMenu: () => void; - unfreezeMenu: () => void; - - // Handles drag & drop events for blocks. - blockDragStart: (event: DragEvent) => void; - blockDragEnd: () => void; -}; - export type SideMenuState = BaseUiElementState & { // The block that the side menu is attached to. block: Block; @@ -244,49 +225,36 @@ function dragStart(e: DragEvent, view: EditorView) { } export class SideMenuView implements PluginView { - editor: BlockNoteEditor; - ttEditor: Editor; - private sideMenuState?: SideMenuState; - public updateSideMenu: () => void; // When true, the drag handle with be anchored at the same level as root elements // When false, the drag handle with be just to the left of the element // TODO: Is there any case where we want this to be false? - horizontalPosAnchoredAtRoot: boolean; - horizontalPosAnchor: number; + private horizontalPosAnchoredAtRoot: boolean; + private horizontalPosAnchor: number; - hoveredBlock: HTMLElement | undefined; + private hoveredBlock: HTMLElement | undefined; // Used to check if currently dragged content comes from this editor instance. - isDragging = false; + public isDragging = false; - menuFrozen = false; + public menuFrozen = false; constructor( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateSideMenu: (sideMenuState: SideMenuState) => void + private readonly editor: BlockNoteEditor, + private readonly pmView: EditorView, + private readonly updateSideMenu: ( + sideMenuState: SideMenuState + ) => void ) { - this.editor = editor; - this.ttEditor = tiptapEditor; - this.horizontalPosAnchoredAtRoot = true; this.horizontalPosAnchor = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect().x; - this.updateSideMenu = () => { - if (!this.sideMenuState) { - throw new Error("Attempting to update uninitialized side menu"); - } - - updateSideMenu(this.sideMenuState); - }; - document.body.addEventListener("drop", this.onDrop, true); document.body.addEventListener("dragover", this.onDragOver); - this.ttEditor.view.dom.addEventListener("dragstart", this.onDragStart); + this.pmView.dom.addEventListener("dragstart", this.onDragStart); // Shows or updates menu position whenever the cursor moves, if the menu isn't frozen. document.body.addEventListener("mousemove", this.onMouseMove, true); @@ -296,7 +264,7 @@ export class SideMenuView implements PluginView { // Hides and unfreezes the menu whenever the user selects the editor with the mouse or presses a key. // TODO: Better integration with suggestions menu and only editor scope? - document.body.addEventListener("mousedown", this.onMouseDown, true); + // document.body.addEventListener("mousedown", this.onMouseDown, true); document.body.addEventListener("keydown", this.onKeyDown, true); } @@ -313,13 +281,13 @@ export class SideMenuView implements PluginView { * when dragging / dropping to the side of the editor */ onDrop = (event: DragEvent) => { - this.ttEditor.commands.blur(); + this.editor._tiptapEditor.commands.blur(); if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.ttEditor.view.posAtCoords({ + let pos = this.pmView.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -329,7 +297,7 @@ export class SideMenuView implements PluginView { if (!pos || pos.inside === -1) { const evt = new Event("drop", event) as any; const editorBoundingBox = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -337,7 +305,7 @@ export class SideMenuView implements PluginView { evt.preventDefault = () => event.preventDefault(); evt.synthetic = true; // prevent recursion // console.log("dispatch fake drop"); - this.ttEditor.view.dom.dispatchEvent(evt); + this.pmView.dom.dispatchEvent(evt); } }; @@ -350,7 +318,7 @@ export class SideMenuView implements PluginView { if ((event as any).synthetic || !this.isDragging) { return; } - let pos = this.ttEditor.view.posAtCoords({ + let pos = this.pmView.posAtCoords({ left: event.clientX, top: event.clientY, }); @@ -358,7 +326,7 @@ export class SideMenuView implements PluginView { if (!pos || pos.inside === -1) { const evt = new Event("dragover", event) as any; const editorBoundingBox = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect(); evt.clientX = editorBoundingBox.left + editorBoundingBox.width / 2; evt.clientY = event.clientY; @@ -366,32 +334,18 @@ export class SideMenuView implements PluginView { evt.preventDefault = () => event.preventDefault(); evt.synthetic = true; // prevent recursion // console.log("dispatch fake dragover"); - this.ttEditor.view.dom.dispatchEvent(evt); + this.pmView.dom.dispatchEvent(evt); } }; onKeyDown = (_event: KeyboardEvent) => { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } this.menuFrozen = false; }; - onMouseDown = (_event: MouseEvent) => { - // TODO: Fix - // if (this.blockMenu.element?.contains(event.target as HTMLElement)) { - // return; - // } - // - // if (this.sideMenuState?.show) { - // this.sideMenuState.show = false; - // this.updateSideMenu(); - // } - // - // this.menuFrozen = false; - }; - onMouseMove = (event: MouseEvent) => { if (this.menuFrozen) { return; @@ -402,19 +356,18 @@ export class SideMenuView implements PluginView { // blockGroup that wraps all blocks in the editor) for more accurate side // menu placement. const editorBoundingBox = ( - this.ttEditor.view.dom.firstChild! as HTMLElement + this.pmView.dom.firstChild! as HTMLElement ).getBoundingClientRect(); // We want the full area of the editor to check if the cursor is hovering // above it though. - const editorOuterBoundingBox = - this.ttEditor.view.dom.getBoundingClientRect(); + const editorOuterBoundingBox = this.pmView.dom.getBoundingClientRect(); const cursorWithinEditor = event.clientX >= editorOuterBoundingBox.left && event.clientX <= editorOuterBoundingBox.right && event.clientY >= editorOuterBoundingBox.top && event.clientY <= editorOuterBoundingBox.bottom; - const editorWrapper = this.ttEditor.view.dom.parentElement!; + const editorWrapper = this.pmView.dom.parentElement!; // Doesn't update if the mouse hovers an element that's over the editor but // isn't a part of it or the side menu. @@ -432,7 +385,7 @@ export class SideMenuView implements PluginView { ) { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } return; @@ -445,13 +398,13 @@ export class SideMenuView implements PluginView { left: editorBoundingBox.left + editorBoundingBox.width / 2, // take middle of editor top: event.clientY, }; - const block = getDraggableBlockFromCoords(coords, this.ttEditor.view); + const block = getDraggableBlockFromCoords(coords, this.pmView); // Closes the menu if the mouse cursor is beyond the editor vertically. if (!block || !this.editor.isEditable) { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } return; @@ -494,7 +447,7 @@ export class SideMenuView implements PluginView { )!, }; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } }; @@ -511,20 +464,20 @@ export class SideMenuView implements PluginView { blockContentBoundingBox.width, blockContentBoundingBox.height ); - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } }; destroy() { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } document.body.removeEventListener("mousemove", this.onMouseMove); document.body.removeEventListener("dragover", this.onDragOver); - this.ttEditor.view.dom.removeEventListener("dragstart", this.onDragStart); + this.pmView.dom.removeEventListener("dragstart", this.onDragStart); document.body.removeEventListener("drop", this.onDrop, true); - document.body.removeEventListener("mousedown", this.onMouseDown, true); + // document.body.removeEventListener("mousedown", this.onMouseDown, true); document.removeEventListener("scroll", this.onScroll); document.body.removeEventListener("keydown", this.onKeyDown, true); } @@ -532,7 +485,7 @@ export class SideMenuView implements PluginView { addBlock() { if (this.sideMenuState?.show) { this.sideMenuState.show = false; - this.updateSideMenu(); + this.updateSideMenu(this.sideMenuState); } this.menuFrozen = true; @@ -540,7 +493,7 @@ export class SideMenuView implements PluginView { const blockContent = this.hoveredBlock!.firstChild! as HTMLElement; const blockContentBoundingBox = blockContent.getBoundingClientRect(); - const pos = this.ttEditor.view.posAtCoords({ + const pos = this.pmView.posAtCoords({ left: blockContentBoundingBox.left + blockContentBoundingBox.width / 2, top: blockContentBoundingBox.top + blockContentBoundingBox.height / 2, }); @@ -548,7 +501,10 @@ export class SideMenuView implements PluginView { return; } - const blockInfo = getBlockInfoFromPos(this.ttEditor.state.doc, pos.pos); + const blockInfo = getBlockInfoFromPos( + this.editor._tiptapEditor.state.doc, + pos.pos + ); if (blockInfo === undefined) { return; } @@ -560,20 +516,20 @@ export class SideMenuView implements PluginView { const newBlockInsertionPos = endPos + 1; const newBlockContentPos = newBlockInsertionPos + 2; - this.ttEditor + this.editor._tiptapEditor .chain() .BNCreateBlock(newBlockInsertionPos) .BNUpdateBlock(newBlockContentPos, { type: "paragraph", props: {} }) .setTextSelection(newBlockContentPos) .run(); } else { - this.ttEditor.commands.setTextSelection(endPos); + this.editor._tiptapEditor.commands.setTextSelection(endPos); } // Focuses and activates the suggestion menu. - this.ttEditor.view.focus(); - this.ttEditor.view.dispatch( - this.ttEditor.view.state.tr.scrollIntoView().setMeta(slashMenuPluginKey, { + this.pmView.focus(); + this.pmView.dispatch( + this.pmView.state.tr.scrollIntoView().setMeta(slashMenuPluginKey, { // TODO import suggestion plugin key activate: true, type: "drag", @@ -584,33 +540,61 @@ export class SideMenuView implements PluginView { export const sideMenuPluginKey = new PluginKey("SideMenuPlugin"); -export function setupSideMenu( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateSideMenu: (sideMenuState: SideMenuState) => void -): { - plugin: Plugin; - callbacks: Omit; -} { - let sideMenuView: SideMenuView; - - return { - plugin: new Plugin({ +export class SideMenuProsemirrorPlugin< + BSchema extends BlockSchema +> extends EventEmitter { + private sideMenuView: SideMenuView | undefined; + public readonly plugin: Plugin; + + constructor(private readonly editor: BlockNoteEditor) { + super(); + this.plugin = new Plugin({ key: sideMenuPluginKey, - view: () => { - sideMenuView = new SideMenuView(editor, tiptapEditor, updateSideMenu); - return sideMenuView; + view: (editorView) => { + this.sideMenuView = new SideMenuView( + editor, + editorView, + (sideMenuState) => { + this.emit("update", sideMenuState); + } + ); + return this.sideMenuView; }, - }), - callbacks: { - addBlock: () => sideMenuView.addBlock(), - blockDragStart: (event: DragEvent) => { - sideMenuView.isDragging = true; - dragStart(event, sideMenuView.ttEditor.view); - }, - blockDragEnd: () => unsetDragImage(), - freezeMenu: () => (sideMenuView.menuFrozen = true), - unfreezeMenu: () => (sideMenuView.menuFrozen = false), - }, + }); + } + + public onUpdate(callback: (state: SideMenuState) => void) { + return this.on("update", callback); + } + + /** + * If the block is empty, opens the slash menu. If the block has content, + * creates a new block below and opens the slash menu in it. + */ + addBlock = () => this.sideMenuView!.addBlock(); + + /** + * Handles drag & drop events for blocks. + */ + blockDragStart = (event: DragEvent) => { + this.sideMenuView!.isDragging = true; + dragStart(event, this.editor.prosemirrorView); }; + + /** + * Handles drag & drop events for blocks. + */ + blockDragEnd = () => unsetDragImage(); + /** + * Freezes the side menu. When frozen, the side menu will stay + * attached to the same block regardless of which block is hovered by the + * mouse cursor. + */ + freezeMenu = () => (this.sideMenuView!.menuFrozen = true); + /** + * Unfreezes the side menu. When frozen, the side menu will stay + * attached to the same block regardless of which block is hovered by the + * mouse cursor. + */ + unfreezeMenu = () => (this.sideMenuView!.menuFrozen = false); } diff --git a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts index bc6c058b0b..a190cc3209 100644 --- a/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts +++ b/packages/core/src/extensions/SlashMenu/SlashMenuPlugin.ts @@ -1,45 +1,51 @@ import { Plugin, PluginKey } from "prosemirror-state"; + import { BlockNoteEditor } from "../../BlockNoteEditor"; +import { EventEmitter } from "../../shared/EventEmitter"; import { - setupSuggestionsMenu, SuggestionsMenuState, - SuggestionsMenuCallbacks, + setupSuggestionsMenu, } from "../../shared/plugins/suggestion/SuggestionPlugin"; -import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; -import { Editor } from "@tiptap/core"; import { BlockSchema } from "../Blocks/api/blockTypes"; +import { BaseSlashMenuItem } from "./BaseSlashMenuItem"; export const slashMenuPluginKey = new PluginKey("SlashMenuPlugin"); -export const setupSlashMenu = < + +export class SlashMenuProsemirrorPlugin< BSchema extends BlockSchema, SlashMenuItem extends BaseSlashMenuItem ->( - editor: BlockNoteEditor, - tiptapEditor: Editor, - updateSlashMenu: ( - slashMenuState: SuggestionsMenuState - ) => void, - items: SlashMenuItem[] -): { - plugin: Plugin; - callbacks: Omit, "destroy">; -} => { - return setupSuggestionsMenu( - editor, - tiptapEditor, - updateSlashMenu, +> extends EventEmitter { + public readonly plugin: Plugin; + public readonly itemCallback: (item: SlashMenuItem) => void; + + constructor(editor: BlockNoteEditor, items: SlashMenuItem[]) { + super(); + const suggestions = setupSuggestionsMenu( + editor, + (state) => { + this.emit("update", state); + }, + slashMenuPluginKey, + "/", + (query) => + items.filter( + ({ name, aliases }: SlashMenuItem) => + name.toLowerCase().startsWith(query.toLowerCase()) || + (aliases && + aliases.filter((alias) => + alias.toLowerCase().startsWith(query.toLowerCase()) + ).length !== 0) + ), + ({ item, editor }) => item.execute(editor) + ); + + this.plugin = suggestions.plugin; + this.itemCallback = suggestions.itemCallback; + } - slashMenuPluginKey, - "/", - (query) => - items.filter( - ({ name, aliases }: SlashMenuItem) => - name.toLowerCase().startsWith(query.toLowerCase()) || - (aliases && - aliases.filter((alias) => - alias.toLowerCase().startsWith(query.toLowerCase()) - ).length !== 0) - ), - ({ item, editor }) => item.execute(editor) - ); -}; + public onUpdate( + callback: (state: SuggestionsMenuState) => void + ) { + return this.on("update", callback); + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7ecea91239..f80626d5cf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,21 +1,17 @@ export * from "./BlockNoteEditor"; export * from "./BlockNoteExtensions"; - export * from "./extensions/Blocks/api/block"; export * from "./extensions/Blocks/api/blockTypes"; export * from "./extensions/Blocks/api/defaultBlocks"; export * from "./extensions/Blocks/api/inlineContentTypes"; export * from "./extensions/Blocks/api/serialization"; - +export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; export * from "./extensions/FormattingToolbar/FormattingToolbarPlugin"; export * from "./extensions/HyperlinkToolbar/HyperlinkToolbarPlugin"; -export * from "./extensions/DraggableBlocks/DraggableBlocksPlugin"; -export * from "./shared/plugins/suggestion/SuggestionPlugin"; -export * from "./extensions/SlashMenu/SlashMenuPlugin"; -export * from "./shared/BaseUiElementTypes"; - -export * as blockStyles from "./extensions/Blocks/nodes/Block.module.css"; - +export * from "./extensions/SideMenu/SideMenuPlugin"; export * from "./extensions/SlashMenu/BaseSlashMenuItem"; +export * from "./extensions/SlashMenu/SlashMenuPlugin"; export { getDefaultSlashMenuItems } from "./extensions/SlashMenu/defaultSlashMenuItems"; +export * from "./shared/BaseUiElementTypes"; export type { SuggestionItem } from "./shared/plugins/suggestion/SuggestionItem"; +export * from "./shared/plugins/suggestion/SuggestionPlugin"; diff --git a/packages/core/src/shared/EventEmitter.ts b/packages/core/src/shared/EventEmitter.ts new file mode 100644 index 0000000000..538473488d --- /dev/null +++ b/packages/core/src/shared/EventEmitter.ts @@ -0,0 +1,58 @@ +// from https://raw.githubusercontent.com/ueberdosis/tiptap/develop/packages/core/src/EventEmitter.ts (MIT) + +type StringKeyOf = Extract; +type CallbackType< + T extends Record, + EventName extends StringKeyOf +> = T[EventName] extends any[] ? T[EventName] : [T[EventName]]; +type CallbackFunction< + T extends Record, + EventName extends StringKeyOf +> = (...props: CallbackType) => any; + +export class EventEmitter> { + private callbacks: { [key: string]: Function[] } = {}; + + public on>( + event: EventName, + fn: CallbackFunction + ) { + if (!this.callbacks[event]) { + this.callbacks[event] = []; + } + + this.callbacks[event].push(fn); + + return () => this.off(event, fn); + } + + protected emit>( + event: EventName, + ...args: CallbackType + ) { + const callbacks = this.callbacks[event]; + + if (callbacks) { + callbacks.forEach((callback) => callback.apply(this, args)); + } + } + + public off>( + event: EventName, + fn?: CallbackFunction + ) { + const callbacks = this.callbacks[event]; + + if (callbacks) { + if (fn) { + this.callbacks[event] = callbacks.filter((callback) => callback !== fn); + } else { + delete this.callbacks[event]; + } + } + } + + protected removeAllListeners(): void { + this.callbacks = {}; + } +} diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 46c3c55461..0c63690bee 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -3,18 +3,8 @@ import { Decoration, DecorationSet, EditorView } from "prosemirror-view"; import { BlockNoteEditor } from "../../../BlockNoteEditor"; import { BlockSchema } from "../../../extensions/Blocks/api/blockTypes"; import { findBlock } from "../../../extensions/Blocks/helpers/findBlock"; -import { - BaseUiElementCallbacks, - BaseUiElementState, -} from "../../BaseUiElementTypes"; +import { BaseUiElementState } from "../../BaseUiElementTypes"; import { SuggestionItem } from "./SuggestionItem"; -import { Editor } from "@tiptap/core"; - -export type SuggestionsMenuCallbacks = - BaseUiElementCallbacks & { - // The function to execute when selecting a suggested item. - itemCallback: (item: T) => void; - }; export type SuggestionsMenuState = BaseUiElementState & { @@ -28,32 +18,18 @@ class SuggestionsMenuView< T extends SuggestionItem, BSchema extends BlockSchema > { - editor: BlockNoteEditor; - ttEditor: Editor; - pluginKey: PluginKey; - private suggestionsMenuState?: SuggestionsMenuState; public updateSuggestionsMenu: () => void; pluginState: SuggestionPluginState; - itemCallback: (item: T) => void; constructor( - editor: BlockNoteEditor, - tiptapEditor: Editor, - pluginKey: PluginKey, - onSelectItem: (props: { - item: T; - editor: BlockNoteEditor; - }) => void = () => {}, + private readonly editor: BlockNoteEditor, + private readonly pluginKey: PluginKey, updateSuggestionsMenu: ( suggestionsMenuState: SuggestionsMenuState ) => void = () => {} ) { - this.editor = editor; - this.ttEditor = tiptapEditor; - - this.pluginKey = pluginKey; this.pluginState = getDefaultPluginState(); this.updateSuggestionsMenu = () => { @@ -64,24 +40,6 @@ class SuggestionsMenuView< updateSuggestionsMenu(this.suggestionsMenuState); }; - this.itemCallback = (item: T) => { - this.ttEditor - .chain() - .focus() - .deleteRange({ - from: - this.pluginState.queryStartPos! - - this.pluginState.triggerCharacter!.length, - to: this.ttEditor.state.selection.from, - }) - .run(); - - onSelectItem({ - item: item, - editor: editor, - }); - }; - document.addEventListener("scroll", this.handleScroll); } @@ -190,7 +148,6 @@ export const setupSuggestionsMenu = < BSchema extends BlockSchema >( editor: BlockNoteEditor, - tiptapEditor: Editor, updateSuggestionsMenu: ( suggestionsMenuState: SuggestionsMenuState ) => void, @@ -202,10 +159,7 @@ export const setupSuggestionsMenu = < item: T; editor: BlockNoteEditor; }) => void = () => {} -): { - plugin: Plugin; - callbacks: Omit, "destroy">; -} => { +) => { // Assertions if (defaultTriggerCharacter.length !== 1) { throw new Error("'char' should be a single character"); @@ -224,12 +178,8 @@ export const setupSuggestionsMenu = < view: () => { suggestionsPluginView = new SuggestionsMenuView( editor, - tiptapEditor, pluginKey, - (props: { item: T; editor: BlockNoteEditor }) => { - deactivate(tiptapEditor.view); - onSelectItem(props); - }, + updateSuggestionsMenu ); return suggestionsPluginView; @@ -393,12 +343,12 @@ export const setupSuggestionsMenu = < // Selects an item and closes the menu. if (event.key === "Enter") { deactivate(view); - tiptapEditor + editor._tiptapEditor .chain() .focus() .deleteRange({ from: queryStartPos! - triggerCharacter!.length, - to: tiptapEditor.state.selection.from, + to: editor._tiptapEditor.state.selection.from, }) .run(); @@ -467,24 +417,22 @@ export const setupSuggestionsMenu = < }, }, }), - callbacks: { - itemCallback: (item: T) => { - tiptapEditor - .chain() - .focus() - .deleteRange({ - from: - suggestionsPluginView.pluginState.queryStartPos! - - suggestionsPluginView.pluginState.triggerCharacter!.length, - to: tiptapEditor.state.selection.from, - }) - .run(); - - onSelectItem({ - item: item, - editor: editor, - }); - }, + itemCallback: (item: T) => { + editor._tiptapEditor + .chain() + .focus() + .deleteRange({ + from: + suggestionsPluginView.pluginState.queryStartPos! - + suggestionsPluginView.pluginState.triggerCharacter!.length, + to: editor._tiptapEditor.state.selection.from, + }) + .run(); + + onSelectItem({ + item: item, + editor: editor, + }); }, }; }; diff --git a/packages/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index ee6182884a..90b115f5ec 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -1,17 +1,20 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; -import { getBlockNoteTheme } from "./BlockNoteTheme"; import { ReactNode, useEffect, useState } from "react"; +import { getBlockNoteTheme } from "./BlockNoteTheme"; import { FormattingToolbarPositioner } from "./FormattingToolbar/components/FormattingToolbarPositioner"; import { HyperlinkToolbarPositioner } from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; -import { SlashMenuPositioner } from "./SlashMenu/components/SlashMenuPositioner"; import { SideMenuPositioner } from "./SideMenu/components/SideMenuPositioner"; +import { SlashMenuPositioner } from "./SlashMenu/components/SlashMenuPositioner"; -export function BlockNoteView(props: { - editor: BlockNoteEditor; - children?: ReactNode; -}) { +export function BlockNoteView( + props: { + editor: BlockNoteEditor; + children?: ReactNode; + } & React.HTMLAttributes +) { + const { editor, children, ...rest } = props; const [ready, setReady] = useState(false); useEffect(() => { @@ -33,10 +36,7 @@ export function BlockNoteView(props: { return ( - + {ready && (props.children || ( <> diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 86b14174cd..2db0b7d238 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -1,12 +1,11 @@ -import { FC, useEffect, useMemo, useRef, useState } from "react"; -import Tippy from "@tippyjs/react"; -import { sticky } from "tippy.js"; import { BlockNoteEditor, BlockSchema, DefaultBlockSchema, - FormattingToolbarCallbacks, } from "@blocknote/core"; +import Tippy from "@tippyjs/react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; +import { sticky } from "tippy.js"; import { DefaultFormattingToolbar } from "./DefaultFormattingToolbar"; @@ -15,6 +14,7 @@ export type FormattingToolbarProps< > = { editor: BlockNoteEditor; }; + export const FormattingToolbarPositioner = < BSchema extends BlockSchema = DefaultBlockSchema >(props: { @@ -24,16 +24,13 @@ export const FormattingToolbarPositioner = < const [show, setShow] = useState(false); const referencePos = useRef(); - const callbacks = useRef(); useEffect(() => { - callbacks.current = props.editor.createFormattingToolbar((state) => { + return props.editor.formattingToolbar.onUpdate((state) => { setShow(state.show); referencePos.current = state.referencePos; }); - - return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo( @@ -63,7 +60,9 @@ export const FormattingToolbarPositioner = < animation={"fade"} placement={"top-start"} sticky={true} - plugins={[sticky]} + plugins={tippyPlugins} /> ); }; + +const tippyPlugins = [sticky]; diff --git a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx index 1fa0a2d7e5..9f93103e43 100644 --- a/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx +++ b/packages/react/src/HyperlinkToolbar/components/HyperlinkToolbarPositioner.tsx @@ -1,20 +1,19 @@ -import { FC, useEffect, useMemo, useRef, useState } from "react"; -import Tippy from "@tippyjs/react"; import { - BaseUiElementCallbacks, BaseUiElementState, BlockNoteEditor, BlockSchema, DefaultBlockSchema, - HyperlinkToolbarCallbacks, + HyperlinkToolbarProsemirrorPlugin, HyperlinkToolbarState, } from "@blocknote/core"; +import Tippy from "@tippyjs/react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; import { DefaultHyperlinkToolbar } from "./DefaultHyperlinkToolbar"; -export type HyperlinkToolbarProps = Omit< - HyperlinkToolbarCallbacks, - keyof BaseUiElementCallbacks +export type HyperlinkToolbarProps = Pick< + HyperlinkToolbarProsemirrorPlugin, + "editHyperlink" | "deleteHyperlink" | "startHideTimer" | "stopHideTimer" > & Omit; @@ -29,10 +28,10 @@ export const HyperlinkToolbarPositioner = < const [text, setText] = useState(); const referencePos = useRef(); - const callbacks = useRef(); useEffect(() => { - callbacks.current = props.editor.createHyperlinkToolbar( + return props.editor.hyperlinkToolbar.on( + "update", (hyperlinkToolbarState) => { setShow(hyperlinkToolbarState.show); setUrl(hyperlinkToolbarState.url); @@ -41,8 +40,6 @@ export const HyperlinkToolbarPositioner = < referencePos.current = hyperlinkToolbarState.referencePos; } ); - - return callbacks.current.destroy; }, [props.editor]); const getReferenceClientRect = useMemo( @@ -57,7 +54,7 @@ export const HyperlinkToolbarPositioner = < ); const hyperlinkToolbarElement = useMemo(() => { - if (!url || !text || !callbacks.current) { + if (!url || !text) { return null; } @@ -67,13 +64,13 @@ export const HyperlinkToolbarPositioner = < ); - }, [props.hyperlinkToolbar, text, url]); + }, [props.hyperlinkToolbar, props.editor, text, url]); return ( = - Omit & - Omit, keyof BaseUiElementState> & { - editor: BlockNoteEditor; - }; - -// export type a = { -// callbacks: SideMenuCallbacks; -// state: SideMenuState; -// }; -// -// export type b = { -// callbacks: Omit; -// state: SideMenuState; -// }; + Pick< + SideMenuProsemirrorPlugin, + | "blockDragStart" + | "blockDragEnd" + | "addBlock" + | "freezeMenu" + | "unfreezeMenu" + > & { + block: Block; + editor: BlockNoteEditor; + }; export const SideMenuPositioner = < BSchema extends BlockSchema = DefaultBlockSchema @@ -39,17 +33,13 @@ export const SideMenuPositioner = < const [block, setBlock] = useState>(); const referencePos = useRef(); - const callbacks = useRef(); useEffect(() => { - callbacks.current = props.editor.createSideMenu((sideMenuState) => { + return props.editor.sideMenu.onUpdate((sideMenuState) => { setShow(sideMenuState.show); setBlock(sideMenuState.block); - referencePos.current = sideMenuState.referencePos; }); - - return callbacks.current!.destroy; }, [props.editor]); const getReferenceClientRect = useMemo( @@ -64,7 +54,7 @@ export const SideMenuPositioner = < ); const sideMenuElement = useMemo(() => { - if (!block || !callbacks.current) { + if (!block) { return null; } @@ -74,11 +64,11 @@ export const SideMenuPositioner = < ); }, [block, props.editor, props.sideMenu]); diff --git a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx index 82a79f2308..35b79eb423 100644 --- a/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx +++ b/packages/react/src/SlashMenu/components/SlashMenuPositioner.tsx @@ -1,26 +1,21 @@ -import { FC, useEffect, useMemo, useRef, useState } from "react"; -import Tippy from "@tippyjs/react"; import { BlockNoteEditor, BlockSchema, - BaseUiElementCallbacks, - SuggestionsMenuState, - BaseUiElementState, - SuggestionsMenuCallbacks, DefaultBlockSchema, + SlashMenuProsemirrorPlugin, + SuggestionsMenuState, } from "@blocknote/core"; +import Tippy from "@tippyjs/react"; +import { FC, useEffect, useMemo, useRef, useState } from "react"; import { ReactSlashMenuItem } from "../ReactSlashMenuItem"; import { DefaultSlashMenu } from "./DefaultSlashMenu"; export type SlashMenuProps = - Omit< - SuggestionsMenuCallbacks>, - keyof BaseUiElementCallbacks - > & - Omit< + Pick, "itemCallback"> & + Pick< SuggestionsMenuState>, - keyof BaseUiElementState + "filteredItems" | "keyboardHoveredItemIndex" >; export const SlashMenuPositioner = < @@ -36,21 +31,15 @@ export const SlashMenuPositioner = < useState(); const referencePos = useRef(); - const callbacks = - useRef>>(); useEffect(() => { - callbacks.current = props.editor.createSlashMenu((slashMenuState) => { + return props.editor.slashMenu.onUpdate((slashMenuState) => { setShow(slashMenuState.show); - setFilteredItems( - slashMenuState.filteredItems as ReactSlashMenuItem[] - ); + setFilteredItems(slashMenuState.filteredItems); setKeyboardHoveredItemIndex(slashMenuState.keyboardHoveredItemIndex); referencePos.current = slashMenuState.referencePos; - }) as SuggestionsMenuCallbacks>; - - return callbacks.current!.destroy; + }); }, [props.editor]); const getReferenceClientRect = useMemo( @@ -65,11 +54,7 @@ export const SlashMenuPositioner = < ); const slashMenuElement = useMemo(() => { - if ( - !filteredItems || - keyboardHoveredItemIndex === undefined || - !callbacks.current - ) { + if (!filteredItems || keyboardHoveredItemIndex === undefined) { return null; } @@ -77,12 +62,17 @@ export const SlashMenuPositioner = < return ( callbacks.current!.itemCallback(item)} - keyboardHoveredItemIndex={keyboardHoveredItemIndex!} + filteredItems={filteredItems} + itemCallback={(item) => props.editor.slashMenu.itemCallback(item)} + keyboardHoveredItemIndex={keyboardHoveredItemIndex} /> ); - }, [filteredItems, keyboardHoveredItemIndex, props.slashMenu]); + }, [ + filteredItems, + keyboardHoveredItemIndex, + props.editor.slashMenu, + props.slashMenu, + ]); return ( Date: Mon, 31 Jul 2023 15:16:40 +0200 Subject: [PATCH 29/42] Implemented PR feedback --- .../src/extensions/SideMenu/SideMenuPlugin.ts | 15 ++++++----- .../FormattingToolbarPositioner.tsx | 4 +++ .../components/DefaultHyperlinkToolbar.tsx | 2 -- .../SideMenu/components/DefaultSideMenu.tsx | 25 ++++--------------- packages/react/src/hooks/useBlockNote.ts | 2 -- 5 files changed, 18 insertions(+), 30 deletions(-) diff --git a/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts b/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts index 63e5aa1bd6..1d8b40fdbb 100644 --- a/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts +++ b/packages/core/src/extensions/SideMenu/SideMenuPlugin.ts @@ -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; } @@ -262,9 +265,7 @@ export class SideMenuView implements PluginView { // Makes menu scroll with the page. document.addEventListener("scroll", this.onScroll); - // 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); + // Hides and unfreezes the menu whenever the user presses a key. document.body.addEventListener("keydown", this.onKeyDown, true); } @@ -477,7 +478,6 @@ export class SideMenuView implements PluginView { document.body.removeEventListener("dragover", this.onDragOver); this.pmView.dom.removeEventListener("dragstart", this.onDragStart); document.body.removeEventListener("drop", this.onDrop, true); - // document.body.removeEventListener("mousedown", this.onMouseDown, true); document.removeEventListener("scroll", this.onScroll); document.body.removeEventListener("keydown", this.onKeyDown, true); } @@ -576,7 +576,10 @@ export class SideMenuProsemirrorPlugin< /** * Handles drag & drop events for blocks. */ - blockDragStart = (event: DragEvent) => { + blockDragStart = (event: { + dataTransfer: DataTransfer | null; + clientY: number; + }) => { this.sideMenuView!.isDragging = true; dragStart(event, this.editor.prosemirrorView); }; diff --git a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx index 2db0b7d238..2baaca73cb 100644 --- a/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx +++ b/packages/react/src/FormattingToolbar/components/FormattingToolbarPositioner.tsx @@ -65,4 +65,8 @@ export const FormattingToolbarPositioner = < ); }; +// 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/components/DefaultHyperlinkToolbar.tsx b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx index 89b8b4cb82..ec0850ec34 100644 --- a/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx +++ b/packages/react/src/HyperlinkToolbar/components/DefaultHyperlinkToolbar.tsx @@ -33,8 +33,6 @@ export const DefaultHyperlinkToolbar = (props: HyperlinkToolbarProps) => { return ( event.preventDefault()} onMouseEnter={props.stopHideTimer} onMouseLeave={props.startHideTimer}> ( dragHandleMenu?: FC>; } ) => { - 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 DragHandleMenu = props.dragHandleMenu || DefaultDragHandleMenu; return ( @@ -45,7 +27,10 @@ export const DefaultSideMenu = ( width={100} position={"left"}> -
+
{} diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index beeada5248..1f468a0897 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -15,8 +15,6 @@ export const useBlockNote = ( options: Partial> = {}, _deps: DependencyList = [] ) => { - console.log("create new blocknote instance"); - return new BlockNoteEditor({ slashCommands: getDefaultReactSlashMenuItems( options.blockSchema || defaultBlockSchema From bbecf890d9f94c1c2e5f867153c9dd190895bdf3 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 31 Jul 2023 15:21:05 +0200 Subject: [PATCH 30/42] Implemented PR feedback --- examples/editor/src/App.tsx | 30 +----------------------------- 1 file changed, 1 insertion(+), 29 deletions(-) diff --git a/examples/editor/src/App.tsx b/examples/editor/src/App.tsx index ada4b8c3b9..4c2a3720fa 100644 --- a/examples/editor/src/App.tsx +++ b/examples/editor/src/App.tsx @@ -27,35 +27,7 @@ function App() { // Give tests a way to get prosemirror instance (window as WindowWithProseMirror).ProseMirror = editor?._tiptapEditor; - // Use mock ID if tests are running. - if ((window as any).__TEST_OPTIONS === undefined) { - // (window as any).__TEST_OPTIONS = {}; - } - - return ( - -
Formatting Toolbar
} - /> - - - - {/* (*/} - {/* (*/} - {/* */} - {/* Item*/} - {/* */} - {/* )}*/} - {/* />*/} - {/* )}*/} - {/*/>*/} -
- ); + return ; } export default App; From 5e68b915a1f561d93b4102ba61810df849ef583e Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 31 Jul 2023 15:24:05 +0200 Subject: [PATCH 31/42] Implemented PR feedback --- examples/editor/src/App.tsx | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/examples/editor/src/App.tsx b/examples/editor/src/App.tsx index 4c2a3720fa..55ce63eb93 100644 --- a/examples/editor/src/App.tsx +++ b/examples/editor/src/App.tsx @@ -1,13 +1,6 @@ // import logo from './logo.svg' import "@blocknote/core/style.css"; -import { - BlockNoteView, - FormattingToolbarPositioner, - HyperlinkToolbarPositioner, - SideMenuPositioner, - SlashMenuPositioner, - useBlockNote, -} from "@blocknote/react"; +import { BlockNoteView, useBlockNote } from "@blocknote/react"; import styles from "./App.module.css"; type WindowWithProseMirror = Window & typeof globalThis & { ProseMirror: any }; From 95fdc42750f61bde8345d4f71e1918b1466d0f04 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 31 Jul 2023 17:41:34 +0200 Subject: [PATCH 32/42] Implemented PR feedback --- packages/react/src/hooks/useBlockNote.ts | 33 +++++++++++++++++------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 1f468a0897..02f4d15e02 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -5,20 +5,35 @@ import { defaultBlockSchema, DefaultBlockSchema, } from "@blocknote/core"; -import { DependencyList } from "react"; +import { DependencyList, useMemo, useRef } from "react"; import { getDefaultReactSlashMenuItems } from "../SlashMenu/defaultReactSlashMenuItems"; -/** - * Main hook for importing a BlockNote editor into a React project - */ -export const useBlockNote = ( - options: Partial> = {}, - _deps: DependencyList = [] -) => { - return new BlockNoteEditor({ +const initEditor = ( + options: Partial> +) => + new BlockNoteEditor({ slashCommands: getDefaultReactSlashMenuItems( options.blockSchema || defaultBlockSchema ), ...options, }); + +/** + * Main hook for importing a BlockNote editor into a React project + */ +export const useBlockNote = ( + options: Partial> = {}, + deps: DependencyList = [] +): BlockNoteEditor => { + const editorRef = useRef>(initEditor(options)); + + useMemo(() => { + if (editorRef.current) { + editorRef.current && editorRef.current._tiptapEditor.destroy(); + } + + editorRef.current = initEditor(options); + }, [options, ...deps]); + + return editorRef.current; }; From e12754655ca3b2c7ccc1b9ac564273c9a27f5350 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 31 Jul 2023 21:50:24 +0200 Subject: [PATCH 33/42] Added docs & small tweaks --- packages/core/src/BlockNoteEditor.ts | 4 +- .../src/extensions/Blocks/api/blockTypes.ts | 5 +- .../extensions/SlashMenu/BaseSlashMenuItem.ts | 5 +- .../DefaultButtons/TextAlignButton.tsx | 9 + .../DefaultButtons/ToggledStyleButton.tsx | 5 + .../react/src/SlashMenu/ReactSlashMenuItem.ts | 21 +- packages/react/src/hooks/useBlockNote.ts | 2 +- packages/website/docs/.vitepress/config.ts | 3 +- .../website/docs/docs/formatting-toolbar.md | 275 +++--------------- packages/website/docs/docs/side-menu.md | 109 +++---- packages/website/docs/docs/slash-menu.md | 157 +++++----- packages/website/docs/docs/ui-elements.md | 134 +++++++++ tests/utils/components/Editor.tsx | 2 +- 13 files changed, 339 insertions(+), 392 deletions(-) create mode 100644 packages/website/docs/docs/ui-elements.md diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index bf954f7776..e4ff547559 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -55,7 +55,7 @@ export type BlockNoteEditorOptions = { * * @default defaultSlashMenuItems from `./extensions/SlashMenu` */ - slashCommands: BaseSlashMenuItem[]; + slashMenuItems: BaseSlashMenuItem[]; /** * The HTML element that should be used as the parent element for the editor. @@ -175,7 +175,7 @@ export class BlockNoteEditor { this.formattingToolbar = new FormattingToolbarProsemirrorPlugin(this); this.slashMenu = new SlashMenuProsemirrorPlugin( this, - newOptions.slashCommands || + newOptions.slashMenuItems || getDefaultSlashMenuItems(newOptions.blockSchema) ); this.hyperlinkToolbar = new HyperlinkToolbarProsemirrorPlugin(this); 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/SlashMenu/BaseSlashMenuItem.ts b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts index d133a62347..41fc78917c 100644 --- a/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts +++ b/packages/core/src/extensions/SlashMenu/BaseSlashMenuItem.ts @@ -1,8 +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"; -export type BaseSlashMenuItem = SuggestionItem & { +export type BaseSlashMenuItem< + BSchema extends BlockSchema = DefaultBlockSchema +> = SuggestionItem & { execute: (editor: BlockNoteEditor) => void; aliases?: string[]; }; diff --git a/packages/react/src/FormattingToolbar/components/DefaultButtons/TextAlignButton.tsx b/packages/react/src/FormattingToolbar/components/DefaultButtons/TextAlignButton.tsx index fd8b226cfb..8f2a58fe74 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/TextAlignButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/TextAlignButton.tsx @@ -14,6 +14,7 @@ import { } from "react-icons/ri"; import { ToolbarButton } from "../../../SharedComponents/Toolbar/components/ToolbarButton"; import { useEditorContentChange } from "../../../hooks/useEditorContentChange"; +import { useEditorSelectionChange } from "../../../hooks/useEditorSelectionChange"; type TextAlignment = DefaultProps["textAlignment"]["values"][number]; @@ -46,6 +47,14 @@ export const TextAlignButton = (props: { } }); + 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(); diff --git a/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx b/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx index 618f367cc5..5328b5e5ba 100644 --- a/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx +++ b/packages/react/src/FormattingToolbar/components/DefaultButtons/ToggledStyleButton.tsx @@ -11,6 +11,7 @@ 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", @@ -40,6 +41,10 @@ export const ToggledStyleButton = (props: { setActive(props.toggledStyle in props.editor.getActiveStyles()); }); + useEditorSelectionChange(props.editor, () => { + setActive(props.toggledStyle in props.editor.getActiveStyles()); + }); + const toggleStyle = (style: ToggledStyle) => { props.editor.focus(); props.editor.toggleStyles({ [style]: true }); diff --git a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts index 96416c7b98..b5e6f24091 100644 --- a/packages/react/src/SlashMenu/ReactSlashMenuItem.ts +++ b/packages/react/src/SlashMenu/ReactSlashMenuItem.ts @@ -1,9 +1,14 @@ -import { BaseSlashMenuItem, BlockSchema } from "@blocknote/core"; +import { + BaseSlashMenuItem, + BlockSchema, + DefaultBlockSchema, +} from "@blocknote/core"; -export type ReactSlashMenuItem = - BaseSlashMenuItem & { - group: string; - icon: JSX.Element; - hint?: string; - shortcut?: string; - }; +export type ReactSlashMenuItem< + BSchema extends BlockSchema = DefaultBlockSchema +> = BaseSlashMenuItem & { + group: string; + icon: JSX.Element; + hint?: string; + shortcut?: string; +}; diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 02f4d15e02..432c4f72ce 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -12,7 +12,7 @@ const initEditor = ( options: Partial> ) => new BlockNoteEditor({ - slashCommands: getDefaultReactSlashMenuItems( + slashMenuItems: getDefaultReactSlashMenuItems( options.blockSchema || defaultBlockSchema ), ...options, 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 e27cb5bef2..e72fa1db52 100644 --- a/packages/website/docs/docs/formatting-toolbar.md +++ b/packages/website/docs/docs/formatting-toolbar.md @@ -18,9 +18,11 @@ The Formatting Toolbar appears whenever you highlight text in the editor, and is image -## Custom Formatting Toolbar Element +## Custom Formatting Toolbar -You can create a custom Formatting Toolbar using a React component. 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. +If you want to change the buttons/dropdowns in the Formatting Toolbar, 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 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} @@ -28,98 +30,51 @@ You can create a custom Formatting Toolbar using a React component. The example import { BlockNoteEditor } from "@blocknote/core"; import { BlockNoteView, - createReactFormattingToolbarFactory, + FormattingToolbarPositioner, + HyperlinkToolbarPositioner, + SideMenuPositioner, + SlashMenuPositioner, ToggledStyleButton, Toolbar, ToolbarButton, useBlockNote, + useEditorContentChange, + useEditorSelectionChange, } from "@blocknote/react"; import "@blocknote/core/style.css"; +import { useState } from "react"; 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 - - + // Tracks whether the text & background are both blue. + const [isSelected, setIsSelected] = useState( + props.editor.getActiveStyles().textColor === "blue" && + props.editor.getActiveStyles().backgroundColor === "blue" ); -}; -export default function App() { - // Creates a new editor instance. - const editor: BlockNoteEditor = useBlockNote({ - theme: "{{ getTheme(isDark) }}", + // Updates state on content change. + useEditorContentChange(props.editor, () => { + setIsSelected( + props.editor.getActiveStyles().textColor === "blue" && + props.editor.getActiveStyles().backgroundColor === "blue" + ); }); - // Renders the editor instance. - return ( - - - - - - - ); -} -``` - -```css-vue /styles.css [hidden] -{{ getStyles(isDark) }} -``` - -::: - -Let's go over this code, starting with the `CustomFormattingToolbar` component, which is used to render the toolbar and takes the following props: - -```typescript -type FormattingToolbarProps = { - editor: BlockNoteEditor -}; -``` - -`editor:` The BlockNote editor instance to attach the toolbar to. + // Updates state on selection change. + useEditorSelectionChange(props.editor, () => { + setIsSelected( + props.editor.getActiveStyles().textColor === "blue" && + props.editor.getActiveStyles().backgroundColor === "blue" + ); + }); -```jsx -const CustomFormattingToolbar = (props: FormattingToolbarProps) => { return ( {/*Default button to toggle bold.*/} - + {/*Default button to toggle italic.*/} - + {/*Default button to toggle underline.*/} - + {/*Custom button to toggle blue text & background color.*/} { backgroundColor: "blue", }); }} - isSelected={ - props.editor.getActiveStyles().textColor === "blue" && - props.editor.getActiveStyles().backgroundColor === "blue" - } - > + isSelected={isSelected}> Blue ); }; -``` - -The components used to build this custom Formatting Toolbar are pre-made and come with BlockNote. These can be used if you need to change the functionality or layout, but want to keep the default styling. You can find all the pre-made components BlockNote offers in the [Default Items](/docs/formatting-toolbar#default-items) and [Custom Items](/docs/formatting-toolbar#custom-items) subsections. - -However, you could render whatever you like in `CustomFormattingToolbar`, allowing for fully custom designs. -Also, if you're unsure about what's happening inside `ToolbarButton`'s `onClick` and `isSelected` props, head to [Introduction to Blocks](/docs/blocks), which will guide you through reading & manipulating blocks in the editor using code. - -After creating a custom toolbar and editor instance, we can add it to the editor by rendering it inside `BlockNoteView`: - -```jsx export default function App() { // Creates a new editor instance. - const editor: BlockNoteEditor = useBlockNote({}); - + const editor: BlockNoteEditor = useBlockNote({ + theme: "{{ getTheme(isDark) }}", + }); + // Renders the editor instance. return ( @@ -169,147 +112,27 @@ export default function App() { } ``` -There's a bit more we have to explain here though. First of all, let's talk about the `FormattingToolbarPositioner` component. Not only can you change what's inside the Formatting Toolbar and how it looks, but also when it's shown/hidden, as well as where it's positioned. - -If you're looking to customize this to create, for example, a static Formatting Toolbar, head to [Custom Formatting Toolbar Positioner](/docs/formatting-toolbar#custom-formatting-toolbar-positioner). If you only want to change the toolbar element itself, you can use the `FormattingToolbarPositioner` to apply the default behaviour. - -TODO: Text below is not final. We should change how we remove & customize the menus & toolbars. Take the scenarios: -- Customizing 1 UI element -- Customizing all UI elements -- Removing 1 UI element -- Removing all UI elements - -By default, if you don't provide any children the `BlockNoteView`, BlockNote uses the default UI. However, if you want to provide a custom Formatting Toolbar, you should also add the default positioners for them (default components are used if custom ones aren't provided), as BlockNote won't render them otherwise. - -This also means you can remove the Formatting Toolbar from the editor by only adding default positioners for all other menus & toolbars in `BlockNoteView`: - -```jsx -return ( - - - - - -); -``` - -```typescript -type CustomFormattingToolbarProps = { - editor: BlockNoteEditor -}; - -const CustomFormattingToolbar = (props: CustomFormattingToolbarProps): JSX.Element => ...; -``` - -However, this means you also have to handle showing, hiding, and positioning the Formatting Toolbar yourself. While this allows for additional customization, there are a lot of cases where you only want to change the toolbar itself and not have to deal with all of that. Therefore, BlockNote provides a `FormattingToolbarPositioner` component which handles showing, hiding, and positioning for you: - -```typescript jsx -import { - FormattingToolbarProps, - FormattingToolbarPositioner -} from "@blocknote/react"; - -const FormattingToolbarPositioner = (props: { - editor: BlockNoteEditor, - formattingToolbar?: (props: FormattingToolbarProps) => JSX.Element -}): JSX.Element => { - ... -}, -```` - -You can then tell BlockNote to use your custom Formatting Toolbar by adding it as a child of `BlockNoteView`: - -```jsx -import { BlockNoteEditor } from "@blocknote/core"; -import { - BlockNoteView, - FormattingToolbarProps, - FormattingToolbarPositioner, - useBlockNote -} from "@blocknote/react"; -import "@blocknote/core/style.css"; - -const CustomFormattingToolbar = (props: CustomFormattingToolbarProps) => { - // Define your custom toolbar here component here - ... -}; - -function App() { - // Creates a new editor instance. - const editor: BlockNoteEditor = useBlockNote({}); - - // Renders the editor instance using a React component. - return ( - - - - ); -} +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} ``` -## Default Items - -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 and more - both the toolbar itself and the items in it. Below are all the default components you can use to build your custom toolbar: - -```typescript -// Toolbar which wraps all the items. -type ToolbarProps = { - children: ReactNode; -}; -const Toolbar = (props: ToolbarProps) => ...; - -// Dropdown which changes the block type. -type BlockTypeDropdownProps = { - editor: BlockNoteEditor -}; -const BlockTypeDropdown = (props: BlockTypeDropdownProps) => ...; +::: -// Button which toggles a simple style on the highlighted text. -type ToggledStyleButtonProps = { - editor: BlockNoteEditor; - toggledStyle: "bold" | "italic" | "underline" | "strike" | "code"; -}; -const ToggledStyleButton = (props: ToggledStyleButtonProps) => ...; +`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 sets the text alignment on the block. -type TextAlignButtonProps = { - editor: BlockNoteEditor; - textAlignment: "left" | "center" | "right" | "center"; -}; -const TextAlignButton = (props: TextAlignButtonProps) => ...; +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 dropdown on hover. The dropdown lets you set the -// highlighted text's color. -type ColorStyleButtonProps = { - editor: BlockNoteEditor -}; -const ColorStyleButton = (props: ColorStyleButtonProps) => ...; +## Components -// Button which nests the block, if it can be nested. -type NestBlockButtonProps = { - editor: BlockNoteEditor -}; -const NestBlockButton = (props: NestBlockButtonProps) => ...; +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. -// Button which unnests the block, if it can be nested. -type UnestBlockButtonProps = { - editor: BlockNoteEditor -}; -const UnestBlockButton = (props: UnestBlockButtonProps) => ...; +### Default Components -// Button which opens a dialog box to create a new link. -type CreateLinkButtonProps = { - editor: BlockNoteEditor -}; -const CreateLinkButton = (props: CreateLinkButtonProps) => ...; -``` +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 Items +### Custom Components -BlockNote also provides components that you can use to make your own toolbar items, which match BlockNote's UI styling: +BlockNote also provides components that you can use to make your own toolbar items, which also match the default styling: ```typescript // Custom dropdown. @@ -352,7 +175,3 @@ type ToolbarButtonProps = { }; export const ToolbarButton = (props: ToolbarButtonProps) => ...; ``` - -## Custom Formatting Toolbar Positioner - -TODO \ No newline at end of file diff --git a/packages/website/docs/docs/side-menu.md b/packages/website/docs/docs/side-menu.md index d6d2733a66..4389463e8d 100644 --- a/packages/website/docs/docs/side-menu.md +++ b/packages/website/docs/docs/side-menu.md @@ -25,7 +25,9 @@ You can also click the drag handle in the Block Side Menu (`⠿`) to open the Dr ## 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 +35,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 +50,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 +67,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 +92,23 @@ 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 => ...; -``` +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. -You can then tell BlockNote to use your custom Drag Handle Menu using -the `customElements` option in `useBlockNote`: +## Components -```typescript -const editor = useBlockNote({ - customElements: { - blockSideMenuFactory: CustomBlockSideMenu - }, -}); -``` +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. -## Default Items +### Default Components -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: +BlockNote exports all components used to create the default layout - both the menu itself and the items in it. Head to the [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. -```typescript -// Menu which wraps all the items. -type BlockSideMenuProps = { - children: ReactNode -} -const BlockSideMenu = (props: BlockSideMenuProps) => ...; +### Custom Components -// 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) => ...; -``` - -## Custom Items - -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 +// 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 11ede34380..c2c554565d 100644 --- a/packages/website/docs/docs/slash-menu.md +++ b/packages/website/docs/docs/slash-menu.md @@ -18,41 +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; - group: string; - icon: JSX.Element; - execute: (editor: BlockNoteEditor) => void; - aliases?: 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.", +}; -`group:` The name of the group the item belongs to, e.g. "Headings" or "Basic Blocks". +// List containing all default Slash Menu Items, as well as our custom one. +const customSlashMenuItemList = [ + ...getDefaultReactSlashMenuItems(), + insertHelloWorldItem, +]; -`icon:` An element which displays the item's icon. +export default function App() { + // Creates a new editor instance. + const editor: BlockNoteEditor = useBlockNote({ + theme: "{{ getTheme(isDark) }}", + slashCommands: customSlashMenuItemList, + }); -`execute:` A function that runs when the item is selected. + // Renders the editor instance. + return ; +} -`aliases:` Other names for the item, which as used as shortcuts for search. +``` -`hint:` A short phrase to describe what the item is for, which is displayed below its name. +```css-vue /styles.css [hidden] +{{ getStyles(isDark) }} +``` -`shortcuts:` A keyboard shortcut which can be used to run the item's `execute` function outside the Slash Menu. +::: -## Default Items +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) + +## Slash Menu 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. @@ -62,6 +101,7 @@ If you want to change, remove & reorder the default items , you first import and import { BlockNoteView, getDefaultReactSlashMenuItems, + ReactSlashMenuItem, useBlockNote } from "@blocknote/react"; import "@blocknote/core/style.css"; @@ -79,65 +119,32 @@ function App() { } ``` -## Custom Items +### 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: +Creating a custom Slash Menu item is easy! Just declare a plain JavaScript object with the following fields: -::: sandbox {template=react-ts} - -```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: ReactSlashMenuItem = { - name: "Insert Hello World", - group: "Other", - icon: , - execute: insertHelloWorld, - aliases: ["helloworld", "hw"], - hint: "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: [...getDefaultReactSlashMenuItems(), 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..5d426708b7 --- /dev/null +++ b/packages/website/docs/docs/ui-elements.md @@ -0,0 +1,134 @@ +--- +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. + +## Positioner Components + +Each of the UI elements not only have to show and hide, but also show in the correct positions. This is handled using `Positioner` components. Each UI element has its own `Positioner` component, e.g. the Formatting Toolbar: + +```jsx +export const FormattingToolbarPositioner = (props: { + editor: BlockNoteEditor; + formattingToolbar?: FC>; +}): JSX.Element => { + ... +} +``` + +## Removing UI Elements + +In the following example, we remove the Side Menu from the editor. This is done by adding `Positioner` components 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/tests/utils/components/Editor.tsx b/tests/utils/components/Editor.tsx index fd42103672..7389421c39 100644 --- a/tests/utils/components/Editor.tsx +++ b/tests/utils/components/Editor.tsx @@ -44,7 +44,7 @@ export default function Editor() { "data-test": "editor", }, blockSchema: blockSchema, - slashCommands: [...defaultReactSlashMenuItems, ...slashCommands], + slashMenuItems: [...defaultReactSlashMenuItems, ...slashCommands], }); console.log(editor); From c417714d04102bd9795b651dbb9de22c8cffdb6e Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Mon, 31 Jul 2023 22:20:03 +0200 Subject: [PATCH 34/42] Renamed remaining slashCommand references to slashMenuItems --- packages/core/src/BlockNoteEditor.ts | 1 - tests/utils/components/Editor.tsx | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index e4ff547559..25c2323cbb 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -49,7 +49,6 @@ export type BlockNoteEditorOptions = { // TODO: Figure out if enableBlockNoteExtensions/disableHistoryExtension are needed and document them. enableBlockNoteExtensions: boolean; /** - * TODO: why is this called slashCommands and not slashMenuItems? * * (couldn't fix any type, see https://github.com/TypeCellOS/BlockNote/pull/191#discussion_r1210708771) * diff --git a/tests/utils/components/Editor.tsx b/tests/utils/components/Editor.tsx index 7389421c39..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, - slashMenuItems: [...defaultReactSlashMenuItems, ...slashCommands], + slashMenuItems: [...getDefaultReactSlashMenuItems(), ...slashMenuItems], }); console.log(editor); From 61cddafcd69656afdd4133800f748d8d55c17f63 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 1 Aug 2023 00:16:31 +0200 Subject: [PATCH 35/42] Implemented PR feedback --- packages/website/docs/docs/side-menu.md | 4 ++-- packages/website/docs/docs/ui-elements.md | 28 +++++++++++++++-------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/packages/website/docs/docs/side-menu.md b/packages/website/docs/docs/side-menu.md index 4389463e8d..315b5938c8 100644 --- a/packages/website/docs/docs/side-menu.md +++ b/packages/website/docs/docs/side-menu.md @@ -19,7 +19,7 @@ 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 @@ -98,7 +98,7 @@ After creating `CustomDragHandleMenu`, we tell BlockNote to use it inside `Block ## 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. +It might seem daunting to create your own Side Menu from scratch, which is why BlockNote provides React components that you can use which match the default styling. ### Default Components diff --git a/packages/website/docs/docs/ui-elements.md b/packages/website/docs/docs/ui-elements.md index 5d426708b7..d0f9b76794 100644 --- a/packages/website/docs/docs/ui-elements.md +++ b/packages/website/docs/docs/ui-elements.md @@ -24,22 +24,32 @@ Along with the editor itself, BlockNote includes a few additional UI elements in By default, these are all included in the editor, but you can remove or replace each of them with your own React components. -## Positioner Components +## Default Setup -Each of the UI elements not only have to show and hide, but also show in the correct positions. This is handled using `Positioner` components. Each UI element has its own `Positioner` component, e.g. the Formatting Toolbar: +In many of the examples, you'll see we render `BlockNoteView` like so: ```jsx -export const FormattingToolbarPositioner = (props: { - editor: BlockNoteEditor; - formattingToolbar?: FC>; -}): JSX.Element => { - ... -} + ``` +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 `Positioner` components for each UI element except the Side Menu: +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} From 0cad47805a51a133046b3a05e2566f16b609f633 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 1 Aug 2023 00:28:30 +0200 Subject: [PATCH 36/42] Fixed lint warning --- packages/react/src/hooks/useBlockNote.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 432c4f72ce..cb5ce28faa 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -29,11 +29,11 @@ export const useBlockNote = ( useMemo(() => { if (editorRef.current) { - editorRef.current && editorRef.current._tiptapEditor.destroy(); + editorRef.current._tiptapEditor.destroy(); } editorRef.current = initEditor(options); - }, [options, ...deps]); + }, [deps, options]); //eslint-disable-line react-hooks/exhaustive-deps return editorRef.current; }; From be406b745a1eddc4a9868f7e0bb1e136a473e580 Mon Sep 17 00:00:00 2001 From: Yousef Date: Tue, 1 Aug 2023 15:55:55 +0200 Subject: [PATCH 37/42] fix initialcontent and uniqueid (#289) * fix initialcontent and uniqueid * fix * Removed ready check in `BlockNoteView` --------- Co-authored-by: Matthew Lipski --- packages/core/src/BlockNoteEditor.ts | 36 +++++++---- .../core/src/extensions/UniqueID/UniqueID.ts | 59 +++++++++---------- packages/react/src/BlockNoteView.tsx | 39 ++++-------- packages/react/src/hooks/useBlockNote.ts | 7 ++- 4 files changed, 69 insertions(+), 72 deletions(-) diff --git a/packages/core/src/BlockNoteEditor.ts b/packages/core/src/BlockNoteEditor.ts index 25c2323cbb..524967c824 100644 --- a/packages/core/src/BlockNoteEditor.ts +++ b/packages/core/src/BlockNoteEditor.ts @@ -16,7 +16,10 @@ import { blocksToMarkdown, 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 styles from "./editor.module.css"; import { @@ -44,6 +47,7 @@ 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. @@ -201,22 +205,34 @@ export class BlockNoteEditor { 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 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/react/src/BlockNoteView.tsx b/packages/react/src/BlockNoteView.tsx index 90b115f5ec..6e237ad1c1 100644 --- a/packages/react/src/BlockNoteView.tsx +++ b/packages/react/src/BlockNoteView.tsx @@ -1,7 +1,7 @@ import { BlockNoteEditor, BlockSchema } from "@blocknote/core"; import { MantineProvider } from "@mantine/core"; import { EditorContent } from "@tiptap/react"; -import { ReactNode, useEffect, useState } from "react"; +import { HTMLAttributes, ReactNode } from "react"; import { getBlockNoteTheme } from "./BlockNoteTheme"; import { FormattingToolbarPositioner } from "./FormattingToolbar/components/FormattingToolbarPositioner"; import { HyperlinkToolbarPositioner } from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; @@ -12,40 +12,21 @@ export function BlockNoteView( props: { editor: BlockNoteEditor; children?: ReactNode; - } & React.HTMLAttributes + } & HTMLAttributes ) { const { editor, children, ...rest } = props; - const [ready, setReady] = useState(false); - - useEffect(() => { - function checkReady() { - if (!props.editor.ready) { - window.setTimeout(checkReady, 100); - } else { - setReady(true); - } - } - checkReady(); - - // TODO: Shouldn't this work with props.editor.ready in deps? It fails in - // tests so it doesn't seem to. - // if (props.editor.ready) { - // setReady(true); - // } - }, [props.editor.ready]); return ( - {ready && - (props.children || ( - <> - - - - - - ))} + {props.children || ( + <> + + + + + + )} ); diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index cb5ce28faa..25996000d8 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -25,15 +25,16 @@ export const useBlockNote = ( options: Partial> = {}, deps: DependencyList = [] ): BlockNoteEditor => { - const editorRef = useRef>(initEditor(options)); + const editorRef = useRef>(); - useMemo(() => { + const ret = useMemo(() => { if (editorRef.current) { editorRef.current._tiptapEditor.destroy(); } editorRef.current = initEditor(options); + return editorRef.current; }, [deps, options]); //eslint-disable-line react-hooks/exhaustive-deps - return editorRef.current; + return ret; }; From f954d678a2163f0e26de7c8d8e9ace59073ec752 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 1 Aug 2023 19:33:22 +0200 Subject: [PATCH 38/42] Added pre-made components for side menu --- .../plugins/suggestion/SuggestionPlugin.ts | 6 +-- .../DefaultButtons/AddBlockButton.tsx | 16 +++++++ .../components/DefaultButtons/DragHandle.tsx | 33 +++++++++++++ .../SideMenu/components/DefaultSideMenu.tsx | 48 ++++--------------- .../DefaultButtons/BlockColorsButton.tsx | 6 +-- .../DefaultButtons/RemoveBlockButton.tsx | 4 +- .../DragHandleMenu/DefaultDragHandleMenu.tsx | 4 +- .../src/SideMenu/components/SideMenu.tsx | 6 +++ .../SideMenu/components/SideMenuButton.tsx | 5 ++ .../components/SideMenuPositioner.tsx | 2 + packages/react/src/index.ts | 4 +- 11 files changed, 82 insertions(+), 52 deletions(-) create mode 100644 packages/react/src/SideMenu/components/DefaultButtons/AddBlockButton.tsx create mode 100644 packages/react/src/SideMenu/components/DefaultButtons/DragHandle.tsx rename packages/react/src/SideMenu/components/{ => DragHandleMenu}/DefaultButtons/BlockColorsButton.tsx (90%) rename packages/react/src/SideMenu/components/{ => DragHandleMenu}/DefaultButtons/RemoveBlockButton.tsx (71%) create mode 100644 packages/react/src/SideMenu/components/SideMenu.tsx create mode 100644 packages/react/src/SideMenu/components/SideMenuButton.tsx diff --git a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts index 0c63690bee..9381d7988f 100644 --- a/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts +++ b/packages/core/src/shared/plugins/suggestion/SuggestionPlugin.ts @@ -369,11 +369,6 @@ export const setupSuggestionsMenu = < 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 } = ( @@ -418,6 +413,7 @@ export const setupSuggestionsMenu = < }, }), itemCallback: (item: T) => { + deactivate(editor._tiptapEditor.view); editor._tiptapEditor .chain() .focus() 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 index 47d435f39a..46623a9c12 100644 --- a/packages/react/src/SideMenu/components/DefaultSideMenu.tsx +++ b/packages/react/src/SideMenu/components/DefaultSideMenu.tsx @@ -1,43 +1,15 @@ -import { FC } from "react"; -import { ActionIcon, Group, Menu } from "@mantine/core"; -import { AiOutlinePlus } from "react-icons/ai"; -import { MdDragIndicator } from "react-icons/md"; import { BlockSchema } from "@blocknote/core"; import { SideMenuProps } from "./SideMenuPositioner"; -import { DragHandleMenuProps } from "./DragHandleMenu/DragHandleMenu"; -import { DefaultDragHandleMenu } from "./DragHandleMenu/DefaultDragHandleMenu"; +import { SideMenu } from "./SideMenu"; +import { AddBlockButton } from "./DefaultButtons/AddBlockButton"; +import { DragHandle } from "./DefaultButtons/DragHandle"; export const DefaultSideMenu = ( - props: SideMenuProps & { - dragHandleMenu?: FC>; - } -) => { - const DragHandleMenu = props.dragHandleMenu || DefaultDragHandleMenu; - - return ( - - - - - - -
- - {} - -
-
- -
-
- ); -}; + props: SideMenuProps +) => ( + + + + +); diff --git a/packages/react/src/SideMenu/components/DefaultButtons/BlockColorsButton.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton.tsx similarity index 90% rename from packages/react/src/SideMenu/components/DefaultButtons/BlockColorsButton.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton.tsx index c366bbec8d..f506655b85 100644 --- a/packages/react/src/SideMenu/components/DefaultButtons/BlockColorsButton.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton.tsx @@ -3,9 +3,9 @@ import { Box, Menu } from "@mantine/core"; import { HiChevronRight } from "react-icons/hi"; import { BlockSchema, PartialBlock } from "@blocknote/core"; -import { DragHandleMenuProps } from "../DragHandleMenu/DragHandleMenu"; -import { DragHandleMenuItem } from "../DragHandleMenu/DragHandleMenuItem"; -import { ColorPicker } from "../../../SharedComponents/ColorPicker/components/ColorPicker"; +import { DragHandleMenuProps } from "../DragHandleMenu"; +import { DragHandleMenuItem } from "../DragHandleMenuItem"; +import { ColorPicker } from "../../../../SharedComponents/ColorPicker/components/ColorPicker"; export const BlockColorsButton = ( props: DragHandleMenuProps & { children: ReactNode } diff --git a/packages/react/src/SideMenu/components/DefaultButtons/RemoveBlockButton.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton.tsx similarity index 71% rename from packages/react/src/SideMenu/components/DefaultButtons/RemoveBlockButton.tsx rename to packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton.tsx index dd44bf569e..bbd5e2331c 100644 --- a/packages/react/src/SideMenu/components/DefaultButtons/RemoveBlockButton.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton.tsx @@ -1,8 +1,8 @@ import { ReactNode } from "react"; import { BlockSchema } from "@blocknote/core"; -import { DragHandleMenuProps } from "../DragHandleMenu/DragHandleMenu"; -import { DragHandleMenuItem } from "../DragHandleMenu/DragHandleMenuItem"; +import { DragHandleMenuProps } from "../DragHandleMenu"; +import { DragHandleMenuItem } from "../DragHandleMenuItem"; export const RemoveBlockButton = ( props: DragHandleMenuProps & { children: ReactNode } diff --git a/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx index 7759e9dd70..0e66af7195 100644 --- a/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx +++ b/packages/react/src/SideMenu/components/DragHandleMenu/DefaultDragHandleMenu.tsx @@ -1,8 +1,8 @@ import { BlockSchema } from "@blocknote/core"; import { DragHandleMenu, DragHandleMenuProps } from "./DragHandleMenu"; -import { RemoveBlockButton } from "../DefaultButtons/RemoveBlockButton"; -import { BlockColorsButton } from "../DefaultButtons/BlockColorsButton"; +import { RemoveBlockButton } from "./DefaultButtons/RemoveBlockButton"; +import { BlockColorsButton } from "./DefaultButtons/BlockColorsButton"; export const DefaultDragHandleMenu = ( props: DragHandleMenuProps 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 index dce71893b3..9b9503fbe3 100644 --- a/packages/react/src/SideMenu/components/SideMenuPositioner.tsx +++ b/packages/react/src/SideMenu/components/SideMenuPositioner.tsx @@ -9,6 +9,7 @@ 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< @@ -21,6 +22,7 @@ export type SideMenuProps = > & { block: Block; editor: BlockNoteEditor; + dragHandleMenu?: FC>; }; export const SideMenuPositioner = < diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 6289d21d58..ff298d2351 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -18,8 +18,8 @@ export * from "./SideMenu/components/DefaultSideMenu"; export * from "./SideMenu/components/DragHandleMenu/DragHandleMenu"; export * from "./SideMenu/components/DragHandleMenu/DefaultDragHandleMenu"; export * from "./SideMenu/components/DragHandleMenu/DragHandleMenuItem"; -export * from "./SideMenu/components/DefaultButtons/BlockColorsButton"; -export * from "./SideMenu/components/DefaultButtons/RemoveBlockButton"; +export * from "./SideMenu/components/DragHandleMenu/DefaultButtons/BlockColorsButton"; +export * from "./SideMenu/components/DragHandleMenu/DefaultButtons/RemoveBlockButton"; export * from "./SlashMenu/components/SlashMenuPositioner"; export * from "./SlashMenu/components/DefaultSlashMenu"; From a16163213ee101dfd0ede6ac0dbfe92860b732aa Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 1 Aug 2023 20:05:31 +0200 Subject: [PATCH 39/42] Added custom side menu docs --- packages/react/src/index.ts | 8 ++- packages/website/docs/docs/side-menu.md | 76 ++++++++++++++++++++++++- 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index ff298d2351..7c6983df2e 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -13,17 +13,21 @@ export * from "./FormattingToolbar/components/DefaultButtons/ToggledStyleButton" export * from "./HyperlinkToolbar/components/HyperlinkToolbarPositioner"; 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 "./SideMenu/components/DragHandleMenu/DragHandleMenu"; -export * from "./SideMenu/components/DragHandleMenu/DefaultDragHandleMenu"; 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/DefaultSlashMenu"; export * from "./SlashMenu/components/SlashMenuItem"; +export * from "./SlashMenu/components/DefaultSlashMenu"; export * from "./SlashMenu/ReactSlashMenuItem"; export * from "./SlashMenu/defaultReactSlashMenuItems"; diff --git a/packages/website/docs/docs/side-menu.md b/packages/website/docs/docs/side-menu.md index 315b5938c8..591c2ec8d4 100644 --- a/packages/website/docs/docs/side-menu.md +++ b/packages/website/docs/docs/side-menu.md @@ -23,6 +23,71 @@ You can also click the drag handle (`⠿`) in the Block Side Menu to open the Dr 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 If you want to change the items in the Drag Handle Menu, or replace it altogether, you can do that using a React component. @@ -94,21 +159,28 @@ export default function App() { `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. +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. + 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. ## Components -It might seem daunting to create your own Side Menu from scratch, which is why BlockNote provides React components that you can use which match the default styling. +It might seem daunting to create your own Side Menu or Drag Handle Menu from scratch, which is why BlockNote provides React components that you can use which match the default styling. ### Default Components -BlockNote exports all components used to create the default layout - both the menu itself and the items in it. Head to the [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. +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 Components BlockNote also provides components that you can use to make your own menu items, which also match the default styling: ```typescript +type SideMenuButtonProps = { + children: JSX.Element; +} +export const SideMenuButton = (props: SideMenuButtonProps) => ...; + // Takes same props as `button` elements, e.g. onClick. export const DragHandleMenuItem = (props) => ...; ``` From 934e5154dd6f927cea159c27690d6f8087d314d3 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 1 Aug 2023 21:04:17 +0200 Subject: [PATCH 40/42] Updated docs --- packages/website/docs/docs/side-menu.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/website/docs/docs/side-menu.md b/packages/website/docs/docs/side-menu.md index 591c2ec8d4..f1c846f156 100644 --- a/packages/website/docs/docs/side-menu.md +++ b/packages/website/docs/docs/side-menu.md @@ -165,7 +165,7 @@ After creating `CustomDragHandleMenu`, we tell BlockNote to use it inside `Block ## Components -It might seem daunting to create your own Side Menu or Drag Handle Menu from scratch, which is why BlockNote provides React components that you can use which match the default styling. +BlockNote provides React components that you can reuse, to easily create your menus while matching the default styling. ### Default Components From 3f1ba86a18abc2f930c41101e56bcf68e06deee2 Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 1 Aug 2023 21:26:33 +0200 Subject: [PATCH 41/42] Updated unit tests & snapshots --- .../formatConversions.test.ts.snap | 20 +- .../formatConversions.test.ts | 1192 ++++++++--------- .../nodeConversions.test.ts.snap | 30 +- .../nodeConversions/nodeConversions.test.ts | 184 ++- 4 files changed, 702 insertions(+), 724 deletions(-) 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); }); }); From c034cd1d138042d195777bee5af5eb79ea76652e Mon Sep 17 00:00:00 2001 From: Matthew Lipski Date: Tue, 1 Aug 2023 21:45:17 +0200 Subject: [PATCH 42/42] Updated `useBlockNote` deps --- packages/react/src/hooks/useBlockNote.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/react/src/hooks/useBlockNote.ts b/packages/react/src/hooks/useBlockNote.ts index 25996000d8..39a8dc238f 100644 --- a/packages/react/src/hooks/useBlockNote.ts +++ b/packages/react/src/hooks/useBlockNote.ts @@ -27,14 +27,12 @@ export const useBlockNote = ( ): BlockNoteEditor => { const editorRef = useRef>(); - const ret = useMemo(() => { + return useMemo(() => { if (editorRef.current) { editorRef.current._tiptapEditor.destroy(); } editorRef.current = initEditor(options); return editorRef.current; - }, [deps, options]); //eslint-disable-line react-hooks/exhaustive-deps - - return ret; + }, deps); //eslint-disable-line react-hooks/exhaustive-deps };