Keyboard Shortcuts
TODO: useful example? Non-basic?
In this example, we create a keyboard shortcut which cycles the current block type when Ctrl+G is pressed.
Relevant Docs:
import {
Block,
BlockNoteEditor,
DefaultBlockSchema,
DefaultInlineContentSchema,
DefaultStyleSchema,
} from "@blocknote/core";
import { BlockNoteView, useCreateBlockNote } from "@blocknote/react";
import "@blocknote/react/style.css";
const cycleBlocksShortcut = (
event: React.KeyboardEvent,
editor: BlockNoteEditor
) => {
// Checks for Ctrl+G shortcut
if (event.ctrlKey && event.key === "g") {
// Needs type cast as Object.keys doesn't preserve type
const allBlockTypes = Object.keys(editor.schema.blockSchema) as Block<
DefaultBlockSchema,
DefaultInlineContentSchema,
DefaultStyleSchema
>["type"][];
const currentBlockType = editor.getTextCursorPosition().block.type;
const nextBlockType =
allBlockTypes[
(allBlockTypes.indexOf(currentBlockType) + 1) % allBlockTypes.length
];
editor.updateBlock(editor.getTextCursorPosition().block, {
type: nextBlockType,
});
}
};
export default function App() {
const editor = useCreateBlockNote();
const onKeyDown = (event: React.KeyboardEvent) => {
cycleBlocksShortcut(event, editor);
};
return <BlockNoteView editor={editor} onKeyDown={onKeyDown} />;
}