import React, { Component, useRef, useEffect } from 'react'; import { EditorView, keymap, lineNumbers, highlightActiveLineGutter, highlightSpecialChars, dropCursor, } from '@codemirror/view'; import { EditorState, Prec } from '@codemirror/state'; import { javascript } from '@codemirror/lang-javascript'; import { githubLightInit } from '@uiw/codemirror-theme-github'; import { defaultKeymap, historyKeymap, history } from '@codemirror/commands'; import { indentOnInput, bracketMatching } from '@codemirror/language'; import { closeBrackets, autocompletion } from '@codemirror/autocomplete'; import './index.less'; interface FuncEditorProps { value: string; // 初始代码内容 onChange?: (value: string) => void; // 代码内容变化时的回调函数 } const customTheme = EditorView.theme({ '&': { fontSize: '13px', width: '500px', lineHeight: 1.4, border: '1px solid #ccc', borderRadius: '4px', padding: '0', maxHeight: '205px', fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace', }, '.cm-content': { padding: '0', }, '.cm-editor': { border: '1px solid #d9d9d9', borderRadius: '6px', }, '.cm-scroller': { fontFamily: 'inherit', }, }); // 自定义基础设置,排除 foldGutter const customBasicSetup = [ lineNumbers(), highlightActiveLineGutter(), highlightSpecialChars(), history(), dropCursor(), EditorState.allowMultipleSelections.of(true), indentOnInput(), bracketMatching(), closeBrackets(), autocompletion(), keymap.of([...defaultKeymap, ...historyKeymap]), ]; // 定义中文标点到英文标点的映射 const punctuationMap: { [key: string]: string } = { ',': ',', '。': '.', ':': ':', ';': ';', '?': '?', '!': '!', '(': '(', ')': ')', '【': '[', '】': ']', '「': '"', '」': '"', '“': '"', '”': '"', '‘': "'", '’': "'", '《': '<', '》': '>', '…': '...', '—': '-', '–': '-', ' ': ' ', }; // 简单的 JavaScript 代码格式化函数 const formatJavaScript = (code: string): string => { let formatted = code; let indentLevel = 0; const indentSize = 4; // 缩进大小与lang-javascript中保持一致 const lines: string[] = []; // 1. 移除多余的空白字符,但保留换行符 formatted = formatted.replace(/[ \t]+/g, ' ').trim(); // 2. 中文标点转换为英文标点 let tempFormatted = ''; for (let i = 0; i < formatted.length; i++) { const char = formatted[i]; tempFormatted += punctuationMap[char] || char; } formatted = tempFormatted; // 3. 在特定字符前后添加换行和空格 formatted = formatted // 添加换行 .replace(/;/g, ';\n') .replace(/{/g, ' {\n') .replace(/}/g, '\n}\n') // 添加空格 .replace(/,/g, ', ') // .replace(/\+/g, ' + ') // .replace(/\*/g, ' * ') // .replace(/\//g, ' / ') // .replace(//g, ' > ') // 比较操作符 .replace(/===/g, ' === ') .replace(/!==/g, ' !== ') // 逻辑操作符 .replace(/&&/g, ' && ') .replace(/\|\|/g, ' || ') .replace(/\(/g, '(') .replace(/\)/g, ')'); // 4. 清理多余空格(再次执行,确保规则应用后产生的多余空格被清理) formatted = formatted.replace(/[ \t]+/g, ' '); // 5. 分割成行并处理缩进 (这部分逻辑保持不变) const rawLines = formatted.split('\n'); for (let line of rawLines) { line = line.trim(); if (!line) continue; if (line.includes('}')) { indentLevel = Math.max(0, indentLevel - 1); } const indentedLine = ' '.repeat(indentLevel * indentSize) + line; lines.push(indentedLine); if (line.includes('{')) { indentLevel++; } } return lines.join('\n'); }; // 格式化命令 const formatCode = (view: EditorView) => { try { const currentCode = view.state.doc.toString(); const cursorPos = view.state.selection.main.head; // 使用自定义格式化函数 const formattedCode = formatJavaScript(currentCode); // 如果代码有变化,则更新编辑器内容 if (formattedCode !== currentCode) { // 计算格式化后光标的新位置 const newCursorPos = Math.min(cursorPos, formattedCode.length); view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: formattedCode, }, selection: { anchor: newCursorPos, head: newCursorPos }, }); } return true; // 阻止默认行为 } catch (error) { console.error('代码格式化失败:', error); return false; } }; // 格式化代码快捷键映射 const formatKeymap = keymap.of([ { key: 'Shift-Alt-f', run: formatCode, preventDefault: true, }, ]); const isEnglishChar = (char: string): boolean => { // 英文字母、数字和常用英文符号的正则表达式 const englishRegex = /^[a-zA-Z0-9`~!@#$%^&*()_\-+={}\[\]|\\:;"'<>,.?/\s]$/; return englishRegex.test(char); }; // 添加一个函数转换中文标点为英文标点 const convertChinesePunctuation = (text: string): string => { let result = ''; for (let i = 0; i < text.length; i++) { const char = text[i]; result += punctuationMap[char] || char; } return result; }; const FuncEditorSetter: React.FC = ({ value = '', onChange }) => { const editorRef = useRef(null); const viewRef = useRef(null); useEffect(() => { if (editorRef.current && !viewRef.current) { const startState = EditorState.create({ doc: value, extensions: [ customBasicSetup, javascript(), githubLightInit({ settings: { caret: '#111', // 光标颜色 fontFamily: 'monospace', }, }), customTheme, // 添加输入处理器 EditorView.inputHandler.of((view, from, to, text) => { const convertedText = convertChinesePunctuation(text); if (text !== convertedText) { const newCursorPos = from + convertedText.length; view.dispatch({ changes: { from, to, insert: convertedText }, selection: { anchor: newCursorPos, head: newCursorPos }, // 设置光标位置 }); return true; // 返回 true 表示已处理此输入 } // 如果没有中文标点或者已经是转换后的文本,则检查是否为非英文符号(排除中文) for (let i = 0; i < convertedText.length; i++) { const char = convertedText[i]; // 允许中文字符、大写字母和数字 if (!isEnglishChar(char) && !/[\u4e00-\u9fa5A-Z0-9]/.test(char)) { // 如果包含不允许的非英文符号(且不是中文、大写字母、数字),阻止输入 return true; // 返回 true 表示已处理此输入,不再继续处理 } } // 如果全是允许的字符,返回 false 让 CodeMirror 继续处理 return false; }), // 添加格式化快捷键,使用 Prec.highest 确保优先级 Prec.highest(formatKeymap), EditorView.updateListener.of((update) => { if (update.docChanged && onChange) { onChange(update.state.doc.toString()); } }), // 添加失焦事件监听器 EditorView.domEventHandlers({ blur: (event, view) => { formatCode(view); }, }), ], }); viewRef.current = new EditorView({ state: startState, parent: editorRef.current, }); } return () => { if (viewRef.current) { viewRef.current.destroy(); viewRef.current = null; } }; }, []); // 当外部 value 变化时更新编辑器内容 useEffect(() => { if (viewRef.current && value !== viewRef.current.state.doc.toString()) { viewRef.current.dispatch({ changes: { from: 0, to: viewRef.current.state.doc.length, insert: value, }, }); } }, [value]); return
; }; export default class extends Component { static displayName = 'FuncEditorSetter'; render() { return ; } }