-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
widget.ts
1059 lines (939 loc) · 28.4 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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import ResizeObserver from 'resize-observer-polyfill';
import {
JSONObject,
PromiseDelegate,
ReadonlyJSONObject,
ReadonlyPartialJSONObject
} from '@lumino/coreutils';
import { Message } from '@lumino/messaging';
import { AttachedProperty } from '@lumino/properties';
import { Signal } from '@lumino/signaling';
import { Panel, PanelLayout } from '@lumino/widgets';
import { Widget } from '@lumino/widgets';
import { ISessionContext } from '@jupyterlab/apputils';
import * as nbformat from '@jupyterlab/nbformat';
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();
const model = (this.model = options.model);
this.addClass(OUTPUT_AREA_CLASS);
this.rendermime = options.rendermime;
this.contentFactory =
options.contentFactory || OutputArea.defaultContentFactory;
this.layout = new PanelLayout();
this.trimmedOutputModels = new Array<IOutputModel>();
this.maxNumberOutputs = options.maxNumberOutputs || 0;
this.headTailNumberOutputs = Math.round(this.maxNumberOutputs / 2);
this.headEndIndex = this.headTailNumberOutputs;
for (let i = 0; i < model.length; i++) {
const 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;
/**
* The hidden output models.
*/
private trimmedOutputModels: IOutputModel[];
/*
* The maximum outputs to show in the trimmed
* output area.
*/
private maxNumberOutputs: number;
/*
* The maximum outputs to show in the trimmed
* output head and tail areas.
*/
private headTailNumberOutputs: number;
/*
* The index for the end of the head in case of trim mode.
*/
private headEndIndex: number;
/**
* 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.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
> {
return this._future;
}
set future(
value: Kernel.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
>
) {
// 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':
if (this.widgets.length) {
// all items removed from model
if (this.model.length === 0) {
this._clear();
} else {
// range of items removed from model
// remove widgets corresponding to removed model items
const startIndex = args.oldIndex;
for (
let i = 0;
i < args.oldValues.length && startIndex < this.widgets.length;
++i
) {
const widget = this.widgets[startIndex];
widget.parent = null;
widget.dispose();
}
// apply item offset to target model item indices in _displayIdMap
this._moveDisplayIdIndices(startIndex, args.oldValues.length);
// prevent jitter caused by immediate height change
this._preventHeightChangeJitter();
}
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;
}
}
/**
* Update indices in _displayIdMap in response to element remove from model items
* *
* @param startIndex - The index of first element removed
*
* @param count - The number of elements removed from model items
*
*/
private _moveDisplayIdIndices(startIndex: number, count: number) {
this._displayIdMap.forEach((indices: number[]) => {
const rangeEnd = startIndex + count;
const numIndices = indices.length;
// reverse loop in order to prevent removing element affecting the index
for (let i = numIndices - 1; i >= 0; --i) {
const index = indices[i];
// remove model item indices in removed range
if (index >= startIndex && index < rangeEnd) {
indices.splice(i, 1);
} else if (index >= rangeEnd) {
// move model item indices that were larger than range end
indices[i] -= count;
}
}
});
}
/**
* Follow changes on the output model state.
*/
protected onStateChanged(sender: IOutputAreaModel): void {
this.trimmedOutputModels = new Array<IOutputModel>();
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.
const length = this.widgets.length;
for (let i = 0; i < length; i++) {
const widget = this.widgets[0];
widget.parent = null;
widget.dispose();
}
// Clear the display id map.
this._displayIdMap.clear();
// prevent jitter caused by immediate height change
this._preventHeightChangeJitter();
}
private _preventHeightChangeJitter() {
// 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.
const rect = this.node.getBoundingClientRect();
this.node.style.minHeight = `${rect.height}px`;
if (this._minHeightTimeout) {
window.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.IShellFuture
): void {
// Add an output widget to the end.
const factory = this.contentFactory;
const stdinPrompt = msg.content.prompt;
const password = msg.content.password;
const panel = new Panel();
panel.addClass(OUTPUT_AREA_ITEM_CLASS);
panel.addClass(OUTPUT_AREA_STDIN_ITEM_CLASS);
const prompt = factory.createOutputPrompt();
prompt.addClass(OUTPUT_AREA_PROMPT_CLASS);
panel.addWidget(prompt);
const input = factory.createStdin({
prompt: stdinPrompt,
password,
future
});
input.addClass(OUTPUT_AREA_OUTPUT_CLASS);
panel.addWidget(input);
const 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 {
const layout = this.layout as PanelLayout;
const panel = layout.widgets[index] as Panel;
const renderer = (panel.widgets
? panel.widgets[1]
: panel) as IRenderMime.IRenderer;
// Check whether it is safe to reuse renderer:
// - Preferred mime type has not changed
// - Isolation has not changed
const mimeType = this.rendermime.preferredMimeType(
model.data,
model.trusted ? 'any' : 'ensure'
);
if (
renderer.renderModel &&
Private.currentPreferredMimetype.get(renderer) === mimeType &&
OutputArea.isIsolated(mimeType, model.metadata) ===
renderer instanceof Private.IsolatedRenderer
) {
void renderer.renderModel(model);
} else {
layout.widgets[index].dispose();
this._insertOutput(index, model);
}
}
/**
* Render and insert a single output into the layout.
*
* @param index - The index of the output to be inserted.
* @param model - The model of the output to be inserted.
*/
private _insertOutput(index: number, model: IOutputModel): void {
if (index === 0) {
this.trimmedOutputModels = new Array<IOutputModel>();
}
if (index === this.maxNumberOutputs && this.maxNumberOutputs !== 0) {
// TODO Improve style of the display message.
const separatorModel = this.model.contentFactory.createOutputModel({
value: {
output_type: 'display_data',
data: {
'text/html': `
<a style="margin: 10px; text-decoration: none;">
<pre>Output of this cell has been trimmed on the initial display.</pre>
<pre>Displaying the first ${this.maxNumberOutputs} top and last bottom outputs.</pre>
<pre>Click on this message to get the complete output.</pre>
</a>
`
}
}
});
const onClick = () =>
this._showTrimmedOutputs(this.headTailNumberOutputs);
const separator = this.createOutputItem(separatorModel);
separator!.node.addEventListener('click', onClick);
const layout = this.layout as PanelLayout;
layout.insertWidget(this.headEndIndex, separator!);
}
const output = this._createOutput(model);
const layout = this.layout as PanelLayout;
if (index < this.maxNumberOutputs || this.maxNumberOutputs === 0) {
layout.insertWidget(index, output);
} else if (index >= this.maxNumberOutputs) {
layout.removeWidgetAt(this.headTailNumberOutputs + 1);
layout.insertWidget(index, output);
}
if (index >= this.headTailNumberOutputs && this.maxNumberOutputs !== 0) {
this.trimmedOutputModels.push(model);
}
}
private _createOutput(model: IOutputModel): Widget {
let output = this.createOutputItem(model);
if (output) {
output.toggleClass(EXECUTE_CLASS, model.executionCount !== null);
} else {
output = new Widget();
}
return output;
}
/**
* Remove the information message related to the trimmed output
* and show all previously trimmed outputs.
*/
private _showTrimmedOutputs(headTailNumberOutputs: number) {
const layout = this.layout as PanelLayout;
layout.removeWidgetAt(headTailNumberOutputs);
for (
let i = 0;
i < this.trimmedOutputModels.length - this.headTailNumberOutputs;
i++
) {
const output = this._createOutput(this.trimmedOutputModels[i]);
layout.insertWidget(headTailNumberOutputs + i, output);
}
}
/**
* Create an output item with a prompt and actual output
*
* @returns a rendered widget, or null if we cannot render
* #### Notes
*/
protected createOutputItem(model: IOutputModel): Widget | null {
const output = this.createRenderedMimetype(model);
if (!output) {
return null;
}
const panel = new Panel();
panel.addClass(OUTPUT_AREA_ITEM_CLASS);
const prompt = this.contentFactory.createOutputPrompt();
prompt.executionCount = model.executionCount;
prompt.addClass(OUTPUT_AREA_PROMPT_CLASS);
panel.addWidget(prompt);
output.addClass(OUTPUT_AREA_OUTPUT_CLASS);
panel.addWidget(output);
return panel;
}
/**
* Render a mimetype
*/
protected createRenderedMimetype(model: IOutputModel): Widget | null {
const mimeType = this.rendermime.preferredMimeType(
model.data,
model.trusted ? 'any' : 'ensure'
);
if (!mimeType) {
return null;
}
let output = this.rendermime.createRenderer(mimeType);
const isolated = OutputArea.isIsolated(mimeType, model.metadata);
if (isolated === true) {
output = new Private.IsolatedRenderer(output);
}
Private.currentPreferredMimetype.set(output, mimeType);
output.renderModel(model).catch(error => {
// Manually append error message to output
const pre = document.createElement('pre');
pre.textContent = `Javascript Error: ${error.message}`;
output.node.appendChild(pre);
// Remove mime-type-specific CSS classes
output.node.className = 'lm-Widget jp-RenderedText';
output.node.setAttribute(
'data-mime-type',
'application/vnd.jupyter.stderr'
);
});
return output;
}
/**
* Handle an iopub message.
*/
private _onIOPub = (msg: KernelMessage.IIOPubMessage) => {
const model = this.model;
const msgType = msg.header.msg_type;
let output: nbformat.IOutput;
const transient = ((msg.content as any).transient || {}) as JSONObject;
const displayId = transient['display_id'] as string;
let targets: number[] | undefined;
switch (msgType) {
case 'execute_result':
case 'display_data':
case 'stream':
case 'error':
output = { ...msg.content, output_type: msgType };
model.add(output);
break;
case 'clear_output': {
const wait = (msg as KernelMessage.IClearOutputMsg).content.wait;
model.clear(wait);
break;
}
case 'update_display_data':
output = { ...msg.content, output_type: 'display_data' };
targets = this._displayIdMap.get(displayId);
if (targets) {
for (const 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.
const model = this.model;
const content = msg.content;
if (content.status !== 'ok') {
return;
}
const payload = content && content.payload;
if (!payload || !payload.length) {
return;
}
const pages = payload.filter((i: any) => (i as any).source === 'page');
if (!pages.length) {
return;
}
const page = JSON.parse(JSON.stringify(pages[0]));
const output: nbformat.IOutput = {
output_type: 'display_data',
data: (page as any).data as nbformat.IMimeBundle,
metadata: {}
};
model.add(output);
};
private _minHeightTimeout: number | null = null;
private _future: Kernel.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
>;
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.IShellFuture
): void {
return;
}
/**
* Create an output item without a prompt, just the output widgets
*/
protected createOutputItem(model: IOutputModel): Widget | null {
const output = this.createRenderedMimetype(model);
if (output) {
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;
/**
* The maximum number of output items to display on top and bottom of cell output.
*/
maxNumberOutputs?: number;
}
/**
* Execute code on an output area.
*/
export async function execute(
code: string,
output: OutputArea,
sessionContext: ISessionContext,
metadata?: JSONObject
): Promise<KernelMessage.IExecuteReplyMsg | undefined> {
// Override the default for `stop_on_error`.
let stopOnError = true;
if (
metadata &&
Array.isArray(metadata.tags) &&
metadata.tags.indexOf('raises-exception') !== -1
) {
stopOnError = false;
}
const content: KernelMessage.IExecuteRequestMsg['content'] = {
code,
stop_on_error: stopOnError
};
const kernel = sessionContext.session?.kernel;
if (!kernel) {
throw new Error('Session has no kernel.');
}
const future = kernel.requestExecute(content, false, metadata);
output.future = future;
return future.done;
}
export function isIsolated(
mimeType: string,
metadata: ReadonlyPartialJSONObject
): boolean {
const mimeMd = metadata[mimeType] as ReadonlyJSONObject | undefined;
// mime-specific higher priority
if (mimeMd && mimeMd['isolated'] !== undefined) {
return !!mimeMd['isolated'];
} else {
// fallback on global
return !!metadata['isolated'];
}
}
/**
* 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 {
const input = this._input;
if (event.type === 'keydown') {
if ((event as KeyboardEvent).keyCode === 13) {
// Enter
this._future.sendInputReply({
status: 'ok',
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.IShellFuture;
private _input: HTMLInputElement;
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.IShellFuture;
}
}
/** ****************************************************************************
* Private namespace
******************************************************************************/
/**
* A namespace for private data.
*/
namespace Private {
/**
* Create the node for an InputWidget.
*/
export function createInputWidgetNode(
prompt: string,
password: boolean
): HTMLElement {
const node = document.createElement('div');
const promptNode = document.createElement('pre');
promptNode.className = STDIN_PROMPT_CLASS;
promptNode.textContent = prompt;
const 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;