create-react-app中使用CodeMirror轻量级代码编辑器,实现自动提示,自动补全代码问题

构建create-react-app,这里忽略······

安装   代码编辑器 CodeMirror 的轻量级 React 组件

npm install @uiw/react-codemirror --save

安装好了之后,就可以直接引入使用了,直接上代码:

import CodeMirror from '@uiw/react-codemirror';
import 'codemirror/theme/monokai.css';
import 'codemirror/addon/selection/active-line'
import 'codemirror/addon/hint/javascript-hint'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/show-hint.css'


class App extends React.Component{
    render() {
      const code = 'var a = 0;';
        return (
            
); } } export default App;

代码解析:

import CodeMirror from '@uiw/react-codemirror';    //引入组件,然后这个标签组件就是代码编辑器了

import 'codemirror/theme/monokai.css';    //主题样式 引入后 配置其属性  theme: 'monokai'

import 'codemirror/addon/hint/javascript-hint'    //光标所在行突出颜色   引入后 配置其属性  styleActiveLine: true

//JavaScript代码提示功能需要引入三个依赖

import 'codemirror/addon/hint/javascript-hint'    //js代码提示语库

import 'codemirror/addon/hint/show-hint'    //代码提示功能

import 'codemirror/addon/hint/show-hint.css'    //代码提示样式

以上三个依赖引入后,配置其属性    

mode: 'JavaScript',  //提示语言
extraKeys: {"Ctrl": "autocomplete"},//ctrl可以弹出提示

这样就有了JavaScript的代码提示,这里仅仅用了JavaScript来示范,其他语言同理。

create-react-app中使用CodeMirror轻量级代码编辑器,实现自动提示,自动补全代码问题_第1张图片

到这里虽然有了提示,但是按一个快捷键才会触发的提示,远没达到我们想要的自动提示的效果。

接下来,想要做成自动提示,一般想到的是,从onChange 函数入手

值得注意的是,CodeMirror不能用onChange函数来触发代码提示功能,会死循环。。

我们用的是 onCursorActivity 事件函数  //当鼠标点击内容区、选中内容、修改内容时被触发

onCursorActivity={e => e.showHint()/*调用显示提示*/}

这样自动提示功能就有了。

但是呢,还有问题需要处理,就是点击和选中,换行,空格,等都会触发提示,而且关键词删除不了等问题。

这样就比较尴尬了,需要优化一下。

打开 import 'codemirror/addon/hint/javascript-hint' 这个的源码。

先找到 scriptHint 函数 ,在该函数最后的 return 调 getCompletions函数,这里开始做手脚。

create-react-app中使用CodeMirror轻量级代码编辑器,实现自动提示,自动补全代码问题_第2张图片

献上改动的代码部分:

// If it is a property, find out what it is a property of.
    while (tprop.type == "property") {
      tprop = getToken(editor, Pos(cur.line, tprop.start));
      if (tprop.string != ".") return;
      tprop = getToken(editor, Pos(cur.line, tprop.start));
      if (!context) var context = [];
      context.push(tprop);
    }

    var uValues = this.uValues;//获取上次的内容
    this.uValues = editor.getValue();//更新上次内容
    var isUpdate = uValues==this.uValues;//比较内容是否和上次的一样

    return {list: getCompletions(token, context,isUpdate, keywords, options),
            from: Pos(cur.line, token.start),
            to: Pos(cur.line, token.end)};
  }

找到 getCompletions 函数,添加一下代码:

create-react-app中使用CodeMirror轻量级代码编辑器,实现自动提示,自动补全代码问题_第3张图片

献上改动的代码:

