Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue下使用Monaco Editor - 简书 #213

Open
xiaodongxier opened this issue Sep 14, 2023 · 0 comments
Open

vue下使用Monaco Editor - 简书 #213

xiaodongxier opened this issue Sep 14, 2023 · 0 comments

Comments

@xiaodongxier
Copy link
Owner

1.简介

​ Monaco Editor是为VS Code提供支持的代码编辑器。描述代码编辑器的功能,良好的网页是在这里。它已获得MIT许可,并支持Classic Edge,Edge,Chrome,Firefox,Safari和Opera。移动浏览器或移动Web框架支持Monaco编辑器(但移动的有的浏览器是支持的,起码我用的几个都支持)。

2.开始

2.1 安装环境

npm install monaco-editor@0.21.2 --save 
npm install monaco-editor-webpack-plugin --save 

2.2 配置文件

修改webpack.base.conf.js配置文件。(前几步借鉴时间脱臼大神博客,步骤大同小异)

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = {
  ...
  plugins: [
    ...
    new MonacoWebpackPlugin()
  ]
}; 

2.3 开始使用

新建vue文件,添加如下代码即可使用

<div id="container"></div> 
import * as monaco from 'monaco-editor'
export default{
    data(){
        return {
            editor:null,
        }
    },
    mounted(){
      this.initEditor();  
    },
    methods:{
        initEditor(){
            
            this.editor = monaco.editor.create(document.getElementById('container'), {
                value:'',
                language:'sql',
                automaticLayout: true,
                theme:'vs-dark' 
            });
        },
        getValue(){
            this.editor.getValue(); 
        }
    }
} 

附:Monaco Editor demo

image-20201012143856748.png

附:语言支持(当然支持自定义语言)

 var modesIds = monaco.languages.getLanguages().map(function(lang) { return lang.id; }); 

附:配置项(根据自身需要在初始化编辑器是配置) 配置项链接

selectOnLineNumbers: true,
roundedSelection: false,
readOnly: false,        
cursorStyle: 'line',        
automaticLayout: false, 
glyphMargin: true,  
useTabStops: false,
fontSize: 28,       
autoIndent:true,
quickSuggestionsDelay: 500, 

至此,最简单的文档编辑器已经完成。

3. 进阶

3.1 文件改动状态

export default{
    data(){
        return {
            editor:null,
            isSave:true,
            oldValue:'' 
        }
    },
    methods:{
        initEditor(){
            
            this.editor = monaco.editor.create(document.getElementById('container'), {
                value:'',
                language:'sql',
                automaticLayout: true,
                theme:'vs-dark' 
            });
            this.editor.onKeyUp(() => {
                
                if(this.editor.getValue() != this.oldValue){
                    this.isSave = false;
                }
            });
        },
        
        saveEditor(){
            this.oldValue = this.editor.getValue();
            ...保存逻辑
        }
    }
} 

3.2 更改编辑器语言

export default{
    data(){
        return {
            editor:null,
        }
    },
    methods:{
        initEditor(){
            
            this.editor = monaco.editor.create(document.getElementById('container'), {
                value:'',
                language:'sql',
                automaticLayout: true,
                theme:'vs-dark' 
            });
        },
        changeModel(){
            var oldModel = this.editor.getModel();
            var value = this.editor.getValue();
            
            
            
            var newModel = monaco.editor.createModel(value,id);
            
            if(oldModel){
                oldModel.dispose();
            }
            
            this.editor.setModel(newModel);
        }
    }
} 

3.3 更改编辑器配置

 this.editor.updateOptions({readOnly:true}) 

3.4 触发编辑器事件

 this.editor.trigger('anything','editor.action.formatDocument'); 

3.5 获取选中内容

 var selection = this.editor.getSelection();

var text = currentFn(editor,selection.startLineNumber,selection.startColumn,selection.endLineNumber,selection.endColumn); 
function currentFn(monacoEditor, startLineNumber, startColumn, endLineNumber, endColumn) {
    let currentText = '' 
    let num = 0;
    let startIndex = null;
    let endIndex = null;
    
    if (startLineNumber < endLineNumber) {
        monacoEditor.getValue().split('').map((item, index) => {
            if (startLineNumber === 1) {
            startIndex = startColumn - 1;
            if (item === '\n') {
                num += 1;
                if (num === endLineNumber - 1) {
                endIndex = index + endColumn
                }
            }
            } else {
            if (item === '\n') {
                num += 1
                if (num === startLineNumber - 1) {
                startIndex = index + startColumn
                }
                if (num === endLineNumber - 1) {
                endIndex = index + endColumn
                }
            }
            }
        })
    } else if (startLineNumber > endLineNumber) {
        monacoEditor.getValue().split('').map((item, index) => {
            if (endLineNumber === 1) {
            startIndex = endColumn - 1;
            if (item === '\n') {
                num += 1;
                if (num === startLineNumber - 1) {
                endIndex = index + startColumn
                }
            }
            } else {
            if (item === '\n') {
                num += 1
                if (num === endLineNumber - 1) {
                startIndex = index + endColumn
                }
                if (num === startLineNumber - 1) {
                endIndex = index + startColumn
                }
            }
            }
        })
    } else if (startLineNumber === endLineNumber) {
        monacoEditor.getValue().split('').map((item, index) => {
            if (endLineNumber === 1) {
            startIndex = startColumn < endColumn ? startColumn - 1 : endColumn - 1
            endIndex = startColumn > endColumn ? startColumn - 1 : endColumn - 1
            } else {
            if (item === '\n') {
                num += 1
                if (num === endLineNumber - 1) {
                startIndex = startColumn < endColumn ? startColumn + index : endColumn + index
                endIndex = startColumn > endColumn ? startColumn + index : endColumn + index
                }
            }
            }
        })
    }
    currentText = monacoEditor.getValue().slice(startIndex, endIndex)
    return currentText
} 

3.6 代码提示

monaco.languages.registerCompletionItemProvider('sql', {
    provideCompletionItems: function(model, position) {
        
        const line = position.lineNumber;

        
        const column = position.column;
        
        const content = model.getLineContent(line)
        
        const sym = content[column - 2];
        var textUntilPosition = model.getValueInRange({startLineNumber: 1, startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column});
        var word = model.getWordUntilPosition(position);
        var range = {
            startLineNumber: position.lineNumber,
            endLineNumber: position.lineNumber,
            startColumn: word.startColumn,
            endColumn: word.endColumn
        };
        
        
        
        var suggestions = [];
        if(sym == "$"){
            
            
        }else{
            
            var sqlStr = ['SELECT','FROM','WHERE','AND','OR','LIMIT','ORDER BY','GROUP BY'];
            for(var i in sqlStr){
                suggestions.push({
                    label: sqlStr[i], 
                    kind: monaco.languages.CompletionItemKind['Function'], 
                    insertText: sqlStr[i], 
                    detail: '', 
                    range:range
                });
            }
        }
        return {
            suggestions: suggestions
        };
    },
    triggerCharacters: ["$",""]
}); 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant