集成概述
本文档介绍如何将 Schema Element Editor 集成到您的 Web 应用中。
集成要求
要使用 Schema Element Editor 插件,您的页面需要:
- 标记可编辑元素 - 在 HTML 元素上添加特定属性
- 提供数据接口 - 实现获取和更新 Schema 的方法
核心概念
元素标记
在需要编辑的 HTML 元素上添加 data-id 属性:
<!-- 单个参数 -->
<div data-id="message-1">可编辑的内容</div>
<!-- 多个参数 -->
<div data-id="user-123,message-456">可编辑的内容</div>
- 属性名默认为
data-id,可在配置中修改 - 属性值作为参数传递给获取/更新函数
- 多个参数用逗号分隔
Schema 数据类型
Schema 数据支持所有 JSON 类型:
type SchemaValue =
| Record<string, unknown> // 对象
| unknown[] // 数组
| string // 字符串
| number // 数字
| boolean // 布尔值
| null // null
核心 API
需要实现两个核心方法:
// 获取 Schema(必需)
type GetSchemaFunc = (params: string) => SchemaValue
// 更新 Schema(必需)
type UpdateSchemaFunc = (schema: SchemaValue, params: string) => boolean
参数说明:
params- 元素的data-id属性值,如"message-1"或"user-123,message-456"schema- Schema 数据,可以是任意 JSON 类型- 返回值 -
updateSchema返回boolean表示是否更新成功
预览 API(可选)
如果需要支持实时预览:
type PreviewFunc = (schema: SchemaValue, containerId: string) => (() => void) | void
containerId- 预览容器的 DOM ID,宿主页面可通过document.getElementById()获取容器元素进行渲染- 返回值 - 可选的清理函数,插件关闭预览时自动调用
快速开始
使用 SDK(推荐)
- 安装 SDK:
npm install @schema-element-editor/host-sdk
- 在页面中集成:
import { useSchemaElementEditor } from '@schema-element-editor/host-sdk'
function App() {
useSchemaElementEditor({
getSchema: (params) => dataStore[params],
updateSchema: (schema, params) => {
dataStore[params] = schema
return true
},
})
return (
<div data-id="message-1">
可编辑的内容
</div>
)
}
手动集成
如果不使用 SDK,可以直接监听 postMessage:
window.addEventListener('message', (event) => {
if (event.data?.source !== 'schema-element-editor-content') return
const { type, payload, requestId } = event.data
// 处理请求并响应
window.postMessage(
{
source: 'schema-element-editor-host',
requestId,
// ... 响应数据
},
'*'
)
})
Agentic UI 集成
如果您使用 Agentic UI,集成更加简单:
Agentic UI 已内置 postMessage 通信适配,开发环境下开箱即用。
组件要求:
| 组件 | 要求 |
|---|---|
Bubble | 配置 id 属性 |
BubbleList | 数据项包含 id 字段 |
// Bubble 需指定 id
<Bubble
id="msg-1"
originData={{ id: 'msg-1', role: 'assistant', originContent: '# Hello' }}
/>
// BubbleList 数据项需包含 id 字段
<BubbleList
bubbleList={[
{ id: 'msg-1', role: 'assistant', content: '...' }
]}
/>
配置选项
集成相关的配置项在插件配置页面的「集成配置」中设置:
元素标记配置
| 配置项 | 说明 | 默认值 |
|---|---|---|
| 属性名称 | 用于标记可编辑元素的属性名 | id(即 data-id) |
postMessage 配置
| 配置项 | 说明 | 默认值 |
|---|---|---|
| 请求超时时间 | 等待响应的最长时间 | 5 秒 |
| 插件端 source | 插件发送消息的标识 | schema-element-editor-content |
| 宿主端 source | 宿主响应消息的标识 | schema-element-editor-host |
| 消息类型 | 各类操作的消息类型名 | GET_SCHEMA 等 |
下一步
- postMessage 模式 - 详细的 postMessage 集成指南
- SDK 使用指南 - 官方 SDK 的完整使用文档
故障排除
元素无法被检测
- 检查元素是否有正确的
data-id属性 - 检查属性名配置是否与页面一致
- 确认插件已激活
点击元素后无反应
- 检查是否实现了
getSchema方法 - 检查浏览器控制台是否有错误
- 检查通信配置是否正确
保存后页面无变化
- 检查
updateSchema方法是否正确实现
postMessage 通信失败
- 检查 source 标识是否匹配
- 检查消息类型是否匹配
- 检查是否正确响应请求(包含 requestId)