BlockNote Docs参考操作内容

操作内容

BlockNote 提供了全面的 API 来操作编辑器中的块和内联内容。本指南涵盖了如何以编程方式操作文档结构(块)及块内的内容(文本、链接、样式)。

概览

内容操作 API 分为两大类:

块操作

内联内容操作

常用类型

块标识符

大多数块方法需要 BlockIdentifier 来引用已有块:

type BlockIdentifier = string | { id: string };

你可以传入:

  • 表示块 ID 的字符串
  • 任何带有 id: string 属性的对象,如 Block

部分块

创建或更新块时,使用具有可选属性的 PartialBlock 对象:

type PartialBlock = {
  id?: string; // 如果未提供则自动生成
  type?: string; // 块类型(段落、标题等)
  props?: Partial<Record<string, any>>; // 块特定属性
  content?: string | InlineContent[] | TableContent; // 块内容
  children?: PartialBlock[]; // 嵌套块
};

部分内联内容

创建或更新内联内容时,使用 PartialInlineContent 来灵活指定内容:

type PartialLink = {
  type: "link";
  content: string | StyledText[];
  href: string;
};

type PartialInlineContent = string | (string | PartialLink | StyledText)[];

该类型允许你:

  • 传入简单字符串表示纯文本
  • 传入混合内容数组(字符串、链接、样式文本)
  • 使用 PartialLink 表示链接内容
  • 使用 StyledText 表示带格式的文本

块操作

读取块

获取文档

获取编辑器中的所有顶层块:

const blocks = editor.document;

返回文档中所有顶层(非嵌套)块的快照。

获取特定块

// 单个块
getBlock(blockIdentifier: BlockIdentifier): Block | undefined

// 上一个块
getPrevBlock(blockIdentifier: BlockIdentifier): Block | undefined

// 下一个块
getNextBlock(blockIdentifier: BlockIdentifier): Block | undefined

// 父块
getParentBlock(blockIdentifier: BlockIdentifier): Block | undefined
const block = editor.getBlock("block-123");
const prevBlock = editor.getPrevBlock("block-123");
const nextBlock = editor.getNextBlock("block-123");
const parentBlock = editor.getParentBlock("nested-block-123");

遍历所有块

forEachBlock(
  callback: (block: Block) => boolean,
  reverse: boolean = false
): void

深度优先遍历所有块,并对每个块执行回调。

editor.forEachBlock((block) => {
  console.log(`块 ${block.id}: ${block.type}`);
  return true; // 继续遍历
});

创建块

插入块

insertBlocks(
  blocksToInsert: PartialBlock[],
  referenceBlock: BlockIdentifier,
  placement: "before" | "after" = "before"
): void

将新块插入到现有块的相对位置。

// 在现有块前插入段落
editor.insertBlocks(
  [{ type: "paragraph", content: "新段落" }],
  "existing-block-id",
  "before",
);

// 在现有块后插入多个块
editor.insertBlocks(
  [
    { type: "heading", content: "新章节", props: { level: 2 } },
    { type: "paragraph", content: "章节内容" },
  ],
  "existing-block-id",
  "after",
);

更新块

修改现有块

updateBlock(
  blockToUpdate: BlockIdentifier,
  update: PartialBlock
): void

用新属性更新已存在的块。

// 把段落改为标题
editor.updateBlock("block-123", {
  type: "heading",
  props: { level: 2 },
});

// 仅更新内容
editor.updateBlock("block-123", {
  content: "更新后的内容",
});

// 同时更新多个属性
editor.updateBlock("block-123", {
  type: "heading",
  content: "新标题文本",
  props: { level: 1 },
});

删除块

删除块

removeBlocks(blocksToRemove: BlockIdentifier[]): void

从文档中删除一个或多个块。

// 删除单个块
editor.removeBlocks(["block-123"]);

// 删除多个块
editor.removeBlocks(["block-123", "block-456", "block-789"]);

替换块

交换块

replaceBlocks(
  blocksToRemove: BlockIdentifier[],
  blocksToInsert: PartialBlock[]
): void

用新块替换已有块。

// 用标题替换段落
editor.replaceBlocks(
  ["paragraph-block"],
  [{ type: "heading", content: "新标题", props: { level: 2 } }],
);

// 用不同内容替换多个块
editor.replaceBlocks(
  ["block-1", "block-2"],
  [
    { type: "paragraph", content: "替换内容" },
    { type: "bulletListItem", content: "列表项" },
  ],
);

移动块

重新排序块

