github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/ui/app/modifiers/code-mirror.js (about)

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