aboutsummaryrefslogtreecommitdiffstats
path: root/language-web/src/main/js/editor/EditorStore.jsx
blob: b6f9bc0adb1b4b3890517f8b3d06505c8b3038bf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import CodeMirror from 'codemirror';
import { createAtom, makeAutoObservable, observable } from 'mobx';

export default class EditorStore {
  atom;
  /** @type {CodeMirror} */
  editor = null;
  /** @type {string} */
  value = '';
  /** @type {boolean} */
  showLineNumbers = false;
  /** @type {boolean} */
  showLigatures = true;

  constructor() {
    this.atom = createAtom('EditorStore');
    makeAutoObservable(this, {
      atom: false,
      editor: observable.ref,
    });
  }

  /**
   * Attaches a new CodeMirror instance.
   *
   * The store will node subscribe to any CodeMirror events. Instead,
   * the editor component should subscribe to them and relay them to the store.
   *
   * @param {CodeMirror} newEditor The new CodeMirror instance
   */
  updateEditor(newEditor) {
    this.editor = newEditor;
  }

  /**
   * Updates the contents of the editor.
   *
   * @param {string} newValue The new contents of the editor
   */
  updateValue(newValue) {
    this.value = newValue;
  }

  reportChanged() {
    this.atom.reportChanged();
  }

  /**
   * @returns {boolean} `true` if there is history to undo
   */
  get canUndo() {
    this.atom.reportObserved();
    if (!this.editor) {
      return false;
    }
    const { undo: undoSize } = this.editor.historySize();
    return undoSize > 0;
  }

  undo() {
    this.editor.undo();
  }

  /**
   * @returns {boolean} `true` if there is history to redo
   */
  get canRedo() {
    this.atom.reportObserved();
    if (!this.editor) {
      return false;
    }
    const { redo: redoSize } = this.editor.historySize();
    return redoSize > 0;
  }

  redo() {
    this.editor.redo();
  }

  toggleLineNumbers() {
    this.showLineNumbers = !this.showLineNumbers;
  }

  toggleLigatures() {
    this.showLigatures = !this.showLigatures;
  }
}