-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
default.ts
683 lines (611 loc) · 16.3 KB
/
default.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { MainAreaWidget, setToolbar } from '@jupyterlab/apputils';
import { CodeEditor } from '@jupyterlab/codeeditor';
import { IChangedArgs, PathExt } from '@jupyterlab/coreutils';
import { IObservableList } from '@jupyterlab/observables';
import { Contents } from '@jupyterlab/services';
import { DocumentChange, FileChange, ISharedFile } from '@jupyter/ydoc';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { PartialJSONValue } from '@lumino/coreutils';
import { ISignal, Signal } from '@lumino/signaling';
import { Title, Widget } from '@lumino/widgets';
import { DocumentRegistry, IDocumentWidget } from './index';
import { createReadonlyLabel } from './components';
/**
* The default implementation of a document model.
*/
export class DocumentModel
extends CodeEditor.Model
implements DocumentRegistry.ICodeModel
{
/**
* Construct a new document model.
*/
constructor(options: DocumentRegistry.IModelOptions<ISharedFile> = {}) {
super({ sharedModel: options.sharedModel });
this._defaultLang = options.languagePreference ?? '';
this._collaborationEnabled = !!options.collaborationEnabled;
this.sharedModel.changed.connect(this._onStateChanged, this);
}
/**
* A signal emitted when the document content changes.
*/
get contentChanged(): ISignal<this, void> {
return this._contentChanged;
}
/**
* A signal emitted when the document state changes.
*/
get stateChanged(): ISignal<this, IChangedArgs<any>> {
return this._stateChanged;
}
/**
* The dirty state of the document.
*/
get dirty(): boolean {
return this._dirty;
}
set dirty(newValue: boolean) {
const oldValue = this._dirty;
if (newValue === oldValue) {
return;
}
this._dirty = newValue;
this.triggerStateChange({
name: 'dirty',
oldValue,
newValue
});
}
/**
* The read only state of the document.
*/
get readOnly(): boolean {
return this._readOnly;
}
set readOnly(newValue: boolean) {
if (newValue === this._readOnly) {
return;
}
const oldValue = this._readOnly;
this._readOnly = newValue;
this.triggerStateChange({ name: 'readOnly', oldValue, newValue });
}
/**
* The default kernel name of the document.
*
* #### Notes
* This is a read-only property.
*/
get defaultKernelName(): string {
return '';
}
/**
* The default kernel language of the document.
*
* #### Notes
* This is a read-only property.
*/
get defaultKernelLanguage(): string {
return this._defaultLang;
}
/**
* Whether the model is collaborative or not.
*/
get collaborative(): boolean {
return this._collaborationEnabled;
}
/**
* Serialize the model to a string.
*/
toString(): string {
return this.sharedModel.getSource();
}
/**
* Deserialize the model from a string.
*
* #### Notes
* Should emit a [contentChanged] signal.
*/
fromString(value: string): void {
this.sharedModel.setSource(value);
}
/**
* Serialize the model to JSON.
*/
toJSON(): PartialJSONValue {
return JSON.parse(this.sharedModel.getSource() || 'null');
}
/**
* Deserialize the model from JSON.
*
* #### Notes
* Should emit a [contentChanged] signal.
*/
fromJSON(value: PartialJSONValue): void {
this.fromString(JSON.stringify(value));
}
/**
* Initialize the model with its current state.
*/
initialize(): void {
return;
}
/**
* Trigger a state change signal.
*/
protected triggerStateChange(args: IChangedArgs<any>): void {
this._stateChanged.emit(args);
}
/**
* Trigger a content changed signal.
*/
protected triggerContentChange(): void {
this._contentChanged.emit(void 0);
this.dirty = true;
}
private _onStateChanged(sender: ISharedFile, changes: DocumentChange): void {
if ((changes as FileChange).sourceChange) {
this.triggerContentChange();
}
if (changes.stateChange) {
changes.stateChange.forEach(value => {
if (value.name === 'dirty') {
// Setting `dirty` will trigger the state change.
// We always set `dirty` because the shared model state
// and the local attribute are synchronized one way shared model -> _dirty
this.dirty = value.newValue;
} else if (value.oldValue !== value.newValue) {
this.triggerStateChange({
newValue: undefined,
oldValue: undefined,
...value
});
}
});
}
}
/**
* The shared notebook model.
*/
readonly sharedModel: ISharedFile;
private _defaultLang = '';
private _dirty = false;
private _readOnly = false;
private _contentChanged = new Signal<this, void>(this);
private _stateChanged = new Signal<this, IChangedArgs<any>>(this);
private _collaborationEnabled: boolean;
}
/**
* An implementation of a model factory for text files.
*/
export class TextModelFactory implements DocumentRegistry.CodeModelFactory {
/**
* Instantiates a TextModelFactory.
*/
constructor(collaborative?: boolean) {
this._collaborative = collaborative ?? true;
}
/**
* The name of the model type.
*
* #### Notes
* This is a read-only property.
*/
get name(): string {
return 'text';
}
/**
* The type of the file.
*
* #### Notes
* This is a read-only property.
*/
get contentType(): Contents.ContentType {
return 'file';
}
/**
* The format of the file.
*
* This is a read-only property.
*/
get fileFormat(): Contents.FileFormat {
return 'text';
}
/**
* Whether the model is collaborative or not.
*/
get collaborative(): boolean {
return this._collaborative;
}
/**
* Get whether the model factory has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Dispose of the resources held by the model factory.
*/
dispose(): void {
this._isDisposed = true;
}
/**
* Create a new model.
*
* @param options - Model options.
*
* @returns A new document model.
*/
createNew(
options: DocumentRegistry.IModelOptions<ISharedFile> = {}
): DocumentRegistry.ICodeModel {
const collaborative = options.collaborationEnabled && this.collaborative;
return new DocumentModel({
...options,
collaborationEnabled: collaborative
});
}
/**
* Get the preferred kernel language given a file path.
*/
preferredLanguage(path: string): string {
return '';
}
private _isDisposed = false;
private _collaborative: boolean;
}
/**
* An implementation of a model factory for base64 files.
*/
export class Base64ModelFactory extends TextModelFactory {
/**
* The name of the model type.
*
* #### Notes
* This is a read-only property.
*/
get name(): string {
return 'base64';
}
/**
* The type of the file.
*
* #### Notes
* This is a read-only property.
*/
get contentType(): Contents.ContentType {
return 'file';
}
/**
* The format of the file.
*
* This is a read-only property.
*/
get fileFormat(): Contents.FileFormat {
return 'base64';
}
}
/**
* The default implementation of a widget factory.
*/
export abstract class ABCWidgetFactory<
T extends IDocumentWidget,
U extends DocumentRegistry.IModel = DocumentRegistry.IModel
> implements DocumentRegistry.IWidgetFactory<T, U>
{
/**
* Construct a new `ABCWidgetFactory`.
*/
constructor(options: DocumentRegistry.IWidgetFactoryOptions<T>) {
this._translator = options.translator || nullTranslator;
this._name = options.name;
this._label = options.label || options.name;
this._readOnly = options.readOnly === undefined ? false : options.readOnly;
this._defaultFor = options.defaultFor ? options.defaultFor.slice() : [];
this._defaultRendered = (options.defaultRendered || []).slice();
this._fileTypes = options.fileTypes.slice();
this._modelName = options.modelName || 'text';
this._preferKernel = !!options.preferKernel;
this._canStartKernel = !!options.canStartKernel;
this._shutdownOnClose = !!options.shutdownOnClose;
this._autoStartDefault = !!options.autoStartDefault;
this._toolbarFactory = options.toolbarFactory;
}
/**
* A signal emitted when a widget is created.
*/
get widgetCreated(): ISignal<DocumentRegistry.IWidgetFactory<T, U>, T> {
return this._widgetCreated;
}
/**
* Get whether the model factory has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Dispose of the resources used by the document manager.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
/**
* Whether the widget factory is read only.
*/
get readOnly(): boolean {
return this._readOnly;
}
/**
* A unique name identifying of the widget.
*/
get name(): string {
return this._name;
}
/**
* The label of the widget to display in dialogs.
* If not given, name is used instead.
*/
get label(): string {
return this._label;
}
/**
* The file types the widget can view.
*/
get fileTypes(): string[] {
return this._fileTypes.slice();
}
/**
* The registered name of the model type used to create the widgets.
*/
get modelName(): string {
return this._modelName;
}
/**
* The file types for which the factory should be the default.
*/
get defaultFor(): string[] {
return this._defaultFor.slice();
}
/**
* The file types for which the factory should be the default for
* rendering a document model, if different from editing.
*/
get defaultRendered(): string[] {
return this._defaultRendered.slice();
}
/**
* Whether the widgets prefer having a kernel started.
*/
get preferKernel(): boolean {
return this._preferKernel;
}
/**
* Whether the widgets can start a kernel when opened.
*/
get canStartKernel(): boolean {
return this._canStartKernel;
}
/**
* The application language translator.
*/
get translator(): ITranslator {
return this._translator;
}
/**
* Whether the kernel should be shutdown when the widget is closed.
*/
get shutdownOnClose(): boolean {
return this._shutdownOnClose;
}
set shutdownOnClose(value: boolean) {
this._shutdownOnClose = value;
}
/**
* Whether to automatically select the preferred kernel during a kernel start
*/
get autoStartDefault(): boolean {
return this._autoStartDefault;
}
set autoStartDefault(value: boolean) {
this._autoStartDefault = value;
}
/**
* Create a new widget given a document model and a context.
*
* #### Notes
* It should emit the [widgetCreated] signal with the new widget.
*/
createNew(context: DocumentRegistry.IContext<U>, source?: T): T {
// Create the new widget
const widget = this.createNewWidget(context, source);
// Add toolbar
setToolbar(
widget,
this._toolbarFactory ?? this.defaultToolbarFactory.bind(this)
);
// Emit widget created signal
this._widgetCreated.emit(widget);
return widget;
}
/**
* Create a widget for a context.
*/
protected abstract createNewWidget(
context: DocumentRegistry.IContext<U>,
source?: T
): T;
/**
* Default factory for toolbar items to be added after the widget is created.
*/
protected defaultToolbarFactory(widget: T): DocumentRegistry.IToolbarItem[] {
return [];
}
private _toolbarFactory:
| ((
widget: T
) =>
| DocumentRegistry.IToolbarItem[]
| IObservableList<DocumentRegistry.IToolbarItem>)
| undefined;
private _isDisposed = false;
private _translator: ITranslator;
private _name: string;
private _label: string;
private _autoStartDefault: boolean;
private _readOnly: boolean;
private _canStartKernel: boolean;
private _shutdownOnClose: boolean;
private _preferKernel: boolean;
private _modelName: string;
private _fileTypes: string[];
private _defaultFor: string[];
private _defaultRendered: string[];
private _widgetCreated = new Signal<DocumentRegistry.IWidgetFactory<T, U>, T>(
this
);
}
/**
* The class name added to a dirty widget.
*/
const DIRTY_CLASS = 'jp-mod-dirty';
/**
* A document widget implementation.
*/
export class DocumentWidget<
T extends Widget = Widget,
U extends DocumentRegistry.IModel = DocumentRegistry.IModel
>
extends MainAreaWidget<T>
implements IDocumentWidget<T, U>
{
constructor(options: DocumentWidget.IOptions<T, U>) {
// Include the context ready promise in the widget reveal promise
options.reveal = Promise.all([options.reveal, options.context.ready]);
super(options);
this._trans = (options.translator ?? nullTranslator).load('jupyterlab');
this.context = options.context;
// Handle context path changes
this.context.pathChanged.connect(this._onPathChanged, this);
this._onPathChanged(this.context, this.context.path);
// Listen for changes in the dirty state.
this.context.model.stateChanged.connect(this._onModelStateChanged, this);
void this.context.ready.then(() => {
this._handleDirtyState();
});
// listen for changes to the title object
this.title.changed.connect(this._onTitleChanged, this);
}
/**
* Set URI fragment identifier.
*/
setFragment(fragment: string): void {
/* no-op */
}
/**
* Handle a title change.
*/
private async _onTitleChanged(_sender: Title<this>) {
const validNameExp = /[\/\\:]/;
const name = this.title.label;
// Use localPath to avoid the drive name
const filename =
this.context.localPath.split('/').pop() || this.context.localPath;
if (name === filename) {
return;
}
if (name.length > 0 && !validNameExp.test(name)) {
const oldPath = this.context.path;
await this.context.rename(name);
if (this.context.path !== oldPath) {
// Rename succeeded
return;
}
}
// Reset title if name is invalid or rename fails
this.title.label = filename;
}
/**
* Handle a path change.
*/
private _onPathChanged(
sender: DocumentRegistry.IContext<U>,
path: string
): void {
this.title.label = PathExt.basename(sender.localPath);
// The document is not untitled any more.
this.isUntitled = false;
}
/**
* Handle a change to the context model state.
*/
private _onModelStateChanged(
sender: DocumentRegistry.IModel,
args: IChangedArgs<any>
): void {
if (args.name === 'dirty') {
this._handleDirtyState();
}
if (!this.context.model.dirty) {
if (!this.context.model.collaborative) {
if (!this.context.contentsModel?.writable) {
const readOnlyIndicator = createReadonlyLabel(this);
let roi = this.toolbar.insertBefore(
'kernelName',
'read-only-indicator',
readOnlyIndicator
);
if (!roi) {
this.toolbar.addItem('read-only-indicator', readOnlyIndicator);
}
}
}
}
}
/**
* Handle the dirty state of the context model.
*/
private _handleDirtyState(): void {
if (
this.context.model.dirty &&
!this.title.className.includes(DIRTY_CLASS)
) {
this.title.className += ` ${DIRTY_CLASS}`;
} else {
this.title.className = this.title.className.replace(DIRTY_CLASS, '');
}
}
readonly context: DocumentRegistry.IContext<U>;
protected readonly _trans;
/**
* Whether the document has an auto-generated name or not.
*
* #### Notes
* A document has auto-generated name if its name is untitled and up
* to the instant the user saves it manually for the first time.
*/
isUntitled?: boolean;
}
export namespace DocumentWidget {
export interface IOptions<
T extends Widget = Widget,
U extends DocumentRegistry.IModel = DocumentRegistry.IModel
> extends MainAreaWidget.IOptions<T> {
context: DocumentRegistry.IContext<U>;
}
export interface IOptionsOptionalContent<
T extends Widget = Widget,
U extends DocumentRegistry.IModel = DocumentRegistry.IModel
> extends MainAreaWidget.IOptionsOptionalContent<T> {
context: DocumentRegistry.IContext<U>;
/**
* The application language translator.
*/
translator?: ITranslator;
}
}