aboutsummaryrefslogtreecommitdiffstats
path: root/language-web/src/main/js/editor/EditorStore.ts
blob: eb3583380117a341a3ad8192ac5bf67b352b6de9 (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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import { autocompletion, completionKeymap } from '@codemirror/autocomplete';
import { closeBrackets, closeBracketsKeymap } from '@codemirror/closebrackets';
import { defaultKeymap, indentWithTab } from '@codemirror/commands';
import { commentKeymap } from '@codemirror/comment';
import { foldGutter, foldKeymap } from '@codemirror/fold';
import { highlightActiveLineGutter, lineNumbers } from '@codemirror/gutter';
import { classHighlightStyle } from '@codemirror/highlight';
import {
  history,
  historyKeymap,
  redo,
  redoDepth,
  undo,
  undoDepth,
} from '@codemirror/history';
import { indentOnInput } from '@codemirror/language';
import { lintKeymap } from '@codemirror/lint';
import { bracketMatching } from '@codemirror/matchbrackets';
import { rectangularSelection } from '@codemirror/rectangular-selection';
import { searchConfig, searchKeymap } from '@codemirror/search';
import {
  EditorState,
  StateCommand,
  StateEffect,
  Transaction,
  TransactionSpec,
} from '@codemirror/state';
import {
  drawSelection,
  EditorView,
  highlightActiveLine,
  highlightSpecialChars,
  keymap,
} from '@codemirror/view';
import {
  makeAutoObservable,
  observable,
  reaction,
} from 'mobx';

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

const log = getLogger('EditorStore');

export class EditorStore {
  themeStore;

  state: EditorState;

  emptyHistory: unknown;

  showLineNumbers = false;

  showSearchPanel = false;

  showLintPanel = false;

  readonly defaultDispatcher = (tr: Transaction): void => {
    this.onTransaction(tr);
  };

  dispatcher = this.defaultDispatcher;

  constructor(initialValue: string, themeStore: ThemeStore) {
    this.themeStore = themeStore;
    this.state = EditorState.create({
      doc: initialValue,
      extensions: [
        autocompletion(),
        classHighlightStyle.extension,
        closeBrackets(),
        bracketMatching(),
        drawSelection(),
        EditorState.allowMultipleSelections.of(true),
        EditorView.theme({}, {
          dark: this.themeStore.darkMode,
        }),
        highlightActiveLine(),
        highlightActiveLineGutter(),
        highlightSpecialChars(),
        history(),
        indentOnInput(),
        rectangularSelection(),
        searchConfig({
          top: true,
          matchCase: true,
        }),
        // We add the gutters to `extensions` in the order we want them to appear.
        foldGutter(),
        lineNumbers(),
        keymap.of([
          ...closeBracketsKeymap,
          ...commentKeymap,
          ...completionKeymap,
          ...foldKeymap,
          ...historyKeymap,
          indentWithTab,
          // Override keys in `lintKeymap` to go through the `EditorStore`.
          { key: 'Mod-Shift-m', run: () => this.setLintPanelOpen(true) },
          ...lintKeymap,
          // Override keys in `searchKeymap` to go through the `EditorStore`.
          { key: 'Mod-f', run: () => this.setSearchPanelOpen(true), scope: 'editor search-panel' },
          { key: 'Escape', run: () => this.setSearchPanelOpen(false), scope: 'editor search-panel' },
          ...searchKeymap,
          ...defaultKeymap,
        ]),
        problemLanguageSupport(),
      ],
    });
    reaction(
      () => this.themeStore.darkMode,
      (darkMode) => {
        log.debug('Update editor dark mode', darkMode);
        this.dispatch({
          effects: [
            StateEffect.appendConfig.of(EditorView.theme({}, {
              dark: darkMode,
            })),
          ],
        });
      },
    );
    makeAutoObservable(this, {
      themeStore: false,
      state: observable.ref,
      defaultDispatcher: false,
      dispatcher: false,
    });
  }

  updateDispatcher(newDispatcher: ((tr: Transaction) => void) | null): void {
    this.dispatcher = newDispatcher || this.defaultDispatcher;
  }

  onTransaction(tr: Transaction): void {
    log.trace('Editor transaction', tr);
    this.state = tr.state;
  }

  dispatch(...specs: readonly TransactionSpec[]): void {
    this.dispatcher(this.state.update(...specs));
  }

  doStateCommand(command: StateCommand): boolean {
    return command({
      state: this.state,
      dispatch: this.dispatcher,
    });
  }

  /**
   * @returns `true` if there is history to undo
   */
  get canUndo(): boolean {
    return undoDepth(this.state) > 0;
  }

  // eslint-disable-next-line class-methods-use-this
  undo(): void {
    log.debug('Undo', this.doStateCommand(undo));
  }

  /**
   * @returns `true` if there is history to redo
   */
  get canRedo(): boolean {
    return redoDepth(this.state) > 0;
  }

  // eslint-disable-next-line class-methods-use-this
  redo(): void {
    log.debug('Redo', this.doStateCommand(redo));
  }

  toggleLineNumbers(): void {
    this.showLineNumbers = !this.showLineNumbers;
    log.debug('Show line numbers', this.showLineNumbers);
  }

  /**
   * Sets whether the CodeMirror search panel should be open.
   *
   * This method can be used as a CodeMirror command,
   * because it returns `false` if it didn't execute,
   * allowing other commands for the same keybind to run instead.
   * This matches the behavior of the `openSearchPanel` and `closeSearchPanel`
   * commands from `'@codemirror/search'`.
   *
   * @param newShosSearchPanel whether we should show the search panel
   * @returns `true` if the state was changed, `false` otherwise
   */
  setSearchPanelOpen(newShowSearchPanel: boolean): boolean {
    if (this.showSearchPanel === newShowSearchPanel) {
      return false;
    }
    this.showSearchPanel = newShowSearchPanel;
    log.debug('Show search panel', this.showSearchPanel);
    return true;
  }

  toggleSearchPanel(): void {
    this.setSearchPanelOpen(!this.showSearchPanel);
  }

  setLintPanelOpen(newShowLintPanel: boolean): boolean {
    if (this.showLintPanel === newShowLintPanel) {
      return false;
    }
    this.showLintPanel = newShowLintPanel;
    log.debug('Show lint panel', this.showLintPanel);
    return true;
  }

  toggleLintPanel(): void {
    this.setLintPanelOpen(!this.showLintPanel);
  }
}