问答题【342/1977】如何基于现有富文本编辑器(如 Slate、TipTap、Monaco)扩展支持 AIGC 插件?比如一键生成段落或续写?

难度:
2025-04-14 创建
想动手验证一下?打开练习场,写代码、看结果。在线练习

参考答案:

一、核心架构设计

预览

二、编辑器实现方案

Slate.js 实现

1// 注册AI命令扩展 2const withAIGC = (editor: Editor) => { 3 const { insertText } = editor; 4 5 editor.aigenerate = async (type: 'paragraph' | 'continue') => { 6 const selection = editor.selection; 7 if (!selection) return; 8 9 // 获取上下文文本 10 const context = Editor.string(editor, Editor.above(editor)?.trim() || ''; 11 12 // 调用AI服务 13 const aiResult = await fetchAICompletion({ 14 prompt: type === 'continue' ? context : '', 15 mode: type 16 }); 17 18 // 插入结果 19 Transforms.insertText(editor, aiResult, { at: selection }); 20 }; 21 22 return editor; 23}; 24 25// 使用示例 26<button onClick={() => ReactEditor.aigenerate(editor, 'paragraph')}> 27 生成段落 28</button>

三、关键技术实现

1. 上下文感知获取

1// 获取光标前后各200字符作为上下文 2function getEditorContext(editor) { 3 const { selection } = editor; 4 const range = { 5 anchor: { path: selection.anchor.path, offset: Math.max(0, selection.anchor.offset - 200) }, 6 focus: { path: selection.focus.path, offset: selection.focus.offset + 200 } 7 }; 8 return Editor.string(editor, range); 9}

2. 节流请求优化

1const aiRequestQueue = new Map(); 2 3async function throttledAIRequest(key, prompt) { 4 if (aiRequestQueue.has(key)) { 5 return aiRequestQueue.get(key); 6 } 7 8 const promise = fetchAICompletion(prompt) 9 .finally(() => aiRequestQueue.delete(key)); 10 11 aiRequestQueue.set(key, promise); 12 return promise; 13}

3. Markdown兼容处理

1// 转换AI生成的Markdown为编辑器节点 2function parseAIContent(content) { 3 const md = new Remarkable(); 4 const tokens = md.parse(content, {}); 5 6 return tokens.map(token => { 7 if (token.type === 'paragraph_open') { 8 return { type: 'paragraph', children: [] }; 9 } 10 // ...其他转换规则 11 }); 12}

四、用户体验优化

1. 渐进式加载动画

1const [isGenerating, setIsGenerating] = useState(false); 2 3const handleGenerate = async () => { 4 setIsGenerating(true); 5 try { 6 const result = await editor.aigenerate(); 7 // 逐字插入效果 8 for (let i = 0; i < result.length; i++) { 9 await new Promise(r => setTimeout(r, 20)); 10 Transforms.insertText(editor, result[i], { at: editor.selection }); 11 } 12 } finally { 13 setIsGenerating(false); 14 } 15};

2. 多候选结果处理

1// 显示候选结果浮层 2function showAIOptions(editor, results) { 3 const popup = document.createElement('div'); 4 popup.className = 'ai-options-popup'; 5 6 results.forEach((text, i) => { 7 const option = document.createElement('div'); 8 option.textContent = text.substr(0, 50); 9 option.onclick = () => { 10 Transforms.insertText(editor, text); 11 document.body.removeChild(popup); 12 }; 13 popup.appendChild(option); 14 }); 15 16 // 定位到光标下方 17 const [node, path] = Editor.node(editor, editor.selection); 18 const domNode = ReactEditor.toDOMNode(editor, node); 19 const rect = domNode.getBoundingClientRect(); 20 popup.style.top = `${rect.bottom}px`; 21 popup.style.left = `${rect.left}px`; 22 document.body.appendChild(popup); 23}

3. 错误恢复机制

1// 失败时保留草稿并重试 2async function safeAIGenerate(editor, retries = 3) { 3 const originalText = Editor.string(editor, editor.selection); 4 try { 5 return await editor.aigenerate(); 6 } catch (error) { 7 if (retries > 0) { 8 Transforms.insertText(editor, originalText); 9 return safeAIGenerate(editor, retries - 1); 10 } 11 throw error; 12 } 13}

五、生产环境注意事项

  1. API安全:

    • 使用JWT签名请求
    • 限制用户每分钟调用次数
    1// 请求签名示例 2const signRequest = (prompt) => { 3 const nonce = crypto.randomUUID(); 4 const signature = crypto.createHmac('sha256', SECRET) 5 .update(`${prompt}:${nonce}`) 6 .digest('hex'); 7 return { prompt, nonce, signature }; 8};
  2. 本地缓存:

    1// 使用IndexedDB缓存常见请求 2const cacheAIResponse = async (prompt, result) => { 3 const db = await openDB('ai-cache', 1); 4 await db.put('responses', { prompt, result, timestamp: Date.now() }); 5};
  3. 性能监控:

    1// 埋点记录生成耗时 2const start = performance.now(); 3const result = await fetchAICompletion(prompt); 4trackEvent('ai_generate', { 5 duration: performance.now() - start, 6 length: result.length 7});

最近更新时间:2026-11-17

赞赏支持

题库维护不易,您的支持就是我们最大的动力!