function getCompletions(token, context,isUpdate, keywords, options) {
    //这里是优化 点击,选中和改动 都会触发提示,而且关键词删除不了等问题
    var start = this.start;
    var end = this.end;
    this.start = token.start;
    this.end = token.end;
    if (token.type == null || (start == this.start  && !((end - this.end) == -1))||isUpdate) {
      return {list: {}};
    }

···

这样就可以完美解决以上问题了。

不过除了关键词的提示外,我们还可以添加我们自定义的提示词哦。

create-react-app中使用CodeMirror轻量级代码编辑器,实现自动提示,自动补全代码问题_第4张图片

create-react-app中使用CodeMirror轻量级代码编辑器,实现自动提示,自动补全代码问题_第5张图片

create-react-app中使用CodeMirror轻量级代码编辑器,实现自动提示,自动补全代码问题_第6张图片

献上全部代码:

import React from 'react';
import CodeMirror from '@uiw/react-codemirror';
import 'codemirror/theme/monokai.css';
import 'codemirror/addon/hint/javascript-hint'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/selection/active-line'

class App extends React.Component{

  MyOnCursorActivity = e =>{
    //把自定义的提示词传进去
    e.ukeys = ["aaaa","bbbb","cccc"];
    //调用显示提示
    e.showHint()
  }

    render() {
      const code = 'var a = 0;';
        return (
            
this.MyOnCursorActivity(e)} options={{ theme: 'monokai', mode: 'JavaScript', styleActiveLine: true }} />
); } } export default App;
import 'codemirror/addon/hint/javascript-hint' 改动后的代码:
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  var Pos = CodeMirror.Pos;

  function forEach(arr, f) {
    for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
  }

  function arrayContains(arr, item) {
    if (!Array.prototype.indexOf) {
      var i = arr.length;
      while (i--) {
        if (arr[i] === item) {
          return true;
        }
      }
      return false;
    }
    return arr.indexOf(item) != -1;
  }

  function scriptHint(editor, keywords, getToken, options) {
    // Find the token at the cursor
    var cur = editor.getCursor(), token = getToken(editor, cur);
    if (/\b(?:string|comment)\b/.test(token.type)) return;
    var innerMode = CodeMirror.innerMode(editor.getMode(), token.state);
    if (innerMode.mode.helperType === "json") return;
    token.state = innerMode.state;

    // If it's not a 'word-style' token, ignore the token.
    if (!/^[\w$_]*$/.test(token.string)) {
      token = {start: cur.ch, end: cur.ch, string: "", state: token.state,
               type: token.string == "." ? "property" : null};
    } else if (token.end > cur.ch) {
      token.end = cur.ch;
      token.string = token.string.slice(0, cur.ch - token.start);
    }

    var tprop = token;
    // If it is a property, find out what it is a property of.
    while (tprop.type == "property") {
      tprop = getToken(editor, Pos(cur.line, tprop.start));
      if (tprop.string != ".") return;
      tprop = getToken(editor, Pos(cur.line, tprop.start));
      if (!context) var context = [];
      context.push(tprop);
    }

    var ukeys =  editor.ukeys;//获取用户的自定义的单词
    var uValues = this.uValues;//获取上次的内容
    this.uValues = editor.getValue();//更新上次内容
    var isUpdate = uValues==this.uValues;//比较内容是否和上次的一样

    return {list: getCompletions(token, context,ukeys,isUpdate, keywords, options),
            from: Pos(cur.line, token.start),
            to: Pos(cur.line, token.end)};
  }

  function javascriptHint(editor, options) {
    return scriptHint(editor, javascriptKeywords,
                      function (e, cur) {return e.getTokenAt(cur);},
                      options);
  };
  CodeMirror.registerHelper("hint", "javascript", javascriptHint);

  function getCoffeeScriptToken(editor, cur) {
  // This getToken, it is for coffeescript, imitates the behavior of
  // getTokenAt method in javascript.js, that is, returning "property"
  // type and treat "." as indepenent token.
    var token = editor.getTokenAt(cur);
    if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
      token.end = token.start;
      token.string = '.';
      token.type = "property";
    }
    else if (/^\.[\w$_]*$/.test(token.string)) {
      token.type = "property";
      token.start++;
      token.string = token.string.replace(/\./, '');
    }
    return token;
  }

  function coffeescriptHint(editor, options) {
    return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options);
  }
  CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint);

  var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
                     "toUpperCase toLowerCase split concat match replace search").split(" ");
  var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
                    "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
  var funcProps = "prototype apply call bind".split(" ");
  var javascriptKeywords = ("break case catch class const continue debugger default delete do else export extends false finally for function " +
                  "if in import instanceof new null return super switch this throw true try typeof var void while with yield").split(" ");
  var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
                  "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");

  function forAllProps(obj, callback) {
    if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {
      for (var name in obj) callback(name)
    } else {
      for (var o = obj; o; o = Object.getPrototypeOf(o))
        Object.getOwnPropertyNames(o).forEach(callback)
    }
  }

  function getCompletions(token, context,ukeys,isUpdate, keywords, options) {
    //这里是优化 点击,选中和改动 都会触发提示,而且关键词删除不了等问题
    var start = this.start;
    var end = this.end;
    this.start = token.start;
    this.end = token.end;
    if (token.type == null || (start == this.start  && !((end - this.end) == -1))||isUpdate) {
      return {list: {}};
    }

    var found = [], start = token.string, global = options && options.globalScope || window;
    function maybeAdd(str) {
      if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
    }
    function gatherCompletions(obj) {
      if (typeof obj == "string") forEach(stringProps, maybeAdd);
      else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
      else if (obj instanceof Function) forEach(funcProps, maybeAdd);
      if(ukeys!=null&&ukeys.length>0){
        forEach(ukeys,maybeAdd);//添加传进来的自定义的单词
      }
      forAllProps(obj, maybeAdd)
    }

    if (context && context.length) {
      // If this is a property, see if it belongs to some object we can
      // find in the current environment.
      var obj = context.pop(), base;
      if (obj.type && obj.type.indexOf("variable") === 0) {
        if (options && options.additionalContext)
          base = options.additionalContext[obj.string];
        if (!options || options.useGlobalScope !== false)
          base = base || global[obj.string];
      } else if (obj.type == "string") {
        base = "";
      } else if (obj.type == "atom") {
        base = 1;
      } else if (obj.type == "function") {
        if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
            (typeof global.jQuery == 'function'))
          base = global.jQuery();
        else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function'))
          base = global._();
      }
      while (base != null && context.length)
        base = base[context.pop().string];
      if (base != null) gatherCompletions(base);
    } else {
      // If not, just look in the global object and any local scope
      // (reading into JS mode internals to get at the local and global variables)
      for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
      for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
      if (!options || options.useGlobalScope !== false)
        gatherCompletions(global);
      forEach(keywords, maybeAdd);
    }
    return found;
  }
});

如果需要显示用户前面输入过的代码,变量等。还可以用正则表达式,把编辑器的内容拆分出来然后传进提示词里即可:

MyOnCursorActivity 函数,稍微做一下修改如下:

MyOnCursorActivity = e =>{
    //获取用户当前的编辑器中的编写的代码
    var words = e.getValue() + "";
    //利用正则取出用户输入的所有的英文的字母
    words = words.replace(/[a-z]+[\-|\']+[a-z]+/ig, '').match(/([a-z]+)/ig);
    //把单个字母去除掉
    var isFor=true;
    while (isFor){
      if(words==null){break}
      isFor=false;
      for(var i=0;i

这个就可以是挺完美的了。

实现的效果案例 : http://mcshop.vip/js/

你可能感兴趣的:(react)