forked from jupyterlab/jupyterlab
/
model.ts
658 lines (577 loc) · 15.3 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
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
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import { JSONExt, JSONObject, JSONValue } from '@phosphor/coreutils';
import { ISignal, Signal } from '@phosphor/signaling';
import { IAttachmentsModel, AttachmentsModel } from '@jupyterlab/attachments';
import { CodeEditor } from '@jupyterlab/codeeditor';
import { IChangedArgs, nbformat } from '@jupyterlab/coreutils';
import { UUID } from '@phosphor/coreutils';
import {
IObservableJSON,
IModelDB,
IObservableValue,
ObservableValue,
IObservableMap
} from '@jupyterlab/observables';
import { IOutputAreaModel, OutputAreaModel } from '@jupyterlab/outputarea';
/**
* The definition of a model object for a cell.
*/
export interface ICellModel extends CodeEditor.IModel {
/**
* The type of the cell.
*/
readonly type: nbformat.CellType;
/**
* A unique identifier for the cell.
*/
readonly id: string;
/**
* A signal emitted when the content of the model changes.
*/
readonly contentChanged: ISignal<ICellModel, void>;
/**
* A signal emitted when a model state changes.
*/
readonly stateChanged: ISignal<ICellModel, IChangedArgs<any>>;
/**
* Whether the cell is trusted.
*/
trusted: boolean;
/**
* The metadata associated with the cell.
*/
readonly metadata: IObservableJSON;
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.ICell;
}
/**
* The definition of a model cell object for a cell with attachments.
*/
export interface IAttachmentsCellModel extends ICellModel {
/**
* The cell attachments
*/
readonly attachments: IAttachmentsModel;
}
/**
* The definition of a code cell.
*/
export interface ICodeCellModel extends ICellModel {
/**
* The type of the cell.
*
* #### Notes
* This is a read-only property.
*/
readonly type: 'code';
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.ICodeCell;
/**
* The code cell's prompt number. Will be null if the cell has not been run.
*/
executionCount: nbformat.ExecutionCount;
/**
* The cell outputs.
*/
readonly outputs: IOutputAreaModel;
}
/**
* The definition of a markdown cell.
*/
export interface IMarkdownCellModel extends IAttachmentsCellModel {
/**
* The type of the cell.
*/
readonly type: 'markdown';
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IMarkdownCell;
}
/**
* The definition of a raw cell.
*/
export interface IRawCellModel extends IAttachmentsCellModel {
/**
* The type of the cell.
*/
readonly type: 'raw';
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IRawCell;
}
export function isCodeCellModel(model: ICellModel): model is ICodeCellModel {
return model.type === 'code';
}
export function isMarkdownCellModel(
model: ICellModel
): model is IMarkdownCellModel {
return model.type === 'markdown';
}
export function isRawCellModel(model: ICellModel): model is IRawCellModel {
return model.type === 'raw';
}
/**
* An implementation of the cell model.
*/
export class CellModel extends CodeEditor.Model implements ICellModel {
/**
* Construct a cell model from optional cell content.
*/
constructor(options: CellModel.IOptions) {
super({ modelDB: options.modelDB });
this.id = options.id || UUID.uuid4();
this.value.changed.connect(this.onGenericChange, this);
let cellType = this.modelDB.createValue('type');
cellType.set(this.type);
let observableMetadata = this.modelDB.createMap('metadata');
observableMetadata.changed.connect(this.onGenericChange, this);
let cell = options.cell;
let trusted = this.modelDB.createValue('trusted');
trusted.changed.connect(this.onTrustedChanged, this);
if (!cell) {
trusted.set(false);
return;
}
trusted.set(!!cell.metadata['trusted']);
delete cell.metadata['trusted'];
if (Array.isArray(cell.source)) {
this.value.text = (cell.source as string[]).join('');
} else {
this.value.text = cell.source as string;
}
let metadata = JSONExt.deepCopy(cell.metadata);
if (this.type !== 'raw') {
delete metadata['format'];
}
if (this.type !== 'code') {
delete metadata['collapsed'];
delete metadata['scrolled'];
}
for (let key in metadata) {
observableMetadata.set(key, metadata[key]);
}
}
/**
* The type of cell.
*/
readonly type: nbformat.CellType;
/**
* A signal emitted when the state of the model changes.
*/
readonly contentChanged = new Signal<this, void>(this);
/**
* A signal emitted when a model state changes.
*/
readonly stateChanged = new Signal<this, IChangedArgs<any>>(this);
/**
* The id for the cell.
*/
readonly id: string;
/**
* The metadata associated with the cell.
*/
get metadata(): IObservableJSON {
return this.modelDB.get('metadata') as IObservableJSON;
}
/**
* Get the trusted state of the model.
*/
get trusted(): boolean {
return this.modelDB.getValue('trusted') as boolean;
}
/**
* Set the trusted state of the model.
*/
set trusted(newValue: boolean) {
let oldValue = this.trusted;
if (oldValue === newValue) {
return;
}
this.modelDB.setValue('trusted', newValue);
}
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.ICell {
let metadata: nbformat.IBaseCellMetadata = Object.create(null);
for (let key of this.metadata.keys()) {
let value = JSON.parse(JSON.stringify(this.metadata.get(key)));
metadata[key] = value as JSONValue;
}
if (this.trusted) {
metadata['trusted'] = true;
}
return {
cell_type: this.type,
source: this.value.text,
metadata
} as nbformat.ICell;
}
/**
* Handle a change to the trusted state.
*
* The default implementation is a no-op.
*/
onTrustedChanged(
trusted: IObservableValue,
args: ObservableValue.IChangedArgs
): void {
/* no-op */
}
/**
* Handle a change to the observable value.
*/
protected onGenericChange(): void {
this.contentChanged.emit(void 0);
}
}
/**
* The namespace for `CellModel` statics.
*/
export namespace CellModel {
/**
* The options used to initialize a `CellModel`.
*/
export interface IOptions {
/**
* The source cell data.
*/
cell?: nbformat.IBaseCell;
/**
* An IModelDB in which to store cell data.
*/
modelDB?: IModelDB;
/**
* A unique identifier for this cell.
*/
id?: string;
}
}
/**
* A base implementation for cell models with attachments.
*/
export class AttachmentsCellModel extends CellModel {
/**
* Construct a new cell with optional attachments.
*/
constructor(options: AttachmentsCellModel.IOptions) {
super(options);
let factory =
options.contentFactory || AttachmentsCellModel.defaultContentFactory;
let attachments: nbformat.IAttachments | undefined;
let cell = options.cell;
if (cell && (cell.cell_type === 'raw' || cell.cell_type === 'markdown')) {
attachments = (cell as nbformat.IRawCell | nbformat.IMarkdownCell)
.attachments;
}
this._attachments = factory.createAttachmentsModel({
values: attachments,
modelDB: this.modelDB
});
this._attachments.stateChanged.connect(this.onGenericChange, this);
}
/**
* Get the attachments of the model.
*/
get attachments(): IAttachmentsModel {
return this._attachments;
}
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IRawCell | nbformat.IMarkdownCell {
let cell = super.toJSON() as nbformat.IRawCell | nbformat.IMarkdownCell;
if (this.attachments.length) {
cell.attachments = this.attachments.toJSON();
}
return cell;
}
private _attachments: IAttachmentsModel | null = null;
}
/**
* The namespace for `AttachmentsCellModel` statics.
*/
export namespace AttachmentsCellModel {
/**
* The options used to initialize a `AttachmentsCellModel`.
*/
export interface IOptions extends CellModel.IOptions {
/**
* The factory for attachment model creation.
*/
contentFactory?: IContentFactory;
}
/**
* A factory for creating code cell model content.
*/
export interface IContentFactory {
/**
* Create an output area.
*/
createAttachmentsModel(
options: IAttachmentsModel.IOptions
): IAttachmentsModel;
}
/**
* The default implementation of an `IContentFactory`.
*/
export class ContentFactory implements IContentFactory {
/**
* Create an attachments model.
*/
createAttachmentsModel(
options: IAttachmentsModel.IOptions
): IAttachmentsModel {
return new AttachmentsModel(options);
}
}
/**
* The shared `ContentFactory` instance.
*/
export const defaultContentFactory = new ContentFactory();
}
/**
* An implementation of a raw cell model.
*/
export class RawCellModel extends AttachmentsCellModel {
/**
* The type of the cell.
*/
get type(): 'raw' {
return 'raw';
}
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IRawCell {
return super.toJSON() as nbformat.IRawCell;
}
}
/**
* An implementation of a markdown cell model.
*/
export class MarkdownCellModel extends AttachmentsCellModel {
/**
* Construct a markdown cell model from optional cell content.
*/
constructor(options: CellModel.IOptions) {
super(options);
// Use the Github-flavored markdown mode.
this.mimeType = 'text/x-ipythongfm';
}
/**
* The type of the cell.
*/
get type(): 'markdown' {
return 'markdown';
}
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IMarkdownCell {
return super.toJSON() as nbformat.IMarkdownCell;
}
}
/**
* An implementation of a code cell Model.
*/
export class CodeCellModel extends CellModel implements ICodeCellModel {
/**
* Construct a new code cell with optional original cell content.
*/
constructor(options: CodeCellModel.IOptions) {
super(options);
let factory = options.contentFactory || CodeCellModel.defaultContentFactory;
let trusted = this.trusted;
let cell = options.cell as nbformat.ICodeCell;
let outputs: nbformat.IOutput[] = [];
let executionCount = this.modelDB.createValue('executionCount');
if (!executionCount.get()) {
if (cell && cell.cell_type === 'code') {
executionCount.set(cell.execution_count || null);
outputs = cell.outputs;
} else {
executionCount.set(null);
}
}
executionCount.changed.connect(this._onExecutionCountChanged, this);
this._outputs = factory.createOutputArea({ trusted, values: outputs });
this._outputs.changed.connect(this.onGenericChange, this);
// We keep `collapsed` and `jupyter.outputs_hidden` metadata in sync, since
// they are redundant in nbformat 4.4. See
// https://github.com/jupyter/nbformat/issues/137
this.metadata.changed.connect(Private.collapseChanged, this);
// Sync `collapsed` and `jupyter.outputs_hidden` for the first time, giving
// preference to `collapsed`.
if (this.metadata.has('collapsed')) {
let collapsed = this.metadata.get('collapsed');
Private.collapseChanged(this.metadata, {
type: 'change',
key: 'collapsed',
oldValue: collapsed,
newValue: collapsed
});
} else if (this.metadata.has('jupyter')) {
let jupyter = this.metadata.get('jupyter') as JSONObject;
if (jupyter.hasOwnProperty('outputs_hidden')) {
Private.collapseChanged(this.metadata, {
type: 'change',
key: 'jupyter',
oldValue: jupyter,
newValue: jupyter
});
}
}
}
/**
* The type of the cell.
*/
get type(): 'code' {
return 'code';
}
/**
* The execution count of the cell.
*/
get executionCount(): nbformat.ExecutionCount {
return this.modelDB.getValue('executionCount') as nbformat.ExecutionCount;
}
set executionCount(newValue: nbformat.ExecutionCount) {
let oldValue = this.executionCount;
if (newValue === oldValue) {
return;
}
this.modelDB.setValue('executionCount', newValue || null);
}
/**
* The cell outputs.
*/
get outputs(): IOutputAreaModel {
return this._outputs;
}
/**
* Dispose of the resources held by the model.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._outputs.dispose();
this._outputs = null;
super.dispose();
}
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.ICodeCell {
let cell = super.toJSON() as nbformat.ICodeCell;
cell.execution_count = this.executionCount || null;
cell.outputs = this.outputs.toJSON();
return cell;
}
/**
* Handle a change to the trusted state.
*/
onTrustedChanged(
trusted: IObservableValue,
args: ObservableValue.IChangedArgs
): void {
if (this._outputs) {
this._outputs.trusted = args.newValue as boolean;
}
this.stateChanged.emit({
name: 'trusted',
oldValue: args.oldValue,
newValue: args.newValue
});
}
/**
* Handle a change to the execution count.
*/
private _onExecutionCountChanged(
count: IObservableValue,
args: ObservableValue.IChangedArgs
): void {
this.contentChanged.emit(void 0);
this.stateChanged.emit({
name: 'executionCount',
oldValue: args.oldValue,
newValue: args.newValue
});
}
private _outputs: IOutputAreaModel = null;
}
/**
* The namespace for `CodeCellModel` statics.
*/
export namespace CodeCellModel {
/**
* The options used to initialize a `CodeCellModel`.
*/
export interface IOptions extends CellModel.IOptions {
/**
* The factory for output area model creation.
*/
contentFactory?: IContentFactory;
}
/**
* A factory for creating code cell model content.
*/
export interface IContentFactory {
/**
* Create an output area.
*/
createOutputArea(options: IOutputAreaModel.IOptions): IOutputAreaModel;
}
/**
* The default implementation of an `IContentFactory`.
*/
export class ContentFactory implements IContentFactory {
/**
* Create an output area.
*/
createOutputArea(options: IOutputAreaModel.IOptions): IOutputAreaModel {
return new OutputAreaModel(options);
}
}
/**
* The shared `ContentFactory` instance.
*/
export const defaultContentFactory = new ContentFactory();
}
namespace Private {
export function collapseChanged(
metadata: IObservableJSON,
args: IObservableMap.IChangedArgs<JSONValue>
) {
if (args.key === 'collapsed') {
const jupyter = (metadata.get('jupyter') || {}) as JSONObject;
const { outputs_hidden, ...newJupyter } = jupyter;
if (outputs_hidden !== args.newValue) {
if (args.newValue !== undefined) {
newJupyter['outputs_hidden'] = args.newValue;
}
if (Object.keys(newJupyter).length === 0) {
metadata.delete('jupyter');
} else {
metadata.set('jupyter', newJupyter);
}
}
} else if (args.key === 'jupyter') {
const jupyter = (args.newValue || {}) as JSONObject;
if (jupyter.hasOwnProperty('outputs_hidden')) {
metadata.set('collapsed', jupyter.outputs_hidden);
} else {
metadata.delete('collapsed');
}
}
}
}