-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patheditor.ts
867 lines (754 loc) · 20.6 KB
/
editor.ts
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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { IChangedArgs } from '@jupyterlab/coreutils';
import * as nbformat from '@jupyterlab/nbformat';
import {
IModelDB,
IObservableMap,
IObservableString,
IObservableValue,
ModelDB,
ObservableValue
} from '@jupyterlab/observables';
import * as models from '@jupyterlab/shared-models';
import { ITranslator } from '@jupyterlab/translation';
import { JSONObject } from '@lumino/coreutils';
import { IDisposable } from '@lumino/disposable';
import { ISignal, Signal } from '@lumino/signaling';
const globalModelDBMutex = models.createMutex();
/**
* A namespace for code editors.
*
* #### Notes
* - A code editor is a set of common assumptions which hold for all concrete editors.
* - Changes in implementations of the code editor should only be caused by changes in concrete editors.
* - Common JLab services which are based on the code editor should belong to `IEditorServices`.
*/
export namespace CodeEditor {
/**
* A zero-based position in the editor.
*/
export interface IPosition extends JSONObject {
/**
* The cursor line number.
*/
readonly line: number;
/**
* The cursor column number.
*/
readonly column: number;
}
/**
* The dimension of an element.
*/
export interface IDimension {
/**
* The width of an element in pixels.
*/
readonly width: number;
/**
* The height of an element in pixels.
*/
readonly height: number;
}
/**
* An interface describing editor state coordinates.
*/
export interface ICoordinate extends DOMRectReadOnly {}
/**
* A range.
*/
export interface IRange extends JSONObject {
/**
* The position of the first character in the current range.
*
* #### Notes
* If this position is greater than [end] then the range is considered
* to be backward.
*/
readonly start: IPosition;
/**
* The position of the last character in the current range.
*
* #### Notes
* If this position is less than [start] then the range is considered
* to be backward.
*/
readonly end: IPosition;
}
/**
* A selection style.
*/
export interface ISelectionStyle extends JSONObject {
/**
* A class name added to a selection.
*/
className: string;
/**
* A display name added to a selection.
*/
displayName: string;
/**
* A color for UI elements.
*/
color: string;
}
/**
* The default selection style.
*/
export const defaultSelectionStyle: ISelectionStyle = {
className: '',
displayName: '',
color: 'black'
};
/**
* A text selection.
*/
export interface ITextSelection extends IRange {
/**
* The uuid of the text selection owner.
*/
readonly uuid: string;
/**
* The style of this selection.
*/
readonly style: ISelectionStyle;
}
/**
* An interface for a text token, such as a word, keyword, or variable.
*/
export interface IToken {
/**
* The value of the token.
*/
value: string;
/**
* The offset of the token in the code editor.
*/
offset: number;
/**
* An optional type for the token.
*/
type?: string;
}
/**
* An interface to manage selections by selection owners.
*
* #### Definitions
* - a user code that has an associated uuid is called a selection owner, see `CodeEditor.ISelectionOwner`
* - a selection belongs to a selection owner only if it is associated with the owner by an uuid, see `CodeEditor.ITextSelection`
*
* #### Read access
* - any user code can observe any selection
*
* #### Write access
* - if a user code is a selection owner then:
* - it can change selections belonging to it
* - but it must not change selections belonging to other selection owners
* - otherwise it must not change any selection
*/
/**
* An editor model.
*/
export interface IModel extends IDisposable {
/**
* A signal emitted when a property changes.
*/
mimeTypeChanged: ISignal<IModel, IChangedArgs<string>>;
/**
* A signal emitted when the shared model was switched.
*/
sharedModelSwitched: ISignal<IModel, boolean>;
/**
* The text stored in the model.
*/
readonly value: IObservableString;
/**
* A mime type of the model.
*
* #### Notes
* It is never `null`, the default mime type is `text/plain`.
*/
mimeType: string;
/**
* The currently selected code.
*/
readonly selections: IObservableMap<ITextSelection[]>;
/**
* The underlying `IModelDB` instance in which model
* data is stored.
*/
readonly modelDB: IModelDB;
/**
* The shared model for the cell editor.
*/
readonly sharedModel: models.ISharedText;
/**
* When we initialize a cell model, we create a standalone cell model that cannot be shared in a YNotebook.
* Call this function to re-initialize the local representation based on a fresh shared model (e.g. models.YFile or models.YCodeCell).
*/
switchSharedModel(
sharedModel: models.ISharedText,
reinitialize: boolean
): void;
}
/**
* The default implementation of the editor model.
*/
export class Model implements IModel {
/**
* Construct a new Model.
*/
constructor(options?: Model.IOptions) {
options = options || {};
if (options.modelDB) {
this.modelDB = options.modelDB;
} else {
this.modelDB = new ModelDB();
}
this.sharedModel = models.createStandaloneCell(
this.type,
options.id
) as models.ISharedText;
this.sharedModel.changed.connect(this._onSharedModelChanged, this);
const value = this.modelDB.createString('value');
value.changed.connect(this._onModelDBValueChanged, this);
value.text = value.text || options.value || '';
const mimeType = this.modelDB.createValue('mimeType');
mimeType.changed.connect(this._onModelDBMimeTypeChanged, this);
mimeType.set(options.mimeType || 'text/plain');
this.modelDB.createMap('selections');
}
/**
* When we initialize a cell model, we create a standalone model that cannot be shared in a YNotebook.
* Call this function to re-initialize the local representation based on a fresh shared model (e.g. models.YFile or models.YCodeCell).
*
* @param sharedModel
* @param reinitialize Whether to reinitialize the shared model.
*/
public switchSharedModel(
sharedModel: models.ISharedText,
reinitialize?: boolean
): void {
if (reinitialize) {
// update local modeldb
// @todo also change metadata
this.value.text = sharedModel.getSource();
}
this.sharedModel.changed.disconnect(this._onSharedModelChanged, this);
this.sharedModel.dispose();
// clone model retrieve a shared (not standalone) model
this.sharedModel = sharedModel;
this.sharedModel.changed.connect(this._onSharedModelChanged, this);
this._sharedModelSwitched.emit(true);
}
/**
* We update the modeldb store when the shared model changes.
* To ensure that we don't run into infinite loops, we wrap this call in a "mutex".
* The "mutex" ensures that the wrapped code can only be executed by either the sharedModelChanged handler
* or the modelDB change handler.
*/
protected _onSharedModelChanged(
sender: models.ISharedBaseCell<any>,
change: models.CellChange<nbformat.IBaseCellMetadata>
): void {
globalModelDBMutex(() => {
if (change.sourceChange) {
const value = this.modelDB.get('value') as IObservableString;
let currpos = 0;
change.sourceChange.forEach(delta => {
if (delta.insert != null) {
value.insert(currpos, delta.insert);
currpos += delta.insert.length;
} else if (delta.delete != null) {
value.remove(currpos, currpos + delta.delete);
} else if (delta.retain != null) {
currpos += delta.retain;
}
});
}
});
}
/**
* Handle a change to the modelDB value.
*/
private _onModelDBValueChanged(
value: IObservableString,
event: IObservableString.IChangedArgs
): void {
globalModelDBMutex(() => {
this.sharedModel.transact(() => {
switch (event.type) {
case 'insert':
this.sharedModel.updateSource(
event.start,
event.start,
event.value
);
break;
case 'remove':
this.sharedModel.updateSource(event.start, event.end);
break;
default:
this.sharedModel.setSource(value.text);
break;
}
});
});
}
get type(): nbformat.CellType {
return 'code';
}
/**
* The shared model for the cell editor.
*/
sharedModel: models.ISharedText;
/**
* The underlying `IModelDB` instance in which model
* data is stored.
*/
readonly modelDB: IModelDB;
/**
* A signal emitted when a mimetype changes.
*/
get mimeTypeChanged(): ISignal<this, IChangedArgs<string>> {
return this._mimeTypeChanged;
}
/**
* A signal emitted when the shared model was switched.
*/
get sharedModelSwitched(): ISignal<this, boolean> {
return this._sharedModelSwitched;
}
/**
* Get the value of the model.
*/
get value(): IObservableString {
return this.modelDB.get('value') as IObservableString;
}
/**
* Get the selections for the model.
*/
get selections(): IObservableMap<ITextSelection[]> {
return this.modelDB.get('selections') as IObservableMap<ITextSelection[]>;
}
/**
* A mime type of the model.
*/
get mimeType(): string {
return this.modelDB.getValue('mimeType') as string;
}
set mimeType(newValue: string) {
const oldValue = this.mimeType;
if (oldValue === newValue) {
return;
}
this.modelDB.setValue('mimeType', newValue);
}
/**
* Whether the model is disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Dispose of the resources used by the model.
*/
dispose(): void {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
this.modelDB.dispose();
Signal.clearData(this);
}
private _onModelDBMimeTypeChanged(
mimeType: IObservableValue,
args: ObservableValue.IChangedArgs
): void {
this._mimeTypeChanged.emit({
name: 'mimeType',
oldValue: args.oldValue as string,
newValue: args.newValue as string
});
}
private _isDisposed = false;
private _mimeTypeChanged = new Signal<this, IChangedArgs<string>>(this);
private _sharedModelSwitched = new Signal<this, boolean>(this);
}
/**
* A selection owner.
*/
export interface ISelectionOwner {
/**
* The uuid of this selection owner.
*/
uuid: string;
/**
* Returns the primary position of the cursor, never `null`.
*/
getCursorPosition(): IPosition;
/**
* Set the primary position of the cursor.
*
* @param position - The new primary position.
*
* #### Notes
* This will remove any secondary cursors.
*/
setCursorPosition(position: IPosition): void;
/**
* Returns the primary selection, never `null`.
*/
getSelection(): IRange;
/**
* Set the primary selection.
*
* @param selection - The desired selection range.
*
* #### Notes
* This will remove any secondary cursors.
*/
setSelection(selection: IRange): void;
/**
* Gets the selections for all the cursors, never `null` or empty.
*/
getSelections(): IRange[];
/**
* Sets the selections for all the cursors.
*
* @param selections - The new selections.
*
* #### Notes
* Cursors will be removed or added, as necessary.
* Passing an empty array resets a cursor position to the start of a
* document.
*/
setSelections(selections: IRange[]): void;
}
/**
* A keydown handler type.
*
* #### Notes
* Return `true` to prevent the default handling of the event by the
* editor.
*/
export type KeydownHandler = (
instance: IEditor,
event: KeyboardEvent
) => boolean;
/**
* The location of requested edges.
*/
export type EdgeLocation = 'top' | 'topLine' | 'bottom';
/**
* A widget that provides a code editor.
*/
export interface IEditor extends ISelectionOwner, IDisposable {
/**
* A signal emitted when either the top or bottom edge is requested.
*/
readonly edgeRequested: ISignal<IEditor, EdgeLocation>;
/**
* The default selection style for the editor.
*/
selectionStyle: CodeEditor.ISelectionStyle;
/**
* The DOM node that hosts the editor.
*/
readonly host: HTMLElement;
/**
* The model used by the editor.
*/
readonly model: IModel;
/**
* The height of a line in the editor in pixels.
*/
readonly lineHeight: number;
/**
* The widget of a character in the editor in pixels.
*/
readonly charWidth: number;
/**
* Get the number of lines in the editor.
*/
readonly lineCount: number;
/**
* Get a config option for the editor.
*/
getOption<K extends keyof IConfig>(option: K): IConfig[K];
/**
* Set a config option for the editor.
*/
setOption<K extends keyof IConfig>(option: K, value: IConfig[K]): void;
/**
* Set config options for the editor.
*/
setOptions(options: Partial<IConfig>): void;
/**
* Returns the content for the given line number.
*
* @param line - The line of interest.
*
* @returns The value of the line.
*
* #### Notes
* Lines are 0-based, and accessing a line out of range returns
* `undefined`.
*/
getLine(line: number): string | undefined;
/**
* Find an offset for the given position.
*
* @param position - The position of interest.
*
* @returns The offset at the position, clamped to the extent of the
* editor contents.
*/
getOffsetAt(position: IPosition): number;
/**
* Find a position for the given offset.
*
* @param offset - The offset of interest.
*
* @returns The position at the offset, clamped to the extent of the
* editor contents.
*/
getPositionAt(offset: number): IPosition | undefined;
/**
* Undo one edit (if any undo events are stored).
*/
undo(): void;
/**
* Redo one undone edit.
*/
redo(): void;
/**
* Clear the undo history.
*/
clearHistory(): void;
/**
* Brings browser focus to this editor text.
*/
focus(): void;
/**
* Test whether the editor has keyboard focus.
*/
hasFocus(): boolean;
/**
* Explicitly blur the editor.
*/
blur(): void;
/**
* Resize the editor to fit its host node.
*/
resizeToFit(): void;
/**
* Add a keydown handler to the editor.
*
* @param handler - A keydown handler.
*
* @returns A disposable that can be used to remove the handler.
*/
addKeydownHandler(handler: KeydownHandler): IDisposable;
/**
* Reveals the given position in the editor.
*
* @param position - The desired position to reveal.
*/
revealPosition(position: IPosition): void;
/**
* Reveals the given selection in the editor.
*
* @param position - The desired selection to reveal.
*/
revealSelection(selection: IRange): void;
/**
* Get the window coordinates given a cursor position.
*
* @param position - The desired position.
*
* @returns The coordinates of the position.
*/
getCoordinateForPosition(position: IPosition): ICoordinate;
/**
* Get the cursor position given window coordinates.
*
* @param coordinate - The desired coordinate.
*
* @returns The position of the coordinates, or null if not
* contained in the editor.
*/
getPositionForCoordinate(coordinate: ICoordinate): IPosition | null;
/**
* Get a list of tokens for the current editor text content.
*/
getTokens(): CodeEditor.IToken[];
/**
* Get the token at a given editor position.
*/
getTokenAt(offset: number): CodeEditor.IToken;
/**
* Get the token a the cursor position.
*/
getTokenAtCursor(): CodeEditor.IToken;
/**
* Inserts a new line at the cursor position and indents it.
*/
newIndentedLine(): void;
/**
* Replaces selection with the given text.
*/
replaceSelection?(text: string): void;
}
/**
* A factory used to create a code editor.
*/
export type Factory = (options: IOptions) => CodeEditor.IEditor;
/**
* The configuration options for an editor.
*/
export interface IConfig {
/**
* Half-period in milliseconds used for cursor blinking.
* By setting this to zero, blinking can be disabled.
* A negative value hides the cursor entirely.
*/
cursorBlinkRate: number;
/**
* User preferred font family for text editors.
*/
fontFamily: string | null;
/**
* User preferred size in pixel of the font used in text editors.
*/
fontSize: number | null;
/**
* User preferred text line height, as a multiplier of font size.
*/
lineHeight: number | null;
/**
* Whether line numbers should be displayed.
*/
lineNumbers: boolean;
/**
* Control the line wrapping of the editor. Possible values are:
* - "off", lines will never wrap.
* - "on", lines will wrap at the viewport border.
* - "wordWrapColumn", lines will wrap at `wordWrapColumn`.
* - "bounded", lines will wrap at minimum between viewport width and wordWrapColumn.
*/
lineWrap: 'off' | 'on' | 'wordWrapColumn' | 'bounded';
/**
* Whether the editor is read-only.
*/
readOnly: boolean;
/**
* The number of spaces a tab is equal to.
*/
tabSize: number;
/**
* Whether to insert spaces when pressing Tab.
*/
insertSpaces: boolean;
/**
* Whether to highlight matching brackets when one of them is selected.
*/
matchBrackets: boolean;
/**
* Whether to automatically close brackets after opening them.
*/
autoClosingBrackets: boolean;
/**
* Whether the editor should handle paste events.
*/
handlePaste?: boolean;
/**
* The column where to break text line.
*/
wordWrapColumn: number;
/**
* Column index at which rulers should be added.
*/
rulers: Array<number>;
/**
* Whether to allow code folding
*/
codeFolding: boolean;
/**
* Whether to highlight trailing whitespace
*/
showTrailingSpace: boolean;
}
/**
* The default configuration options for an editor.
*/
export const defaultConfig: IConfig = {
// Order matters as gutters will be sorted by the configuration order
autoClosingBrackets: false,
cursorBlinkRate: 530,
fontFamily: null,
fontSize: null,
handlePaste: true,
insertSpaces: true,
lineHeight: null,
lineNumbers: false,
lineWrap: 'on',
matchBrackets: true,
readOnly: false,
tabSize: 4,
rulers: [],
showTrailingSpace: false,
wordWrapColumn: 80,
codeFolding: false
};
/**
* The options used to initialize an editor.
*/
export interface IOptions {
/**
* The host widget used by the editor.
*/
host: HTMLElement;
/**
* The model used by the editor.
*/
model: IModel;
/**
* The desired uuid for the editor.
*/
uuid?: string;
/**
* The default selection style for the editor.
*/
selectionStyle?: Partial<CodeEditor.ISelectionStyle>;
/**
* The configuration options for the editor.
*/
config?: Partial<IConfig>;
/**
* The configuration options for the editor.
*/
translator?: ITranslator;
}
export namespace Model {
export interface IOptions {
/**
* A unique identifier for the model.
*/
id?: string;
/**
* The initial value of the model.
*/
value?: string;
/**
* The mimetype of the model.
*/
mimeType?: string;
/**
* An optional modelDB for storing model state.
*/
modelDB?: IModelDB;
}
}
}