背景
最近有这样一个需求,网页中需要做一个SQL编辑器,要求有一些基本的SQL编辑器功能,最后选中基于比较完善的CodeMirror来开发相关功能。本片文章涵盖的基本功能包括CodeMirror在React中的引入、输入联想、执行选中部分SQL等功能。因为项目基于React来开发,所以此篇指南也使用React做为示例。
引入
- 执行CodeMirror安装命令(版本5.40.2)
npm install codemirror --save
- React组件中引入CodeMirror
import React from 'react';
import codemirror from 'codemirror';
require('codemirror/codemirror.css'); // CodeMirrory原生样式
require('codemirror/mode/sql/sql');
require('codemirror/mode/shell/shell');
require('codemirror/addon/display/placeholder');
require('codemirror/addon/hint/show-hint.css'); // 用来做代码提示
require('codemirror/addon/hint/show-hint.js'); // 用来做代码提示
require('codemirror/addon/hint/sql-hint.js'); // 用来做代码提示
将CodeMirror做为组件开发
CodeMirror组件:
class CodeMirror extends React.Component {
static defaultProps = {
useFocus: true
}
componentDidMount() {
this.paste = '';
const {
onChange, onBlur, options, value = '', onScroll,
onCursorActivity, onInputRead,
} = this.props;
this.editor = codemirror(this.ref, {
indentWithTabs: true,
smartIndent: true,
lineNumbers: true,
matchBrackets: true,
autofocus: true,
extraKeys: { Tab: 'autocomplete' },
hintOptions: { completeSingle: false }
lineWrapping: true,
value
});
const { editor, setCursor } = this;
setCursor(editor, true);
const changeDelay = debounce((e) => {
setCursor(e);
onChange && onChange(e.getValue());
}, 300);
editor.on('change', changeDelay);
editor.on('blur', (e) => {
setCursor(e);
onBlur && onBlur(e.getValue());
});
editor.on('cursorActivity', onCursorActivity);
editor.on('inputRead', (cm, change) => onInputRead(cm, change, editor));
onScroll && editor.on('scroll', onScroll);
}
shouldComponentUpdate({ paste = '', value = '', }) {
const { editor } = this;
if (paste !== this.paste) {
this.focus();
editor.replaceSelection(` ${paste}`);
this.paste = paste;
} else if (value !== editor.getValue()) {
editor.setOption('value', value);
editor.setValue(value);
this.fixBottom();
this.focus();
}
return false;
}
setCursor = (editor, toEnd) => {
const { line, ch } = editor.doc.getCursor();
this.cursor = { ch, line: toEnd ? line + 1 : line };
}
focus() {
const { editor } = this;
const { options: { readOnly }, useFocus } = this.props;
if (readOnly) return;
if (!useFocus) return;
editor.focus();
editor.setCursor({ ...this.cursor }, readOnly);
}
fixBottom() {
const { fixBottom } = this.props;
if (!fixBottom) return;
const { editor } = this;
const { height } = editor.getScrollInfo();
editor.scrollTo(0, height);
}
render() {
const { className, options: { readOnly } } = this.props;
return (
<div
className={`${className} ${readOnly && 'readOnly'}`}
ref={(self) => { this.ref = self; }}
/>
);
}
}
子组件调用CodeMirror组件
class SqlConsole extends Component {
static defaultProps = {
value: '',
sqlPaste: '',
onChange: () => {},
}
state = {
showModal: false,
source: {},
};
uuid = '';
onCursorActivity = (cm) => {
if (!cm.getSelection()) {
console.log(cm.getSelection()); // 获取到选中部分内容,用来实现执行部分内容
}
}
onInputRead = async (cm, change, editor) => {
const { text } = change;
const dechars = [
'.',
];
const autocomplete = dechars.includes(text[0]);
if (autocomplete) {
const data = getTableList(); // 获取库表列表
editor.setOption('hintOptions', {
tables: data,
completeSingle: false
});
cm.execCommand('autocomplete');
} else {
const tableName = getTableList(); // 获取表列表
editor.setOption('hintOptions', {
tables: tableName,
completeSingle: false
});
}
cm.execCommand('autocomplete');
}
render() {
const { sqlPaste, onChange, } = this.props;
return (
<CodeMirror
className="sql"
value={pane.sql}
paste={sqlPaste}
onChange={sql => { onChange(sql); }} // sql变化事件
onCursorActivity={(cm) => this.onCursorActivity(cm)} // 用来完善选中监听
onInputRead={// 自动补全
(cm, change, editor) => this.onInputRead(cm, change, editor)
}
/>
);
}
}
通过以上两个父子模块,可实现SQL编辑器基本功能,关键部分代码已做注释。接下来详细解释下其中的细节。
自动补全
自动补全主要是依靠设置CodeMirror中的hintOptions来实现的,当然首先需要将依赖的hint包都引入。
const data = { table1: [''], table2: [''], table3: [''] };
cm.on('inputRead', (cm, change) => {
cm.setOption('hintOptions', {
tables: data,
completeSingle: false
});
cm.execCommand('autocomplete');
});
其中cm是CodeMirror中inputRead事件的第一个参数,其实也是CodeMirror实例本身。
总结下自动补全实现的流程就是:
- 通过on方法绑定inputRead方法给CodeMirror
- inputRead中通过setOption方法设置hintOptions,从而实现修改自动补全内容
- inputRead最后执行 cm.execCommand('autocomplete') 执行自动补全
执行选中部分
执行选中部分代码关键是要监听选中事件,获取选中部分内容,这两个方法分别是cursorActivity和getSelection。
cm.on('cursorActivity', (cm) => {
cm.getSelection(); // 选中内容
});
cm为CodeMirror实例,通过这两个个简单的方法,可以实现获取选中部分内容。判断选中内容不为空时展示执行部分SQL即可。
总结
CodeMirror是一个功能较完善的代码编辑框,其支持很多种编程语言,以上仅展示了SQL的,该框架文档比较难啃,欢迎有依赖该框架做开发的小伙伴们一起交流。如果看了这篇文章对我总结的方法有任何问题,也欢迎留言,随缘回复。
网友评论