--- title: 插件配置 description: 如何配置和自定义Plate插件。 --- Plate 插件拥有一个 capability:schema、behavior、state、service、read、 update、rendering,或这些字段的必要组合。独立字段直接在创建时声明, app-owned 值才使用 terminal configuration。 - [入门指南:组件](/docs/installation/plate-ui) - 添加插件到编辑器的说明 - [Plugin API](/docs/api/core/plate-plugin) - 创建插件的完整 API 参考 ## 基础插件配置 ### 新建插件 最基本的插件配置只需一个`name`: ```ts const MyPlugin = definePlugin("minimal", {}); ``` 虽然这个插件目前没有任何功能,但它是更复杂配置的起点。 ### 现有插件 使用`.configure`方法可以配置现有插件: ```ts const ConfiguredPlugin = MyPlugin.configure({ initialState: { myOption: "new value", }, }); ``` ## Schema 插件 Schema 插件在 `schema` 下声明持久化文档身份和结构。React component 位于插件根级。 ### 元素 使用 `schema.element` 声明新元素类型: ```ts import { schema } from "platejs"; const NoticePlugin = definePlugin("noticeFeature", { schema: { element: { ...schema.element.textBlock(), type: "notice" }, }, }); ``` 您可以为元素关联组件。详见[插件组件](/docs/plugin-components)。 ```ts import { schema } from "platejs"; const NoticePlugin = definePlugin("noticeFeature", { component: NoticeElement, schema: { element: { ...schema.element.textBlock(), type: "notice" }, }, }); ``` ### 块内容 Plate 默认把每个非行内元素视为普通文档流中的块内容。结构节点应在 schema 中 声明 `blockContent: false`,而不是用该字段排除仍应可选择的块。 ```ts const RowPlugin = definePlugin("row", { schema: { element: { ...schema.element.textBlock(), blockContent: false, }, }, }); ``` 通过 Plate schema API 读取编译结果: ```ts editor.read.schema.isBlockContent(element); ``` 该分类独立于 `editor.read.nodes.isSelectable(element)`。内容容器通过 `plugins.blockContent(...)` 声明可接受的普通文档流块。 ### 行内元素、Void 元素和文本属性 元素行为位于 `schema.element` 中。使用 `schema.mark` 下的属性描述符声明布尔文本属性: ```ts import { property, schema } from "platejs"; const CustomLinkPlugin = definePlugin("customLink", { schema: { element: { content: schema.content.text({ default: "text", min: 1 }), inline: true, }, }, }); const CustomImagePlugin = definePlugin("customImage", { schema: { element: { void: "block" } }, }); const CustomBoldPlugin = definePlugin("customBold", { schema: { mark: property.boolean({ default: false, omitDefault: true }), }, }); ``` ## 行为插件 除了声明元素或文本属性外,您可能还想自定义编辑器的行为。Plate 提供了多种插件选项来修改编辑器行为。 ### 插件规则 `rules`属性允许您配置常见的编辑行为,如拆分、删除和合并节点,而无需重写编辑器方法。这是为自定义元素定义直观交互的强大方式。 例如,您可以定义当用户在空标题中按`Enter`或在块引用开头按`Backspace`时发生的情况。 ```ts import { HeadingPlugin } from "platejs/react"; HeadingPlugin.configure({ rules: { break: { empty: "reset" }, }, }); ``` 完整规则列表和可用操作请见[插件规则指南](/docs/plugin-rules)。 ### 事件处理器 [#event-handlers] 插件的 `on` 字段同时管理 editor lifecycle 和 React DOM 事件。DOM handler 接收 `PluginContext & { event }` 对象。 子项名称不重复 `on` 前缀。Lifecycle handler 使用 `commit`、`nodeChange` 和 `textChange`;DOM handler 使用 `keyDown`、`paste` 和 `click`。 ```ts showLineNumbers const ExamplePlugin = definePlugin("example", { on: { commit: ({ editor, snapshot }) => { console.info(editor, snapshot.children); }, keyDown: ({ editor, event }) => { console.info(`You pressed ${event.key}`); }, }, }); ``` ### 注入属性 您可能希望向具有特定属性的任何节点注入类名或 CSS 属性。例如,以下插件为具有 `textAlign` 属性的段落设置 `textAlign` CSS 属性。 ```ts showLineNumbers import { PLUGINS, property, schema, target, txLocate } from "platejs"; const TextAlignPlugin = definePlugin("textAlign", { formats: ({ defineFormats }) => defineFormats({ html: { decode: ({ element }) => element.style.textAlign || undefined, encode: ({ value }) => ({ style: { textAlign: value } }), match: [ { style: { textAlign: ["start", "left", "center", "right", "end", "justify"], }, }, ], }, }), inject: { isBlock: true, nodeProps: { styleKey: "textAlign", }, }, schema: ({ targetElementTypes }) => ({ properties: { textAlign: schema.elementProperty(property.string(), { target: target.types(targetElementTypes), typeChange: "preserve-if-allowed", }), }, }), targetPlugins: [PLUGINS.paragraph], update: ({ tx }) => ({ set: txLocate(false, (value: string) => tx.nodes.set({ textAlign: value }) ), }), }); ``` `inject.nodeProps` 负责渲染,constructor 的 `formats` callback 把双向 HTML 声明绑定到插件 schema。`defineFormats` 根据 property 声明推断 `value`。两条 路径都使用 author callback 的 `schema.properties.textAlign` 编译 handle;consumer 通过类型化节点字段或插件语义能力访问数据,而不读取该 property 映射。`name` 只标识能力 namespace。`.configure()` 和 `.extend()` 不更改 schema identity。传给 `createEditor` 或 `useCreateEditor` 的 `schema` 可以重映射 element type 或关系; 插件拥有的 property key 保持固定。 插件 update 传入一个原子 property patch,因此每个 key 和 value 都从插件的 shallow schema contract 推断。Alias 使用精确 author handle 的 key 作为 computed object key。 元素属性的 `landing` 选项说明内容的落点能否改变它,默认为 `preserve`。对相对于落点的值(例如 Indent 的 `indent`)声明 `rebase`,对由落点提供的值(例如 List 的 `listId`)声明 `adopt`。移动文本的拖拽只有在其落地读取只改变 `rebase` 和 `adopt` 属性时才会落地,区块副本或被移动区块的 [`editorReads.transfer.adopt`](/cn/docs/dnd#塑造落地区块) 只能设置 `adopt` 属性。文本属性没有 `landing` 选项。 受该插件影响的段落节点如下: ```ts showLineNumbers {3} const paragraph = { type: 'paragraph', textAlign: 'right', children: [{ text: '本段落右对齐!' }], }; ``` ### 扩展 API 和事务命令 state-bound query 放在 `read`,immutable service 放在 `api`,文档变更放在 `update`。Constructor callback 直接接收 plugin context。 `initialState` 的每个顶层字段都必须存在,且类型不能包含 `undefined`。 请使用具体默认值或 `null` 表示空值。工厂返回的 state 和通过 `.extend()` 添加的字段也遵循此规则。嵌套对象可以包含可选属性; `.configure({ initialState })` 可以只覆盖部分默认值。 ```ts export type CustomPluginState = { prefix: string; }; const CustomPlugin = definePlugin("custom", { api: ({ store }) => ({ getPrefix: () => store.get("prefix"), }), initialState: { prefix: "Note: ", } satisfies CustomPluginState, update: ({ store, tx }) => ({ insertPrefix: () => { tx.text.insert(store.get("prefix")); }, }), }); ``` 插件解析后,具体 editor 会在 root API 推断其 service;一次性 write 使用 name-scoped update helper: ```ts editor.api.custom.getPrefix(); editor.update.custom.insertPrefix(); ``` 通用包代码可以通过 `editor.plugin(CustomPlugin).api.getPrefix()` 访问同一个 immutable API object。 ### 编辑器能力 Plate 插件直接在插件根级声明 Plate 能力。使用 `readMiddleware`、`commands`、 `corrections`、`stateFields`、`effectTypes`、 `contributions`、`on`、`activate` 和 `validate`, 不再添加第二层 wrapper。 ```ts showLineNumbers import { defineStateField } from "platejs"; import { definePlugin } from "platejs/react"; const enabledField = defineStateField({ initial: false, key: "customState.enabled", }); const CustomStatePlugin = definePlugin("customState", { stateFields: [enabledField], read: ({ state }) => ({ enabled: () => state.getField(enabledField), }), on: { commit: ({ commit }) => { console.info(commit.changed); }, }, }); ``` - 每个独立能力直接放进 constructor。只有 import/prebuilt descriptor、 constructor 无法访问的 shared factory 或前一阶段类型才使用 `.extend()`。 独立复用的 standalone Plate descriptor 使用从 `platejs` import 的 `definePlugin`。详见 [插件方法](/docs/plugin-methods#commands)。 ## 高级插件配置 ### 插件存储 每个插件都有自己的存储,可用于管理插件特定状态。 ```ts type MyPluginState = { count: number; }; const MyPlugin = definePlugin("myPlugin", { initialState: { count: 0, } satisfies MyPluginState, on: { click: ({ store }) => { store.set({ count: 1 }); }, }, }); ``` 您可以使用以下方法访问和更新存储: ```ts // 获取当前值 const count = editor.plugin(MyPlugin).store.get("count"); // 设置新值 editor.plugin(MyPlugin).store.set({ count: 5 }); // 基于先前状态更新值 editor.plugin(MyPlugin).store.set((state) => { state.count += 1; }); ``` 在 React 组件中使用 `usePluginStore` 订阅存储变更: ```tsx const MyComponent = () => { const count = usePluginStore(MyPlugin, "count"); return
计数: {count}
; }; ``` 更多内容请见[插件上下文](/docs/plugin-context)和[编辑器方法](/docs/editor-methods)指南。 ### 依赖项 使用插件对象声明所需依赖项。Plate 会递归安装依赖图,按插件名称去重,并在依赖插件之后加载当前插件。 ```ts const MyPlugin = definePlugin("myPlugin", { dependencies: [ParagraphPlugin, ListPlugin], }); ``` ### 启用标志 `enabled`属性允许您有条件地启用或禁用插件: ```ts const MyPlugin = definePlugin("myPlugin", { enabled: true, // 或false禁用 }); ``` ### 可选能力 可选能力应作为普通插件直接放在使用者的插件数组中。当增强能力需要宿主时,由增强 能力依赖宿主: ```ts const CodeHighlightPlugin = definePlugin("codeHighlight", { dependencies: [CodeBlockPlugin], }); const plugins = [CodeBlockPlugin, CodeHighlightPlugin]; ``` 需要纯文本代码块时省略 `CodeHighlightPlugin`。宿主不会安装可选增强能力。 ### 插件顺序 依赖项会在其使用者之前加载。互不依赖的插件保持应用提供的顺序: ```ts const plugins = [LinkPlugin, MentionPlugin, HighlightPlugin]; ``` 真正的安装要求应使用 `dependencies`。有冲突的快捷键、输入规则和编解码器各自 使用局部 `priority`;插件注册没有全局优先级。 ### 装饰样式 在复制的功能文件中配置 `decorate.attributes`。已有的 `read` 负责范围与语义标记, `observe` 负责失效通知。 ```tsx import { BaseFindPlugin } from 'platejs/find'; const FindPlugin = BaseFindPlugin.configure({ decorate: { attributes: { className: 'rounded-sm bg-yellow-200' }, }, }); ``` 需要按范围决定样式时,使用接收推断插件上下文、`entry` 和 `decoration` 的纯函数。 `null` 清除继承的展示属性。类名拼接,style 浅合并,其他属性以最后提供的值为准。 共享的 `Editor` 样式不包含功能选择器。参见 [装饰 API](/docs/api/core/plate-plugin#properties-attrs-decorate)。 ### View-Local Element Attribute plugin 需要为少量完整 element host 添加响应式 attribute 时,使用 `render.useViewElementAttributes`。每个 mounted view 中启用的 plugin 只有一个 hook program,并返回 `{ key, attributes }[]`。`render.attributes` 与 `inject.nodeProps.transformProps` 会按 node 运行,因此必须保持纯函数。只绘制带有其 node key 的 text 的注入应设置 `inject.nodeProps.textScope: 'nodeKey'`,这样在其他 text 中输入时,该注入不再强制触发 React 渲染。inline range 使用 `decorate`,结构化输出使用 component 或 slot。参见 [Plate Plugin API](/docs/api/core/plate-plugin#properties-attrs-render)。 ### HTML document preparation 当 node matching 需要先规范化 DOM 时,HTML mapping 可以声明一次 `prepareDocument`。Callback 接收 inert、operation-owned detached document, 以及其他 HTML callback 使用的冻结 mapping context。它不能读取 browser `DataTransfer` 或 live editor。它的 `report` 接收一条诊断,以及可选的、该损失所关联的 `element`。只要 document 仍包含该元素,诊断就会指出它在报告时 document 中的位置。更早运行的 mapping `prepareDocument`(例如 List 的)可能先移动节点,因此该位置可能与粘贴的 HTML 不同。以相同消息报告的两个元素会得到两条诊断。请在移除元素之前报告它的损失。 Whole-payload admission、source-string cleanup、Word/RTF 处理与 post-decode slice repair 属于 `DataTransferFormat`。该 owner 可以准备 payload,然后返回 `platejs/html` 的 `decodeHtmlDataTransfer({ ...context, data: prepared })`。 空结果会认领 paste;若要让下一个 format 尝试,改为返回 `null`。 ## 类型化插件 `definePlugin` 会从 author object 推断一个精确 definition。通过带类型的 `initialState` 值或 `satisfies` 固定 state contract;不要向 factory 传入调用方 泛型。 ### 使用 definePlugin 推断后的 definition 会携带插件 name、state、API、read 和 update: ```ts import { property, schema } from "platejs"; import { definePlugin } from "platejs/react"; export type SnippetPluginState = { language: string; syntax: boolean; syntaxPopularFirst: boolean; }; export const SnippetPlugin = definePlugin("snippet", { api: ({ store }) => ({ getLanguage: () => store.get("language"), getSyntaxState: () => store.get("syntax"), }), initialState: { language: "typescript", syntax: true, syntaxPopularFirst: false, } satisfies SnippetPluginState, schema: { element: schema.element.textBlock({ properties: { language: property.string() }, }), }, update: ({ schema: { type }, store, tx }) => ({ insertCurrentLanguage: () => { tx.nodes.insert({ type, language: store.get("language"), children: [{ text: "" }], }); }, }), }); ``` ### 使用类型化插件 使用类型化插件时,您将获得完整的类型检查和自动补全功能 ✨ ```ts const editor = createEditor({ plugins: [SnippetPlugin], }); // 类型安全的 state 访问 const state = editor.plugin(SnippetPlugin).store.get(); state.language; state.syntax; state.syntaxPopularFirst; // 类型安全的API editor.api.snippet.getSyntaxState(); editor.api.snippet.getLanguage(); // 类型安全的更新 editor.update.snippet.insertCurrentLanguage(); ``` ## 另请参阅 更多插件选项请见[Plugin API](/docs/api/core/plate-plugin)。