import React, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react'; import { basicSetup } from 'codemirror'; import { EditorState } from '@codemirror/state'; import { EditorView, ViewUpdate } from '@codemirror/view'; import placeholderTag from './placeholder-tag'; import { FormulaType } from '@/constants'; const baseTheme = EditorView.baseTheme({ // 字段样式 '.cm-tag': { paddingLeft: '6px', paddingRight: '6px', paddingTop: '3px', paddingBottom: '3px', marginLeft: '3px', marginRight: '3px', backgroundColor: '#178cdf', borderRadius: '4px', color: '#fff', }, // 函数样式 '.cm-fn': { color: '#708', fontWeight: 'bold', fontSize: '14px', }, }); const Editor = forwardRef((props: any, ref: any) => { const view = useRef(null); const editorRef = useRef(null); const { value, inputChange } = props; // 定义一个函数,用于创建监听 = 输入的扩展 const equalsSignListener = (): any => { return EditorView.updateListener.of((update: ViewUpdate) => { if (update.docChanged) { const changes = update.changes; changes.iterChanges((fromA, toA, fromB, toB, inserted) => { const insertedText = inserted.toString(); if (insertedText === '=') { // 在这里触发你想要的事件 inputChange && inputChange(); // 你可以添加更多自定义逻辑,比如显示提示框、插入特定内容等 } }); } }); }; useEffect(() => { view.current = new EditorView({ state: EditorState.create({ doc: value, extensions: [basicSetup, baseTheme, placeholderTag, equalsSignListener()], }), parent: editorRef.current as Element | undefined, }); return () => { view?.current?.destroy(); // 注意:此后此处要随组件销毁 view.current = null; }; }, []); useImperativeHandle(ref, () => ({ /** * @description 插入文本并设置光标位置 */ insertText: insertText, getValue: getValue, })); const insertText = (text: string, type: 'fn' | 'opera' | 'tag' = 'tag') => { const value = view.current; console.log('insert', view, value); if (value) { let content = `[[${text}]]`; if (type === FormulaType.OPERA) { content = text; } else if (type === FormulaType.FN) { content = `{{${text}}}()`; } const selection = value.state.selection; if (!selection.main.empty) { // 如果选中文本,则替换选中文本 const from = selection.main.from; const to = selection.main.to; const anchor = type === FormulaType.TAG || type === FormulaType.OPERA ? from + content.length : from + content.length - 1; const transaction = value!.state.update({ changes: { from, to, insert: content }, // 在当前光标位置插入标签 selection: { anchor, }, // 指定新光标位置 }); value.dispatch(transaction); } else { // 如果没有选中文本,则插入标签 const pos = selection.main.head; const anchor = type === FormulaType.TAG || type === FormulaType.OPERA ? pos + content.length : pos + content.length - 1; const transaction = value.state.update({ changes: { from: pos, to: pos, insert: content }, // 在当前光标位置插入标签 selection: { anchor: anchor, }, // 指定新光标位置 }); value.dispatch(transaction); } setTimeout(() => { value?.focus(); }, 0); } }; const getValue = () => { return view.current?.state.doc.toString(); }; return
; }); export default Editor;