forked from jupyterlab/jupyterlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.ts
529 lines (480 loc) · 13.4 KB
/
model.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { DocumentModel, DocumentRegistry } from '@jupyterlab/docregistry';
import {
ICellModel,
ICodeCellModel,
IRawCellModel,
IMarkdownCellModel,
CodeCellModel,
RawCellModel,
MarkdownCellModel,
CellModel
} from '@jupyterlab/cells';
import { nbformat } from '@jupyterlab/coreutils';
import { UUID } from '@phosphor/coreutils';
import {
IObservableJSON,
IObservableUndoableList,
IObservableList,
IModelDB
} from '@jupyterlab/observables';
import { CellList } from './celllist';
/**
* The definition of a model object for a notebook widget.
*/
export interface INotebookModel extends DocumentRegistry.IModel {
/**
* The list of cells in the notebook.
*/
readonly cells: IObservableUndoableList<ICellModel>;
/**
* The cell model factory for the notebook.
*/
readonly contentFactory: NotebookModel.IContentFactory;
/**
* The major version number of the nbformat.
*/
readonly nbformat: number;
/**
* The minor version number of the nbformat.
*/
readonly nbformatMinor: number;
/**
* The metadata associated with the notebook.
*/
readonly metadata: IObservableJSON;
/**
* The array of deleted cells since the notebook was last run.
*/
readonly deletedCells: string[];
}
/**
* An implementation of a notebook Model.
*/
export class NotebookModel extends DocumentModel implements INotebookModel {
/**
* Construct a new notebook model.
*/
constructor(options: NotebookModel.IOptions = {}) {
super(options.languagePreference, options.modelDB);
let factory = options.contentFactory || NotebookModel.defaultContentFactory;
this.contentFactory = factory.clone(this.modelDB.view('cells'));
this._cells = new CellList(this.modelDB, this.contentFactory);
// Add an initial code cell by default.
if (!this._cells.length) {
this._cells.push(factory.createCodeCell({}));
}
this._cells.changed.connect(
this._onCellsChanged,
this
);
// Handle initial metadata.
let metadata = this.modelDB.createMap('metadata');
if (!metadata.has('language_info')) {
let name = options.languagePreference || '';
metadata.set('language_info', { name });
}
this._ensureMetadata();
metadata.changed.connect(
this.triggerContentChange,
this
);
this._deletedCells = [];
}
/**
* The cell model factory for the notebook.
*/
readonly contentFactory: NotebookModel.IContentFactory;
/**
* The metadata associated with the notebook.
*/
get metadata(): IObservableJSON {
return this.modelDB.get('metadata') as IObservableJSON;
}
/**
* Get the observable list of notebook cells.
*/
get cells(): IObservableUndoableList<ICellModel> {
return this._cells;
}
/**
* The major version number of the nbformat.
*/
get nbformat(): number {
return this._nbformat;
}
/**
* The minor version number of the nbformat.
*/
get nbformatMinor(): number {
return this._nbformatMinor;
}
/**
* The default kernel name of the document.
*/
get defaultKernelName(): string {
let spec = this.metadata.get('kernelspec') as nbformat.IKernelspecMetadata;
return spec ? spec.name : '';
}
/**
* The default kernel name of the document.
*/
get deletedCells(): string[] {
return this._deletedCells;
}
/**
* The default kernel language of the document.
*/
get defaultKernelLanguage(): string {
let info = this.metadata.get(
'language_info'
) as nbformat.ILanguageInfoMetadata;
return info ? info.name : '';
}
/**
* Dispose of the resources held by the model.
*/
dispose(): void {
// Do nothing if already disposed.
if (this.cells === null) {
return;
}
let cells = this.cells;
this._cells = null;
cells.dispose();
super.dispose();
}
/**
* Serialize the model to a string.
*/
toString(): string {
return JSON.stringify(this.toJSON());
}
/**
* Deserialize the model from a string.
*
* #### Notes
* Should emit a [contentChanged] signal.
*/
fromString(value: string): void {
this.fromJSON(JSON.parse(value));
}
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.INotebookContent {
let cells: nbformat.ICell[] = [];
for (let i = 0; i < this.cells.length; i++) {
let cell = this.cells.get(i);
cells.push(cell.toJSON());
}
this._ensureMetadata();
let metadata = Object.create(null) as nbformat.INotebookMetadata;
for (let key of this.metadata.keys()) {
metadata[key] = JSON.parse(JSON.stringify(this.metadata.get(key)));
}
return {
metadata,
nbformat_minor: this._nbformatMinor,
nbformat: this._nbformat,
cells
};
}
/**
* Deserialize the model from JSON.
*
* #### Notes
* Should emit a [contentChanged] signal.
*/
fromJSON(value: nbformat.INotebookContent): void {
let cells: ICellModel[] = [];
let factory = this.contentFactory;
for (let cell of value.cells) {
switch (cell.cell_type) {
case 'code':
cells.push(factory.createCodeCell({ cell }));
break;
case 'markdown':
cells.push(factory.createMarkdownCell({ cell }));
break;
case 'raw':
cells.push(factory.createRawCell({ cell }));
break;
default:
continue;
}
}
this.cells.beginCompoundOperation();
this.cells.clear();
this.cells.pushAll(cells);
this.cells.endCompoundOperation();
let oldValue = 0;
let newValue = 0;
this._nbformatMinor = nbformat.MINOR_VERSION;
this._nbformat = nbformat.MAJOR_VERSION;
if (value.nbformat !== this._nbformat) {
oldValue = this._nbformat;
this._nbformat = newValue = value.nbformat;
this.triggerStateChange({ name: 'nbformat', oldValue, newValue });
}
if (value.nbformat_minor > this._nbformatMinor) {
oldValue = this._nbformatMinor;
this._nbformatMinor = newValue = value.nbformat_minor;
this.triggerStateChange({ name: 'nbformatMinor', oldValue, newValue });
}
// Update the metadata.
this.metadata.clear();
let metadata = value.metadata;
for (let key in metadata) {
// orig_nbformat is not intended to be stored per spec.
if (key === 'orig_nbformat') {
continue;
}
this.metadata.set(key, metadata[key]);
}
this._ensureMetadata();
this.dirty = true;
}
/**
* Initialize the model with its current state.
*/
initialize(): void {
super.initialize();
this.cells.clearUndo();
}
/**
* Handle a change in the cells list.
*/
private _onCellsChanged(
list: IObservableList<ICellModel>,
change: IObservableList.IChangedArgs<ICellModel>
): void {
switch (change.type) {
case 'add':
change.newValues.forEach(cell => {
cell.contentChanged.connect(
this.triggerContentChange,
this
);
});
break;
case 'remove':
break;
case 'set':
change.newValues.forEach(cell => {
cell.contentChanged.connect(
this.triggerContentChange,
this
);
});
break;
default:
break;
}
let factory = this.contentFactory;
// Add code cell if there are no cells remaining.
if (!this.cells.length) {
// Add the cell in a new context to avoid triggering another
// cell changed event during the handling of this signal.
requestAnimationFrame(() => {
if (!this.isDisposed && !this.cells.length) {
this.cells.push(factory.createCodeCell({}));
}
});
}
this.triggerContentChange();
}
/**
* Make sure we have the required metadata fields.
*/
private _ensureMetadata(): void {
let metadata = this.metadata;
if (!metadata.has('language_info')) {
metadata.set('language_info', { name: '' });
}
if (!metadata.has('kernelspec')) {
metadata.set('kernelspec', { name: '', display_name: '' });
}
}
private _cells: CellList;
private _nbformat = nbformat.MAJOR_VERSION;
private _nbformatMinor = nbformat.MINOR_VERSION;
private _deletedCells: string[];
}
/**
* The namespace for the `NotebookModel` class statics.
*/
export namespace NotebookModel {
/**
* An options object for initializing a notebook model.
*/
export interface IOptions {
/**
* The language preference for the model.
*/
languagePreference?: string;
/**
* A factory for creating cell models.
*
* The default is a shared factory instance.
*/
contentFactory?: IContentFactory;
/**
* A modelDB for storing notebook data.
*/
modelDB?: IModelDB;
}
/**
* A factory for creating notebook model content.
*/
export interface IContentFactory {
/**
* The factory for output area models.
*/
readonly codeCellContentFactory: CodeCellModel.IContentFactory;
/**
* The IModelDB in which to put data for the notebook model.
*/
modelDB: IModelDB;
/**
* Create a new code cell.
*
* @param options - The options used to create the cell.
*
* @returns A new code cell. If a source cell is provided, the
* new cell will be initialized with the data from the source.
*/
createCodeCell(options: CodeCellModel.IOptions): ICodeCellModel;
/**
* Create a new markdown cell.
*
* @param options - The options used to create the cell.
*
* @returns A new markdown cell. If a source cell is provided, the
* new cell will be initialized with the data from the source.
*/
createMarkdownCell(options: CellModel.IOptions): IMarkdownCellModel;
/**
* Create a new raw cell.
*
* @param options - The options used to create the cell.
*
* @returns A new raw cell. If a source cell is provided, the
* new cell will be initialized with the data from the source.
*/
createRawCell(options: CellModel.IOptions): IRawCellModel;
/**
* Clone the content factory with a new IModelDB.
*/
clone(modelDB: IModelDB): IContentFactory;
}
/**
* The default implementation of an `IContentFactory`.
*/
export class ContentFactory {
/**
* Create a new cell model factory.
*/
constructor(options: ContentFactory.IOptions) {
this.codeCellContentFactory =
options.codeCellContentFactory || CodeCellModel.defaultContentFactory;
this.modelDB = options.modelDB;
}
/**
* The factory for code cell content.
*/
readonly codeCellContentFactory: CodeCellModel.IContentFactory;
/**
* The IModelDB in which to put the notebook data.
*/
readonly modelDB: IModelDB | undefined;
/**
* Create a new code cell.
*
* @param source - The data to use for the original source data.
*
* @returns A new code cell. If a source cell is provided, the
* new cell will be initialized with the data from the source.
* If the contentFactory is not provided, the instance
* `codeCellContentFactory` will be used.
*/
createCodeCell(options: CodeCellModel.IOptions): ICodeCellModel {
if (options.contentFactory) {
options.contentFactory = this.codeCellContentFactory;
}
if (this.modelDB) {
if (!options.id) {
options.id = UUID.uuid4();
}
options.modelDB = this.modelDB.view(options.id);
}
return new CodeCellModel(options);
}
/**
* Create a new markdown cell.
*
* @param source - The data to use for the original source data.
*
* @returns A new markdown cell. If a source cell is provided, the
* new cell will be initialized with the data from the source.
*/
createMarkdownCell(options: CellModel.IOptions): IMarkdownCellModel {
if (this.modelDB) {
if (!options.id) {
options.id = UUID.uuid4();
}
options.modelDB = this.modelDB.view(options.id);
}
return new MarkdownCellModel(options);
}
/**
* Create a new raw cell.
*
* @param source - The data to use for the original source data.
*
* @returns A new raw cell. If a source cell is provided, the
* new cell will be initialized with the data from the source.
*/
createRawCell(options: CellModel.IOptions): IRawCellModel {
if (this.modelDB) {
if (!options.id) {
options.id = UUID.uuid4();
}
options.modelDB = this.modelDB.view(options.id);
}
return new RawCellModel(options);
}
/**
* Clone the content factory with a new IModelDB.
*/
clone(modelDB: IModelDB): ContentFactory {
return new ContentFactory({
modelDB: modelDB,
codeCellContentFactory: this.codeCellContentFactory
});
}
}
/**
* A namespace for the notebook model content factory.
*/
export namespace ContentFactory {
/**
* The options used to initialize a `ContentFactory`.
*/
export interface IOptions {
/**
* The factory for code cell model content.
*/
codeCellContentFactory?: CodeCellModel.IContentFactory;
/**
* The modelDB in which to place new content.
*/
modelDB?: IModelDB;
}
}
/**
* The default `ContentFactory` instance.
*/
export const defaultContentFactory = new ContentFactory({});
}