@instructure/ui-source-code-editor 11.7.8 → 11.7.9-pr-snapshot-1792147648392

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,5 @@
1
- var _dec, _dec2, _dec3, _class;
2
- /*
3
- * The MIT License (MIT)
4
- *
5
- * Copyright (c) 2015 - present Instructure, Inc.
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in all
15
- * copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- * SOFTWARE.
24
- */
25
-
1
+ import { _ as _ts_decorate } from "@swc/helpers/_/_ts_decorate";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
26
3
  import { Component } from 'react';
27
4
  import { createPortal } from 'react-dom';
28
5
  import { deepEqual as isEqual } from '@instructure/ui-utils';
@@ -40,8 +17,6 @@ import { markdown } from '@codemirror/lang-markdown';
40
17
  import { json } from '@codemirror/lang-json';
41
18
  import { shell } from '@codemirror/legacy-modes/mode/shell';
42
19
  import { yaml } from '@codemirror/legacy-modes/mode/yaml';
43
- // import { oneDarkTheme, oneDarkHighlightStyle } from '@codemirror/theme-one-dark'
44
-
45
20
  import { omitProps, passthroughProps, withDeterministicId } from '@instructure/ui-react-utils';
46
21
  import { requestAnimationFrame } from '@instructure/ui-dom-utils';
47
22
  import { ScreenReaderContent } from '@instructure/ui-a11y-content';
@@ -51,536 +26,517 @@ import customSearch, { SearchPanel } from './SearchPanel.js';
51
26
  import generateStyle from './styles.js';
52
27
  import { rtlHorizontalArrowKeymap } from './customKeybinding.js';
53
28
  import { allowedProps } from './props.js';