moveBlocksUp(): void
moveBlocksDown(): void

将当前选择的块上移或下移。

// 上移选中块
editor.moveBlocksUp();

// 下移选中块
editor.moveBlocksDown();

嵌套块

创建层级结构

canNestBlock(): boolean
nestBlock(): void
canUnnestBlock(): boolean
unnestBlock(): void

管理块的嵌套层级(缩进)。

// 检查当前块是否可嵌套
if (editor.canNestBlock()) {
  editor.nestBlock(); // 缩进块
}

// 检查当前块是否可解除嵌套
if (editor.canUnnestBlock()) {
  editor.unnestBlock(); // 减少缩进
}

内联内容操作

插入内联内容

基础插入

insertInlineContent(
  content: PartialInlineContent,
  options?: { updateSelection?: boolean }
): void

在当前光标位置插入内容或替换当前选区。

// 插入纯文本
editor.insertInlineContent("Hello, world!");

// 插入混合内容
editor.insertInlineContent([
  "Hello ",
  { type: "text", text: "World", styles: { bold: true } },
  "! Welcome to ",
  { type: "link", content: "BlockNote", href: "https://blocknotejs.org" },
]);

// 插入并更新选区
editor.insertInlineContent("新内容", { updateSelection: true });

高级内容示例

// 插入样式文本
editor.insertInlineContent([
  {
    type: "text",
    text: "加粗且斜体",
    styles: { bold: true, italic: true },
  },
]);

// 插入带样式内容的链接
editor.insertInlineContent([
  {
    type: "link",
    content: [
      { type: "text", text: "访问 ", styles: {} },
      { type: "text", text: "BlockNote", styles: { bold: true } },
    ],
    href: "https://blocknotejs.org",
  },
]);

// 插入复杂混合内容
editor.insertInlineContent([
  "这是 ",
  { type: "text", text: "重要的", styles: { bold: true, textColor: "red" } },
  ",你应该 ",
  { type: "link", content: "阅读更多", href: "https://example.com" },
  " 相关内容。",
]);

读取内容

获取选中文本

getSelectedText(): string

以纯文本形式获取当前选中的文本。

const selectedText = editor.getSelectedText();
console.log("选中文本:", selectedText);

// 示例:复制选中文本到剪贴板
if (selectedText) {
  navigator.clipboard.writeText(selectedText);
}

获取激活样式

getActiveStyles(): Styles

返回当前光标位置或选区末尾的激活文本样式。

const activeStyles = editor.getActiveStyles();
console.log("激活样式:", activeStyles);

// 示例:检测文本是否加粗
if (activeStyles.bold) {
  console.log("文本是加粗的");
}

// 示例:获取文本颜色
if (activeStyles.textColor) {
  console.log("文本颜色:", activeStyles.textColor);
}

获取选中链接

getSelectedLinkUrl(): string | undefined

返回当前选区中最后一个链接的 URL,若无链接则返回 undefined

const linkUrl = editor.getSelectedLinkUrl();

if (linkUrl) {
  console.log("选中链接 URL:", linkUrl);
  // 新标签页打开链接
  window.open(linkUrl, "_blank");
} else {
  console.log("未选中链接");
}

样式文本

添加样式

addStyles(styles: Styles): void

向当前选中文本应用样式。

// 添加单一样式
editor.addStyles({ bold: true });

// 添加多种样式
editor.addStyles({
  bold: true,
  italic: true,
  textColor: "red",
});

// 添加背景色
editor.addStyles({ backgroundColor: "yellow" });

移除样式

removeStyles(styles: Styles): void

从当前选中文本移除指定样式。

// 移除单一样式
editor.removeStyles({ bold: true });

// 移除多种样式
editor.removeStyles({ bold: true, italic: true });

// 移除颜色样式
editor.removeStyles({ textColor: "red", backgroundColor: "yellow" });

切换样式

toggleStyles(styles: Styles): void

切换当前选中文本的样式(若存在则移除,否则添加)。

// 切换单一样式
editor.toggleStyles({ bold: true });

// 切换多种样式
editor.toggleStyles({ bold: true, italic: true });

// 切换颜色样式
editor.toggleStyles({ textColor: "blue" });

操作链接

创建链接

createLink(url: string, text?: string): void

创建一个新链接,可选择替换当前选中的文本。

// 将选中文本创建为链接
editor.createLink("https://blocknotejs.org");

// 创建带自定义文本的链接
editor.createLink("https://blocknotejs.org", "访问 BlockNote");

// 创建空链接(移除链接)
editor.createLink("");