光标与选区
BlockNote 提供了用于操作光标位置和文本选区的 API,帮助你了解用户在编辑器中的交互位置,并以编程方式控制选区状态。
文本光标
文本光标表示用户输入时闪烁的竖线。BlockNote 提供了关于光标位置及其周围上下文的详细信息。
TextCursorPosition 类型
type TextCursorPosition = {
block: Block;
prevBlock: Block | undefined;
nextBlock: Block | undefined;
parentBlock: Block | undefined;
};block:当前包含文本光标的区块prevBlock:同一级别的前一个区块(如果是第一个则为 undefined)nextBlock:同一级别的下一个区块(如果是最后一个则为 undefined)parentBlock:如果光标位于嵌套区块中,则为父区块(顶层则为 undefined)
获取光标位置
getTextCursorPosition(): TextCursorPosition;
// 用法
const cursorPos = editor.getTextCursorPosition();
console.log("光标在区块中:", cursorPos.block.id);设置光标位置
setTextCursorPosition(
targetBlock: BlockIdentifier,
placement: "start" | "end" = "start"
): void;
// 用法
editor.setTextCursorPosition(blockId, "start");
editor.setTextCursorPosition(blockId, "end");参数:
targetBlock:要定位光标的区块 ID 或区块对象placement:将光标放在区块的开头还是结尾
抛出异常: 如果目标区块不存在,则抛出错误
选区
选区表示跨多个区块的高亮内容。BlockNote 提供了以编程方式获取和设置选区的 API。
Selection 类型
type Selection = {
blocks: Block[];
};blocks:被选区覆盖的所有区块数组(包括嵌套区块)
获取当前选区
getSelection(): Selection | undefined;
// 用法
const selection = editor.getSelection();
if (selection) {
console.log("选中的区块数:", selection.blocks.length);
}返回值: 当前选区,如果没有选区,则返回 undefined
设置选区
setSelection(startBlock: BlockIdentifier, endBlock: BlockIdentifier): void;
// 用法
editor.setSelection(startBlockId, endBlockId);参数:
startBlock:选区开始的区块endBlock:选区结束的区块
要求:
- 两个区块都必须包含内容
- 选区从第一个区块的开头到最后一个区块的结尾
抛出异常: 如果区块不存在或无内容,则抛出错误