Mermaid Live Editor
社区案例 #1
src/lib/util/editorAPI.ts
src/routes/+layout.svelte
Mermaid Live Editor 是 Mermaid 官方的在线图表编辑器,支持流程图、时序图、类图等十余种图表语法。我们通过 不到 30 行胶水代码 接入了 rtc-agent,让 AI 能够:
- 🗣️ 根据自然语言描述生成 Mermaid 代码
- ✍️ 自动写入编辑器并触发实时预览
- ✅ 主动调用语法校验,发现错误后自修复
- 🎨 全程无需用户手写一行代码
上方视频展示了用户用自然语言描述需求 → AI 自动写代码 → 校验 → 渲染的完整过程。
整个接入只改了 2 个核心文件,对上游源码 零侵入:
| 文件 | 改动 | 行数 |
|---|---|---|
src/routes/+layout.svelte | 加载 rtc-agent、挂载组件、配置 agentConfig | +98 |
src/lib/util/editorAPI.ts | 暴露 window.editorAPI 程序化接口 | +105(新增) |
第一步:暴露宿主状态 API
Section titled “第一步:暴露宿主状态 API”rtc-agent 的核心设计是 “Agent 不碰你的源码,只通过声明式 API 操作状态”。因此接入的第一步是把应用的关键状态暴露到 window 上:
export interface EditorAPI { getCode(): string; // 获取当前编辑器代码 getDiagramType(): string; // 获取图表类型(flowchart/sequence/...) setCode(code: string): void; // 替换编辑器内容并触发校验 validate(): ValidateResult; // 返回校验结果(含错误位置) waitForReady(): Promise<void>; // 等待异步校验完成}
// 挂到 window,让 rtc-agent 的工具能调用window.editorAPI = { getCode, setCode, validate, getDiagramType, waitForReady };这个 API 的设计原则:
- 读写对称:有
getCode就有setCode,Agent 能读也能写 - 校验闭环:写完代码后 Agent 会主动调
validate(),发现错误自修复 - 异步感知:
waitForReady()让 Agent 知道校验何时完成,避免读到过期结果
第二步:声明 Agent 身份与工具
Section titled “第二步:声明 Agent 身份与工具”使用 createRtcAgent 工厂函数创建 rtc-agent 实例:
<script> import { z, withMeta, createRtcAgent } from '@rtc-agent/component'; import type { RtcAgentWithLifecycle } from '@rtc-agent/component'; import { onMount, onDestroy } from 'svelte'; import { base } from '$app/paths'; import { mode } from 'mode-watcher';
let rtcAgent: RtcAgentWithLifecycle | null = null;
onMount(() => { rtcAgent = createRtcAgent({ agentDescription: 'Mermaid Live Editor - AI assistant for creating diagrams', agentName: 'MermaidEditor', appLabel: 'Mermaid AI', groups: [{ description: 'Editor operations for reading and writing Mermaid code', name: 'editor', functions: [ { name: 'getCode', description: 'Get the current Mermaid code from the editor', handler: () => window.editorAPI.getCode(), returns: { schema: { description: 'The current Mermaid code', type: 'string' } } }, { name: 'setCode', description: 'Replace the entire editor content with new Mermaid code.', handler: (params: { code: string }) => { window.editorAPI.setCode(params.code); return { success: true }; }, zodSchema: z.object({ code: withMeta(z.string(), { example: 'graph TD\n A-->B' }) .describe('The Mermaid code to write to the editor') }), returns: { schema: { properties: { success: { type: 'boolean' } }, type: 'object' } } }, { name: 'getDiagramType', description: 'Get the detected diagram type', handler: () => window.editorAPI.getDiagramType() ?? 'unknown', returns: { schema: { description: 'The diagram type or "unknown"', type: 'string' } } }, { name: 'validate', description: 'Validate the current Mermaid code and return any syntax errors.', handler: () => window.editorAPI.validate(), returns: { schema: { description: 'Validation result', type: 'object' } } } ] }], persona: `You are a helpful Mermaid diagram assistant. You help users create and editMermaid diagrams through natural language conversation. You can write Mermaid code,check for syntax errors, and fix issues. Always validate your code after writing itto ensure correctness. When creating diagrams, explain what you're drawing and useclear, descriptive node names.`, scenariosURL: `${base}/rtc-agent/scenarios/`, server: { url: 'https://rtc-agent.cherish.chat', redirectUri: `${base}/auth/callback.html` }, theme: mode.current ?? 'light', window: { bubblePosition: { corner: 'bottom-left', offset: { x: 20, y: 20 } } }, workerURL: `${base}/rtc-agent/shared-worker.js`, on: { ready: () => { console.log('[Mermaid AI] RTC Agent ready'); } } });
document.body.appendChild(rtcAgent); });
// Sync host theme changes to <rtc-agent> $effect(() => { if (rtcAgent) { rtcAgent.theme = mode.current ?? 'light'; } });
onDestroy(() => { if (rtcAgent) { rtcAgent.destroy(); rtcAgent = null; } });</script>第三步:主题同步(可选)
Section titled “第三步:主题同步(可选)”rtc-agent 支持亮色/暗色主题。主题在初始化时通过 theme 属性设置,并可以使用 Svelte 的 $effect 与宿主应用的主题保持同步:
// 监听宿主主题变化,同步到 rtc-agent$effect(() => { if (rtcAgent) { rtcAgent.theme = mode.current ?? 'light'; }});这部分代码已包含在上方的第二步示例中。
除了上述两个核心文件,还新增了:
| 文件 | 用途 |
|---|---|
src/rtc-agent.d.ts | rtc-agent TypeScript 类型声明 |
static/auth/callback.html | OAuth 回调页 |
static/rtc-agent/scenarios/ | 3 个预置场景模板 + manifest |
整个接入 不修改上游任何源码,改动率 < 2%。rtc-agent 通过本地构建产物加载(生产环境可换为 CDN),3MB 的 bundle 不进仓库。
rtc-agent/mermaid-live-editor(fork 自 mermaid-js/mermaid-live-editor)