自定义插件开发指南

核心生命周期协议、实例 API 注册与独立的 React UI 贡献协议。

让文档进入你的工作流

MuseCanto Editor 提供了完备的扩展机制,允许业务团队或开源开发者针对特定需求自研插件。

插件由两部分组成:

  1. 核心插件(Core Plugin):通过 defineEditorPlugin 注入原生 Tiptap 扩展、生命周期监听与实例 API(无 UI 依赖)。
  2. UI 注册(UI Contribution):通过 EditorUIContribution 向工具栏、菜单、气泡或侧边栏注入 React 组件(独立于核心包)。

一、编写核心插件

核心插件从 @musecanto/editor 导入协议,禁止引用 React 或 @musecanto/editor-kit:

import { defineEditorPlugin } from "@musecanto/editor";

export interface WordCountApi {
  getWordCount(): number;
  getCharacterCount(): number;
}

export function createWordCountPlugin() {
  return defineEditorPlugin({
    name: "wordCount",
    // 导出暴露在 instance.plugins 上的方法
    api: (host) => ({
      getWordCount: () => {
        const text = host.getEditor()?.getText() ?? "";
        return text.trim() ? text.trim().split(/\s+/).length : 0;
      },
      getCharacterCount: () => {
        return host.getEditor()?.getText().length ?? 0;
      },
    }),
    // 生命周期与事件绑定
    setup({ editor, documentId }) {
      console.log(`正在为文档 [${documentId}] 初始化字数统计插件`);

      const handleUpdate = () => {
        // 可监听编辑器内容变化
      };
      editor.on("update", handleUpdate);

      // 返回函数在编辑器销毁或插件卸载时执行
      return () => {
        editor.off("update", handleUpdate);
      };
    },
    // 可选:拦截 Ctrl+S / Cmd+S 保存快捷键
    onSaveShortcut({ instance }) {
      console.log("检测到保存快捷键触发");
      return false; // 返回 true 表示已消费该事件
    },
  });
}

TypeScript 类型扩展声明

在代码中通过模块增强(Module Augmentation)将插件声明合并到 @musecanto/editor,为使用者提供完美的类型推导:

declare module "@musecanto/editor" {
  interface EditorPluginApis {
    wordCount: WordCountApi;
  }
}

二、编写 React UI Contribution

若插件包含界面呈现,需在独立的 /react 入口声明 EditorUIContribution,使用 @musecanto/editor-react 提供的规范:

import type { EditorUIContribution } from "@musecanto/editor-react";
import { useEditorRuntime, useEditorT } from "@musecanto/editor-react";
import { FileText } from "lucide-react";

// 自定义工具栏状态展示组件
function WordCountDisplay() {
  const { editor, instance } = useEditorRuntime();
  const count = instance?.plugins.wordCount?.getWordCount() ?? 0;

  return (
    <div className="flex items-center gap-1.5 px-2 text-xs text-muted-foreground">
      <FileText className="size-3.5" />
      <span>{count} 词</span>
    </div>
  );
}

// 导出 UI Contribution 实体
export const wordCountUI: EditorUIContribution = {
  id: "wordCount",
  order: 90, // 控制在工具栏上的摆放顺序
  toolbarItems: () => [
    {
      type: "component",
      key: "wordCountDisplay",
      component: <WordCountDisplay />,
    },
  ],
};

三、组装与使用

在 @musecanto/editor-kit 中使用

import { createEditor } from "@musecanto/editor-kit";
import { createWordCountPlugin } from "./my-word-count-plugin";
import { wordCountUI } from "./my-word-count-plugin/react";

const editor = createEditor({
  el: "#editor",
  plugins: [createWordCountPlugin()],
  ui: {
    contributions: [wordCountUI],
  },
  onCreate(instance) {
    // 享受全类型补全
    console.log("统计结果:", instance.plugins.wordCount?.getWordCount());
  },
});

在自定义 React 组装中使用

<EditorProvider editor={editor} instance={instance}>
  <EditorUIProvider contributions={[basicUI, wordCountUI]}>
    <Toolbar editor={editor} />
    <EditorContent editor={editor} />
  </EditorUIProvider>
</EditorProvider>

四、开发最佳实践

  1. 单向解耦:核心逻辑与 React UI 必须严格分离,保证核心插件能在 Node.js、测试脚本或无头实例中安全运行。
  2. 唯一标识保护:plugin.name 与 contribution.id 必须全局唯一,系统在初始化阶段会检测冲突并给出明确报错。
  3. 资源清理:在 setup() 返回的函数中务必清理所有的定时器、全局 DOM 监听器与第三方 SDK 连接。

本页目录

继续探索编辑器 Playground试写并查看文档输出在 GitHub 查看源码问题反馈与参与贡献

示例使用私有 SDK。
你的内容与存储,由你掌控。