-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathplayground-code-editor.ts
More file actions
1227 lines (1080 loc) · 36.8 KB
/
playground-code-editor.ts
File metadata and controls
1227 lines (1080 loc) · 36.8 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {LitElement, css, PropertyValues, html, nothing, render} from 'lit';
import {
customElement,
property,
query,
state,
queryAssignedElements,
} from 'lit/decorators.js';
import {ifDefined} from 'lit/directives/if-defined.js';
import {
EditorState,
Extension,
StateEffect,
StateField,
Range,
Compartment,
Transaction,
Annotation,
} from '@codemirror/state';
import {
EditorView,
ViewUpdate,
lineNumbers as cmLineNumbers,
keymap,
Decoration,
DecorationSet,
WidgetType,
highlightSpecialChars,
drawSelection,
dropCursor,
} from '@codemirror/view';
import {lit} from './cm-lang-lit.js';
import {html as cmHtml} from '@codemirror/lang-html';
import {css as cmCss} from '@codemirror/lang-css';
import {
autocompletion,
closeBrackets,
closeBracketsKeymap,
Completion,
completionKeymap,
CompletionContext,
CompletionResult,
} from '@codemirror/autocomplete';
import {syntaxHighlighting} from '@codemirror/language';
import {
history,
defaultKeymap,
historyKeymap,
indentWithTab,
} from '@codemirror/commands';
import {
bracketMatching,
foldGutter,
foldKeymap,
indentOnInput,
} from '@codemirror/language';
import {classHighlighter} from '@lezer/highlight';
import './internal/overlay.js';
import {Diagnostic} from 'vscode-languageserver-protocol';
import {
EditorCompletion,
EditorPosition,
EditorToken,
} from './shared/worker-api.js';
import {highlightSelectionMatches, searchKeymap} from '@codemirror/search';
import {lintKeymap} from '@codemirror/lint';
import {playgroundTheme} from './playground-styles.js';
import {
CodemirrorExtensionRegisteredEvent,
PlaygroundEditorReadyEvent,
RegisterCodemirrorExtensionEvent,
} from './codemirror-extension-mixin.js';
// TODO(aomarks) Could we upstream this to lit-element? It adds much stricter
// types to the ChangedProperties type.
interface TypedMap<T> extends Map<keyof T, unknown> {
get<K extends keyof T>(key: K): T[K];
set<K extends keyof T>(key: K, value: T[K]): this;
delete<K extends keyof T>(key: K): boolean;
keys(): MapIterator<keyof T>;
values(): MapIterator<T[keyof T]>;
entries(): MapIterator<{[K in keyof T]: [K, T[K]]}[keyof T]>;
}
const unreachable = (n: never) => n;
// Annotation to mark programmatic changes (not user edits)
const programmaticChangeAnnotation = Annotation.define<boolean>();
/**
* A basic text editor with syntax highlighting for HTML, CSS, and JavaScript.
*/
@customElement('playground-code-editor')
export class PlaygroundCodeEditor extends LitElement {
static override styles = [
css`
:host {
display: block;
}
:host,
#focusContainer {
border-end-start-radius: inherit;
}
#focusContainer {
height: 100%;
position: relative;
}
#focusContainer:focus {
outline: none;
}
.cm-editor {
height: 100% !important;
border-radius: inherit;
}
.cm-foldMarker {
font-family: sans-serif;
}
.cm-foldMarker:hover {
cursor: pointer;
/* Pretty much any color from the theme is good enough. */
color: var(--playground-code-keyword-color, #770088);
}
#keyboardHelp {
font-size: 18px;
font-family: sans-serif;
padding: 10px 20px;
}
.diagnostic {
position: relative;
}
.diagnostic::before {
/* It would be nice to use "text-decoration: red wavy underline" here,
but unfortunately it renders nothing at all for single characters.
See https://bugs.chromium.org/p/chromium/issues/detail?id=668042. */
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==');
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
}
#tooltip {
position: absolute;
padding: 7px;
z-index: 4;
font-family: var(--playground-code-font-family, monospace);
}
#tooltip > div {
background: var(--playground-code-background, #fff);
color: var(--playground-code-default-color, #000);
/* Kind of hacky... line number color tends to work out as a good
default border, because it's usually visible on top of the
background, but slightly muted. */
border: 1px solid var(--playground-code-linenumber-color, #ccc);
padding: 5px;
}
[contenteditable='true'] {
outline: none;
}
slot[name='extensions'] {
display: none;
}
`,
];
/**
* A CodeMirror extension or extensions to apply to the editor.
*/
@property({attribute: false})
extensions?: Extension | Extension[];
protected _editorView?: EditorView;
get cursorPosition(): EditorPosition {
if (!this._editorView) {
return {ch: 0, line: 0};
}
const pos = this._editorView.state.selection.main.head;
const line = this._editorView.state.doc.lineAt(pos);
return {
ch: pos - line.from,
line: line.number - 1,
};
}
get cursorIndex(): number {
if (!this._editorView) return 0;
return this._editorView.state.selection.main.head;
}
get tokenUnderCursor(): EditorToken {
if (!this._editorView) return {start: 0, end: 0, string: ''};
const pos = this._editorView.state.selection.main.head;
const line = this._editorView.state.doc.lineAt(pos);
const wordRange = this._editorView.state.wordAt(pos);
if (wordRange) {
const start = wordRange.from - line.from;
const end = wordRange.to - line.from;
return {
start,
end,
string: line.text.slice(start, end),
};
}
return {
start: 0,
end: 0,
string: '',
};
}
// We store _value ourselves, rather than using a public reactive property, so
// that we can set this value internally without triggering an update.
private _value?: string;
@property()
get value() {
return this._value;
}
set value(v: string | undefined) {
const oldValue = this._value;
this._value = v;
this.requestUpdate('value', oldValue);
}
/**
* Provide a `documentKey` to create a CodeMirror document instance which
* isolates history and value changes per `documentKey`.
*
* Use to keep edit history separate between files while reusing the same
* playground-code-editor instance.
*/
@property({attribute: false})
// eslint-disable-next-line @typescript-eslint/ban-types
documentKey?: object;
/**
* WeakMap associating a `documentKey` with CodeMirror document state.
* A WeakMap is used so that this component does not become the source of
* memory leaks.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
private readonly _docCache = new WeakMap<object, EditorState>();
/**
* The type of the file being edited, as represented by its usual file
* extension.
*/
@property()
type: 'js' | 'ts' | 'html' | 'css' | 'json' | 'jsx' | 'tsx' | undefined;
/**
* If true, display a left-hand-side gutter with line numbers. Default false
* (hidden).
*/
@property({type: Boolean, attribute: 'line-numbers', reflect: true})
lineNumbers = false;
/**
* If true, wrap for long lines. Default false
*/
@property({type: Boolean, attribute: 'line-wrapping', reflect: true})
lineWrapping = false;
/**
* If true, this editor is not editable.
*/
@property({type: Boolean, reflect: true})
readonly = false;
/**
* If true, will disable code completions in the code-editor.
*/
@property({type: Boolean, attribute: 'no-completions'})
noCompletions = false;
/**
* Diagnostics to display on the current file.
*/
@property({attribute: false})
diagnostics?: Array<Diagnostic>;
@state()
_completions?: EditorCompletion[];
@state()
_completionsOpen = false;
/**
* How to handle `playground-hide` and `playground-fold` comments.
*
* See https://github.com/google/playground-elements#hiding--folding for
* more details.
*
* Options:
* - on: Hide and fold regions, and hide the special comments.
* - off: Don't hide or fold regions, but still hide the special comments.
* - off-visible: Don't hide or fold regions, and show the special comments as
* literal text.
*/
@property()
pragmas: 'on' | 'off' | 'off-visible' = 'on';
@state()
private _tooltipDiagnostic?: {
diagnostic: Diagnostic;
position: string;
};
@state()
private _showKeyboardHelp = false;
@query('#focusContainer')
private _focusContainer?: HTMLDivElement;
@query('.cm-content')
private _editorContent?: HTMLDivElement;
@queryAssignedElements({slot: 'extensions', flatten: true})
private _extensionElements!: HTMLElement[];
private _diagnosticDecorations: DecorationSet = Decoration.none;
private _diagnosticsMouseoverListenerActive = false;
private _lastTransactions: Transaction[] = [];
private _declarativeExtensions = new Set<Extension>();
private _hasNotifiedExtensionsReady = false;
// Compartments for dynamic configuration
private readonly _lineNumbersCompartment = new Compartment();
private readonly _lineWrappingCompartment = new Compartment();
private readonly _languageCompartment = new Compartment();
private readonly _readOnlyCompartment = new Compartment();
private readonly _autocompletionCompartment = new Compartment();
private readonly _declarativeExtensionsCompartment = new Compartment();
private readonly _programmaticExtensionsCompartment = new Compartment();
autocompleteDelay = 1250;
private _lastAutocompleteRequest = 0;
// Create StateField for storing diagnostics decorations
private readonly _diagnosticField = StateField.define<DecorationSet>({
create: () => Decoration.none,
update: () => {
return this._diagnosticDecorations;
},
provide: (f) => EditorView.decorations.from(f),
});
override createRenderRoot() {
const root = this.attachShadow({mode: 'open'});
this._editorView?.setRoot(root);
root.adoptedStyleSheets = [
...PlaygroundCodeEditor.styles.map((s) => s.styleSheet!),
...root.adoptedStyleSheets,
];
return root;
}
override update(changedProperties: PropertyValues) {
const changedTyped = changedProperties as TypedMap<
Omit<
PlaygroundCodeEditor,
keyof LitElement | 'render' | 'update' | 'createRenderRoot'
> & {extensions: Extension | Extension[]}
>;
const view = this._editorView;
// Collect all CodeMirror state effects (configuration changes) to dispatch them together
// in a single transaction at the end of the update cycle.
const effects: StateEffect<unknown>[] = [];
for (const prop of changedTyped.keys()) {
switch (prop) {
case 'extensions':
effects.push(
this._programmaticExtensionsCompartment.reconfigure(
[this.extensions ?? []].flat()
)
);
break;
case 'documentKey': {
const docKey = this.documentKey ?? {};
let docState = this._docCache.get(docKey);
const lastKey = changedProperties.get('documentKey');
let needsHideAndFold = false;
// If a documentKey was previously active, cache its EditorState.
// This preserves the content and history when the user switches away
// from it and switches back later.
if (lastKey && this._editorView) {
const lastState = this._editorView.state;
this._docCache.set(lastKey, lastState);
// Value differs, so that means we need to update the view to
// reflect the new state's value.
if (lastState.doc.toString() !== this.value) {
view?.dispatch({
changes: [
{
from: 0,
to: lastState.doc.length,
insert: this.value ?? '',
},
],
annotations: programmaticChangeAnnotation.of(true),
});
}
}
if (!docState) {
// No cached EditorState exists for the new documentKey because it's
// likely being loaded for the first time.
docState = this._createEditorState(this.value ?? '');
this._docCache.set(docKey, docState);
needsHideAndFold = true;
} else if (docState.doc.toString() !== this.value) {
// A cached EditorState exists, but its content differs from the
// value property. We need to sync the cached state with the new
// value to preserve cmd+z history.
const tempView = new EditorView({state: docState});
tempView.dispatch({
changes: [
{
from: 0,
to: docState.doc.length,
insert: this.value ?? '',
},
],
annotations: programmaticChangeAnnotation.of(true),
});
docState = tempView.state;
this._docCache.set(docKey, docState);
tempView.destroy();
}
// Replace the entire view with the new editor state. Unlike CM5, CM6
// is modular, and the history stays on the state object rather than
// the editor / view.
this._editorView?.setState(docState);
// If a brand new document state was created, hiding and folding
// regions must be reapplied to this new state.
if (needsHideAndFold) {
void this._applyHideAndFoldRegions();
}
break;
}
case 'value':
if (changedTyped.has('documentKey')) {
// Handled in the `documentKey` case.
break;
}
if (this.value !== view?.state.doc.toString()) {
// The 'value' property was changed externally and it differs from
// the editor's current document content, so we need to update the
// view model to match.
view?.dispatch({
// Mark as an input userEvent so that the user can undo / redo
// this change
userEvent: 'input',
changes: [
{
from: 0,
to: view.state.doc.length,
insert: this.value ?? '',
},
],
annotations: programmaticChangeAnnotation.of(true),
});
}
break;
case 'lineNumbers':
effects.push(
this._lineNumbersCompartment.reconfigure(
this.lineNumbers ? cmLineNumbers() : []
)
);
break;
case 'lineWrapping':
effects.push(
this._lineWrappingCompartment.reconfigure(
this.lineWrapping ? EditorView.lineWrapping : []
)
);
break;
case 'type': {
const lang = this._getLanguageExtension();
effects.push(this._languageCompartment.reconfigure(lang || []));
break;
}
case 'readonly':
effects.push(
this._readOnlyCompartment.reconfigure(
this.readonly ? EditorState.readOnly.of(true) : []
)
);
break;
case 'pragmas':
void this._applyHideAndFoldRegions();
break;
case 'diagnostics':
this._showDiagnostics();
break;
case 'cursorIndex': {
const index = this.cursorIndex ?? 0;
if (view && index >= 0 && index <= view.state.doc.length) {
view.dispatch({
selection: {anchor: index, head: index},
});
}
break;
}
case 'cursorPosition': {
const pos = this.cursorPosition ?? {ch: 0, line: 0};
// Convert line/ch position to absolute position
const line = Math.max(
0,
Math.min(pos.line, view!.state.doc.lines - 1)
);
const lineObj = view!.state.doc.line(line + 1);
const ch = Math.max(0, Math.min(pos.ch, lineObj.length));
const index = lineObj.from + ch;
view?.dispatch({
selection: {anchor: index, head: index},
});
break;
}
case 'noCompletions':
effects.push(
this._autocompletionCompartment.reconfigure(
this.noCompletions ? [] : [this._getAutocompletions()]
)
);
break;
case '_completions':
this._showCompletions();
break;
case 'tokenUnderCursor':
case 'autocompleteDelay':
case '_completionsOpen':
// Ignored properties that do not require direct editor state updates
// or are handled by other mechanisms (e.g., getters, internal state changes).
break;
default:
unreachable(prop);
}
}
// If any configuration changes (effects like line numbers, wrapping, language mode) were queued
// during the property update loop, dispatch them to the CodeMirror editor now.
// This applies all pending configuration updates in a single, batched operation,
// which is generally more performant and ensures consistency.
if (effects.length > 0) {
view?.dispatch({effects});
}
super.update(changedProperties);
}
override render() {
if (this.readonly) {
return this._editorView?.dom;
}
return html`
<div
id="focusContainer"
tabindex="0"
@mousedown=${this._onMousedown}
@focus=${this._onFocus}
@blur=${this._onBlur}
@keydown=${this._onKeyDown}
>
<slot
name="extensions"
@register-codemirror-extension=${this._onRegisterExtension}
@slotchange=${this._onSlotChange}
></slot>
${this._showKeyboardHelp
? html`<playground-internal-overlay>
<p id="keyboardHelp" part="dialog">
Press <strong>Enter</strong> to start editing<br />
Press <strong>Escape</strong> to exit editor
</p>
</playground-internal-overlay>`
: nothing}
${this._editorView?.dom}
<div
id="tooltip"
?hidden=${!this._tooltipDiagnostic}
style=${ifDefined(this._tooltipDiagnostic?.position)}
>
<div part="diagnostic-tooltip">
${this._tooltipDiagnostic?.diagnostic.message}
</div>
</div>
</div>
`;
}
override connectedCallback() {
if (!this._editorView) {
this._editorView = new EditorView({
state: this._createEditorState(this.value ?? ''),
root: this.shadowRoot ?? undefined,
});
}
super.connectedCallback();
}
private _onSlotChange() {
if (this._hasNotifiedExtensionsReady) {
return;
}
this._hasNotifiedExtensionsReady = true;
this._notifyExtensionsReady();
}
override disconnectedCallback() {
this._editorView?.destroy();
this._editorView = undefined;
super.disconnectedCallback();
}
private _createEditorState(content: string): EditorState {
const baseExtensions: Extension[] = [
syntaxHighlighting(classHighlighter, {fallback: true}),
highlightSpecialChars(),
history(),
drawSelection(),
dropCursor(),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
bracketMatching(),
closeBrackets(),
highlightSelectionMatches(),
keymap.of([
...closeBracketsKeymap,
...defaultKeymap,
...searchKeymap,
...historyKeymap,
...foldKeymap,
...completionKeymap,
...lintKeymap,
indentWithTab,
]),
this._diagnosticField,
this._readOnlyCompartment.of(
this.readonly ? EditorState.readOnly.of(true) : []
),
this._lineNumbersCompartment.of(
this.lineNumbers ? [cmLineNumbers(), foldGutter()] : []
),
this._lineWrappingCompartment.of(
this.lineWrapping ? EditorView.lineWrapping : []
),
this._languageCompartment.of(
(() => {
return this._getLanguageExtension() || [];
})()
),
this._autocompletionCompartment.of(
this.noCompletions ? [] : [this._getAutocompletions()]
),
this._declarativeExtensionsCompartment.of([
...this._declarativeExtensions,
]),
this._programmaticExtensionsCompartment.of(
[this.extensions ?? []].flat()
),
playgroundTheme,
];
// Listen for changes
baseExtensions.push(
EditorView.updateListener.of((update: ViewUpdate) => {
if (update.docChanged) {
this._lastTransactions = [...update.transactions];
this._value = update.state.doc.toString();
const isUndoRedo = update.transactions.some(
(tr) =>
tr.annotation(Transaction.userEvent) === 'undo' ||
tr.annotation(Transaction.userEvent) === 'redo'
);
// Check if ALL transactions are programmatic (not user edits).
// We fire the change event if ANY transaction is a user edit, even if
// there are also programmatic transactions in the same update.
const allProgrammatic = update.transactions.every(
(tr) => tr.annotation(programmaticChangeAnnotation) === true
);
// External changes are usually things like the editor switching which
// file it is displaying.
if (allProgrammatic) {
// Apply hide/fold regions when value changes from outside
void this._applyHideAndFoldRegions();
this._showDiagnostics();
} else {
if (isUndoRedo) {
// Always reapply hide/fold regions after undo/redo
void this._applyHideAndFoldRegions();
}
// Only fire change event for user-initiated edits
this.dispatchEvent(new Event('change'));
}
}
})
);
return EditorState.create({
doc: content,
extensions: baseExtensions,
});
}
private _notifyExtensionsReady() {
for (const el of this._extensionElements) {
el.dispatchEvent(new PlaygroundEditorReadyEvent());
}
}
private _onRegisterExtension(e: RegisterCodemirrorExtensionEvent) {
e.stopPropagation();
const newExtensions = e.getExtensions();
const newExtArr = Array.isArray(newExtensions)
? [...newExtensions]
: [newExtensions];
for (const ext of newExtArr) {
this._declarativeExtensions.add(ext);
}
const unregister = () => {
for (const ext of newExtArr) {
this._declarativeExtensions.delete(ext);
}
this._reconfigureDeclarativeExtensions();
};
e.composedPath()[0].dispatchEvent(
new CodemirrorExtensionRegisteredEvent(unregister)
);
this._reconfigureDeclarativeExtensions();
}
private _reconfigureDeclarativeExtensions() {
this._editorView?.dispatch({
effects: this._declarativeExtensionsCompartment.reconfigure([
...this._declarativeExtensions,
]),
});
}
private _getLanguageExtension(): Extension | null {
switch (this.type) {
case 'js':
return lit();
case 'jsx':
return lit({jsx: true});
case 'ts':
return lit({typescript: true});
case 'tsx':
return lit({typescript: true, jsx: true});
case 'html':
return cmHtml();
case 'css':
return cmCss();
case 'json':
return lit();
default:
return null;
}
}
private _currentFiletypeSupportsCompletion() {
// Currently we are only supporting code completion for these. Change
// this in a case that we start to support configuring completions for
// other languages too.
return ['ts', 'js', 'tsx', 'jsx'].includes(this.type as string);
}
override focus() {
this._editorContent?.focus();
}
private _customCompletionSource = async (
context: CompletionContext
): Promise<CompletionResult | null> => {
if (this.noCompletions) {
return null;
}
// Only show completions when explicitly requested or when there's
// a token to complete
const wordBefore = context.matchBefore(/\w*/);
if (
(!wordBefore || wordBefore.from === wordBefore.to) &&
!context.explicit
) {
return null;
}
const wasTextEvent = this._lastTransactions.some(
(transaction) =>
transaction.annotation(Transaction.userEvent) === 'input.type'
);
const now = Date.now();
const wasRecent =
now - this._lastAutocompleteRequest <= this.autocompleteDelay;
if (now > this._lastAutocompleteRequest) {
this._lastAutocompleteRequest = now;
}
const isRefinement =
!context.explicit &&
wasTextEvent &&
(wordBefore?.text?.startsWith('.') ||
(wasRecent && (wordBefore?.text?.length ?? 0) > 1));
let resolve: (
value: EditorCompletion[] | Promise<EditorCompletion[]>
) => void;
const completionsPromise = new Promise<EditorCompletion[]>((res) => {
resolve = res;
});
this.dispatchEvent(
new CustomEvent('request-completions', {
detail: {
isRefinement,
fileContent: this.value,
tokenUnderCursor: this.tokenUnderCursor.string,
cursorIndex: this.cursorIndex,
provideCompletions: (completions: EditorCompletion[]) => {
resolve(completions);
},
},
})
);
const completions = await completionsPromise;
if (context.aborted) {
return null;
}
if (!completions || completions.length <= 0) {
return null;
}
const optionsPromises = completions.map(async (comp, i) => {
return {
label: comp.displayText || comp.text,
detail:
comp.details !== undefined ? (await comp.details).text : undefined,
apply: comp.text,
boost: i === 0 ? 99 : undefined, // Boost first suggestion
} satisfies Completion;
});
const options = await Promise.all(optionsPromises);
return {
from: wordBefore?.from ?? 0,
options,
};
};
private _getAutocompletions() {
return autocompletion({
// Only show completions when we explicitly support the language.
// Otherwise, default to whatever Codemirror does for it by default.
override: this._currentFiletypeSupportsCompletion()
? [this._customCompletionSource]
: undefined,
});
}
private _showCompletions() {
if (
!this._editorView ||
!this._completions ||
this._completions.length <= 0
)
return;
}
private _onMousedown() {
// Directly focus editable region.
this._editorContent?.focus();
}
private _onFocus() {
// Outer container was focused, either by tabbing from outside, or by
// pressing Escape.
this._showKeyboardHelp = true;
}
private _onBlur() {
// Outer container was unfocused, either by tabbing away from it, or by
// pressing Enter.
this._showKeyboardHelp = false;
}
private _onKeyDown(event: KeyboardEvent) {
if (event.key === 'Enter' && event.target === this._focusContainer) {
this._editorContent?.focus();
// Prevent typing a newline from this same event.
event.preventDefault();
} else if (event.key === 'Escape') {
// If the user has completions selection UI opened up, Escape's default action
// is to close the completion UI instead of escaping the code editor instance.
// Therefore we only focus on the focusContainer in situations where the completions
// UI is not open.
if (!this._completionsOpen) {
// Note there is no API for "select the next naturally focusable element",
// so instead we just re-focus the outer container, from which point the
// user can tab to move focus entirely elsewhere.
this._focusContainer?.focus();
}
}
}
private async _applyHideAndFoldRegions() {
if (!this._editorView) {
return;
}
if (this.pragmas === 'off-visible') {
return;
}
const pattern = this._maskPatternForLang();
if (pattern === undefined) {
return;
}
// CM6 decorations can be used for the '...' of hide/fold regions because
// they are designed to modify the appearance of what is rendered in the
// editor, so we also use it to simply hide the hide comments as well.
const decorations: Range<Decoration>[] = [];
const text = this._editorView.state.doc.toString();
// Annotations in CM6 are used for attaching metadata, in this case the
// fold ID, to dispatched actions.
const unfoldAnnotation = Annotation.define<number>();
for (const match of text.matchAll(pattern)) {
const [, opener, kind, content, closer] = match;
const openerStart = match.index ?? 0;
const foldId = openerStart; // Use the start position as the UID for the fold
const openerEnd = openerStart + opener.length;
// Hide opening comment
decorations.push(Decoration.replace({}).range(openerStart, openerEnd));
const contentStart = openerEnd;
let contentEnd;
if (content && closer) {
contentEnd = contentStart + content.length;
const closerStart = contentEnd;
const closerEnd = contentEnd + closer.length;