forked from jupyterlab/jupyterlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
widget.ts
854 lines (752 loc) · 22.1 KB
/
widget.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
JSONObject,
PromiseDelegate,
ReadonlyJSONObject
} from '@phosphor/coreutils';
import { Message } from '@phosphor/messaging';
import { Signal } from '@phosphor/signaling';
import { Panel, PanelLayout } from '@phosphor/widgets';
import { Widget } from '@phosphor/widgets';
import { IClientSession } from '@jupyterlab/apputils';
import { nbformat } from '@jupyterlab/coreutils';
import { IOutputModel, IRenderMimeRegistry } from '@jupyterlab/rendermime';
import { IRenderMime } from '@jupyterlab/rendermime-interfaces';
import { Kernel, KernelMessage } from '@jupyterlab/services';
import { IOutputAreaModel } from './model';
/**
* The class name added to an output area widget.
*/
const OUTPUT_AREA_CLASS = 'jp-OutputArea';
/**
* The class name added to the direction children of OutputArea
*/
const OUTPUT_AREA_ITEM_CLASS = 'jp-OutputArea-child';
/**
* The class name added to actual outputs
*/
const OUTPUT_AREA_OUTPUT_CLASS = 'jp-OutputArea-output';
/**
* The class name added to prompt children of OutputArea.
*/
const OUTPUT_AREA_PROMPT_CLASS = 'jp-OutputArea-prompt';
/**
* The class name added to OutputPrompt.
*/
const OUTPUT_PROMPT_CLASS = 'jp-OutputPrompt';
/**
* The class name added to an execution result.
*/
const EXECUTE_CLASS = 'jp-OutputArea-executeResult';
/**
* The class name added stdin items of OutputArea
*/
const OUTPUT_AREA_STDIN_ITEM_CLASS = 'jp-OutputArea-stdin-item';
/**
* The class name added to stdin widgets.
*/
const STDIN_CLASS = 'jp-Stdin';
/**
* The class name added to stdin data prompt nodes.
*/
const STDIN_PROMPT_CLASS = 'jp-Stdin-prompt';
/**
* The class name added to stdin data input nodes.
*/
const STDIN_INPUT_CLASS = 'jp-Stdin-input';
/******************************************************************************
* OutputArea
******************************************************************************/
/**
* An output area widget.
*
* #### Notes
* The widget model must be set separately and can be changed
* at any time. Consumers of the widget must account for a
* `null` model, and may want to listen to the `modelChanged`
* signal.
*/
export class OutputArea extends Widget {
/**
* Construct an output area widget.
*/
constructor(options: OutputArea.IOptions) {
super();
let model = (this.model = options.model);
this.addClass(OUTPUT_AREA_CLASS);
this.rendermime = options.rendermime;
this.contentFactory =
options.contentFactory || OutputArea.defaultContentFactory;
this.layout = new PanelLayout();
for (let i = 0; i < model.length; i++) {
let output = model.get(i);
this._insertOutput(i, output);
}
model.changed.connect(this.onModelChanged, this);
model.stateChanged.connect(this.onStateChanged, this);
}
/**
* The model used by the widget.
*/
readonly model: IOutputAreaModel;
/**
* The content factory used by the widget.
*/
readonly contentFactory: OutputArea.IContentFactory;
/**
* The rendermime instance used by the widget.
*/
readonly rendermime: IRenderMimeRegistry;
/**
* A read-only sequence of the chidren widgets in the output area.
*/
get widgets(): ReadonlyArray<Widget> {
return (this.layout as PanelLayout).widgets;
}
/**
* A public signal used to indicate the number of outputs has changed.
*
* #### Notes
* This is useful for parents who want to apply styling based on the number
* of outputs. Emits the current number of outputs.
*/
readonly outputLengthChanged = new Signal<this, number>(this);
/**
* The kernel future associated with the output area.
*/
get future(): Kernel.IFuture {
return this._future;
}
set future(value: Kernel.IFuture) {
// Bail if the model is disposed.
if (this.model.isDisposed) {
throw Error('Model is disposed');
}
if (this._future === value) {
return;
}
if (this._future) {
this._future.dispose();
}
this._future = value;
this.model.clear();
// Make sure there were no input widgets.
if (this.widgets.length) {
this._clear();
this.outputLengthChanged.emit(this.model.length);
}
// Handle published messages.
value.onIOPub = this._onIOPub;
// Handle the execute reply.
value.onReply = this._onExecuteReply;
// Handle stdin.
value.onStdin = msg => {
if (KernelMessage.isInputRequestMsg(msg)) {
this.onInputRequest(msg, value);
}
};
}
/**
* Dispose of the resources used by the output area.
*/
dispose(): void {
if (this._future) {
this._future.dispose();
}
this._future = null;
this._displayIdMap.clear();
super.dispose();
}
/**
* Follow changes on the model state.
*/
protected onModelChanged(
sender: IOutputAreaModel,
args: IOutputAreaModel.ChangedArgs
): void {
switch (args.type) {
case 'add':
this._insertOutput(args.newIndex, args.newValues[0]);
this.outputLengthChanged.emit(this.model.length);
break;
case 'remove':
// Only clear is supported by the model.
if (this.widgets.length) {
this._clear();
this.outputLengthChanged.emit(this.model.length);
}
break;
case 'set':
this._setOutput(args.newIndex, args.newValues[0]);
this.outputLengthChanged.emit(this.model.length);
break;
default:
break;
}
}
/**
* Follow changes on the output model state.
*/
protected onStateChanged(sender: IOutputAreaModel): void {
for (let i = 0; i < this.model.length; i++) {
this._setOutput(i, this.model.get(i));
}
this.outputLengthChanged.emit(this.model.length);
}
/**
* Clear the widget inputs and outputs.
*/
private _clear(): void {
// Bail if there is no work to do.
if (!this.widgets.length) {
return;
}
// Remove all of our widgets.
let length = this.widgets.length;
for (let i = 0; i < length; i++) {
let widget = this.widgets[0];
widget.parent = null;
widget.dispose();
}
// Clear the display id map.
this._displayIdMap.clear();
// When an output area is cleared and then quickly replaced with new
// content (as happens with @interact in widgets, for example), the
// quickly changing height can make the page jitter.
// We introduce a small delay in the minimum height
// to prevent this jitter.
let rect = this.node.getBoundingClientRect();
this.node.style.minHeight = `${rect.height}px`;
if (this._minHeightTimeout) {
clearTimeout(this._minHeightTimeout);
}
this._minHeightTimeout = window.setTimeout(() => {
if (this.isDisposed) {
return;
}
this.node.style.minHeight = '';
}, 50);
}
/**
* Handle an input request from a kernel.
*/
protected onInputRequest(
msg: KernelMessage.IInputRequestMsg,
future: Kernel.IFuture
): void {
// Add an output widget to the end.
let factory = this.contentFactory;
let stdinPrompt = msg.content.prompt;
let password = msg.content.password;
let panel = new Panel();
panel.addClass(OUTPUT_AREA_ITEM_CLASS);
panel.addClass(OUTPUT_AREA_STDIN_ITEM_CLASS);
let prompt = factory.createOutputPrompt();
prompt.addClass(OUTPUT_AREA_PROMPT_CLASS);
panel.addWidget(prompt);
let input = factory.createStdin({ prompt: stdinPrompt, password, future });
input.addClass(OUTPUT_AREA_OUTPUT_CLASS);
panel.addWidget(input);
let layout = this.layout as PanelLayout;
layout.addWidget(panel);
/**
* Wait for the stdin to complete, add it to the model (so it persists)
* and remove the stdin widget.
*/
void input.value.then(value => {
// Use stdin as the stream so it does not get combined with stdout.
this.model.add({
output_type: 'stream',
name: 'stdin',
text: value + '\n'
});
panel.dispose();
});
}
/**
* Update an output in the layout in place.
*/
private _setOutput(index: number, model: IOutputModel): void {
let layout = this.layout as PanelLayout;
let panel = layout.widgets[index] as Panel;
let renderer = (panel.widgets
? panel.widgets[1]
: panel) as IRenderMime.IRenderer;
if (renderer.renderModel) {
void renderer.renderModel(model);
} else {
layout.widgets[index].dispose();
this._insertOutput(index, model);
}
}
/**
* Render and insert a single output into the layout.
*/
private _insertOutput(index: number, model: IOutputModel): void {
let output = this.createOutputItem(model);
output.toggleClass(EXECUTE_CLASS, model.executionCount !== null);
let layout = this.layout as PanelLayout;
layout.insertWidget(index, output);
}
/**
* Create an output item with a prompt and actual output
*/
protected createOutputItem(model: IOutputModel): Widget {
let panel = new Panel();
panel.addClass(OUTPUT_AREA_ITEM_CLASS);
let prompt = this.contentFactory.createOutputPrompt();
prompt.executionCount = model.executionCount;
prompt.addClass(OUTPUT_AREA_PROMPT_CLASS);
panel.addWidget(prompt);
let output = this.createRenderedMimetype(model);
output.addClass(OUTPUT_AREA_OUTPUT_CLASS);
panel.addWidget(output);
return panel;
}
/**
* Render a mimetype
*/
protected createRenderedMimetype(model: IOutputModel): Widget {
let widget: Widget;
let mimeType = this.rendermime.preferredMimeType(
model.data,
model.trusted ? 'any' : 'ensure'
);
if (mimeType) {
let metadata = model.metadata;
let mimeMd = metadata[mimeType] as ReadonlyJSONObject;
let isolated = false;
// mime-specific higher priority
if (mimeMd && mimeMd['isolated'] !== undefined) {
isolated = mimeMd['isolated'] as boolean;
} else {
// fallback on global
isolated = metadata['isolated'] as boolean;
}
let output = this.rendermime.createRenderer(mimeType);
if (isolated === true) {
output = new Private.IsolatedRenderer(output);
}
output.renderModel(model).catch(error => {
// Manually append error message to output
output.node.innerHTML = `<pre>Javascript Error: ${error.message}</pre>`;
// Remove mime-type-specific CSS classes
output.node.className = 'p-Widget jp-RenderedText';
output.node.setAttribute(
'data-mime-type',
'application/vnd.jupyter.stderr'
);
});
widget = output;
} else {
widget = new Widget();
widget.node.innerHTML =
`No ${model.trusted ? '' : '(safe) '}renderer could be ` +
'found for output. It has the following MIME types: ' +
Object.keys(model.data).join(', ');
}
return widget;
}
/**
* Handle an iopub message.
*/
private _onIOPub = (msg: KernelMessage.IIOPubMessage) => {
let model = this.model;
let msgType = msg.header.msg_type;
let output: nbformat.IOutput;
let transient = (msg.content.transient || {}) as JSONObject;
let displayId = transient['display_id'] as string;
let targets: number[];
switch (msgType) {
case 'execute_result':
case 'display_data':
case 'stream':
case 'error':
output = msg.content as nbformat.IOutput;
output.output_type = msgType as nbformat.OutputType;
model.add(output);
break;
case 'clear_output':
let wait = (msg as KernelMessage.IClearOutputMsg).content.wait;
model.clear(wait);
break;
case 'update_display_data':
output = msg.content as nbformat.IOutput;
output.output_type = 'display_data';
targets = this._displayIdMap.get(displayId);
if (targets) {
for (let index of targets) {
model.set(index, output);
}
}
break;
default:
break;
}
if (displayId && msgType === 'display_data') {
targets = this._displayIdMap.get(displayId) || [];
targets.push(model.length - 1);
this._displayIdMap.set(displayId, targets);
}
};
/**
* Handle an execute reply message.
*/
private _onExecuteReply = (msg: KernelMessage.IExecuteReplyMsg) => {
// API responses that contain a pager are special cased and their type
// is overridden from 'execute_reply' to 'display_data' in order to
// render output.
let model = this.model;
let content = msg.content as KernelMessage.IExecuteOkReply;
let payload = content && content.payload;
if (!payload || !payload.length) {
return;
}
let pages = payload.filter((i: any) => (i as any).source === 'page');
if (!pages.length) {
return;
}
let page = JSON.parse(JSON.stringify(pages[0]));
let output: nbformat.IOutput = {
output_type: 'display_data',
data: (page as any).data as nbformat.IMimeBundle,
metadata: {}
};
model.add(output);
};
private _minHeightTimeout: number = null;
private _future: Kernel.IFuture = null;
private _displayIdMap = new Map<string, number[]>();
}
export class SimplifiedOutputArea extends OutputArea {
/**
* Handle an input request from a kernel by doing nothing.
*/
protected onInputRequest(
msg: KernelMessage.IInputRequestMsg,
future: Kernel.IFuture
): void {
return;
}
/**
* Create an output item without a prompt, just the output widgets
*/
protected createOutputItem(model: IOutputModel): Widget {
let output = this.createRenderedMimetype(model);
output.addClass(OUTPUT_AREA_OUTPUT_CLASS);
return output;
}
}
/**
* A namespace for OutputArea statics.
*/
export namespace OutputArea {
/**
* The options to create an `OutputArea`.
*/
export interface IOptions {
/**
* The model used by the widget.
*/
model: IOutputAreaModel;
/**
* The content factory used by the widget to create children.
*/
contentFactory?: IContentFactory;
/**
* The rendermime instance used by the widget.
*/
rendermime: IRenderMimeRegistry;
}
/**
* Execute code on an output area.
*/
export function execute(
code: string,
output: OutputArea,
session: IClientSession,
metadata?: JSONObject
): Promise<KernelMessage.IExecuteReplyMsg> {
// Override the default for `stop_on_error`.
let stopOnError = true;
if (
metadata &&
metadata.tags &&
(metadata.tags as string[]).indexOf('raises-exception') !== -1
) {
stopOnError = false;
}
let content: KernelMessage.IExecuteRequest = {
code,
stop_on_error: stopOnError
};
if (!session.kernel) {
return Promise.reject('Session has no kernel.');
}
let future = session.kernel.requestExecute(content, false, metadata);
output.future = future;
return future.done as Promise<KernelMessage.IExecuteReplyMsg>;
}
/**
* An output area widget content factory.
*
* The content factory is used to create children in a way
* that can be customized.
*/
export interface IContentFactory {
/**
* Create an output prompt.
*/
createOutputPrompt(): IOutputPrompt;
/**
* Create an stdin widget.
*/
createStdin(options: Stdin.IOptions): IStdin;
}
/**
* The default implementation of `IContentFactory`.
*/
export class ContentFactory implements IContentFactory {
/**
* Create the output prompt for the widget.
*/
createOutputPrompt(): IOutputPrompt {
return new OutputPrompt();
}
/**
* Create an stdin widget.
*/
createStdin(options: Stdin.IOptions): IStdin {
return new Stdin(options);
}
}
/**
* The default `ContentFactory` instance.
*/
export const defaultContentFactory = new ContentFactory();
}
/******************************************************************************
* OutputPrompt
******************************************************************************/
/**
* The interface for an output prompt.
*/
export interface IOutputPrompt extends Widget {
/**
* The execution count for the prompt.
*/
executionCount: nbformat.ExecutionCount;
}
/**
* The default output prompt implementation
*/
export class OutputPrompt extends Widget implements IOutputPrompt {
/*
* Create an output prompt widget.
*/
constructor() {
super();
this.addClass(OUTPUT_PROMPT_CLASS);
}
/**
* The execution count for the prompt.
*/
get executionCount(): nbformat.ExecutionCount {
return this._executionCount;
}
set executionCount(value: nbformat.ExecutionCount) {
this._executionCount = value;
if (value === null) {
this.node.textContent = '';
} else {
this.node.textContent = `[${value}]:`;
}
}
private _executionCount: nbformat.ExecutionCount = null;
}
/******************************************************************************
* Stdin
******************************************************************************/
/**
* The stdin interface
*/
export interface IStdin extends Widget {
/**
* The stdin value.
*/
readonly value: Promise<string>;
}
/**
* The default stdin widget.
*/
export class Stdin extends Widget implements IStdin {
/**
* Construct a new input widget.
*/
constructor(options: Stdin.IOptions) {
super({
node: Private.createInputWidgetNode(options.prompt, options.password)
});
this.addClass(STDIN_CLASS);
this._input = this.node.getElementsByTagName('input')[0];
this._input.focus();
this._future = options.future;
this._value = options.prompt + ' ';
}
/**
* The value of the widget.
*/
get value() {
return this._promise.promise.then(() => this._value);
}
/**
* Handle the DOM events for the widget.
*
* @param event - The DOM event sent to the widget.
*
* #### Notes
* This method implements the DOM `EventListener` interface and is
* called in response to events on the dock panel's node. It should
* not be called directly by user code.
*/
handleEvent(event: Event): void {
let input = this._input;
if (event.type === 'keydown') {
if ((event as KeyboardEvent).keyCode === 13) {
// Enter
this._future.sendInputReply({
value: input.value
});
if (input.type === 'password') {
this._value += Array(input.value.length + 1).join('·');
} else {
this._value += input.value;
}
this._promise.resolve(void 0);
}
}
}
/**
* Handle `after-attach` messages sent to the widget.
*/
protected onAfterAttach(msg: Message): void {
this._input.addEventListener('keydown', this);
this.update();
}
/**
* Handle `update-request` messages sent to the widget.
*/
protected onUpdateRequest(msg: Message): void {
this._input.focus();
}
/**
* Handle `before-detach` messages sent to the widget.
*/
protected onBeforeDetach(msg: Message): void {
this._input.removeEventListener('keydown', this);
}
private _future: Kernel.IFuture = null;
private _input: HTMLInputElement = null;
private _value: string;
private _promise = new PromiseDelegate<void>();
}
export namespace Stdin {
/**
* The options to create a stdin widget.
*/
export interface IOptions {
/**
* The prompt text.
*/
prompt: string;
/**
* Whether the input is a password.
*/
password: boolean;
/**
* The kernel future associated with the request.
*/
future: Kernel.IFuture;
}
}
/******************************************************************************
* Private namespace
******************************************************************************/
/**
* A namespace for private data.
*/
namespace Private {
/**
* Create the node for an InputWidget.
*/
export function createInputWidgetNode(
prompt: string,
password: boolean
): HTMLElement {
let node = document.createElement('div');
let promptNode = document.createElement('pre');
promptNode.className = STDIN_PROMPT_CLASS;
promptNode.textContent = prompt;
let input = document.createElement('input');
input.className = STDIN_INPUT_CLASS;
if (password) {
input.type = 'password';
}
node.appendChild(promptNode);
promptNode.appendChild(input);
return node;
}
/**
* A renderer for IFrame data.
*/
export class IsolatedRenderer extends Widget
implements IRenderMime.IRenderer {
/**
* Create an isolated renderer.
*/
constructor(wrapped: IRenderMime.IRenderer) {
super({ node: document.createElement('iframe') });
this.addClass('jp-mod-isolated');
this._wrapped = wrapped;
// Once the iframe is loaded, the subarea is dynamically inserted
let iframe = this.node as HTMLIFrameElement;
iframe.frameBorder = '0';
iframe.scrolling = 'auto';
iframe.addEventListener('load', () => {
// Workaround needed by Firefox, to properly render svg inside
// iframes, see https://stackoverflow.com/questions/10177190/
// svg-dynamically-added-to-iframe-does-not-render-correctly
iframe.contentDocument.open();
// Insert the subarea into the iframe
// We must directly write the html. At this point, subarea doesn't
// contain any user content.
iframe.contentDocument.write(this._wrapped.node.innerHTML);
iframe.contentDocument.close();
let body = iframe.contentDocument.body;
// Adjust the iframe height automatically
iframe.style.height = body.scrollHeight + 'px';
});
}
/**
* Render a mime model.
*
* @param model - The mime model to render.
*
* @returns A promise which resolves when rendering is complete.
*
* #### Notes
* This method may be called multiple times during the lifetime
* of the widget to update it if and when new data is available.
*/
renderModel(model: IRenderMime.IMimeModel): Promise<void> {
return this._wrapped.renderModel(model).then(() => {
let win = (this.node as HTMLIFrameElement).contentWindow;
if (win) {
win.location.reload();
}
});
}
private _wrapped: IRenderMime.IRenderer;
}
}