Created
November 24, 2020 03:08
-
-
Save disco0/c9b81142228d5023e42534979baec977 to your computer and use it in GitHub Desktop.
Monaco Editor - Text Append + Editor Action Enumeration Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* For use with [Monaco Editor Playground](https://microsoft.github.io/monaco-editor/playground.html), | |
* otherwise monaco must be loaded via import or another method | |
*/ | |
//#region Initialize | |
//#region Document Intial Text | |
let jsCode = /* js */ ` | |
//#region Editor Initial Text | |
//#endregion Editor Initial Text | |
`.trim(); | |
//#endregion Document Intial Text | |
//#region Editor | |
const containerEl = document.getElementById("container") ?? (() => { | |
const containerEl = document.createElement('div'); | |
containerEl.id = 'container'; | |
return containerEl; | |
})(); | |
const editorOptions = { value: jsCode, language: "javascript" } | |
const editor = monaco.editor.create(containerEl, editorOptions); | |
//#endregion Editor | |
//#endregion Initialize | |
//#region Editor Actions | |
/** | |
* @param {monaco.editor.IStandaloneCodeEditor} editor | |
* @param {RegExp | string} search | |
*/ | |
function searchEditorActions(editor, search) | |
{ | |
return editor.getSupportedActions() | |
.filter(action => action.id.match(search)); | |
} | |
//#region Build Editor Action List | |
const actions = searchEditorActions(editor, /.*/); | |
const actionIds = actions.map(({ id }) => id); | |
function quote(text){ return `'${text}'` }; | |
function indent(text) { return `${' '.repeat(this.level ?? 2)}${text}` } | |
const actionIdStrings = actionIds.map(quote); | |
const actionListDeclarationSource = ` | |
const Commands = [ | |
${actionIdStrings.map(indent, {level: 2}).join(',\n')} | |
] | |
`; | |
//#endregion Build Editor Action List | |
//#endregion Editor Actions | |
//#region Editor Edits | |
function appendEditor(editor, text, newLine = true) | |
{ | |
if(newLine === true) text = `\n${text}`; | |
const lineCount = editor.getModel().getLineCount(); | |
const {lineNumber: line, column} = new monaco.Position(lineCount + 1, 0); | |
const range = new monaco.Range( line, column, line, column ); | |
const edit = { text, range }; | |
editor.executeEdits("command-list", [edit]); | |
} | |
//#endregion Editor Edits | |
//#region (Finally) Insert Edits | |
// Final text content inserted | |
const insertion = | |
` | |
//#region Inserted Text | |
${actionListDeclarationSource} | |
//#endregion Inserted Text | |
`; | |
setTimeout(() => { | |
appendEditor(editor, insertion); | |
}, 2000); | |
//#endregion (Finally) Insert Edits |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment