aboutsummaryrefslogtreecommitdiffstats
path: root/language-web/src/main/js/editor/EditorStore.ts
blob: 8b9432dd5b5870f38d280451aa307fbd741dd368 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import type { Editor, EditorConfiguration } from 'codemirror';
import {
  createAtom,
  makeAutoObservable,
  observable,
  runInAction,
} from 'mobx';
import type { IXtextOptions, IXtextServices } from 'xtext/xtext-codemirror';

import type { IEditorChunk } from './editor';
import { getLogger } from '../logging';
import type { ThemeStore } from '../theme/ThemeStore';

const log = getLogger('EditorStore');

const xtextLang = 'problem';

const xtextOptions: IXtextOptions = {
  xtextLang,
  enableFormattingAction: true,
};

const codeMirrorGlobalOptions: EditorConfiguration = {
  mode: `xtext/${xtextLang}`,
  indentUnit: 2,
  styleActiveLine: true,
};

export class EditorStore {
  themeStore;

  atom;

  chunk?: IEditorChunk;

  editor?: Editor;

  xtextServices?: IXtextServices;

  value = '';

  showLineNumbers = false;

  initialSelection!: { start: number, end: number, focused: boolean };

  constructor(themeStore: ThemeStore) {
    this.themeStore = themeStore;
    this.atom = createAtom('EditorStore');
    this.resetInitialSelection();
    makeAutoObservable(this, {
      themeStore: false,
      atom: false,
      chunk: observable.ref,
      editor: observable.ref,
      xtextServices: observable.ref,
      initialSelection: false,
    });
    this.loadChunk();
  }

  private loadChunk(): void {
    const loadingStartMillis = Date.now();
    log.info('Requesting editor chunk');
    import('./editor').then(({ editorChunk }) => {
      runInAction(() => {
        this.chunk = editorChunk;
      });
      const loadingDurationMillis = Date.now() - loadingStartMillis;
      log.info('Loaded editor chunk in', loadingDurationMillis, 'ms');
    }).catch((error) => {
      log.error('Error while loading editor', error);
    });
  }

  setInitialSelection(start: number, end: number, focused: boolean): void {
    this.initialSelection = { start, end, focused };
    this.applyInitialSelectionToEditor();
  }

  private resetInitialSelection(): void {
    this.initialSelection = {
      start: 0,
      end: 0,
      focused: false,
    };
  }

  private applyInitialSelectionToEditor(): void {
    if (this.editor) {
      const { start, end, focused } = this.initialSelection;
      const doc = this.editor.getDoc();
      const startPos = doc.posFromIndex(start);
      const endPos = doc.posFromIndex(end);
      doc.setSelection(startPos, endPos, {
        scroll: true,
      });
      if (focused) {
        this.editor.focus();
      }
      this.resetInitialSelection();
    }
  }

  /**
   * Attaches a new CodeMirror instance and creates Xtext services.
   *
   * The store will not subscribe to any CodeMirror events. Instead,
   * the editor component should subscribe to them and relay them to the store.
   *
   * @param newEditor The new CodeMirror instance
   */
  editorDidMount(newEditor: Editor): void {
    if (!this.chunk) {
      throw new Error('Editor not loaded yet');
    }
    if (this.editor) {
      throw new Error('CoreMirror editor mounted before unmounting');
    }
    this.editor = newEditor;
    this.xtextServices = this.chunk.createServices(newEditor, xtextOptions);
    this.applyInitialSelectionToEditor();
  }

  editorWillUnmount(): void {
    if (!this.chunk) {
      throw new Error('Editor not loaded yet');
    }
    if (this.editor) {
      this.chunk.removeServices(this.editor);
    }
    delete this.editor;
    delete this.xtextServices;
  }

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

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

  protected observeEditorChanges(): void {
    this.atom.reportObserved();
  }

  get codeMirrorTheme(): string {
    return `problem-${this.themeStore.className}`;
  }

  get codeMirrorOptions(): EditorConfiguration {
    return {
      ...codeMirrorGlobalOptions,
      theme: this.codeMirrorTheme,
      lineNumbers: this.showLineNumbers,
    };
  }

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

  undo(): void {
    this.editor?.undo();
  }

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

  redo(): void {
    this.editor?.redo();
  }

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