-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCodeMirror.tsx
More file actions
566 lines (507 loc) · 21.3 KB
/
CodeMirror.tsx
File metadata and controls
566 lines (507 loc) · 21.3 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
import React, { useMemo, useRef } from "react";
import { defaultKeymap, indentWithTab } from "@codemirror/commands";
import { defaultHighlightStyle, foldKeymap } from "@codemirror/language";
import { Compartment,EditorState, Extension } from "@codemirror/state";
import { DOMEventHandlers, EditorView, KeyBinding, keymap, Rect, ViewUpdate } from "@codemirror/view";
import { minimalSetup } from "codemirror";
import { Markdown } from "../../cmem/markdown/Markdown";
import { EditorAppearanceConfigMenu } from "./toolbars/EditorAppearanceConfigMenu";
import { IntentTypes } from "../../common/Intent";
import { markField } from "../../components/AutoSuggestion/extensions/markText";
import { TestableComponent } from "../../components/interfaces";
import { CLASSPREFIX as eccgui } from "../../configuration/constants";
//hooks
import {
SupportedCodeEditorModes,
supportedCodeEditorModes,
useCodeMirrorModeExtension,
} from "./hooks/useCodemirrorModeExtension.hooks";
import { jsLinter } from "./linters/jsLinter";
import { turtleLinter } from "./linters/turtleLinter";
//adaptations
import {
adaptedCodeFolding,
AdaptedEditorView,
AdaptedEditorViewDomEventHandlers,
adaptedFoldGutter,
adaptedHighlightActiveLine,
adaptedHighlightSpecialChars,
adaptedLineNumbers,
adaptedLintGutter,
adaptedPlaceholder,
adaptedSyntaxHighlighting,
compartment,
} from "./tests/codemirrorTestHelper";
import { MarkdownToolbar } from "./toolbars/markdown.toolbar";
import { ExtensionCreator } from "./types";
interface EditorAppearance {
/**
* If enabled the code editor won't show numbers before each line.
*/
preventLineNumbers?: boolean;
/** Long lines are wrapped and displayed on multiple lines */
wrapLines?: boolean;
}
export interface CodeEditorProps extends EditorAppearance, Omit<React.HTMLAttributes<HTMLDivElement>, "translate" | "onChange" | "onKeyDown" | "onMouseDown" | "onScroll">, TestableComponent {
// Is called with the editor instance that allows access via the CodeMirror API
setEditorView?: (editor: EditorView | undefined) => void;
/**
* `name` attribute of connected textarea element.
*/
name: string;
/**
* Placeholder to be shown when no text has been entered, yet.
*/
placeholder?: string;
/**
* `id` attribute of connected textarea element.
* If not set then the default value is created by `codemirror-${name-attribute}`.
*/
id?: string;
/**
* Handler method to receive onChange events.
* As input the new value is given.
*/
onChange?: (v: string) => void;
/**
* Called when the focus status changes
*/
onFocusChange?: (focused: boolean) => void;
/**
* Called when the user presses a key
*/
onKeyDown?: (event: KeyboardEvent) => boolean;
/**
* function invoked when any click occurs
*/
onMouseDown?: (view: EditorView) => void;
/**
* Called when the user selects text
*/
onSelection?: (ranges: { from: number; to: number }[]) => void;
/**
* Called when the cursor position changes
*/
onCursorChange?: (pos: number, coords: Rect, scrollinfo: HTMLElement, cm: EditorView) => void;
/**
* Syntax mode of the code editor.
*/
mode?: SupportedCodeEditorModes;
/**
* Default value used first when the editor is instanciated.
*/
defaultValue?: string;
/** Set read-only mode. Default: false */
readOnly?: boolean;
/** Optional height of the component */
height?: number | string;
/**
* Add properties to the `div` used as wrapper element.
* @deprecated (v26) You can now use all properties directly on `CodeEditor`.
*/
outerDivAttributes?: Omit<React.HTMLAttributes<HTMLDivElement>, "id" | "data-test-id" | "data-testid" | "translate" | "onChange" | "onKeyDown" | "onMouseDown" | "onScroll">;
/**
* Size in spaces that is used for a tabulator key.
*/
tabIntentSize?: number;
/**
* Set the char type that is used for the tabulator key.
* If set to `space` the a number of `tabIntentSize` spaces is used instead of a tab.
*/
tabIntentStyle?: "tab" | "space";
/**
* For some modes an indent style with `space` can be forced, even if `tabIntentStyle="tab"` is set.
*/
tabForceSpaceForModes?: SupportedCodeEditorModes[];
/**
* handler for scroll event
*/
onScroll?: (event: Event, view: EditorView) => boolean | void;
/**
* optional property to fold code for the supported modes e.g: xml, json etc.
*/
supportCodeFolding?: boolean;
/**
* highlight active line where the cursor is currently in
*/
shouldHighlightActiveLine?: boolean;
/**
* additional extensions to customize the editor further
*/
additionalExtensions?: Extension[];
/**
* codemirror minimal setup flag
*/
shouldHaveMinimalSetup?: boolean;
/**
* If the <Tab> key is enabled as normal input, i.e. it won't have the behavior of changing to the next input element, expected in a web app.
*/
enableTab?: boolean;
/**
* Enables linting feature in the editor ("turtle" and "javascript" modes can use linting currently).
*/
useLinting?: boolean;
/**
* Autofocus the editor when it is rendered
*/
autoFocus?: boolean;
/**
* Intent state of the code editor.
*/
intent?: IntentTypes | "edited" | "removed";
/**
* Disables the editor.
*/
disabled?: boolean;
/**
* Add toolbar for mode.
* Currently only `markdown` is supported.
*/
useToolbar?: boolean;
/**
* Get the translation for a specific key
*/
translate?: (key: string) => string | false;
}
const addExtensionsFor = (flag: boolean, ...extensions: Extension[]) => (flag ? [...extensions] : []);
const addToKeyMapConfigFor = (flag: boolean, ...keys: KeyBinding[]) => (flag ? [...keys] : []);
const addHandlersFor = (flag: boolean, handlerName: string, handler: any) =>
flag ? ({ [handlerName]: handler } as DOMEventHandlers<any>) : {};
const ModeLinterMap: ReadonlyMap<SupportedCodeEditorModes, ReadonlyArray<ExtensionCreator>> = new Map([
["turtle", [turtleLinter]],
["javascript", [jsLinter]],
]);
const ModeToolbarSupport: ReadonlyArray<SupportedCodeEditorModes> = ["markdown"];
const defaultAppearanceForModeWithToolbar: ReadonlyMap<SupportedCodeEditorModes, EditorAppearance> = new Map([
["markdown", { wrapLines: true, preventLineNumbers: true }]
]);
const getDefaultAppearanceForModeWithToolbar = (hasToolbar: boolean, mode?: SupportedCodeEditorModes): EditorAppearance | undefined => {
if (hasToolbar && mode) {
return defaultAppearanceForModeWithToolbar.get(mode);
}
return undefined;
}
/**
* Includes a code editor, currently we use CodeMirror library as base.
*/
export const CodeEditor = ({
className,
onChange,
onSelection,
onMouseDown,
onFocusChange,
onKeyDown,
onCursorChange,
name,
id,
mode,
preventLineNumbers,
wrapLines,
defaultValue = "",
readOnly = false,
shouldHaveMinimalSetup = true,
onScroll,
setEditorView,
supportCodeFolding = false,
shouldHighlightActiveLine = false,
outerDivAttributes,
tabIntentSize = 2,
tabIntentStyle = "tab",
placeholder,
additionalExtensions = [],
tabForceSpaceForModes = ["python", "yaml"],
enableTab = false,
height,
useLinting = false,
autoFocus = false,
disabled = false,
intent,
useToolbar = false,
translate,
...otherCodeEditorProps
}: CodeEditorProps) => {
const parent = useRef<any>(undefined);
const [view, setView] = React.useState<EditorView | undefined>();
const defaultAppearanceForModeWithToolbar = getDefaultAppearanceForModeWithToolbar(useToolbar, mode);
const [editorAppearance, setEditorAppearance] = React.useState<{[s: string]: boolean;}>(
{
// we also set the fallback default here
wrapLines: wrapLines ?? defaultAppearanceForModeWithToolbar?.wrapLines ?? false,
preventLineNumbers: preventLineNumbers ?? defaultAppearanceForModeWithToolbar?.preventLineNumbers ?? false,
}
)
const currentView = React.useRef<EditorView>()
currentView.current = view
const currentReadOnly = React.useRef(readOnly)
currentReadOnly.current = readOnly
const currentOnChange = React.useRef(onChange)
currentOnChange.current = onChange
const currentDisabled = React.useRef(disabled)
currentDisabled.current = disabled
const currentIntent = React.useRef(intent)
currentIntent.current = intent
const [showPreview, setShowPreview] = React.useState<boolean>(false);
// CodeMirror Compartments in order to allow for re-configuration after initialization
const readOnlyCompartment = React.useRef<Compartment>(compartment())
const wrapLinesCompartment = React.useRef<Compartment>(compartment())
const preventLineNumbersCompartment = React.useRef<Compartment>(compartment())
const shouldHaveMinimalSetupCompartment = React.useRef<Compartment>(compartment())
const placeholderCompartment = React.useRef<Compartment>(compartment())
const modeCompartment = React.useRef<Compartment>(compartment())
const keyMapConfigsCompartment = React.useRef<Compartment>(compartment())
const tabIntentSizeCompartment = React.useRef<Compartment>(compartment())
const disabledCompartment = React.useRef<Compartment>(compartment())
const supportCodeFoldingCompartment = React.useRef<Compartment>(compartment())
const useLintingCompartment = React.useRef<Compartment>(compartment())
const shouldHighlightActiveLineCompartment = React.useRef<Compartment>(compartment())
const linters = useMemo(() => {
if (!mode) {
return [];
}
const values = [adaptedLintGutter()];
const linters = ModeLinterMap.get(mode);
if (linters) {
values.push(...linters.map((linter) => linter()));
}
return values;
}, [mode]);
const onKeyDownHandler = (event: KeyboardEvent, view: EditorView) => {
if (onKeyDown && !onKeyDown(event)) {
if (event.key === "Enter" && !currentReadOnly.current) {
const cursor = view.state.selection.main.head;
view.dispatch({
changes: {
from: cursor,
insert: "\n",
},
selection: {
anchor: cursor + 1,
},
});
}
}
};
const getTranslation = (key: string): string | false => {
if (translate && typeof translate === "function") {
return translate(key);
}
return false;
};
const createKeyMapConfigs = () => {
const tabIndent =
!!(tabIntentStyle === "tab" && mode && !(tabForceSpaceForModes ?? []).includes(mode)) || enableTab;
return [
defaultKeymap as KeyBinding,
...addToKeyMapConfigFor(supportCodeFolding, ...foldKeymap),
...addToKeyMapConfigFor(tabIndent, indentWithTab),
];
}
React.useEffect(() => {
const domEventHandlers = {
...addHandlersFor(!!onScroll, "scroll", onScroll),
...addHandlersFor(
!!onMouseDown,
"mousedown",
(_: any, view: EditorView) => onMouseDown && onMouseDown(view)
),
...addHandlersFor(!!onFocusChange, "blur", () => onFocusChange && onFocusChange(false)),
...addHandlersFor(!!onFocusChange, "focus", () => onFocusChange && onFocusChange(true)),
...addHandlersFor(!!onKeyDown, "keydown", onKeyDownHandler),
} as DOMEventHandlers<any>;
const extensions = [
markField,
placeholderCompartment.current.of(adaptedPlaceholder(placeholder)),
adaptedHighlightSpecialChars(),
modeCompartment.current.of(useCodeMirrorModeExtension(mode)),
keyMapConfigsCompartment.current.of(keymap?.of(createKeyMapConfigs())),
tabIntentSizeCompartment.current.of(EditorState?.tabSize.of(tabIntentSize)),
readOnlyCompartment.current.of(EditorState?.readOnly.of(readOnly)),
disabledCompartment.current.of(EditorView?.editable.of(!disabled)),
AdaptedEditorViewDomEventHandlers(domEventHandlers) as Extension,
EditorView?.updateListener.of((v: ViewUpdate) => {
if (currentDisabled.current) return;
if (currentOnChange.current && v.docChanged) {
// Only fire if the text has actually been changed
currentOnChange.current(v.state.doc.toString());
}
if (onSelection)
onSelection(v.state.selection.ranges.filter((r) => !r.empty).map(({ from, to }) => ({ from, to })));
if (onFocusChange && currentIntent.current && !v.view.dom.classList?.contains(`${eccgui}-intent--${currentIntent.current}`)) {
v.view.dom.classList.add(`${eccgui}-intent--${currentIntent.current}`);
}
if (onCursorChange) {
const cursorPosition = v.state.selection.main.head ?? 0;
const editorRect = v.view.dom.getBoundingClientRect();
const coords = v.view.coordsAtPos(cursorPosition),
scrollInfo = v.view.scrollDOM;
if (coords && scrollInfo && editorRect) {
// Calculate the coordinates relative to the editor's top-left corner
const relativeLeft = coords.left - editorRect.left;
const relativeBottom = coords.bottom - editorRect.bottom;
onCursorChange(
cursorPosition,
{ ...coords, left: relativeLeft, bottom: relativeBottom },
scrollInfo,
v.view
);
}
}
}),
shouldHaveMinimalSetupCompartment.current.of(addExtensionsFor(shouldHaveMinimalSetup, minimalSetup)),
preventLineNumbersCompartment.current.of(addExtensionsFor(!editorAppearance.preventLineNumbers, adaptedLineNumbers())),
shouldHighlightActiveLineCompartment.current.of(addExtensionsFor(shouldHighlightActiveLine, adaptedHighlightActiveLine())),
wrapLinesCompartment.current.of(addExtensionsFor((editorAppearance.wrapLines!), EditorView?.lineWrapping)),
supportCodeFoldingCompartment.current.of(addExtensionsFor(supportCodeFolding, adaptedFoldGutter(), adaptedCodeFolding())),
useLintingCompartment.current.of(addExtensionsFor(useLinting, ...linters)),
adaptedSyntaxHighlighting(defaultHighlightStyle),
additionalExtensions,
];
const view: EditorView = new AdaptedEditorView({
state: EditorState?.create({
doc: defaultValue,
extensions,
}),
parent: parent.current,
});
setView(view);
if (view?.dom) {
if (height) {
view.dom.style.height = typeof height === "string" ? height : `${height}px`;
}
if (disabled) {
view.dom.classList.add(`${eccgui}-disabled`);
}
if (currentIntent.current) {
view.dom.className += ` ${eccgui}-intent--${currentIntent.current}`;
}
if (autoFocus) {
view.focus();
}
if (setEditorView) {
setEditorView(view);
}
}
return () => {
view.destroy();
if (setEditorView) {
setEditorView(undefined);
setView(undefined);
}
};
}, [parent.current]);
// Updates an extension for a specific parameter that has changed after the initialization
const updateExtension = (extension: Extension | undefined, parameterCompartment: Compartment): void => {
if(extension) {
currentView.current?.dispatch({
effects: parameterCompartment.reconfigure(extension)
})
}
}
React.useEffect(() => {
updateExtension(EditorState?.readOnly.of(readOnly!), readOnlyCompartment.current)
}, [readOnly])
React.useEffect(() => {
updateExtension(adaptedPlaceholder(placeholder), placeholderCompartment.current)
}, [placeholder])
React.useEffect(() => {
updateExtension(useCodeMirrorModeExtension(mode), modeCompartment.current)
}, [mode])
React.useEffect(() => {
updateExtension(keymap?.of(createKeyMapConfigs()), keyMapConfigsCompartment.current)
}, [supportCodeFolding, mode, tabIntentStyle, (tabForceSpaceForModes ?? []).join(", "), enableTab])
React.useEffect(() => {
updateExtension(EditorState?.tabSize.of(tabIntentSize ?? 2), tabIntentSizeCompartment.current)
}, [tabIntentSize])
React.useEffect(() => {
updateExtension(EditorView?.editable.of(!disabled), disabledCompartment.current);
if (view?.dom) {
if (disabled) {
view.dom.classList.add(`${eccgui}-disabled`);
} else {
view.dom.classList.remove(`${eccgui}-disabled`);
}
}
}, [disabled])
React.useEffect(() => {
setEditorAppearance({
...editorAppearance,
preventLineNumbers: preventLineNumbers ?? editorAppearance?.preventLineNumbers ?? false,
});
updateExtension(addExtensionsFor(!editorAppearance.preventLineNumbers, adaptedLineNumbers()), preventLineNumbersCompartment.current)
}, [preventLineNumbers, editorAppearance.preventLineNumbers])
React.useEffect(() => {
setEditorAppearance({
...editorAppearance,
wrapLines: wrapLines ?? editorAppearance?.wrapLines ?? false,
});
updateExtension(addExtensionsFor(editorAppearance.wrapLines!, EditorView?.lineWrapping), wrapLinesCompartment.current)
}, [wrapLines, editorAppearance.wrapLines])
React.useEffect(() => {
updateExtension(addExtensionsFor(shouldHaveMinimalSetup ?? true, minimalSetup), shouldHaveMinimalSetupCompartment.current)
}, [shouldHaveMinimalSetup])
React.useEffect(() => {
updateExtension(addExtensionsFor(shouldHighlightActiveLine ?? false, adaptedHighlightActiveLine()), shouldHighlightActiveLineCompartment.current)
}, [shouldHighlightActiveLine])
React.useEffect(() => {
updateExtension(addExtensionsFor(supportCodeFolding ?? false, adaptedFoldGutter(), adaptedCodeFolding()), supportCodeFoldingCompartment.current)
}, [supportCodeFolding])
React.useEffect(() => {
updateExtension(addExtensionsFor(useLinting ?? false, ...linters), useLintingCompartment.current)
}, [mode, useLinting])
const hasToolbarSupport = mode && ModeToolbarSupport.indexOf(mode) > -1 && useToolbar;
const editorToolbar = (mode?: SupportedCodeEditorModes): JSX.Element => {
switch (mode) {
case "markdown":
return (
<div>
<div className={`${eccgui}-codeeditor__toolbar`}>
<MarkdownToolbar
view={view}
togglePreviewStatus={() => setShowPreview((p) => !p)}
showPreview={showPreview}
translate={getTranslation}
disabled={disabled}
readonly={readOnly}
configMenu={(
<EditorAppearanceConfigMenu
config={{...editorAppearance}}
configLocked={{
wrapLines,
preventLineNumbers,
}}
setConfig={setEditorAppearance}
configPropertyTranslate={getTranslation}
/>
)}
/>
</div>
{showPreview && (
<div className={`${eccgui}-codeeditor__preview`}>
<Markdown>{view?.state.doc.toString() ?? ""}</Markdown>
</div>
)}
</div>
);
default:
return <></>;
}
};
return (
<div
{...outerDivAttributes}
// overwrite/extend some attributes
id={id ? id : name ? `codemirror-${name}` : undefined}
ref={parent}
{...otherCodeEditorProps}
className={
`${eccgui}-codeeditor ${eccgui}-codeeditor--mode-${mode}` +
(className ? ` ${className}` : "") +
(outerDivAttributes?.className ? ` ${outerDivAttributes?.className}` : "") +
(hasToolbarSupport ? ` ${eccgui}-codeeditor--has-toolbar` : "")
}
>
{hasToolbarSupport && editorToolbar(mode)}
</div>
);
};
CodeEditor.supportedModes = supportedCodeEditorModes;