54
- import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
55
- /**
56
- ---
57
- category: components
58
- ---
59
- **/
60
- let SourceCodeEditor = (_dec = withDeterministicId(), _dec2 = withStyleNew(generateStyle), _dec3 = textDirectionContextConsumer(), _dec(_class = _dec2(_class = _dec3(_class = class SourceCodeEditor extends Component {
61
- static displayName = 'SourceCodeEditor';
62
- static componentId = 'SourceCodeEditor';
63
- static allowedProps = allowedProps;
64
- static defaultProps = {
65
- language: 'jsx',
66
- readOnly: false,
67
- editable: true,
68
- lineNumbers: false,
69
- foldGutter: false,
70
- highlightActiveLine: false,
71
- highlightActiveLineGutter: false,
72
- lineWrapping: false,
73
- autofocus: false,
74
- spellcheck: false,
75
- rtlMoveVisually: true,
76
- indentOnLoad: false,
77
- indentWithTab: false,
78
- defaultValue: '',
79
- height: 'auto'
80
- };
81
- _id;
82
- ref = null;
83
- state = {
84
- searchPanels: []
85
- };
86
- _containerRef;
87
- _editorView;
88
- _raf = [];
89
- _searchPanelId = 0;
90
- _isUnmounting = false;
91
- _newSelectionAfterValueChange;
92
- handleSearchPanelMount = (dom, view) => {
93
- this.setState(state => ({
94
- searchPanels: [...state.searchPanels, {
95
- id: ++this._searchPanelId,
96
- dom,
97
- view
98
- }]
99
- }));
100
- };
101
- handleSearchPanelDestroy = dom => {
102
- if (this._isUnmounting) return;
103
- this.setState(state => ({
104
- searchPanels: state.searchPanels.filter(panel => panel.dom !== dom)
105
- }));
106
- };
107
- handleRef = el => {
108
- const {
109
- elementRef
110
- } = this.props;
111
- this.ref = el;
112
- if (typeof elementRef === 'function') {
113
- elementRef(el);
114
- }
115
- };
116
- handleContainerRef = el => {
117
- const {
118
- containerRef
119
- } = this.props;
120
- this._containerRef = el || undefined;
121
- if (typeof containerRef === 'function') {
122
- containerRef(el);
123
- }
124
- };
125
- addAnimationFrame(callback) {
126
- if (typeof callback === 'function') {
127
- this._raf.push(requestAnimationFrame(callback));
128
- }
129
- }
130
- cancelAnimationFrames() {
131
- this._raf.forEach(request => request.cancel());
132
- this._raf = [];
133
- }
134
- focus() {
135
- this.addAnimationFrame(() => {
136
- this._editorView?.focus();
137
- });
138
- }
139
- get hasFocus() {
140
- return this._editorView?.hasFocus;
141
- }
142
- selectAll() {
143
- if (this._editorView) {
144
- this.addAnimationFrame(() => {
145
- this.dispatchViewSelection({
146
- anchor: 0,
147
- head: this.currentDocValue?.length
29
+ class SourceCodeEditor extends Component {
30
+ static{
31
+ this.displayName = 'SourceCodeEditor';
32
+ }
33
+ static{
34
+ this.componentId = 'SourceCodeEditor';
35
+ }
36
+ static{
37
+ this.allowedProps = allowedProps;
38
+ }
39
+ static{
40
+ this.defaultProps = {
41
+ language: 'jsx',
42
+ readOnly: false,
43
+ editable: true,
44
+ lineNumbers: false,
45
+ foldGutter: false,
46
+ highlightActiveLine: false,
47
+ highlightActiveLineGutter: false,
48
+ lineWrapping: false,
49
+ autofocus: false,
50
+ spellcheck: false,
51
+ rtlMoveVisually: true,
52
+ indentOnLoad: false,
53
+ indentWithTab: false,
54
+ defaultValue: '',
55
+ height: 'auto'
56
+ };
57
+ }
58
+ addAnimationFrame(callback) {
59
+ if (typeof callback === 'function') {
60
+ this._raf.push(requestAnimationFrame(callback));
61
+ }
62
+ }
63
+ cancelAnimationFrames() {
64
+ this._raf.forEach((request)=>request.cancel());
65
+ this._raf = [];
66
+ }
67
+ focus() {
68
+ this.addAnimationFrame(()=>{
69
+ this._editorView?.focus();
148
70
  });
149
- });
150
- }
151
- }
152
- deselectAll() {
153
- if (this._editorView) {
154
- this.addAnimationFrame(() => {
155
- this.dispatchViewSelection({
156
- anchor: 0,
157
- head: 0
71
+ }
72
+ get hasFocus() {
73
+ return this._editorView?.hasFocus;
74
+ }
75
+ selectAll() {
76
+ if (this._editorView) {
77
+ this.addAnimationFrame(()=>{
78
+ this.dispatchViewSelection({
79
+ anchor: 0,
80
+ head: this.currentDocValue?.length
81
+ });
82
+ });
83
+ }
84
+ }
85
+ deselectAll() {
86
+ if (this._editorView) {
87
+ this.addAnimationFrame(()=>{
88
+ this.dispatchViewSelection({
89
+ anchor: 0,
90
+ head: 0
91
+ });
92
+ });
93
+ }
94
+ }
95
+ indentCurrentSelection() {
96
+ this.addAnimationFrame(()=>{
97
+ if (this._editorView) {
98
+ indentSelection({
99
+ state: this._editorView.state,
100
+ dispatch: (transaction)=>{
101
+ this._editorView?.update([
102
+ transaction
103
+ ]);
104
+ }
105
+ });
106
+ }
158
107
  });
159
- });
160
- }
161
- }
162
- indentCurrentSelection() {
163
- this.addAnimationFrame(() => {
164
- if (this._editorView) {
165
- indentSelection({
166
- state: this._editorView.state,
167
- dispatch: transaction => {
168
- this._editorView?.update([transaction]);
169
- }
108
+ }
109
+ indentAll() {
110
+ this.addAnimationFrame(()=>{
111
+ if (this._editorView && this.currentDocValue) {
112
+ this.indentCodeRange(0, this.currentDocValue.length);
113
+ }
170
114
  });
171
- }
172
- });
173
- }
174
- indentAll() {
175
- this.addAnimationFrame(() => {
176
- if (this._editorView && this.currentDocValue) {
177
- this.indentCodeRange(0, this.currentDocValue.length);
178
- }
179
- });
180
- }
181
- indentCodeRange(from, to) {
182
- this.addAnimationFrame(() => {
183
- if (this._editorView && this.currentDocValue) {
184
- this.dispatchViewChanges({
185
- changes: indentRange(this._editorView.state, from, to)
115
+ }
116
+ indentCodeRange(from, to) {
117
+ this.addAnimationFrame(()=>{
118
+ if (this._editorView && this.currentDocValue) {
119
+ this.dispatchViewChanges({
120
+ changes: indentRange(this._editorView.state, from, to)
121
+ });
122
+ }
186
123
  });
187
- }
188
- });
189
- }
190
-
191
- // Attach state effects
192
- dispatchViewEffects(effects) {
193
- if (!this._editorView || !effects) return;
194
- this._editorView.dispatch({
195
- effects
196
- });
197
- }
198
-
199
- // Dispatch changes to the document
200
- dispatchViewChanges({
201
- changes,
202
- selection,
203
- userEvent
204
- }) {
205
- if (!this._editorView || !changes) return;
206
- this._editorView.dispatch({
207
- changes,
208
- ...(selection ? {
209
- selection
210
- } : undefined),
211
- ...(userEvent ? {
212
- userEvent
213
- } : undefined)
214
- });
215
- }
216
-
217
- // Select a portion of the document
218
- dispatchViewSelection(selection) {
219
- if (!this._editorView || !selection) return;
220
- this._editorView.dispatch({
221
- selection
222
- });
223
- }
224
- get currentDocValue() {
225
- return this._editorView?.state.doc;
226
- }
227
-
228
- // when value is passed, the editor should be controlled
229
- get isControlled() {
230
- return typeof this.props.value === 'string';
231
- }
232
- constructor(props) {
233
- super(props);
234
- this._id = props.deterministicId();
235
- }
236
- componentDidMount() {
237
- const {
238
- value,
239
- defaultValue,
240
- autofocus,
241
- indentOnLoad
242
- } = this.props;
243
- this.props.makeStyles?.();
244
- const state = EditorState.create({
245
- doc: value || defaultValue,
246
- extensions: this.extensions
247
- });
248
- this._editorView = new EditorView({
249
- state,
250
- parent: this._containerRef
251
- });
252
-
253
- // from the a11y team:
254
- // axe devtools and other automated a11y tests both flagging this issue,
255
- // which can be observed while navigating with keyboard:
256
- // Ensure elements that have scrollable content are accessible by keyboard
257
- // To solve this problem, you need to fix at least (1) of the following:
258
- // Element should have focusable content, Element should be focusable
259
- this._editorView.scrollDOM.tabIndex = 0;
260
- if (autofocus) {
261
- this.focus();
262
- }
263
- if (indentOnLoad) {
264
- this.indentAll();
265
- }
266
- this.assignAriaLabel();
267
- }
268
- componentWillUnmount() {
269
- this._isUnmounting = true;
270
- this._editorView?.destroy();
271
- this.cancelAnimationFrames();
272
- }
273
- componentDidUpdate(prevProps) {
274
- this.props.makeStyles?.();
275
- if (this._editorView) {
276
- if (this.props.value !== prevProps.value) {
277
- this.refreshEditorValue();
278
- }
279
- if (this.shouldUpdateExtensions(prevProps)) {
280
- this.refreshExtensions();
281
- }
282
- }
283
- }
284
- shouldUpdateExtensions(prevProps) {
285
- const propsToObserve = ['styles',
286
- // needed for theme update
287
- 'themeOverride', 'language', 'readOnly', 'editable', 'lineNumbers', 'highlightActiveLineGutter', 'foldGutter', 'lineWrapping', 'autofocus', 'spellcheck', 'direction', 'dir', 'rtlMoveVisually', 'indentOnLoad', 'indentWithTab', 'indentUnit', 'highlightActiveLine', 'attachment', 'searchConfig'];
288
- for (const prop of propsToObserve) {
289
- if (!isEqual(this.props[prop], prevProps[prop])) {
290
- return true;
291
- }
292
- }
293
- return false;
294
- }
295
- get direction() {
296
- // comes from the `direction` prop and
297
- // falls back to the `dir` prop coming from the bidirectional decorator
298
- return this.props.direction || this.props.dir;
299
- }
300
- get extensions() {
301
- const extensions = [...this.baseExtensions,
302
- // our custom extensions
303
- this.languageExtension, this.onChangeExtension, this.focusListenerExtension, this.announceLineNumberExtension];
304
- if (this.themeExtension) {
305
- extensions.push(this.themeExtension);
306
- }
307
- if (this.props.lineNumbers) {
308
- extensions.push(lineNumbers());
309
- }
310
- if (this.props.highlightActiveLine) {
311
- extensions.push(highlightActiveLine());
312
- }
313
- if (this.props.highlightActiveLineGutter) {
314
- extensions.push(highlightActiveLineGutter());
315
- }
316
- if (this.props.foldGutter) {
317
- extensions.push(foldGutter());
318
- }
319
- if (this.props.lineWrapping) {
320
- extensions.push(EditorView.lineWrapping);
321
- }
322
- if (this.props.editable === false) {
323
- extensions.push(EditorView.editable.of(false));
324
- }
325
- if (this.props.readOnly) {
326
- extensions.push(EditorState.readOnly.of(true));
327
- }
328
- if (this.props.spellcheck) {
329
- extensions.push(EditorView.contentAttributes.of({
330
- spellcheck: 'true'
331
- }));
332
- }
333
- if (this.direction) {
334
- extensions.push(EditorView.contentAttributes.of({
335
- dir: this.direction
336
- }));
337
- }
338
- if (this.props.indentUnit) {
339
- extensions.push(indentUnit.of(this.props.indentUnit));
340
- }
341
- return extensions;
342
- }
343
- get baseExtensions() {
344
- return [
345
- // The extensions are based on codemirrors basic setup from 'codemirror'.
346
- // It is recommended by CodeMirror, that if we want to configure
347
- // our editor more precisely, we have to copy the source
348
- // and adjust it as desired.
349
- highlightSpecialChars(), history(), drawSelection(), dropCursor(), EditorState.allowMultipleSelections.of(true), syntaxHighlighting(defaultHighlightStyle, {
350
- fallback: true
351
- }), bracketMatching(), closeBrackets(), autocompletion(), rectangularSelection(), crosshairCursor(), highlightSelectionMatches(), indentOnInput(), customSearch(this.props.searchConfig, {
352
- onMount: this.handleSearchPanelMount,
353
- onDestroy: this.handleSearchPanelDestroy
354
- }), keymap.of(this.keymaps)];
355
- }
356
- get keymaps() {
357
- // TODO: if more keymaps are added, list them in the docs as well (#Command keybinding)
358
- const keymaps = [...closeBracketsKeymap, ...this.commandKeybinding, ...historyKeymap, ...foldKeymap, ...completionKeymap, ...lintKeymap, ...(this.props.searchConfig ? searchKeymap : [])];
359
- if (this.props.indentWithTab) {
360
- keymaps.push(indentWithTab);
361
- }
362
- return keymaps;
363
- }
364
- get commandKeybinding() {
365
- const {
366
- rtlMoveVisually
367
- } = this.props;
368
- if (this.direction === 'rtl' && !rtlMoveVisually) {
369
- const overrideableKeys = rtlHorizontalArrowKeymap.map(binding => binding.key ? binding.key : binding.mac ? binding.mac : binding);
370
- // we have to remove the binding we want to override from the original,
371
- // otherwise all will be merged and the defaults will still apply
372
- const filteredOriginal = defaultKeymap.filter(binding => binding.key ? overrideableKeys.indexOf(binding.key) < 0 : binding.mac ? overrideableKeys.indexOf(binding.mac) < 0 : false);
373
- return [...filteredOriginal, ...rtlHorizontalArrowKeymap];
374
- }
375
- return defaultKeymap;
376
- }
377
- get themeExtension() {
378
- const {
379
- styles
380
- } = this.props;
381
- if (!styles?.theme || !styles.highlightStyle) {
382
- return undefined;
383
- }
384
- const theme = EditorView.theme(styles?.theme);
385
- const highlightStyle = syntaxHighlighting(HighlightStyle.define(styles?.highlightStyle));
386
-
387
- // see notes in props.ts
388
- // if (darkTheme) {
389
- // theme = oneDarkTheme
390
- // highlightStyle = syntaxHighlighting(oneDarkHighlightStyle)
391
- // }
392
-
393
- return [theme, highlightStyle];
394
- }
395
- get languageExtension() {
396
- const {
397
- language
398
- } = this.props;
399
- switch (language) {
400
- case 'json':
401
- return json();
402
- case 'js':
403
- case 'jsx':
404
- case 'javascript':
405
- return javascript({
406
- jsx: true,
407
- typescript: true
124
+ }
125
+ dispatchViewEffects(effects) {
126
+ if (!this._editorView || !effects) return;
127
+ this._editorView.dispatch({
128
+ effects
408
129
  });
409
- case 'html':
410
- return html({
411
- matchClosingTags: true,
412
- autoCloseTags: true
130
+ }
131
+ dispatchViewChanges({ changes, selection, userEvent }) {
132
+ if (!this._editorView || !changes) return;
133
+ this._editorView.dispatch({
134
+ changes,
135
+ ...selection ? {
136
+ selection
137
+ } : undefined,
138
+ ...userEvent ? {
139
+ userEvent
140
+ } : undefined
413
141
  });
414
- case 'css':
415
- return css();
416
- case 'markdown':
417
- return markdown();
418
- case 'sh':
419
- case 'shell':
420
- case 'bash':
421
- // ????
422
- return StreamLanguage.define(shell);
423
- case 'yml':
424
- case 'yaml':
425
- return StreamLanguage.define(yaml);
426
- default:
427
- return javascript({
428
- jsx: true,
429
- typescript: true
142
+ }
143
+ dispatchViewSelection(selection) {
144
+ if (!this._editorView || !selection) return;
145
+ this._editorView.dispatch({
146
+ selection
430
147
  });
431
148
  }
432
- }
433
- callOnChangeHandler(newValue) {
434
- const {
435
- onChange,
436
- value
437
- } = this.props;
438
- this.addAnimationFrame(() => {
439
- if (typeof onChange === 'function' && newValue !== value) {
440
- onChange(newValue);
441
- }
442
- });
443
- }
444
- get onChangeExtension() {
445
- return EditorState.changeFilter.of(transaction => {
446
- if (!this._editorView) {
447
- return false;
448
- }
449
- if (transaction.docChanged) {
450
- const newDoc = transaction.newDoc.toString();
451
- if (this.isControlled) {
452
- // the value will be changed by the onChange handler,
453
- // refreshEditorValue has to run first
454
- if (newDoc !== this.props.value) {
455
- this._newSelectionAfterValueChange = transaction.selection;
456
- this.cancelAnimationFrames();
457
- this.callOnChangeHandler(newDoc);
458
- return false;
459
- } else {
460
- return true;
461
- }
462
- } else {
463
- this.callOnChangeHandler(newDoc);
149
+ get currentDocValue() {
150
+ return this._editorView?.state.doc;
151
+ }
152
+ get isControlled() {
153
+ return typeof this.props.value === 'string';
154
+ }
155
+ constructor(props){
156
+ super(props), this.ref = null, this.state = {
157
+ searchPanels: []
158
+ }, this._raf = [], this._searchPanelId = 0, this._isUnmounting = false, this.handleSearchPanelMount = (dom, view)=>{
159
+ this.setState((state)=>({
160
+ searchPanels: [
161
+ ...state.searchPanels,
162
+ {
163
+ id: ++this._searchPanelId,
164
+ dom,
165
+ view
166
+ }
167
+ ]
168
+ }));
169
+ }, this.handleSearchPanelDestroy = (dom)=>{
170
+ if (this._isUnmounting) return;
171
+ this.setState((state)=>({
172
+ searchPanels: state.searchPanels.filter((panel)=>panel.dom !== dom)
173
+ }));
174
+ }, this.handleRef = (el)=>{
175
+ const { elementRef } = this.props;
176
+ this.ref = el;
177
+ if (typeof elementRef === 'function') {
178
+ elementRef(el);
179
+ }
180
+ }, this.handleContainerRef = (el)=>{
181
+ const { containerRef } = this.props;
182
+ this._containerRef = el || undefined;
183
+ if (typeof containerRef === 'function') {
184
+ containerRef(el);
185
+ }
186
+ }, this.assignAriaLabel = ()=>{
187
+ if (this._containerRef) {
188
+ const editorDiv = this._containerRef.querySelector('[role="textbox"]');
189
+ if (editorDiv) {
190
+ editorDiv.setAttribute('aria-labelledby', `${this._id}`);
191
+ }
192
+ }
193
+ };
194
+ this._id = props.deterministicId();
195
+ }
196
+ componentDidMount() {
197
+ const { value, defaultValue, autofocus, indentOnLoad } = this.props;
198
+ this.props.makeStyles?.();
199
+ const state = EditorState.create({
200
+ doc: value || defaultValue,
201
+ extensions: this.extensions
202
+ });
203
+ this._editorView = new EditorView({
204
+ state,
205
+ parent: this._containerRef
206
+ });
207
+ this._editorView.scrollDOM.tabIndex = 0;
208
+ if (autofocus) {
209
+ this.focus();
464
210
  }
465
- }
466
- return true;
467
- });
468
- }
469
- get focusListenerExtension() {
470
- const {
471
- onFocus,
472
- onBlur
473
- } = this.props;
474
- return EditorView.updateListener.of(update => {
475
- if (update.focusChanged && this._editorView) {
476
- if (this.hasFocus) {
477
- if (typeof onFocus === 'function') {
478
- onFocus();
479
- }
480
- } else {
481
- if (typeof onBlur === 'function') {
482
- onBlur();
483
- }
211
+ if (indentOnLoad) {
212
+ this.indentAll();
484
213
  }
485
- }
486
- });
487
- }
488
- get announceLineNumberExtension() {
489
- return EditorState.transactionExtender.of(tr => {
490
- const selection = tr.selection;
491
- const oldSelection = tr.startState.selection.main;
492
- if (selection && selection.main.empty && oldSelection.empty) {
493
- const oldLine = tr.startState.doc.lineAt(oldSelection.head);
494
- const newLine = tr.newDoc.lineAt(selection.main.head);
495
- if (oldLine.number != newLine.number) return {
496
- effects: EditorView.announce.of(tr.startState.phrase('line ') + newLine.number + '.')
497
- };
498
- }
499
- return null;
500
- });
501
- }
502
- refreshExtensions() {
503
- this.dispatchViewEffects(StateEffect.reconfigure.of(this.extensions));
504
- }
505
- refreshEditorValue() {
506
- if (!this._editorView) return;
507
- const {
508
- value
509
- } = this.props;
510
- const currentValue = this._editorView.state.doc.toString();
511
- if (typeof value !== 'undefined' && currentValue !== value) {
512
- let userEvent;
513
- const lengthDiff = value.length - currentValue.length;
514
-
515
- // setting user events are needed for the autocomplete to work
516
- // (only these 2 events, autocomplete doesn't work on paste, etc.)
517
- if (lengthDiff === 1) {
518
- userEvent = 'input.type';
519
- } else if (lengthDiff === -1) {
520
- userEvent = 'delete.backward';
521
- }
522
- const scrollTop = this._editorView.scrollDOM.scrollTop;
523
- this.dispatchViewChanges({
524
- changes: {
525
- from: 0,
526
- to: currentValue.length,
527
- insert: value || ''
528
- },
529
- selection: this._newSelectionAfterValueChange,
530
- userEvent: userEvent
531
- });
532
-
533
- // Restore scroll position after CodeMirror updates the DOM
534
- this.addAnimationFrame(() => {
214
+ this.assignAriaLabel();
215
+ }
216
+ componentWillUnmount() {
217
+ this._isUnmounting = true;
218
+ this._editorView?.destroy();
219
+ this.cancelAnimationFrames();
220
+ }
221
+ componentDidUpdate(prevProps) {
222
+ this.props.makeStyles?.();
535
223
  if (this._editorView) {
536
- this._editorView.scrollDOM.scrollTop = scrollTop;
224
+ if (this.props.value !== prevProps.value) {
225
+ this.refreshEditorValue();
226
+ }
227
+ if (this.shouldUpdateExtensions(prevProps)) {
228
+ this.refreshExtensions();
229
+ }
537
230
  }
538
- });
539
- this._newSelectionAfterValueChange = undefined;
540
- }
541
- if (this.props.indentOnLoad) {
542
- this.indentAll();
543
- }
544
- }
545
- assignAriaLabel = () => {
546
- if (this._containerRef) {
547
- const editorDiv = this._containerRef.querySelector('[role="textbox"]');
548
- if (editorDiv) {
549
- editorDiv.setAttribute('aria-labelledby', `${this._id}`);
550
- }
551
- }
552
- };
553
- render() {
554
- const {
555
- label,
556
- styles,
557
- searchConfig,
558
- ...restProps
559
- } = this.props;
560
- return _jsxs("div", {
561
- "data-cid": "SourceCodeEditor",
562
- ref: this.handleRef,
563
- css: styles?.codeEditor,
564
- ...passthroughProps(omitProps(restProps, SourceCodeEditor.allowedProps)),
565
- children: [_jsxs("label", {
566
- css: styles?.label,
567
- id: this._id,
568
- children: [_jsx(ScreenReaderContent, {
569
- children: label
570
- }), _jsx("div", {
571
- ref: this.handleContainerRef,
572
- css: styles?.codeEditorContainer
573
- })]
574
- }), searchConfig && this.state.searchPanels.map(({
575
- id,
576
- dom,
577
- view
578
- }) => /*#__PURE__*/createPortal(_jsx(SearchPanel, {
579
- view: view,
580
- searchConfig: searchConfig
581
- }), dom, String(id)))]
582
- });
583
- }
584
- }) || _class) || _class) || _class);
231
+ }
232
+ shouldUpdateExtensions(prevProps) {
233
+ const propsToObserve = [
234
+ 'styles',
235
+ 'themeOverride',
236
+ 'language',
237
+ 'readOnly',
238
+ 'editable',
239
+ 'lineNumbers',
240
+ 'highlightActiveLineGutter',
241
+ 'foldGutter',
242
+ 'lineWrapping',
243
+ 'autofocus',
244
+ 'spellcheck',
245
+ 'direction',
246
+ 'dir',
247
+ 'rtlMoveVisually',
248
+ 'indentOnLoad',
249
+ 'indentWithTab',
250
+ 'indentUnit',
251
+ 'highlightActiveLine',
252
+ 'attachment',
253
+ 'searchConfig'
254
+ ];
255
+ for (const prop of propsToObserve){
256
+ if (!isEqual(this.props[prop], prevProps[prop])) {
257
+ return true;
258
+ }
259
+ }
260
+ return false;
261
+ }
262
+ get direction() {
263
+ return this.props.direction || this.props.dir;
264
+ }
265
+ get extensions() {
266
+ const extensions = [
267
+ ...this.baseExtensions,
268
+ this.languageExtension,
269
+ this.onChangeExtension,
270
+ this.focusListenerExtension,
271
+ this.announceLineNumberExtension
272
+ ];
273
+ if (this.themeExtension) {
274
+ extensions.push(this.themeExtension);
275
+ }
276
+ if (this.props.lineNumbers) {
277
+ extensions.push(lineNumbers());
278
+ }
279
+ if (this.props.highlightActiveLine) {
280
+ extensions.push(highlightActiveLine());
281
+ }
282
+ if (this.props.highlightActiveLineGutter) {
283
+ extensions.push(highlightActiveLineGutter());
284
+ }
285
+ if (this.props.foldGutter) {
286
+ extensions.push(foldGutter());
287
+ }
288
+ if (this.props.lineWrapping) {
289
+ extensions.push(EditorView.lineWrapping);
290
+ }
291
+ if (this.props.editable === false) {
292
+ extensions.push(EditorView.editable.of(false));
293
+ }
294
+ if (this.props.readOnly) {
295
+ extensions.push(EditorState.readOnly.of(true));
296
+ }
297
+ if (this.props.spellcheck) {
298
+ extensions.push(EditorView.contentAttributes.of({
299
+ spellcheck: 'true'
300
+ }));
301
+ }
302
+ if (this.direction) {
303
+ extensions.push(EditorView.contentAttributes.of({
304
+ dir: this.direction
305
+ }));
306
+ }
307
+ if (this.props.indentUnit) {
308
+ extensions.push(indentUnit.of(this.props.indentUnit));
309
+ }
310
+ return extensions;
311
+ }
312
+ get baseExtensions() {
313
+ return [
314
+ highlightSpecialChars(),
315
+ history(),
316
+ drawSelection(),
317
+ dropCursor(),
318
+ EditorState.allowMultipleSelections.of(true),
319
+ syntaxHighlighting(defaultHighlightStyle, {
320
+ fallback: true
321
+ }),
322
+ bracketMatching(),
323
+ closeBrackets(),
324
+ autocompletion(),
325
+ rectangularSelection(),
326
+ crosshairCursor(),
327
+ highlightSelectionMatches(),
328
+ indentOnInput(),
329
+ customSearch(this.props.searchConfig, {
330
+ onMount: this.handleSearchPanelMount,
331
+ onDestroy: this.handleSearchPanelDestroy
332
+ }),
333
+ keymap.of(this.keymaps)
334
+ ];
335
+ }
336
+ get keymaps() {
337
+ const keymaps = [
338
+ ...closeBracketsKeymap,
339
+ ...this.commandKeybinding,
340
+ ...historyKeymap,
341
+ ...foldKeymap,
342
+ ...completionKeymap,
343
+ ...lintKeymap,
344
+ ...this.props.searchConfig ? searchKeymap : []
345
+ ];
346
+ if (this.props.indentWithTab) {
347
+ keymaps.push(indentWithTab);
348
+ }
349
+ return keymaps;
350
+ }
351
+ get commandKeybinding() {
352
+ const { rtlMoveVisually } = this.props;
353
+ if (this.direction === 'rtl' && !rtlMoveVisually) {
354
+ const overrideableKeys = rtlHorizontalArrowKeymap.map((binding)=>binding.key ? binding.key : binding.mac ? binding.mac : binding);
355
+ const filteredOriginal = defaultKeymap.filter((binding)=>binding.key ? overrideableKeys.indexOf(binding.key) < 0 : binding.mac ? overrideableKeys.indexOf(binding.mac) < 0 : false);
356
+ return [
357
+ ...filteredOriginal,
358
+ ...rtlHorizontalArrowKeymap
359
+ ];
360
+ }
361
+ return defaultKeymap;
362
+ }
363
+ get themeExtension() {
364
+ const { styles } = this.props;
365
+ if (!styles?.theme || !styles.highlightStyle) {
366
+ return undefined;
367
+ }
368
+ const theme = EditorView.theme(styles?.theme);
369
+ const highlightStyle = syntaxHighlighting(HighlightStyle.define(styles?.highlightStyle));
370
+ return [
371
+ theme,
372
+ highlightStyle
373
+ ];
374
+ }
375
+ get languageExtension() {
376
+ const { language } = this.props;
377
+ switch(language){
378
+ case 'json':
379
+ return json();
380
+ case 'js':
381
+ case 'jsx':
382
+ case 'javascript':
383
+ return javascript({
384
+ jsx: true,
385
+ typescript: true
386
+ });
387
+ case 'html':
388
+ return html({
389
+ matchClosingTags: true,
390
+ autoCloseTags: true
391
+ });
392
+ case 'css':
393
+ return css();
394
+ case 'markdown':
395
+ return markdown();
396
+ case 'sh':
397
+ case 'shell':
398
+ case 'bash':
399
+ return StreamLanguage.define(shell);
400
+ case 'yml':
401
+ case 'yaml':
402
+ return StreamLanguage.define(yaml);
403
+ default:
404
+ return javascript({
405
+ jsx: true,
406
+ typescript: true
407
+ });
408
+ }
409
+ }
410
+ callOnChangeHandler(newValue) {
411
+ const { onChange, value } = this.props;
412
+ this.addAnimationFrame(()=>{
413
+ if (typeof onChange === 'function' && newValue !== value) {
414
+ onChange(newValue);
415
+ }
416
+ });
417
+ }
418
+ get onChangeExtension() {
419
+ return EditorState.changeFilter.of((transaction)=>{
420
+ if (!this._editorView) {
421
+ return false;
422
+ }
423
+ if (transaction.docChanged) {
424
+ const newDoc = transaction.newDoc.toString();
425
+ if (this.isControlled) {
426
+ if (newDoc !== this.props.value) {
427
+ this._newSelectionAfterValueChange = transaction.selection;
428
+ this.cancelAnimationFrames();
429
+ this.callOnChangeHandler(newDoc);
430
+ return false;
431
+ } else {
432
+ return true;
433
+ }
434
+ } else {
435
+ this.callOnChangeHandler(newDoc);
436
+ }
437
+ }
438
+ return true;
439
+ });
440
+ }
441
+ get focusListenerExtension() {
442
+ const { onFocus, onBlur } = this.props;
443
+ return EditorView.updateListener.of((update)=>{
444
+ if (update.focusChanged && this._editorView) {
445
+ if (this.hasFocus) {
446
+ if (typeof onFocus === 'function') {
447
+ onFocus();
448
+ }
449
+ } else {
450
+ if (typeof onBlur === 'function') {
451
+ onBlur();
452
+ }
453
+ }
454
+ }
455
+ });
456
+ }
457
+ get announceLineNumberExtension() {
458
+ return EditorState.transactionExtender.of((tr)=>{
459
+ const selection = tr.selection;
460
+ const oldSelection = tr.startState.selection.main;
461
+ if (selection && selection.main.empty && oldSelection.empty) {
462
+ const oldLine = tr.startState.doc.lineAt(oldSelection.head);
463
+ const newLine = tr.newDoc.lineAt(selection.main.head);
464
+ if (oldLine.number != newLine.number) return {
465
+ effects: EditorView.announce.of(tr.startState.phrase('line ') + newLine.number + '.')
466
+ };
467
+ }
468
+ return null;
469
+ });
470
+ }
471
+ refreshExtensions() {
472
+ this.dispatchViewEffects(StateEffect.reconfigure.of(this.extensions));
473
+ }
474
+ refreshEditorValue() {
475
+ if (!this._editorView) return;
476
+ const { value } = this.props;
477
+ const currentValue = this._editorView.state.doc.toString();
478
+ if (typeof value !== 'undefined' && currentValue !== value) {
479
+ let userEvent;
480
+ const lengthDiff = value.length - currentValue.length;
481
+ if (lengthDiff === 1) {
482
+ userEvent = 'input.type';
483
+ } else if (lengthDiff === -1) {
484
+ userEvent = 'delete.backward';
485
+ }
486
+ const scrollTop = this._editorView.scrollDOM.scrollTop;
487
+ this.dispatchViewChanges({
488
+ changes: {
489
+ from: 0,
490
+ to: currentValue.length,
491
+ insert: value || ''
492
+ },
493
+ selection: this._newSelectionAfterValueChange,
494
+ userEvent: userEvent
495
+ });
496
+ this.addAnimationFrame(()=>{
497
+ if (this._editorView) {
498
+ this._editorView.scrollDOM.scrollTop = scrollTop;
499
+ }
500
+ });
501
+ this._newSelectionAfterValueChange = undefined;
502
+ }
503
+ if (this.props.indentOnLoad) {
504
+ this.indentAll();
505
+ }
506
+ }
507
+ render() {
508
+ const { label, styles, searchConfig, ...restProps } = this.props;
509
+ return /*#__PURE__*/ _jsxs("div", {
510
+ "data-cid": "SourceCodeEditor",
511
+ ref: this.handleRef,
512
+ css: styles?.codeEditor,
513
+ ...passthroughProps(omitProps(restProps, SourceCodeEditor.allowedProps)),
514
+ children: [
515
+ /*#__PURE__*/ _jsxs("label", {
516
+ css: styles?.label,
517
+ id: this._id,
518
+ children: [
519
+ /*#__PURE__*/ _jsx(ScreenReaderContent, {
520
+ children: label
521
+ }),
522
+ /*#__PURE__*/ _jsx("div", {
523
+ ref: this.handleContainerRef,
524
+ css: styles?.codeEditorContainer
525
+ })
526
+ ]
527
+ }),
528
+ searchConfig && this.state.searchPanels.map(({ id, dom, view })=>/*#__PURE__*/ createPortal(/*#__PURE__*/ _jsx(SearchPanel, {
529
+ view: view,
530
+ searchConfig: searchConfig
531
+ }), dom, String(id)))
532
+ ]
533
+ });
534
+ }
535
+ }
536
+ SourceCodeEditor = _ts_decorate([
537
+ withDeterministicId(),
538
+ withStyleNew(generateStyle),
539
+ textDirectionContextConsumer()
540
+ ], SourceCodeEditor);
585
541
  export default SourceCodeEditor;
586
- export { SourceCodeEditor };
542
+ export { SourceCodeEditor };