import { useState, useEffect } from 'react'; interface SimpleCodeEditorProps { id: string; initialValue?: string; language?: 'javascript' | 'python'; onChange?: (value: string) => void; } export function SimpleCodeEditor({ id, initialValue = '', language = 'javascript', onChange }: SimpleCodeEditorProps) { const [code, setCode] = useState(initialValue || getDefaultCode(language)); const [copySuccess, setCopySuccess] = useState(false); // 复制代码到剪贴板 const copyToClipboard = () => { navigator.clipboard.writeText(code).then(() => { setCopySuccess(true); setTimeout(() => setCopySuccess(false), 2000); }); }; // 处理代码变化 const handleChange = (e: React.ChangeEvent) => { const value = e.target.value; setCode(value); if (onChange) { onChange(value); } }; // 初始示例代码 function getDefaultCode(lang: string) { if (lang === 'javascript') { return `// 示例代码 function checkRule(data) { // data 包含抽取的字段 try { // 在此编写检查逻辑 if (data.fieldName && condition) { return { pass: true, message: "检查通过" }; } else { return { pass: false, message: "检查不通过,原因:..." }; } } catch (error) { return { pass: false, message: "执行出错:" + error.message }; } }`; } else { return `# 示例代码 def check_rule(data): # data 包含抽取的字段 try: # 在此编写检查逻辑 if 'field_name' in data and condition: return { 'pass': True, 'message': "检查通过" } else: return { 'pass': False, 'message': "检查不通过,原因:..." } except Exception as error: return { 'pass': False, 'message': f"执行出错:{str(error)}" }`; } } // 当语言变化时更新代码 useEffect(() => { if (!initialValue) { setCode(getDefaultCode(language)); } }, [language, initialValue]); return (
{language === 'javascript' ? 'script.js' : 'script.py'}
{copySuccess && (
代码已复制到剪贴板
)}
); }