-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmonaco.ts
More file actions
232 lines (211 loc) · 6.9 KB
/
monaco.ts
File metadata and controls
232 lines (211 loc) · 6.9 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
import { registerDestructor } from '@ember/destroyable';
import { service } from '@ember/service';
import { isTesting } from '@embroider/macros';
import { restartableTask, timeout } from 'ember-concurrency';
import Modifier from 'ember-modifier';
import * as MonacoSDK from 'monaco-editor';
import config from '@cardstack/host/config/environment';
import type MonacoService from '@cardstack/host/services/monaco-service';
import { createMonacoWaiterManager } from '@cardstack/host/utils/editor/monaco-test-waiter';
interface Signature {
Args: {
Named: {
content: string;
contentChanged: (text: string) => void;
initialCursorPosition?: MonacoSDK.Position;
onCursorPositionChange?: (position: MonacoSDK.Position) => void;
onSetup?: (editor: MonacoSDK.editor.IStandaloneCodeEditor) => void;
onDispose?: () => void;
language?: string;
readOnly?: boolean;
monacoSDK: typeof MonacoSDK;
editorDisplayOptions?: MonacoEditorOptions;
};
};
}
const { monacoDebounceMs, monacoCursorDebounceMs } = config;
export type MonacoEditorOptions =
MonacoSDK.editor.IStandaloneEditorConstructionOptions;
export default class Monaco extends Modifier<Signature> {
private model: MonacoSDK.editor.ITextModel | undefined;
private editor: MonacoSDK.editor.IStandaloneCodeEditor | undefined;
private lastLanguage: string | undefined;
private lastContent: string | undefined;
private lastReadOnly: boolean | undefined;
private lastModified = Date.now();
private lastCursorPosition: MonacoSDK.Position | undefined;
private waiterManager = createMonacoWaiterManager();
private onDispose: (() => void) | undefined;
@service declare private monacoService: MonacoService;
modify(
element: HTMLElement,
_positional: [],
{
content,
language,
contentChanged,
initialCursorPosition,
onCursorPositionChange,
onSetup,
onDispose,
readOnly,
monacoSDK,
editorDisplayOptions,
}: Signature['Args']['Named'],
) {
if (this.editor && this.model) {
if (language && language !== this.lastLanguage) {
monacoSDK.editor.setModelLanguage(this.model, language);
}
if (
content !== this.model.getValue() &&
// ignore realm event echoes of our own saves by not processing content changes
// within serverEchoDebounceMs of the last monaco change in memory
Date.now() >=
this.lastModified + this.monacoService.serverEchoDebounceMs
) {
this.lastContent = content;
this.model.setValue(content);
}
if (readOnly !== this.lastReadOnly) {
this.editor.updateOptions({ readOnly });
this.lastReadOnly = readOnly;
}
} else {
this.setupEditor({
element,
content,
language,
readOnly,
editorDisplayOptions,
monacoSDK,
contentChanged,
onCursorPositionChange,
onSetup,
});
}
this.lastLanguage = language;
if (initialCursorPosition != null) {
this.initializeCursorPosition.perform(initialCursorPosition);
}
this.onDispose = onDispose;
}
private setupEditor({
element,
content,
language,
readOnly,
editorDisplayOptions,
monacoSDK,
contentChanged,
onCursorPositionChange,
onSetup,
}: Omit<Signature['Args']['Named'], 'initialCursorPosition'> & {
element: HTMLElement;
}) {
monacoSDK.editor.defineTheme('boxel-monaco-dark-theme', {
base: 'vs-dark', // base themes: vs, vs-dark
inherit: true,
rules: [],
colors: {
'editor.background': readOnly ? '#606060' : '#413e4e',
},
});
let editorOptions: MonacoEditorOptions = {
readOnly,
value: content,
language,
scrollBeyondLastLine: true,
automaticLayout: true,
minimap: {
enabled: false,
},
theme: 'boxel-monaco-dark-theme',
...editorDisplayOptions,
};
// Code rendering is inconsistently wrapped without this, producing spurious visual diffs
if (isTesting()) {
editorOptions.wordWrap = 'on';
}
this.editor = monacoSDK.editor.create(element, editorOptions);
this.lastReadOnly = readOnly;
// Track editor initialization for test waiters
if (this.waiterManager) {
const operationId = `monaco-modifier-init-${this.editor.getId()}`;
this.waiterManager.trackEditorInit(this.editor, operationId);
}
onSetup?.(this.editor);
registerDestructor(this, () => {
this.onDispose?.();
let model = this.model;
this.model = undefined;
let editor = this.editor;
this.editor = undefined;
if (editor) {
this.disposeEditorAfterInitialLayout(editor, model);
}
});
this.model = this.editor.getModel()!;
this.model.onDidChangeContent(() =>
this.onContentChanged.perform(contentChanged),
);
this.editor.onDidChangeCursorSelection((event) => {
if (
this.editor &&
event.source !== 'model' &&
event.selection.startLineNumber === event.selection.endLineNumber &&
event.selection.startColumn === event.selection.endColumn
) {
let position = this.editor.getPosition();
if (position) {
onCursorPositionChange?.(position);
this.lastCursorPosition = position;
}
}
});
}
private onContentChanged = restartableTask(
async (contentChanged: (text: string) => void) => {
let content = this.model?.getValue();
if (this.lastContent === content) {
return;
}
this.lastModified = Date.now();
await timeout(monacoDebounceMs);
if (this.model) {
this.lastContent = this.model.getValue();
contentChanged(this.lastContent);
}
},
);
// Initialize cursor position asynchronously
// to avoid potential effects on other elements.
// If this affects other elements, there is a potential double update to a value in the same computation,
// leading to an infinite Glimmer invalidation error.
private initializeCursorPosition = restartableTask(
async (position?: MonacoSDK.Position) => {
await timeout(monacoCursorDebounceMs);
if (!position) {
position = new MonacoSDK.Position(1, 1);
}
if (!this.lastCursorPosition) {
this.monacoService.updateCursorPosition(position);
}
},
);
private disposeEditorAfterInitialLayout(
editor: MonacoSDK.editor.IStandaloneCodeEditor,
model: MonacoSDK.editor.ITextModel | undefined,
) {
// Monaco can still be instantiating editor contributions in the same turn
// that Glimmer tears the modifier down. Disposing on the next paint avoids
// tearing down the instantiation service mid-bootstrap without introducing
// an arbitrary timer.
requestAnimationFrame(() => {
editor.dispose();
if (model && !model.isDisposed() && !model.isAttachedToEditor()) {
model.dispose();
}
});
}
}