【实战】React 必会第三方插件 —— Ace editor 自定义语法提示


  • [【笔记】Ace editor]:(https://blog.csdn.net/qq_32682301/article/details/128801120)

一、基础设置

ace编辑器语法提示最基础设置如下:

{
    
    
    enableBasicAutocompletion: false, //boolean 或 completer 数组
    enableLiveAutocompletion: false, //boolean 或 completer 数组
}

completer,就是拥有一个 getCompletions(editor, session, pos, prefix, callback) 属性的 object,自定义语法提示可以通过 callback(null, tipsData) 回传

相关逻辑源码:https://github.com/ajaxorg/ace/blob/v1.1.4/lib/ace/ext/language_tools.js

如果 enableBasicAutocompletion 和 enableLiveAutocompletion 的值为 completer 数组,就会覆盖编辑器默认的 completers,不推荐使用

1.enableBasicAutocompletion

设置 enableBasicAutocompletion = true,就会在全局 commands 中增加Autocomplete.startCommand 命令(startCommand.bindKey = “Ctrl-Space|Ctrl-Shift-Space|Alt-Space”)。

2.enableLiveAutocompletion

设置enableLiveAutocompletion = true,就会在输入内容时,弹出语法提示框,但是逻辑代码中忽略了一些情况,如删除(vscode也存在此问题。。。)。所以如果交互要求变动就弹出提示的话,可以在editor绑定的onChange事件中触发命令:

editor.execCommand("startAutocomplete");

二、自定义语法提示

// name 显示的名称;value 插入的值;score 权重(数值越大,提示越靠前);meta 描述
let tipsData = [{
    
    meta: "table", caption: "table", value: "table", score: 100}]
let tipsCompleter = {
    
    
    getCompletions: (editor, session, pos, prefix, callback) => {
    
    
        callback(null, tipsData)
    }
}

1.方法一

editor.completers.push(tipsCompleter);

2.方法二

const langTools = ace.require("ace/ext/language_tools");
langTools.addCompleter(tipsCompleter);

3.方法三

和方法二原理一样:

ace.config.loadModule('ace/ext/language_tools', langTools => {
    
    
    langTools.addCompleter(tipsCompleter)
});
  • https://github.com/ajaxorg/ace/issues/4941

4.方法四

import {
    
     addCompleter } from 'ace-builds/src-noconflict/ext-language_tools';

addCompleter(tipsCompleter);
  • https://github.com/securingsincity/react-ace/issues/338#issuecomment-580086476

三、其他定制化

1.insertMatch

这个方法怎么用文档中并没有找到,在 github 的 issue 中见到几种用法,尝试后记录如下:

我的理解是用于快捷输入模板,例如 sql 输入 s* 插入 select * from table:

let tipsData = [ ...otherTipsData, {
    
     value: 's*', meta: "select 模板", insert: 'select * from table', completer: {
    
    
	insertMatch: (editor, data) => {
    
    
        editor.completer.insertMatch(data.insert)
        // 以下两种方式(姑且看做两种)虽然可插入,但是已输入部分不会覆盖
        // editor.forEachSelection(function() {
    
    
        //     editor.insert(data.insert);
        // })
        // 直接执行可也,效果同上(或许有不同,暂未发现)
        // editor.insert(data.insert);
        
        // 根据插入结尾关键字,自动提示表名
        editor.execCommand('startAutocomplete')
        // 若要对提示内容进行操作,下面即是
        // editor.completer.completions.filtered
	}
}]

tips: 以上代码搭配语法提示(addCompleter)使用

哈哈,思路打开后可以进行 模板选择 + 表名选择 等 的 连招


未完待续。。。欢迎留言一起学习探讨


  • https://github.com/securingsincity/react-ace/issues/338#issuecomment-940487234
  • https://stackoverflow.com/questions/27245959/values-and-captions-in-ace-editor-autocomplete

关键文件:

  • https://github.com/ajaxorg/ace/blob/v1.1.4/lib/ace/ext/language_tools.js

四、拓展学习

1.AceEditor

示例demo:https://securingsincity.github.io/react-ace/

在 react 中使用 AceEditor 需要引入以下两个依赖:

npm install react-ace ace-builds

yarn add react-ace ace-builds

截止2023.02.20,最新版本号为:

  • react-ace:10.1.0
  • ace-builds:1.15.2

代码仓库地址:

  • react-ace:https://github.com/securingsincity/react-ace
  • ace-builds:https://github.com/ajaxorg/ace

使用样例:

// 核心组件
import AceEditor from 'react-ace'
// 引入对应的语言
import 'ace-builds/src-noconflict/mode-javascript'
//以下import的是风格
import 'ace-builds/src-noconflict/theme-eclipse'
// 代码提示
import 'ace-builds/src-noconflict/ext-language_tools'
import 'ace-builds/webpack-resolver'
import './code.less'
 
const CodeView = () => {
    
    
  return (
	<AceEditor
      // name类似于id和key需要保持唯一性
      name='myCodeView'
      // 字体大小
      fontSize={
    
    16}
      style={
    
    {
    
     width: '80%', height: '80%', minHeight: 80 }}
      mode='javascript'
	  theme='eclipse'
	 />
  )
}
 
export default CodeView

常用属性:

mode:编辑器的整体模式或样式,这里取值为 markdown,表明需要用这个编辑器来输入 markdown文本,这样编辑器就会进行相应的初始设置。
theme:编辑器主题,这里使用了 github这个主题。
wrapEnabled:当输入的一句文本比一行的长度要长时,是否允许换行。
tabSize:使用几个空格来表示表示一次 Tab按键。
fontSize:文本的字体大小
height:编辑器的高度,单位为 px。
width:编辑器的宽度,单位为 px。
debounceChangePeriod:多长时间对输入响应一次,单位为 ms,类似于节流。
onChange:文本框内容发生变化时的回调函数。
onScroll:文本框内容发生滚动时的回调函数。
name:编辑器的 id。
editorProps:当在文本框内输入内容时,是否需要滚动条进行响应的滚动定位。

全部属性:

Prop Default Type Description
name ‘ace-editor’ String Unique Id to be used for the editor
placeholder null String Placeholder text to be displayed when editor is empty
mode ‘’ String Language for parsing and code highlighting
theme ‘’ String theme to use
value ‘’ String value you want to populate in the code highlighter
defaultValue ‘’ String Default value of the editor
height ‘500px’ String CSS value for height
width ‘500px’ String CSS value for width
className String custom className
fontSize 12 Number pixel value for font-size
showGutter true Boolean show gutter
showPrintMargin true Boolean show print margin
highlightActiveLine true Boolean highlight active line
focus false Boolean whether to focus
cursorStart 1 Number the location of the cursor
wrapEnabled false Boolean Wrapping lines
readOnly false Boolean make the editor read only
minLines Number Minimum number of lines to be displayed
maxLines Number Maximum number of lines to be displayed
enableBasicAutocompletion false Boolean Enable basic autocompletion
enableLiveAutocompletion false Boolean Enable live autocompletion
enableSnippets false Boolean Enable snippets
tabSize 4 Number tabSize
debounceChangePeriod null Number A debounce delay period for the onChange event
onLoad Function called on editor load. The first argument is the instance of the editor
onBeforeLoad Function called before editor load. the first argument is an instance of ace
onChange Function occurs on document change it has 2 arguments the value and the event.
onCopy Function triggered by editor copy event, and passes text as argument
onPaste Function Triggered by editor paste event, and passes text as argument
onSelectionChange Function triggered by editor selectionChange event, and passes a Selection as it’s first argument and the event as the second
onCursorChange Function triggered by editor changeCursor event, and passes a Selection as it’s first argument and the event as the second
onFocus Function triggered by editor focus event
onBlur Function triggered by editor blur event.It has two arguments event and editor
onInput Function triggered by editor input event
onScroll Function triggered by editor scroll event
onValidate Function triggered, when annotations are changed
editorProps Object properties to apply directly to the Ace editor instance
setOptions Object options to apply directly to the Ace editor instance
keyboardHandler String corresponding to the keybinding mode to set (such as vim or emacs)
commands Array new commands to add to the editor
annotations Array annotations to show in the editor i.e. [{ row: 0, column: 2, type: 'error', text: 'Some error.'}], displayed in the gutter.(type:‘error’,‘info’,‘warning’)
markers Array markers to show in the editor, i.e. [{ startRow: 0, startCol: 2, endRow: 1, endCol: 20, className: 'error-marker', type: 'background' }]. Make sure to define the class (eg. “.error-marker”) and set position: absolute for it.
style Object camelCased properties

不同文件中可以引入不同的语言支持包:

import 'brace/mode/javascript';//
import 'brace/mode/html';//
import 'brace/mode/java';//
import 'brace/mode/python';//
import 'brace/mode/lua';//
import 'brace/mode/xml';//
import 'brace/mode/ruby';//
import 'brace/mode/sass';
import 'brace/mode/markdown';//
import 'brace/mode/mysql';
import 'brace/mode/json';//
import 'brace/mode/css';//
import 'brace/mode/typescript';

2.其他代码编辑器

CodeMirror

  • 官网:https://codemirror.net/
  • github:https://github.com/codemirror/CodeMirror
  • 示例代码:https://uiwjs.github.io/react-codemirror/

Monaco

  • github:https://github.com/microsoft/monaco-editor

diff2html

  • 官网:https://diff2html.xyz/
  • gitbub:https://github.com/rtfpessoa/diff2html

猜你喜欢

转载自blog.csdn.net/qq_32682301/article/details/128849799