最近有這樣一個需求,網頁中須要作一個SQL編輯器,要求有一些基本的SQL編輯器功能,最後選中基於比較完善的CodeMirror來開發相關功能。本片文章涵蓋的基本功能包括CodeMirror在React中的引入、輸入聯想、執行選中部分SQL等功能。由於項目基於React來開發,因此此篇指南也使用React作爲示例。css
npm install codemirror --save
複製代碼
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組件:react
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組件sql
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編輯器基本功能,關鍵部分代碼已作註釋。接下來詳細解釋下其中的細節。shell
自動補全主要是依靠設置CodeMirror中的hintOptions來實現的,固然首先須要將依賴的hint包都引入。npm
const data = { table1: [''], table2: [''], table3: [''] };
cm.on('inputRead', (cm, change) => {
cm.setOption('hintOptions', {
tables: data,
completeSingle: false
});
cm.execCommand('autocomplete');
});
複製代碼
其中cm是CodeMirror中inputRead事件的第一個參數,其實也是CodeMirror實例自己。 總結下自動補全實現的流程就是:編程
執行選中部分代碼關鍵是要監聽選中事件,獲取選中部份內容,這兩個方法分別是cursorActivity和getSelection。bash
cm.on('cursorActivity', (cm) => {
cm.getSelection(); // 選中內容
});
複製代碼
cm爲CodeMirror實例,經過這兩個個簡單的方法,能夠實現獲取選中部份內容。判斷選中內容不爲空時展現執行部分SQL便可。app
CodeMirror是一個功能較完善的代碼編輯框,其支持不少種編程語言,以上僅展現了SQL的,該框架文檔比較難啃,歡迎有依賴該框架作開發的小夥伴們一塊兒交流。若是看了這篇文章對我總結的方法有任何問題,也歡迎留言,隨緣回覆。框架