Cursor & Selections
BlockNote provides APIs to work with cursor positions and text selections, allowing you to understand where users are interacting with the editor and programmatically control the selection state.
Text Cursor
The text cursor represents the blinking vertical line where users type. BlockNote provides detailed information about the cursor's position and surrounding context.
TextCursorPosition Type
type TextCursorPosition = {
block: Block;
prevBlock: Block | undefined;
nextBlock: Block | undefined;
};
block
: The block currently containing the text cursorprevBlock
: The previous block at the same nesting level (undefined if first)nextBlock
: The next block at the same nesting level (undefined if last)
Getting Cursor Position
getTextCursorPosition(): TextCursorPosition;
// Usage
const cursorPos = editor.getTextCursorPosition();
console.log("Cursor is in block:", cursorPos.block.id);
Setting Cursor Position
setTextCursorPosition(
targetBlock: BlockIdentifier,
placement: "start" | "end" = "start"
): void;
// Usage
editor.setTextCursorPosition(blockId, "start");
editor.setTextCursorPosition(blockId, "end");
Parameters:
targetBlock
: Block ID or Block object to position cursor inplacement
: Whether to place cursor at start or end of block
Throws: Error if target block doesn't exist
Selections
Selections represent highlighted content spanning multiple blocks. BlockNote provides APIs to get and set selections programmatically.
Selection Type
type Selection = {
blocks: Block[];
};
blocks
: Array of all blocks spanned by the selection (including nested blocks)
Getting Current Selection
getSelection(): Selection | undefined;
// Usage
const selection = editor.getSelection();
if (selection) {
console.log("Selected blocks:", selection.blocks.length);
}
Returns: Current selection or undefined
if no selection is active
Setting Selection
setSelection(startBlock: BlockIdentifier, endBlock: BlockIdentifier): void;
// Usage
editor.setSelection(startBlockId, endBlockId);
Parameters:
startBlock
: Block where selection should beginendBlock
: Block where selection should end
Requirements:
- Both blocks must have content
- Selection spans from start of first block to end of last block
Throws: Error if blocks don't exist or have no content
Related APIs
- Manipulating Blocks - Work with selected blocks
- Manipulating Inline Content - Format selected text
- Events - Listen for selection changes