github.com/hernad/nomad@v1.6.112/ui/app/modifiers/code-mirror.js (about) 1 /** 2 * Copyright (c) HashiCorp, Inc. 3 * SPDX-License-Identifier: MPL-2.0 4 */ 5 6 import { action } from '@ember/object'; 7 import { bind } from '@ember/runloop'; 8 import codemirror from 'codemirror'; 9 import Modifier from 'ember-modifier'; 10 11 import 'codemirror/addon/edit/matchbrackets'; 12 import 'codemirror/addon/selection/active-line'; 13 import 'codemirror/addon/lint/lint.js'; 14 import 'codemirror/addon/lint/json-lint.js'; 15 import 'codemirror/mode/javascript/javascript'; 16 import 'codemirror/mode/ruby/ruby'; 17 18 export default class CodeMirrorModifier extends Modifier { 19 get autofocus() { 20 if (Object.hasOwn({ ...this.args.named }, 'autofocus')) { 21 // spread (...) because proxy, and because Ember over-eagerly prevents named prop lookups for modifier args. 22 return this.args.named.autofocus; 23 } else { 24 return !this.args.named.readOnly; 25 } 26 } 27 28 didInstall() { 29 this._setup(); 30 } 31 32 didUpdateArguments() { 33 this._editor.setOption('lineWrapping', this.args.named.lineWrapping); 34 this._editor.setOption('readOnly', this.args.named.readOnly); 35 if (!this.args.named.content) { 36 return; 37 } 38 if (this._editor.getValue() !== this.args.named.content) { 39 this._editor.setValue(this.args.named.content); 40 } 41 } 42 43 @action 44 _onChange(editor) { 45 this.args.named.onUpdate( 46 editor.getValue(), 47 this._editor, 48 this.args.named.type 49 ); 50 } 51 52 _setup() { 53 if (this.element) { 54 const editor = codemirror(this.element, { 55 gutters: this.args.named.gutters || ['CodeMirror-lint-markers'], 56 matchBrackets: true, 57 lint: { lintOnChange: true }, 58 showCursorWhenSelecting: true, 59 styleActiveLine: true, 60 tabSize: 2, 61 // all values we can pass into the modifier 62 extraKeys: this.args.named.extraKeys || '', 63 lineNumbers: this.args.named.lineNumbers || true, 64 mode: this.args.named.mode || 'application/json', 65 readOnly: this.args.named.readOnly || false, 66 theme: this.args.named.theme || 'hashi', 67 value: this.args.named.content || '', 68 viewportMargin: this.args.named.viewportMargin || '', 69 screenReaderLabel: this.args.named.screenReaderLabel || '', 70 lineWrapping: this.args.named.lineWrapping || false, 71 }); 72 73 if (this.autofocus) { 74 editor.focus(); 75 } 76 77 editor.on('change', bind(this, this._onChange)); 78 79 this._editor = editor; 80 } 81 } 82 }