-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
model.ts
496 lines (437 loc) · 12 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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { each, map, toArray } from '@phosphor/algorithm';
import { IDisposable } from '@phosphor/disposable';
import { ISignal, Signal } from '@phosphor/signaling';
import { nbformat } from '@jupyterlab/coreutils';
import {
IObservableList,
ObservableList,
IObservableValue,
ObservableValue,
IModelDB
} from '@jupyterlab/observables';
import { IOutputModel, OutputModel } from '@jupyterlab/rendermime';
/**
* The model for an output area.
*/
export interface IOutputAreaModel extends IDisposable {
/**
* A signal emitted when the model state changes.
*/
readonly stateChanged: ISignal<IOutputAreaModel, void>;
/**
* A signal emitted when the model changes.
*/
readonly changed: ISignal<IOutputAreaModel, IOutputAreaModel.ChangedArgs>;
/**
* The length of the items in the model.
*/
readonly length: number;
/**
* Whether the output area is trusted.
*/
trusted: boolean;
/**
* The output content factory used by the model.
*/
readonly contentFactory: IOutputAreaModel.IContentFactory;
/**
* Get an item at the specified index.
*/
get(index: number): IOutputModel;
/**
* Add an output, which may be combined with previous output.
*
* #### Notes
* The output bundle is copied.
* Contiguous stream outputs of the same `name` are combined.
*/
add(output: nbformat.IOutput): number;
/**
* Set the value at the specified index.
*/
set(index: number, output: nbformat.IOutput): void;
/**
* Clear all of the output.
*
* @param wait - Delay clearing the output until the next message is added.
*/
clear(wait?: boolean): void;
/**
* Deserialize the model from JSON.
*
* #### Notes
* This will clear any existing data.
*/
fromJSON(values: nbformat.IOutput[]): void;
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IOutput[];
}
/**
* The namespace for IOutputAreaModel interfaces.
*/
export namespace IOutputAreaModel {
/**
* The options used to create a output area model.
*/
export interface IOptions {
/**
* The initial values for the model.
*/
values?: nbformat.IOutput[];
/**
* Whether the output is trusted. The default is false.
*/
trusted?: boolean;
/**
* The output content factory used by the model.
*
* If not given, a default factory will be used.
*/
contentFactory?: IContentFactory;
/**
* An optional IModelDB to store the output area model.
*/
modelDB?: IModelDB;
}
/**
* A type alias for changed args.
*/
export type ChangedArgs = IObservableList.IChangedArgs<IOutputModel>;
/**
* The interface for an output content factory.
*/
export interface IContentFactory {
/**
* Create an output model.
*/
createOutputModel(options: IOutputModel.IOptions): IOutputModel;
}
}
/**
* The default implementation of the IOutputAreaModel.
*/
export class OutputAreaModel implements IOutputAreaModel {
/**
* Construct a new observable outputs instance.
*/
constructor(options: IOutputAreaModel.IOptions = {}) {
this._trusted = !!options.trusted;
this.contentFactory =
options.contentFactory || OutputAreaModel.defaultContentFactory;
this.list = new ObservableList<IOutputModel>();
if (options.values) {
each(options.values, value => {
this._add(value);
});
}
this.list.changed.connect(this._onListChanged, this);
// If we are given a IModelDB, keep an up-to-date
// serialized copy of the OutputAreaModel in it.
if (options.modelDB) {
this._modelDB = options.modelDB;
this._serialized = this._modelDB.createValue('outputs');
if (this._serialized.get()) {
this.fromJSON(this._serialized.get() as nbformat.IOutput[]);
} else {
this._serialized.set(this.toJSON());
}
this._serialized.changed.connect(this._onSerializedChanged, this);
}
}
/**
* A signal emitted when the model state changes.
*/
get stateChanged(): ISignal<IOutputAreaModel, void> {
return this._stateChanged;
}
/**
* A signal emitted when the model changes.
*/
get changed(): ISignal<this, IOutputAreaModel.ChangedArgs> {
return this._changed;
}
/**
* Get the length of the items in the model.
*/
get length(): number {
return this.list ? this.list.length : 0;
}
/**
* Get whether the model is trusted.
*/
get trusted(): boolean {
return this._trusted;
}
/**
* Set whether the model is trusted.
*
* #### Notes
* Changing the value will cause all of the models to re-set.
*/
set trusted(value: boolean) {
if (value === this._trusted) {
return;
}
let trusted = (this._trusted = value);
for (let i = 0; i < this.list.length; i++) {
let item = this.list.get(i);
let value = item.toJSON();
item.dispose();
item = this._createItem({ value, trusted });
this.list.set(i, item);
}
}
/**
* The output content factory used by the model.
*/
readonly contentFactory: IOutputAreaModel.IContentFactory;
/**
* Test 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.list.dispose();
Signal.clearData(this);
}
/**
* Get an item at the specified index.
*/
get(index: number): IOutputModel {
return this.list.get(index);
}
/**
* Set the value at the specified index.
*/
set(index: number, value: nbformat.IOutput): void {
// Normalize stream data.
this._normalize(value);
let item = this._createItem({ value, trusted: this._trusted });
this.list.set(index, item);
}
/**
* Add an output, which may be combined with previous output.
*
* #### Notes
* The output bundle is copied.
* Contiguous stream outputs of the same `name` are combined.
*/
add(output: nbformat.IOutput): number {
// If we received a delayed clear message, then clear now.
if (this.clearNext) {
this.clear();
this.clearNext = false;
}
return this._add(output);
}
/**
* Clear all of the output.
*
* @param wait Delay clearing the output until the next message is added.
*/
clear(wait: boolean = false): void {
this._lastStream = '';
if (wait) {
this.clearNext = true;
return;
}
each(this.list, (item: IOutputModel) => {
item.dispose();
});
this.list.clear();
}
/**
* Deserialize the model from JSON.
*
* #### Notes
* This will clear any existing data.
*/
fromJSON(values: nbformat.IOutput[]) {
this.clear();
each(values, value => {
this._add(value);
});
}
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IOutput[] {
return toArray(map(this.list, (output: IOutputModel) => output.toJSON()));
}
/**
* Add an item to the list.
*/
private _add(value: nbformat.IOutput): number {
let trusted = this._trusted;
// Normalize the value.
this._normalize(value);
// Consolidate outputs if they are stream outputs of the same kind.
if (
nbformat.isStream(value) &&
this._lastStream &&
value.name === this._lastName
) {
// In order to get a list change event, we add the previous
// text to the current item and replace the previous item.
// This also replaces the metadata of the last item.
this._lastStream += value.text as string;
value.text = this._lastStream;
this._removeOverwrittenChars(value);
let item = this._createItem({ value, trusted });
let index = this.length - 1;
let prev = this.list.get(index);
prev.dispose();
this.list.set(index, item);
return index;
}
if (nbformat.isStream(value)) {
this._removeOverwrittenChars(value);
}
// Create the new item.
let item = this._createItem({ value, trusted });
// Update the stream information.
if (nbformat.isStream(value)) {
this._lastStream = value.text as string;
this._lastName = value.name;
} else {
this._lastStream = '';
}
// Add the item to our list and return the new length.
return this.list.push(item);
}
/**
* Normalize an output.
*/
private _normalize(value: nbformat.IOutput): void {
if (nbformat.isStream(value)) {
if (Array.isArray(value.text)) {
value.text = (value.text as string[]).join('\n');
}
}
}
/**
* Remove characters that are overridden by backspace characters.
*/
private _fixBackspace(txt: string): string {
let tmp = txt;
do {
txt = tmp;
// Cancel out anything-but-newline followed by backspace
tmp = txt.replace(/[^\n]\x08/gm, '');
} while (tmp.length < txt.length);
return txt;
}
/**
* Remove chunks that should be overridden by the effect of
* carriage return characters.
*/
private _fixCarriageReturn(txt: string): string {
let tmp = txt;
// Handle multiple carriage returns before a newline
tmp = tmp.replace(/\r\r+\n/gm, '\r\n');
// Remove chunks that should be overridden by carriage returns
do {
// Remove any chunks preceding a carriage return unless carriage
// return followed by a newline
tmp = tmp.replace(/^[^\n]*(?:\r(?!\n))+/gm, '');
} while (tmp.search(/\r(?!\n)/) > -1);
do {
// Replace remaining \r\n characters with a newline
tmp = tmp.replace(/\r\n/gm, '\n');
} while (tmp.indexOf('\r\n') > -1);
return tmp;
}
/*
* Remove characters overridden by backspaces and carriage returns
*/
private _removeOverwrittenChars(value: nbformat.IOutput): void {
let tmp = value.text as string;
value.text = this._fixCarriageReturn(this._fixBackspace(tmp));
}
protected clearNext = false;
protected list: IObservableList<IOutputModel> = null;
/**
* Create an output item and hook up its signals.
*/
private _createItem(options: IOutputModel.IOptions): IOutputModel {
let factory = this.contentFactory;
let item = factory.createOutputModel(options);
item.changed.connect(this._onGenericChange, this);
return item;
}
/**
* Handle a change to the list.
*/
private _onListChanged(
sender: IObservableList<IOutputModel>,
args: IObservableList.IChangedArgs<IOutputModel>
) {
if (this._serialized && !this._changeGuard) {
this._changeGuard = true;
this._serialized.set(this.toJSON());
this._changeGuard = false;
}
this._changed.emit(args);
}
/**
* If the serialized version of the outputs have changed due to a remote
* action, then update the model accordingly.
*/
private _onSerializedChanged(
sender: IObservableValue,
args: ObservableValue.IChangedArgs
) {
if (!this._changeGuard) {
this._changeGuard = true;
this.fromJSON(args.newValue as nbformat.IOutput[]);
this._changeGuard = false;
}
}
/**
* Handle a change to an item.
*/
private _onGenericChange(): void {
this._stateChanged.emit(void 0);
}
private _lastStream: string;
private _lastName: 'stdout' | 'stderr';
private _trusted = false;
private _isDisposed = false;
private _stateChanged = new Signal<IOutputAreaModel, void>(this);
private _changed = new Signal<this, IOutputAreaModel.ChangedArgs>(this);
private _modelDB: IModelDB = null;
private _serialized: IObservableValue = null;
private _changeGuard = false;
}
/**
* The namespace for OutputAreaModel class statics.
*/
export namespace OutputAreaModel {
/**
* The default implementation of a `IModelOutputFactory`.
*/
export class ContentFactory implements IOutputAreaModel.IContentFactory {
/**
* Create an output model.
*/
createOutputModel(options: IOutputModel.IOptions): IOutputModel {
return new OutputModel(options);
}
}
/**
* The default output model factory.
*/
export const defaultContentFactory = new ContentFactory();
}