@jupyterlab/cells 4.0.0-alpha.9 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/widget.ts ADDED
@@ -0,0 +1,2363 @@
1
+ /* -----------------------------------------------------------------------------
2
+ | Copyright (c) Jupyter Development Team.
3
+ | Distributed under the terms of the Modified BSD License.
4
+ |----------------------------------------------------------------------------*/
5
+
6
+ import { Extension } from '@codemirror/state';
7
+
8
+ import { EditorView } from '@codemirror/view';
9
+
10
+ import { AttachmentsResolver } from '@jupyterlab/attachments';
11
+
12
+ import { ISessionContext } from '@jupyterlab/apputils';
13
+
14
+ import { ActivityMonitor, IChangedArgs, URLExt } from '@jupyterlab/coreutils';
15
+
16
+ import { CodeEditor, CodeEditorWrapper } from '@jupyterlab/codeeditor';
17
+
18
+ import { DirListing } from '@jupyterlab/filebrowser';
19
+
20
+ import * as nbformat from '@jupyterlab/nbformat';
21
+
22
+ import {
23
+ IOutputPrompt,
24
+ IStdin,
25
+ OutputArea,
26
+ OutputPrompt,
27
+ SimplifiedOutputArea,
28
+ Stdin
29
+ } from '@jupyterlab/outputarea';
30
+
31
+ import {
32
+ imageRendererFactory,
33
+ IRenderMime,
34
+ IRenderMimeRegistry,
35
+ MimeModel
36
+ } from '@jupyterlab/rendermime';
37
+
38
+ import { Kernel, KernelMessage } from '@jupyterlab/services';
39
+
40
+ import { IMapChange } from '@jupyter/ydoc';
41
+
42
+ import { TableOfContentsUtils } from '@jupyterlab/toc';
43
+
44
+ import { ITranslator, nullTranslator } from '@jupyterlab/translation';
45
+
46
+ import { addIcon } from '@jupyterlab/ui-components';
47
+
48
+ import { JSONObject, PromiseDelegate, UUID } from '@lumino/coreutils';
49
+
50
+ import { some } from '@lumino/algorithm';
51
+
52
+ import { Drag } from '@lumino/dragdrop';
53
+
54
+ import { Message, MessageLoop } from '@lumino/messaging';
55
+
56
+ import { Debouncer } from '@lumino/polling';
57
+
58
+ import { ISignal, Signal } from '@lumino/signaling';
59
+
60
+ import { Panel, PanelLayout, Widget } from '@lumino/widgets';
61
+
62
+ import { InputCollapser, OutputCollapser } from './collapser';
63
+
64
+ import {
65
+ CellFooter,
66
+ CellHeader,
67
+ ICellFooter,
68
+ ICellHeader
69
+ } from './headerfooter';
70
+
71
+ import { IInputPrompt, InputArea, InputPrompt } from './inputarea';
72
+
73
+ import {
74
+ CellModel,
75
+ IAttachmentsCellModel,
76
+ ICellModel,
77
+ ICodeCellModel,
78
+ IMarkdownCellModel,
79
+ IRawCellModel
80
+ } from './model';
81
+
82
+ import { InputPlaceholder, OutputPlaceholder } from './placeholder';
83
+
84
+ import { ResizeHandle } from './resizeHandle';
85
+
86
+ /**
87
+ * The CSS class added to cell widgets.
88
+ */
89
+ const CELL_CLASS = 'jp-Cell';
90
+
91
+ /**
92
+ * The CSS class added to the cell header.
93
+ */
94
+ const CELL_HEADER_CLASS = 'jp-Cell-header';
95
+
96
+ /**
97
+ * The CSS class added to the cell footer.
98
+ */
99
+ const CELL_FOOTER_CLASS = 'jp-Cell-footer';
100
+
101
+ /**
102
+ * The CSS class added to the cell input wrapper.
103
+ */
104
+ const CELL_INPUT_WRAPPER_CLASS = 'jp-Cell-inputWrapper';
105
+
106
+ /**
107
+ * The CSS class added to the cell output wrapper.
108
+ */
109
+ const CELL_OUTPUT_WRAPPER_CLASS = 'jp-Cell-outputWrapper';
110
+
111
+ /**
112
+ * The CSS class added to the cell input area.
113
+ */
114
+ const CELL_INPUT_AREA_CLASS = 'jp-Cell-inputArea';
115
+
116
+ /**
117
+ * The CSS class added to the cell output area.
118
+ */
119
+ const CELL_OUTPUT_AREA_CLASS = 'jp-Cell-outputArea';
120
+
121
+ /**
122
+ * The CSS class added to the cell input collapser.
123
+ */
124
+ const CELL_INPUT_COLLAPSER_CLASS = 'jp-Cell-inputCollapser';
125
+
126
+ /**
127
+ * The CSS class added to the cell output collapser.
128
+ */
129
+ const CELL_OUTPUT_COLLAPSER_CLASS = 'jp-Cell-outputCollapser';
130
+
131
+ /**
132
+ * The class name added to the cell when dirty.
133
+ */
134
+ const DIRTY_CLASS = 'jp-mod-dirty';
135
+
136
+ /**
137
+ * The class name added to code cells.
138
+ */
139
+ const CODE_CELL_CLASS = 'jp-CodeCell';
140
+
141
+ /**
142
+ * The class name added to markdown cells.
143
+ */
144
+ const MARKDOWN_CELL_CLASS = 'jp-MarkdownCell';
145
+
146
+ /**
147
+ * The class name added to rendered markdown output widgets.
148
+ */
149
+ const MARKDOWN_OUTPUT_CLASS = 'jp-MarkdownOutput';
150
+
151
+ const MARKDOWN_HEADING_COLLAPSED = 'jp-MarkdownHeadingCollapsed';
152
+
153
+ const HEADING_COLLAPSER_CLASS = 'jp-collapseHeadingButton';
154
+
155
+ const SHOW_HIDDEN_CELLS_CLASS = 'jp-showHiddenCellsButton';
156
+
157
+ /**
158
+ * The class name added to raw cells.
159
+ */
160
+ const RAW_CELL_CLASS = 'jp-RawCell';
161
+
162
+ /**
163
+ * The class name added to a rendered input area.
164
+ */
165
+ const RENDERED_CLASS = 'jp-mod-rendered';
166
+
167
+ const NO_OUTPUTS_CLASS = 'jp-mod-noOutputs';
168
+
169
+ /**
170
+ * The text applied to an empty markdown cell.
171
+ */
172
+ const DEFAULT_MARKDOWN_TEXT = 'Type Markdown and LaTeX: $ α^2 $';
173
+
174
+ /**
175
+ * The timeout to wait for change activity to have ceased before rendering.
176
+ */
177
+ const RENDER_TIMEOUT = 1000;
178
+
179
+ /**
180
+ * The mime type for a rich contents drag object.
181
+ */
182
+ const CONTENTS_MIME_RICH = 'application/x-jupyter-icontentsrich';
183
+
184
+ /** ****************************************************************************
185
+ * Cell
186
+ ******************************************************************************/
187
+
188
+ /**
189
+ * A base cell widget.
190
+ */
191
+ export class Cell<T extends ICellModel = ICellModel> extends Widget {
192
+ /**
193
+ * Construct a new base cell widget.
194
+ */
195
+ constructor(options: Cell.IOptions<T>) {
196
+ super();
197
+ this.addClass(CELL_CLASS);
198
+ const model = (this._model = options.model);
199
+
200
+ this.contentFactory = options.contentFactory;
201
+ this.layout = options.layout ?? new PanelLayout();
202
+ // Set up translator for aria labels
203
+ this.translator = options.translator ?? nullTranslator;
204
+
205
+ this._editorConfig = options.editorConfig ?? {};
206
+ this._placeholder = true;
207
+ this._inViewport = false;
208
+ this.placeholder = options.placeholder ?? true;
209
+
210
+ model.metadataChanged.connect(this.onMetadataChanged, this);
211
+ }
212
+
213
+ /**
214
+ * Initialize view state from model.
215
+ *
216
+ * #### Notes
217
+ * Should be called after construction. For convenience, returns this, so it
218
+ * can be chained in the construction, like `new Foo().initializeState();`
219
+ */
220
+ initializeState(): this {
221
+ this.loadCollapseState();
222
+ this.loadEditableState();
223
+ return this;
224
+ }
225
+
226
+ /**
227
+ * The content factory used by the widget.
228
+ */
229
+ readonly contentFactory: Cell.IContentFactory;
230
+
231
+ /**
232
+ * Signal to indicate that widget has changed visibly (in size, in type, etc)
233
+ */
234
+ get displayChanged(): ISignal<this, void> {
235
+ return this._displayChanged;
236
+ }
237
+
238
+ /**
239
+ * Whether the cell is in viewport or not.
240
+ */
241
+ get inViewport(): boolean {
242
+ return this._inViewport;
243
+ }
244
+ set inViewport(v: boolean) {
245
+ if (this._inViewport !== v) {
246
+ this._inViewport = v;
247
+ this._inViewportChanged.emit(this._inViewport);
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Will emit true just after the node is attached to the DOM
253
+ * Will emit false just before the node is detached of the DOM
254
+ */
255
+ get inViewportChanged(): ISignal<Cell, boolean> {
256
+ return this._inViewportChanged;
257
+ }
258
+
259
+ /**
260
+ * Whether the cell is a placeholder not yet fully rendered or not.
261
+ */
262
+ protected get placeholder(): boolean {
263
+ return this._placeholder;
264
+ }
265
+ protected set placeholder(v: boolean) {
266
+ if (this._placeholder !== v && v === false) {
267
+ this.initializeDOM();
268
+ this._placeholder = v;
269
+ this._ready.resolve();
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Get the prompt node used by the cell.
275
+ */
276
+ get promptNode(): HTMLElement | null {
277
+ if (this.placeholder) {
278
+ return null;
279
+ }
280
+
281
+ if (!this._inputHidden) {
282
+ return this._input!.promptNode;
283
+ } else {
284
+ return (this._inputPlaceholder!.node as HTMLElement)
285
+ .firstElementChild as HTMLElement;
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Get the CodeEditorWrapper used by the cell.
291
+ */
292
+ get editorWidget(): CodeEditorWrapper | null {
293
+ return this._input?.editorWidget ?? null;
294
+ }
295
+
296
+ /**
297
+ * Get the CodeEditor used by the cell.
298
+ */
299
+ get editor(): CodeEditor.IEditor | null {
300
+ return this._input?.editor ?? null;
301
+ }
302
+
303
+ /**
304
+ * Editor configuration
305
+ */
306
+ get editorConfig(): Record<string, any> {
307
+ return this._editorConfig;
308
+ }
309
+
310
+ /**
311
+ * Cell headings
312
+ */
313
+ get headings(): Cell.IHeading[] {
314
+ return new Array<Cell.IHeading>();
315
+ }
316
+
317
+ /**
318
+ * Get the model used by the cell.
319
+ */
320
+ get model(): T {
321
+ return this._model;
322
+ }
323
+
324
+ /**
325
+ * Get the input area for the cell.
326
+ */
327
+ get inputArea(): InputArea | null {
328
+ return this._input;
329
+ }
330
+
331
+ /**
332
+ * The read only state of the cell.
333
+ */
334
+ get readOnly(): boolean {
335
+ return this._readOnly;
336
+ }
337
+ set readOnly(value: boolean) {
338
+ if (value === this._readOnly) {
339
+ return;
340
+ }
341
+ this._readOnly = value;
342
+ if (this.syncEditable) {
343
+ this.saveEditableState();
344
+ }
345
+ this.update();
346
+ }
347
+
348
+ /**
349
+ * Whether the cell is a placeholder that defer rendering
350
+ *
351
+ * #### Notes
352
+ * You can wait for the promise `Cell.ready` to wait for the
353
+ * cell to be rendered.
354
+ */
355
+ isPlaceholder(): boolean {
356
+ return this.placeholder;
357
+ }
358
+
359
+ /**
360
+ * Save view editable state to model
361
+ */
362
+ saveEditableState(): void {
363
+ const { sharedModel } = this.model;
364
+ const current = sharedModel.getMetadata('editable') as unknown as boolean;
365
+
366
+ if (
367
+ (this.readOnly && current === false) ||
368
+ (!this.readOnly && current === undefined)
369
+ ) {
370
+ return;
371
+ }
372
+ if (this.readOnly) {
373
+ sharedModel.setMetadata('editable', false);
374
+ } else {
375
+ sharedModel.deleteMetadata('editable');
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Load view editable state from model.
381
+ */
382
+ loadEditableState(): void {
383
+ this.readOnly =
384
+ (this.model.sharedModel.getMetadata('editable') as unknown as boolean) ===
385
+ false;
386
+ }
387
+
388
+ /**
389
+ * A promise that resolves when the widget renders for the first time.
390
+ */
391
+ get ready(): Promise<void> {
392
+ return this._ready.promise;
393
+ }
394
+
395
+ /**
396
+ * Set the prompt for the widget.
397
+ */
398
+ setPrompt(value: string): void {
399
+ this.prompt = value;
400
+ this._input?.setPrompt(value);
401
+ }
402
+
403
+ /**
404
+ * The view state of input being hidden.
405
+ */
406
+ get inputHidden(): boolean {
407
+ return this._inputHidden;
408
+ }
409
+ set inputHidden(value: boolean) {
410
+ if (this._inputHidden === value) {
411
+ return;
412
+ }
413
+ if (!this.placeholder) {
414
+ const layout = this._inputWrapper!.layout as PanelLayout;
415
+ if (value) {
416
+ this._input!.parent = null;
417
+ if (this._inputPlaceholder) {
418
+ this._inputPlaceholder.text = this.model.sharedModel
419
+ .getSource()
420
+ .split('\n')?.[0];
421
+ }
422
+ layout.addWidget(this._inputPlaceholder!);
423
+ } else {
424
+ this._inputPlaceholder!.parent = null;
425
+ layout.addWidget(this._input!);
426
+ }
427
+ }
428
+ this._inputHidden = value;
429
+ if (this.syncCollapse) {
430
+ this.saveCollapseState();
431
+ }
432
+ this.handleInputHidden(value);
433
+ }
434
+
435
+ /**
436
+ * Save view collapse state to model
437
+ */
438
+ saveCollapseState(): void {
439
+ const jupyter = { ...(this.model.getMetadata('jupyter') as any) };
440
+
441
+ if (
442
+ (this.inputHidden && jupyter.source_hidden === true) ||
443
+ (!this.inputHidden && jupyter.source_hidden === undefined)
444
+ ) {
445
+ return;
446
+ }
447
+
448
+ if (this.inputHidden) {
449
+ jupyter.source_hidden = true;
450
+ } else {
451
+ delete jupyter.source_hidden;
452
+ }
453
+ if (Object.keys(jupyter).length === 0) {
454
+ this.model.deleteMetadata('jupyter');
455
+ } else {
456
+ this.model.setMetadata('jupyter', jupyter);
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Revert view collapse state from model.
462
+ */
463
+ loadCollapseState(): void {
464
+ const jupyter = (this.model.getMetadata('jupyter') as any) ?? {};
465
+ this.inputHidden = !!jupyter.source_hidden;
466
+ }
467
+
468
+ /**
469
+ * Handle the input being hidden.
470
+ *
471
+ * #### Notes
472
+ * This is called by the `inputHidden` setter so that subclasses
473
+ * can perform actions upon the input being hidden without accessing
474
+ * private state.
475
+ */
476
+ protected handleInputHidden(value: boolean): void {
477
+ return;
478
+ }
479
+
480
+ /**
481
+ * Whether to sync the collapse state to the cell model.
482
+ */
483
+ get syncCollapse(): boolean {
484
+ return this._syncCollapse;
485
+ }
486
+ set syncCollapse(value: boolean) {
487
+ if (this._syncCollapse === value) {
488
+ return;
489
+ }
490
+ this._syncCollapse = value;
491
+ if (value) {
492
+ this.loadCollapseState();
493
+ }
494
+ }
495
+
496
+ /**
497
+ * Whether to sync the editable state to the cell model.
498
+ */
499
+ get syncEditable(): boolean {
500
+ return this._syncEditable;
501
+ }
502
+ set syncEditable(value: boolean) {
503
+ if (this._syncEditable === value) {
504
+ return;
505
+ }
506
+ this._syncEditable = value;
507
+ if (value) {
508
+ this.loadEditableState();
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Clone the cell, using the same model.
514
+ */
515
+ clone(): Cell<T> {
516
+ const constructor = this.constructor as typeof Cell;
517
+ return new constructor({
518
+ model: this.model,
519
+ contentFactory: this.contentFactory,
520
+ placeholder: false,
521
+ translator: this.translator
522
+ });
523
+ }
524
+
525
+ /**
526
+ * Dispose of the resources held by the widget.
527
+ */
528
+ dispose(): void {
529
+ // Do nothing if already disposed.
530
+ if (this.isDisposed) {
531
+ return;
532
+ }
533
+ this._resizeDebouncer.dispose();
534
+ this._input = null!;
535
+ this._model = null!;
536
+ this._inputWrapper = null!;
537
+ this._inputPlaceholder = null!;
538
+ super.dispose();
539
+ }
540
+
541
+ /**
542
+ * Update the editor configuration with the partial provided dictionary.
543
+ *
544
+ * @param v Partial editor configuration
545
+ */
546
+ updateEditorConfig(v: Record<string, any>): void {
547
+ this._editorConfig = { ...this._editorConfig, ...v };
548
+ if (this.editor) {
549
+ this.editor.setOptions(this._editorConfig);
550
+ }
551
+ }
552
+
553
+ /**
554
+ * Create children widgets.
555
+ */
556
+ protected initializeDOM(): void {
557
+ if (!this.placeholder) {
558
+ return;
559
+ }
560
+
561
+ const contentFactory = this.contentFactory;
562
+ const model = this._model;
563
+
564
+ // Header
565
+ const header = contentFactory.createCellHeader();
566
+ header.addClass(CELL_HEADER_CLASS);
567
+ (this.layout as PanelLayout).addWidget(header);
568
+
569
+ // Input
570
+ const inputWrapper = (this._inputWrapper = new Panel());
571
+ inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
572
+ const inputCollapser = new InputCollapser();
573
+ inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
574
+ const input = (this._input = new InputArea({
575
+ model,
576
+ contentFactory,
577
+ editorOptions: this.getEditorOptions()
578
+ }));
579
+ input.addClass(CELL_INPUT_AREA_CLASS);
580
+ inputWrapper.addWidget(inputCollapser);
581
+ inputWrapper.addWidget(input);
582
+ (this.layout as PanelLayout).addWidget(inputWrapper);
583
+
584
+ this._inputPlaceholder = new InputPlaceholder({
585
+ callback: () => {
586
+ this.inputHidden = !this.inputHidden;
587
+ },
588
+ text: input.model.sharedModel.getSource().split('\n')[0],
589
+ translator: this.translator
590
+ });
591
+
592
+ input.model.contentChanged.connect((sender, args) => {
593
+ if (this._inputPlaceholder && this.inputHidden) {
594
+ this._inputPlaceholder.text = sender.sharedModel
595
+ .getSource()
596
+ .split('\n')?.[0];
597
+ }
598
+ });
599
+
600
+ if (this.inputHidden) {
601
+ input.parent = null;
602
+ (inputWrapper.layout as PanelLayout).addWidget(this._inputPlaceholder!);
603
+ }
604
+
605
+ // Footer
606
+ const footer = this.contentFactory.createCellFooter();
607
+ footer.addClass(CELL_FOOTER_CLASS);
608
+ (this.layout as PanelLayout).addWidget(footer);
609
+ }
610
+
611
+ /**
612
+ * Get the editor options at initialization.
613
+ *
614
+ * @returns Editor options
615
+ */
616
+ protected getEditorOptions(): InputArea.IOptions['editorOptions'] {
617
+ return { config: this.editorConfig };
618
+ }
619
+
620
+ /**
621
+ * Handle `before-attach` messages.
622
+ */
623
+ protected onBeforeAttach(msg: Message): void {
624
+ if (this.placeholder) {
625
+ this.placeholder = false;
626
+ }
627
+ }
628
+
629
+ /**
630
+ * Handle `after-attach` messages.
631
+ */
632
+ protected onAfterAttach(msg: Message): void {
633
+ this.update();
634
+ }
635
+
636
+ /**
637
+ * Handle `'activate-request'` messages.
638
+ */
639
+ protected onActivateRequest(msg: Message): void {
640
+ this.editor?.focus();
641
+ }
642
+
643
+ /**
644
+ * Handle `resize` messages.
645
+ */
646
+ protected onResize(msg: Widget.ResizeMessage): void {
647
+ void this._resizeDebouncer.invoke();
648
+ }
649
+
650
+ /**
651
+ * Handle `update-request` messages.
652
+ */
653
+ protected onUpdateRequest(msg: Message): void {
654
+ if (!this._model) {
655
+ return;
656
+ }
657
+ // Handle read only state.
658
+ if (this.editor?.getOption('readOnly') !== this._readOnly) {
659
+ this.editor?.setOption('readOnly', this._readOnly);
660
+ }
661
+ }
662
+
663
+ protected onContentChanged() {
664
+ if (this.inputHidden && this._inputPlaceholder) {
665
+ this._inputPlaceholder.text = this.model.sharedModel
666
+ .getSource()
667
+ .split('\n')?.[0];
668
+ }
669
+ }
670
+
671
+ /**
672
+ * Handle changes in the metadata.
673
+ */
674
+ protected onMetadataChanged(model: CellModel, args: IMapChange): void {
675
+ switch (args.key) {
676
+ case 'jupyter':
677
+ if (this.syncCollapse) {
678
+ this.loadCollapseState();
679
+ }
680
+ break;
681
+ case 'editable':
682
+ if (this.syncEditable) {
683
+ this.loadEditableState();
684
+ }
685
+ break;
686
+ default:
687
+ break;
688
+ }
689
+ }
690
+
691
+ protected prompt = '';
692
+ protected translator: ITranslator;
693
+ protected _displayChanged = new Signal<this, void>(this);
694
+
695
+ private _editorConfig: Record<string, any> = {};
696
+ private _input: InputArea | null;
697
+ private _inputHidden = false;
698
+ private _inputWrapper: Widget | null;
699
+ private _inputPlaceholder: InputPlaceholder | null;
700
+ private _inViewport: boolean;
701
+ private _inViewportChanged: Signal<Cell, boolean> = new Signal<Cell, boolean>(
702
+ this
703
+ );
704
+ private _model: T;
705
+ private _placeholder: boolean;
706
+ private _readOnly = false;
707
+ private _ready = new PromiseDelegate<void>();
708
+ private _resizeDebouncer = new Debouncer(() => {
709
+ this._displayChanged.emit();
710
+ }, 0);
711
+ private _syncCollapse = false;
712
+ private _syncEditable = false;
713
+ }
714
+
715
+ /**
716
+ * The namespace for the `Cell` class statics.
717
+ */
718
+ export namespace Cell {
719
+ /**
720
+ * An options object for initializing a cell widget.
721
+ */
722
+ export interface IOptions<T extends ICellModel> {
723
+ /**
724
+ * The model used by the cell.
725
+ */
726
+ model: T;
727
+
728
+ /**
729
+ * The factory object for customizable cell children.
730
+ */
731
+ contentFactory: IContentFactory;
732
+
733
+ /**
734
+ * The configuration options for the text editor widget.
735
+ */
736
+ editorConfig?: Record<string, any>;
737
+
738
+ /**
739
+ * Editor extensions to be added.
740
+ */
741
+ editorExtensions?: Extension[];
742
+
743
+ /**
744
+ * Cell widget layout.
745
+ */
746
+ layout?: PanelLayout;
747
+
748
+ /**
749
+ * The maximum number of output items to display in cell output.
750
+ */
751
+ maxNumberOutputs?: number;
752
+
753
+ /**
754
+ * Whether to split stdin line history by kernel session or keep globally accessible.
755
+ */
756
+ inputHistoryScope?: 'global' | 'session';
757
+
758
+ /**
759
+ * Whether this cell is a placeholder for future rendering.
760
+ */
761
+ placeholder?: boolean;
762
+
763
+ /**
764
+ * The application language translator.
765
+ */
766
+ translator?: ITranslator;
767
+ }
768
+
769
+ /**
770
+ * Cell heading
771
+ */
772
+ export interface IHeading {
773
+ /**
774
+ * Heading text.
775
+ */
776
+ text: string;
777
+
778
+ /**
779
+ * HTML heading level.
780
+ */
781
+ level: number;
782
+
783
+ /**
784
+ * Index of the output containing the heading
785
+ */
786
+ outputIndex?: number;
787
+
788
+ /**
789
+ * Type of heading
790
+ */
791
+ type: HeadingType;
792
+ }
793
+
794
+ /**
795
+ * Type of headings
796
+ */
797
+ export enum HeadingType {
798
+ /**
799
+ * Heading from HTML output
800
+ */
801
+ HTML,
802
+ /**
803
+ * Heading from Markdown cell or Markdown output
804
+ */
805
+ Markdown
806
+ }
807
+
808
+ /**
809
+ * The factory object for customizable cell children.
810
+ *
811
+ * This is used to allow users of cells to customize child content.
812
+ *
813
+ * This inherits from `OutputArea.IContentFactory` to avoid needless nesting and
814
+ * provide a single factory object for all notebook/cell/outputarea related
815
+ * widgets.
816
+ */
817
+ export interface IContentFactory
818
+ extends OutputArea.IContentFactory,
819
+ InputArea.IContentFactory {
820
+ /**
821
+ * Create a new cell header for the parent widget.
822
+ */
823
+ createCellHeader(): ICellHeader;
824
+
825
+ /**
826
+ * Create a new cell header for the parent widget.
827
+ */
828
+ createCellFooter(): ICellFooter;
829
+ }
830
+
831
+ /**
832
+ * The default implementation of an `IContentFactory`.
833
+ *
834
+ * This includes a CodeMirror editor factory to make it easy to use out of the box.
835
+ */
836
+ export class ContentFactory implements IContentFactory {
837
+ /**
838
+ * Create a content factory for a cell.
839
+ */
840
+ constructor(options: ContentFactory.IOptions) {
841
+ this._editorFactory = options.editorFactory;
842
+ }
843
+
844
+ /**
845
+ * The readonly editor factory that create code editors
846
+ */
847
+ get editorFactory(): CodeEditor.Factory {
848
+ return this._editorFactory;
849
+ }
850
+
851
+ /**
852
+ * Create a new cell header for the parent widget.
853
+ */
854
+ createCellHeader(): ICellHeader {
855
+ return new CellHeader();
856
+ }
857
+
858
+ /**
859
+ * Create a new cell footer for the parent widget.
860
+ */
861
+ createCellFooter(): ICellFooter {
862
+ return new CellFooter();
863
+ }
864
+
865
+ /**
866
+ * Create an input prompt.
867
+ */
868
+ createInputPrompt(): IInputPrompt {
869
+ return new InputPrompt();
870
+ }
871
+
872
+ /**
873
+ * Create the output prompt for the widget.
874
+ */
875
+ createOutputPrompt(): IOutputPrompt {
876
+ return new OutputPrompt();
877
+ }
878
+
879
+ /**
880
+ * Create an stdin widget.
881
+ */
882
+ createStdin(options: Stdin.IOptions): IStdin {
883
+ return new Stdin(options);
884
+ }
885
+
886
+ private _editorFactory: CodeEditor.Factory;
887
+ }
888
+
889
+ /**
890
+ * A namespace for cell content factory.
891
+ */
892
+ export namespace ContentFactory {
893
+ /**
894
+ * Options for the content factory.
895
+ */
896
+ export interface IOptions {
897
+ /**
898
+ * The editor factory used by the content factory.
899
+ */
900
+ editorFactory: CodeEditor.Factory;
901
+ }
902
+ }
903
+ }
904
+
905
+ /** ****************************************************************************
906
+ * CodeCell
907
+ ******************************************************************************/
908
+
909
+ /**
910
+ * Code cell layout
911
+ *
912
+ * It will not detached the output area when the cell is detached.
913
+ */
914
+ export class CodeCellLayout extends PanelLayout {
915
+ /**
916
+ * A message handler invoked on a `'before-attach'` message.
917
+ *
918
+ * #### Notes
919
+ * The default implementation of this method forwards the message
920
+ * to all widgets. It assumes all widget nodes are attached to the
921
+ * parent widget node.
922
+ *
923
+ * This may be reimplemented by subclasses as needed.
924
+ */
925
+ protected onBeforeAttach(msg: Message): void {
926
+ let beforeOutputArea = true;
927
+ const outputAreaWrapper = this.parent!.node.firstElementChild;
928
+ for (const widget of this) {
929
+ if (outputAreaWrapper) {
930
+ if (widget.node === outputAreaWrapper) {
931
+ beforeOutputArea = false;
932
+ } else {
933
+ MessageLoop.sendMessage(widget, msg);
934
+
935
+ if (beforeOutputArea) {
936
+ this.parent!.node.insertBefore(widget.node, outputAreaWrapper);
937
+ } else {
938
+ this.parent!.node.appendChild(widget.node);
939
+ }
940
+
941
+ // Force setting isVisible to true as it requires the parent widget to be
942
+ // visible. But that flag will be set only during the `onAfterAttach` call.
943
+ if (!this.parent!.isHidden) {
944
+ widget.setFlag(Widget.Flag.IsVisible);
945
+ }
946
+
947
+ // Not called in NotebookWindowedLayout to avoid outputArea
948
+ // widgets unwanted update or reset.
949
+ MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);
950
+ }
951
+ }
952
+ }
953
+ }
954
+
955
+ /**
956
+ * A message handler invoked on an `'after-detach'` message.
957
+ *
958
+ * #### Notes
959
+ * The default implementation of this method forwards the message
960
+ * to all widgets. It assumes all widget nodes are attached to the
961
+ * parent widget node.
962
+ *
963
+ * This may be reimplemented by subclasses as needed.
964
+ */
965
+ protected onAfterDetach(msg: Message): void {
966
+ for (const widget of this) {
967
+ // TODO we could improve this further by removing outputs based
968
+ // on their mime type (for example plain/text or markdown could safely be detached)
969
+ // If the cell is out of the view port, its children are already detached -> skip detaching
970
+ if (
971
+ !widget.hasClass(CELL_OUTPUT_WRAPPER_CLASS) &&
972
+ widget.node.isConnected
973
+ ) {
974
+ // Not called in NotebookWindowedLayout for windowed notebook
975
+ MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);
976
+
977
+ this.parent!.node.removeChild(widget.node);
978
+
979
+ MessageLoop.sendMessage(widget, msg);
980
+ }
981
+ }
982
+ }
983
+ }
984
+
985
+ /**
986
+ * A widget for a code cell.
987
+ */
988
+ export class CodeCell extends Cell<ICodeCellModel> {
989
+ /**
990
+ * Construct a code cell widget.
991
+ */
992
+ constructor(options: CodeCell.IOptions) {
993
+ super({ layout: new CodeCellLayout(), ...options, placeholder: true });
994
+ this.addClass(CODE_CELL_CLASS);
995
+ const trans = this.translator.load('jupyterlab');
996
+
997
+ // Only save options not handled by parent constructor.
998
+ const rendermime = (this._rendermime = options.rendermime);
999
+ const contentFactory = this.contentFactory;
1000
+ const model = this.model;
1001
+ this.maxNumberOutputs = options.maxNumberOutputs;
1002
+
1003
+ // Note that modifying the below label warrants one to also modify
1004
+ // the same in this._outputLengthHandler. Ideally, this label must
1005
+ // have been a constant and used in both places but it is not done
1006
+ // so because of limitations in the translation manager.
1007
+ const ariaLabel =
1008
+ model.outputs.length === 0
1009
+ ? trans.__('Code Cell Content')
1010
+ : trans.__('Code Cell Content with Output');
1011
+ this.node.setAttribute('aria-label', ariaLabel);
1012
+
1013
+ const output = (this._output = new OutputArea({
1014
+ model: this.model.outputs,
1015
+ rendermime,
1016
+ contentFactory: contentFactory,
1017
+ maxNumberOutputs: this.maxNumberOutputs,
1018
+ translator: this.translator,
1019
+ promptOverlay: true,
1020
+ inputHistoryScope: options.inputHistoryScope
1021
+ }));
1022
+ output.addClass(CELL_OUTPUT_AREA_CLASS);
1023
+ output.toggleScrolling.connect(() => {
1024
+ this.outputsScrolled = !this.outputsScrolled;
1025
+ });
1026
+
1027
+ // Defer setting placeholder as OutputArea must be instantiated before initializing the DOM
1028
+ this.placeholder = options.placeholder ?? true;
1029
+
1030
+ model.outputs.changed.connect(this.onOutputChanged, this);
1031
+ model.outputs.stateChanged.connect(this.onOutputChanged, this);
1032
+ model.stateChanged.connect(this.onStateChanged, this);
1033
+ }
1034
+
1035
+ /**
1036
+ * Maximum number of outputs to display.
1037
+ */
1038
+ protected maxNumberOutputs: number | undefined;
1039
+
1040
+ /**
1041
+ * Create children widgets.
1042
+ */
1043
+ protected initializeDOM(): void {
1044
+ if (!this.placeholder) {
1045
+ return;
1046
+ }
1047
+
1048
+ super.initializeDOM();
1049
+
1050
+ this.setPrompt(this.prompt);
1051
+
1052
+ // Insert the output before the cell footer.
1053
+ const outputWrapper = (this._outputWrapper = new Panel());
1054
+ outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
1055
+ const outputCollapser = new OutputCollapser();
1056
+ outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
1057
+ outputWrapper.addWidget(outputCollapser);
1058
+ // Set a CSS if there are no outputs, and connect a signal for future
1059
+ // changes to the number of outputs. This is for conditional styling
1060
+ // if there are no outputs.
1061
+ if (this.model.outputs.length === 0) {
1062
+ this.addClass(NO_OUTPUTS_CLASS);
1063
+ }
1064
+ this._output.outputLengthChanged.connect(this._outputLengthHandler, this);
1065
+ outputWrapper.addWidget(this._output);
1066
+ const layout = this.layout as PanelLayout;
1067
+ layout.insertWidget(layout.widgets.length - 1, new ResizeHandle(this.node));
1068
+ layout.insertWidget(layout.widgets.length - 1, outputWrapper);
1069
+
1070
+ if (this.model.isDirty) {
1071
+ this.addClass(DIRTY_CLASS);
1072
+ }
1073
+
1074
+ this._outputPlaceholder = new OutputPlaceholder({
1075
+ callback: () => {
1076
+ this.outputHidden = !this.outputHidden;
1077
+ },
1078
+ text: this.getOutputPlaceholderText(),
1079
+ translator: this.translator
1080
+ });
1081
+
1082
+ const layoutWrapper = outputWrapper.layout as PanelLayout;
1083
+ if (this.outputHidden) {
1084
+ layoutWrapper.removeWidget(this._output);
1085
+ layoutWrapper.addWidget(this._outputPlaceholder);
1086
+ if (this.inputHidden && !outputWrapper.isHidden) {
1087
+ this._outputWrapper!.hide();
1088
+ }
1089
+ }
1090
+
1091
+ const trans = this.translator.load('jupyterlab');
1092
+ const ariaLabel =
1093
+ this.model.outputs.length === 0
1094
+ ? trans.__('Code Cell Content')
1095
+ : trans.__('Code Cell Content with Output');
1096
+ this.node.setAttribute('aria-label', ariaLabel);
1097
+ }
1098
+
1099
+ protected getOutputPlaceholderText(): string | undefined {
1100
+ const firstOutput = this.model.outputs.get(0);
1101
+ const outputData = firstOutput?.data;
1102
+ if (!outputData) {
1103
+ return undefined;
1104
+ }
1105
+ const supportedOutputTypes = [
1106
+ 'text/html',
1107
+ 'image/svg+xml',
1108
+ 'application/pdf',
1109
+ 'text/markdown',
1110
+ 'text/plain',
1111
+ 'application/vnd.jupyter.stderr',
1112
+ 'application/vnd.jupyter.stdout',
1113
+ 'text'
1114
+ ];
1115
+ const preferredOutput = supportedOutputTypes.find(mt => {
1116
+ const data = firstOutput.data[mt];
1117
+ return (Array.isArray(data) ? typeof data[0] : typeof data) === 'string';
1118
+ });
1119
+ const dataToDisplay = firstOutput.data[preferredOutput ?? ''];
1120
+ if (dataToDisplay !== undefined) {
1121
+ return (
1122
+ Array.isArray(dataToDisplay)
1123
+ ? dataToDisplay
1124
+ : (dataToDisplay as string)?.split('\n')
1125
+ )?.find(part => part !== '');
1126
+ }
1127
+ return undefined;
1128
+ }
1129
+
1130
+ /**
1131
+ * Initialize view state from model.
1132
+ *
1133
+ * #### Notes
1134
+ * Should be called after construction. For convenience, returns this, so it
1135
+ * can be chained in the construction, like `new Foo().initializeState();`
1136
+ */
1137
+ initializeState(): this {
1138
+ super.initializeState();
1139
+ this.loadScrolledState();
1140
+
1141
+ this.setPrompt(`${this.model.executionCount || ''}`);
1142
+ return this;
1143
+ }
1144
+
1145
+ get headings(): Cell.IHeading[] {
1146
+ if (!this._headingsCache) {
1147
+ const headings: Cell.IHeading[] = [];
1148
+
1149
+ // Iterate over the code cell outputs to check for Markdown or HTML from which we can generate ToC headings...
1150
+ const outputs = this.model.outputs;
1151
+ for (let j = 0; j < outputs.length; j++) {
1152
+ const m = outputs.get(j);
1153
+
1154
+ let htmlType: string | null = null;
1155
+ let mdType: string | null = null;
1156
+
1157
+ Object.keys(m.data).forEach(t => {
1158
+ if (!mdType && TableOfContentsUtils.Markdown.isMarkdown(t)) {
1159
+ mdType = t;
1160
+ } else if (!htmlType && TableOfContentsUtils.isHTML(t)) {
1161
+ htmlType = t;
1162
+ }
1163
+ });
1164
+
1165
+ // Parse HTML output
1166
+ if (htmlType) {
1167
+ headings.push(
1168
+ ...TableOfContentsUtils.getHTMLHeadings(
1169
+ this._rendermime.sanitizer.sanitize(m.data[htmlType] as string)
1170
+ ).map(heading => {
1171
+ return {
1172
+ ...heading,
1173
+ outputIndex: j,
1174
+ type: Cell.HeadingType.HTML
1175
+ };
1176
+ })
1177
+ );
1178
+ } else if (mdType) {
1179
+ headings.push(
1180
+ ...TableOfContentsUtils.Markdown.getHeadings(
1181
+ m.data[mdType] as string
1182
+ ).map(heading => {
1183
+ return {
1184
+ ...heading,
1185
+ outputIndex: j,
1186
+ type: Cell.HeadingType.Markdown
1187
+ };
1188
+ })
1189
+ );
1190
+ }
1191
+ }
1192
+
1193
+ this._headingsCache = headings;
1194
+ }
1195
+
1196
+ return [...this._headingsCache!];
1197
+ }
1198
+
1199
+ /**
1200
+ * Get the output area for the cell.
1201
+ */
1202
+ get outputArea(): OutputArea {
1203
+ return this._output;
1204
+ }
1205
+
1206
+ /**
1207
+ * The view state of output being collapsed.
1208
+ */
1209
+ get outputHidden(): boolean {
1210
+ return this._outputHidden;
1211
+ }
1212
+ set outputHidden(value: boolean) {
1213
+ if (this._outputHidden === value) {
1214
+ return;
1215
+ }
1216
+
1217
+ if (!this.placeholder) {
1218
+ const layout = this._outputWrapper!.layout as PanelLayout;
1219
+ if (value) {
1220
+ layout.removeWidget(this._output);
1221
+ layout.addWidget(this._outputPlaceholder!);
1222
+ if (this.inputHidden && !this._outputWrapper!.isHidden) {
1223
+ this._outputWrapper!.hide();
1224
+ }
1225
+ if (this._outputPlaceholder) {
1226
+ this._outputPlaceholder.text = this.getOutputPlaceholderText() ?? '';
1227
+ }
1228
+ } else {
1229
+ if (this._outputWrapper!.isHidden) {
1230
+ this._outputWrapper!.show();
1231
+ }
1232
+ layout.removeWidget(this._outputPlaceholder!);
1233
+ layout.addWidget(this._output);
1234
+ }
1235
+ }
1236
+ this._outputHidden = value;
1237
+ if (this.syncCollapse) {
1238
+ this.saveCollapseState();
1239
+ }
1240
+ }
1241
+
1242
+ /**
1243
+ * Save view collapse state to model
1244
+ */
1245
+ saveCollapseState(): void {
1246
+ // Because collapse state for a code cell involves two different pieces of
1247
+ // metadata (the `collapsed` and `jupyter` metadata keys), we block reacting
1248
+ // to changes in metadata until we have fully committed our changes.
1249
+ // Otherwise setting one key can trigger a write to the other key to
1250
+ // maintain the synced consistency.
1251
+ this.model.sharedModel.transact(() => {
1252
+ super.saveCollapseState();
1253
+
1254
+ const collapsed = this.model.getMetadata('collapsed');
1255
+
1256
+ if (
1257
+ (this.outputHidden && collapsed === true) ||
1258
+ (!this.outputHidden && collapsed === undefined)
1259
+ ) {
1260
+ return;
1261
+ }
1262
+
1263
+ // Do not set jupyter.outputs_hidden since it is redundant. See
1264
+ // and https://github.com/jupyter/nbformat/issues/137
1265
+ if (this.outputHidden) {
1266
+ this.model.setMetadata('collapsed', true);
1267
+ } else {
1268
+ this.model.deleteMetadata('collapsed');
1269
+ }
1270
+ }, false);
1271
+ }
1272
+
1273
+ /**
1274
+ * Revert view collapse state from model.
1275
+ *
1276
+ * We consider the `collapsed` metadata key as the source of truth for outputs
1277
+ * being hidden.
1278
+ */
1279
+ loadCollapseState(): void {
1280
+ super.loadCollapseState();
1281
+ this.outputHidden = !!this.model.getMetadata('collapsed');
1282
+ }
1283
+
1284
+ /**
1285
+ * Whether the output is in a scrolled state?
1286
+ */
1287
+ get outputsScrolled(): boolean {
1288
+ return this._outputsScrolled;
1289
+ }
1290
+ set outputsScrolled(value: boolean) {
1291
+ this.toggleClass('jp-mod-outputsScrolled', value);
1292
+ this._outputsScrolled = value;
1293
+ if (this.syncScrolled) {
1294
+ this.saveScrolledState();
1295
+ }
1296
+ }
1297
+
1298
+ /**
1299
+ * Save view collapse state to model
1300
+ */
1301
+ saveScrolledState(): void {
1302
+ const current = this.model.getMetadata('scrolled');
1303
+
1304
+ if (
1305
+ (this.outputsScrolled && current === true) ||
1306
+ (!this.outputsScrolled && current === undefined)
1307
+ ) {
1308
+ return;
1309
+ }
1310
+ if (this.outputsScrolled) {
1311
+ this.model.setMetadata('scrolled', true);
1312
+ } else {
1313
+ this.model.deleteMetadata('scrolled');
1314
+ }
1315
+ }
1316
+
1317
+ /**
1318
+ * Revert view collapse state from model.
1319
+ */
1320
+ loadScrolledState(): void {
1321
+ // We don't have the notion of 'auto' scrolled, so we make it false.
1322
+ if (this.model.getMetadata('scrolled') === 'auto') {
1323
+ this.outputsScrolled = false;
1324
+ } else {
1325
+ this.outputsScrolled = !!this.model.getMetadata('scrolled');
1326
+ }
1327
+ }
1328
+
1329
+ /**
1330
+ * Whether to sync the scrolled state to the cell model.
1331
+ */
1332
+ get syncScrolled(): boolean {
1333
+ return this._syncScrolled;
1334
+ }
1335
+ set syncScrolled(value: boolean) {
1336
+ if (this._syncScrolled === value) {
1337
+ return;
1338
+ }
1339
+ this._syncScrolled = value;
1340
+ if (value) {
1341
+ this.loadScrolledState();
1342
+ }
1343
+ }
1344
+
1345
+ /**
1346
+ * Handle the input being hidden.
1347
+ *
1348
+ * #### Notes
1349
+ * This method is called by the case cell implementation and is
1350
+ * subclasses here so the code cell can watch to see when input
1351
+ * is hidden without accessing private state.
1352
+ */
1353
+ protected handleInputHidden(value: boolean): void {
1354
+ if (this.placeholder) {
1355
+ return;
1356
+ }
1357
+ if (!value && this._outputWrapper!.isHidden) {
1358
+ this._outputWrapper!.show();
1359
+ } else if (value && !this._outputWrapper!.isHidden && this._outputHidden) {
1360
+ this._outputWrapper!.hide();
1361
+ }
1362
+ }
1363
+
1364
+ /**
1365
+ * Clone the cell, using the same model.
1366
+ */
1367
+ clone(): CodeCell {
1368
+ const constructor = this.constructor as typeof CodeCell;
1369
+ return new constructor({
1370
+ model: this.model,
1371
+ contentFactory: this.contentFactory,
1372
+ rendermime: this._rendermime,
1373
+ placeholder: false,
1374
+ translator: this.translator
1375
+ });
1376
+ }
1377
+
1378
+ /**
1379
+ * Clone the OutputArea alone, returning a simplified output area, using the same model.
1380
+ */
1381
+ cloneOutputArea(): OutputArea {
1382
+ return new SimplifiedOutputArea({
1383
+ model: this.model.outputs!,
1384
+ contentFactory: this.contentFactory,
1385
+ rendermime: this._rendermime
1386
+ });
1387
+ }
1388
+
1389
+ /**
1390
+ * Dispose of the resources used by the widget.
1391
+ */
1392
+ dispose(): void {
1393
+ if (this.isDisposed) {
1394
+ return;
1395
+ }
1396
+ this._output.outputLengthChanged.disconnect(
1397
+ this._outputLengthHandler,
1398
+ this
1399
+ );
1400
+ this._rendermime = null!;
1401
+ this._output = null!;
1402
+ this._outputWrapper = null!;
1403
+ this._outputPlaceholder = null!;
1404
+ super.dispose();
1405
+ }
1406
+
1407
+ /**
1408
+ * Handle changes in the model.
1409
+ */
1410
+ protected onStateChanged(model: ICellModel, args: IChangedArgs<any>): void {
1411
+ switch (args.name) {
1412
+ case 'executionCount':
1413
+ this.setPrompt(`${(model as ICodeCellModel).executionCount || ''}`);
1414
+ break;
1415
+ case 'isDirty':
1416
+ if ((model as ICodeCellModel).isDirty) {
1417
+ this.addClass(DIRTY_CLASS);
1418
+ } else {
1419
+ this.removeClass(DIRTY_CLASS);
1420
+ }
1421
+ break;
1422
+ default:
1423
+ break;
1424
+ }
1425
+ }
1426
+
1427
+ /**
1428
+ * Callback on output changes
1429
+ */
1430
+ protected onOutputChanged(): void {
1431
+ this._headingsCache = null;
1432
+ if (this._outputPlaceholder && this.outputHidden) {
1433
+ this._outputPlaceholder.text = this.getOutputPlaceholderText() ?? '';
1434
+ }
1435
+ }
1436
+
1437
+ /**
1438
+ * Handle changes in the metadata.
1439
+ */
1440
+ protected onMetadataChanged(model: CellModel, args: IMapChange): void {
1441
+ switch (args.key) {
1442
+ case 'scrolled':
1443
+ if (this.syncScrolled) {
1444
+ this.loadScrolledState();
1445
+ }
1446
+ break;
1447
+ case 'collapsed':
1448
+ if (this.syncCollapse) {
1449
+ this.loadCollapseState();
1450
+ }
1451
+ break;
1452
+ default:
1453
+ break;
1454
+ }
1455
+ super.onMetadataChanged(model, args);
1456
+ }
1457
+
1458
+ /**
1459
+ * Handle changes in the number of outputs in the output area.
1460
+ */
1461
+ private _outputLengthHandler(sender: OutputArea, args: number) {
1462
+ const force = args === 0 ? true : false;
1463
+ this.toggleClass(NO_OUTPUTS_CLASS, force);
1464
+ const trans = this.translator.load('jupyterlab');
1465
+ const ariaLabel = force
1466
+ ? trans.__('Code Cell Content')
1467
+ : trans.__('Code Cell Content with Output');
1468
+ this.node.setAttribute('aria-label', ariaLabel);
1469
+ }
1470
+
1471
+ private _headingsCache: Cell.IHeading[] | null = null;
1472
+ private _rendermime: IRenderMimeRegistry;
1473
+ private _outputHidden = false;
1474
+ private _outputsScrolled: boolean;
1475
+ private _outputWrapper: Widget | null = null;
1476
+ private _outputPlaceholder: OutputPlaceholder | null = null;
1477
+ private _output: OutputArea;
1478
+ private _syncScrolled = false;
1479
+ }
1480
+
1481
+ /**
1482
+ * The namespace for the `CodeCell` class statics.
1483
+ */
1484
+ export namespace CodeCell {
1485
+ /**
1486
+ * An options object for initializing a base cell widget.
1487
+ */
1488
+ export interface IOptions extends Cell.IOptions<ICodeCellModel> {
1489
+ /**
1490
+ * Code cell layout.
1491
+ */
1492
+ layout?: CodeCellLayout;
1493
+ /**
1494
+ * The mime renderer for the cell widget.
1495
+ */
1496
+ rendermime: IRenderMimeRegistry;
1497
+ }
1498
+
1499
+ /**
1500
+ * Execute a cell given a client session.
1501
+ */
1502
+ export async function execute(
1503
+ cell: CodeCell,
1504
+ sessionContext: ISessionContext,
1505
+ metadata?: JSONObject
1506
+ ): Promise<KernelMessage.IExecuteReplyMsg | void> {
1507
+ const model = cell.model;
1508
+ const code = model.sharedModel.getSource();
1509
+ if (!code.trim() || !sessionContext.session?.kernel) {
1510
+ model.sharedModel.transact(() => {
1511
+ model.clearExecution();
1512
+ }, false);
1513
+ return;
1514
+ }
1515
+ const cellId = { cellId: model.sharedModel.getId() };
1516
+ metadata = {
1517
+ ...model.metadata,
1518
+ ...metadata,
1519
+ ...cellId
1520
+ };
1521
+ const { recordTiming } = metadata;
1522
+ model.sharedModel.transact(() => {
1523
+ model.clearExecution();
1524
+ cell.outputHidden = false;
1525
+ }, false);
1526
+ cell.setPrompt('*');
1527
+ model.trusted = true;
1528
+ let future:
1529
+ | Kernel.IFuture<
1530
+ KernelMessage.IExecuteRequestMsg,
1531
+ KernelMessage.IExecuteReplyMsg
1532
+ >
1533
+ | undefined;
1534
+ try {
1535
+ const msgPromise = OutputArea.execute(
1536
+ code,
1537
+ cell.outputArea,
1538
+ sessionContext,
1539
+ metadata
1540
+ );
1541
+ // cell.outputArea.future assigned synchronously in `execute`
1542
+ if (recordTiming) {
1543
+ const recordTimingHook = (msg: KernelMessage.IIOPubMessage) => {
1544
+ let label: string;
1545
+ switch (msg.header.msg_type) {
1546
+ case 'status':
1547
+ label = `status.${
1548
+ (msg as KernelMessage.IStatusMsg).content.execution_state
1549
+ }`;
1550
+ break;
1551
+ case 'execute_input':
1552
+ label = 'execute_input';
1553
+ break;
1554
+ default:
1555
+ return true;
1556
+ }
1557
+ // If the data is missing, estimate it to now
1558
+ // Date was added in 5.1: https://jupyter-client.readthedocs.io/en/stable/messaging.html#message-header
1559
+ const value = msg.header.date || new Date().toISOString();
1560
+ const timingInfo: any = Object.assign(
1561
+ {},
1562
+ model.getMetadata('execution')
1563
+ );
1564
+ timingInfo[`iopub.${label}`] = value;
1565
+ model.setMetadata('execution', timingInfo);
1566
+ return true;
1567
+ };
1568
+ cell.outputArea.future.registerMessageHook(recordTimingHook);
1569
+ } else {
1570
+ model.deleteMetadata('execution');
1571
+ }
1572
+ // Save this execution's future so we can compare in the catch below.
1573
+ future = cell.outputArea.future;
1574
+ const msg = (await msgPromise)!;
1575
+ model.executionCount = msg.content.execution_count;
1576
+ if (recordTiming) {
1577
+ const timingInfo = Object.assign(
1578
+ {},
1579
+ model.getMetadata('execution') as any
1580
+ );
1581
+ const started = msg.metadata.started as string;
1582
+ // Started is not in the API, but metadata IPyKernel sends
1583
+ if (started) {
1584
+ timingInfo['shell.execute_reply.started'] = started;
1585
+ }
1586
+ // Per above, the 5.0 spec does not assume date, so we estimate is required
1587
+ const finished = msg.header.date as string;
1588
+ timingInfo['shell.execute_reply'] =
1589
+ finished || new Date().toISOString();
1590
+ model.setMetadata('execution', timingInfo);
1591
+ }
1592
+ return msg;
1593
+ } catch (e) {
1594
+ // If we started executing, and the cell is still indicating this
1595
+ // execution, clear the prompt.
1596
+ if (future && !cell.isDisposed && cell.outputArea.future === future) {
1597
+ cell.setPrompt('');
1598
+ }
1599
+ throw e;
1600
+ }
1601
+ }
1602
+ }
1603
+
1604
+ /**
1605
+ * `AttachmentsCell` - A base class for a cell widget that allows
1606
+ * attachments to be drag/drop'd or pasted onto it
1607
+ */
1608
+ export abstract class AttachmentsCell<
1609
+ T extends IAttachmentsCellModel
1610
+ > extends Cell<T> {
1611
+ /**
1612
+ * Handle the DOM events for the widget.
1613
+ *
1614
+ * @param event - The DOM event sent to the widget.
1615
+ *
1616
+ * #### Notes
1617
+ * This method implements the DOM `EventListener` interface and is
1618
+ * called in response to events on the notebook panel's node. It should
1619
+ * not be called directly by user code.
1620
+ */
1621
+ handleEvent(event: Event): void {
1622
+ switch (event.type) {
1623
+ case 'lm-dragover':
1624
+ this._evtDragOver(event as Drag.Event);
1625
+ break;
1626
+ case 'lm-drop':
1627
+ this._evtDrop(event as Drag.Event);
1628
+ break;
1629
+ default:
1630
+ break;
1631
+ }
1632
+ }
1633
+
1634
+ /**
1635
+ * Get the editor options at initialization.
1636
+ *
1637
+ * @returns Editor options
1638
+ */
1639
+ protected getEditorOptions(): InputArea.IOptions['editorOptions'] {
1640
+ const base = super.getEditorOptions() ?? {};
1641
+ base.extensions = [
1642
+ ...(base.extensions ?? []),
1643
+ EditorView.domEventHandlers({
1644
+ dragenter: (event: DragEvent) => {
1645
+ event.preventDefault();
1646
+ },
1647
+ dragover: (event: DragEvent) => {
1648
+ event.preventDefault();
1649
+ },
1650
+ drop: (event: DragEvent) => {
1651
+ this._evtNativeDrop(event);
1652
+ },
1653
+ paste: (event: ClipboardEvent) => {
1654
+ this._evtPaste(event);
1655
+ }
1656
+ })
1657
+ ];
1658
+ return base;
1659
+ }
1660
+
1661
+ /**
1662
+ * Modify the cell source to include a reference to the attachment.
1663
+ */
1664
+ protected abstract updateCellSourceWithAttachment(
1665
+ attachmentName: string,
1666
+ URI?: string
1667
+ ): void;
1668
+
1669
+ /**
1670
+ * Handle `after-attach` messages for the widget.
1671
+ */
1672
+ protected onAfterAttach(msg: Message): void {
1673
+ super.onAfterAttach(msg);
1674
+
1675
+ const node = this.node;
1676
+ node.addEventListener('lm-dragover', this);
1677
+ node.addEventListener('lm-drop', this);
1678
+ }
1679
+
1680
+ /**
1681
+ * A message handler invoked on a `'before-detach'`
1682
+ * message
1683
+ */
1684
+ protected onBeforeDetach(msg: Message): void {
1685
+ const node = this.node;
1686
+ node.removeEventListener('lm-dragover', this);
1687
+ node.removeEventListener('lm-drop', this);
1688
+
1689
+ super.onBeforeDetach(msg);
1690
+ }
1691
+
1692
+ private _evtDragOver(event: Drag.Event) {
1693
+ const supportedMimeType = some(imageRendererFactory.mimeTypes, mimeType => {
1694
+ if (!event.mimeData.hasData(CONTENTS_MIME_RICH)) {
1695
+ return false;
1696
+ }
1697
+ const data = event.mimeData.getData(
1698
+ CONTENTS_MIME_RICH
1699
+ ) as DirListing.IContentsThunk;
1700
+ return data.model.mimetype === mimeType;
1701
+ });
1702
+ if (!supportedMimeType) {
1703
+ return;
1704
+ }
1705
+ event.preventDefault();
1706
+ event.stopPropagation();
1707
+ event.dropAction = event.proposedAction;
1708
+ }
1709
+
1710
+ /**
1711
+ * Handle the `paste` event for the widget
1712
+ */
1713
+ private _evtPaste(event: ClipboardEvent): void {
1714
+ if (event.clipboardData) {
1715
+ const items = event.clipboardData.items;
1716
+ for (let i = 0; i < items.length; i++) {
1717
+ if (items[i].type === 'text/plain') {
1718
+ // Skip if this text is the path to a file
1719
+ if (i < items.length - 1 && items[i + 1].kind === 'file') {
1720
+ continue;
1721
+ }
1722
+ items[i].getAsString(text => {
1723
+ this.editor!.replaceSelection?.(text);
1724
+ });
1725
+ }
1726
+ this._attachFiles(event.clipboardData.items);
1727
+ }
1728
+ }
1729
+ event.preventDefault();
1730
+ }
1731
+
1732
+ /**
1733
+ * Handle the `drop` event for the widget
1734
+ */
1735
+ private _evtNativeDrop(event: DragEvent): void {
1736
+ if (event.dataTransfer) {
1737
+ this._attachFiles(event.dataTransfer.items);
1738
+ }
1739
+ event.preventDefault();
1740
+ }
1741
+
1742
+ /**
1743
+ * Handle the `'lm-drop'` event for the widget.
1744
+ */
1745
+ private _evtDrop(event: Drag.Event): void {
1746
+ const supportedMimeTypes = event.mimeData.types().filter(mimeType => {
1747
+ if (mimeType === CONTENTS_MIME_RICH) {
1748
+ const data = event.mimeData.getData(
1749
+ CONTENTS_MIME_RICH
1750
+ ) as DirListing.IContentsThunk;
1751
+ return (
1752
+ imageRendererFactory.mimeTypes.indexOf(data.model.mimetype) !== -1
1753
+ );
1754
+ }
1755
+ return imageRendererFactory.mimeTypes.indexOf(mimeType) !== -1;
1756
+ });
1757
+ if (supportedMimeTypes.length === 0) {
1758
+ return;
1759
+ }
1760
+ event.preventDefault();
1761
+ event.stopPropagation();
1762
+ if (event.proposedAction === 'none') {
1763
+ event.dropAction = 'none';
1764
+ return;
1765
+ }
1766
+ event.dropAction = 'copy';
1767
+
1768
+ for (const mimeType of supportedMimeTypes) {
1769
+ if (mimeType === CONTENTS_MIME_RICH) {
1770
+ const { model, withContent } = event.mimeData.getData(
1771
+ CONTENTS_MIME_RICH
1772
+ ) as DirListing.IContentsThunk;
1773
+ if (model.type === 'file') {
1774
+ const URI = this._generateURI(model.name);
1775
+ this.updateCellSourceWithAttachment(model.name, URI);
1776
+ void withContent().then(fullModel => {
1777
+ this.model.attachments.set(URI, {
1778
+ [fullModel.mimetype]: fullModel.content
1779
+ });
1780
+ });
1781
+ }
1782
+ } else {
1783
+ // Pure mimetype, no useful name to infer
1784
+ const URI = this._generateURI();
1785
+ this.model.attachments.set(URI, {
1786
+ [mimeType]: event.mimeData.getData(mimeType)
1787
+ });
1788
+ this.updateCellSourceWithAttachment(URI, URI);
1789
+ }
1790
+ }
1791
+ }
1792
+
1793
+ /**
1794
+ * Attaches all DataTransferItems (obtained from
1795
+ * clipboard or native drop events) to the cell
1796
+ */
1797
+ private _attachFiles(items: DataTransferItemList) {
1798
+ for (let i = 0; i < items.length; i++) {
1799
+ const item = items[i];
1800
+ if (item.kind === 'file') {
1801
+ const blob = item.getAsFile();
1802
+ if (blob) {
1803
+ this._attachFile(blob);
1804
+ }
1805
+ }
1806
+ }
1807
+ }
1808
+
1809
+ /**
1810
+ * Takes in a file object and adds it to
1811
+ * the cell attachments
1812
+ */
1813
+ private _attachFile(blob: File) {
1814
+ const reader = new FileReader();
1815
+ reader.onload = evt => {
1816
+ const { href, protocol } = URLExt.parse(reader.result as string);
1817
+ if (protocol !== 'data:') {
1818
+ return;
1819
+ }
1820
+ const dataURIRegex = /([\w+\/\+]+)?(?:;(charset=[\w\d-]*|base64))?,(.*)/;
1821
+ const matches = dataURIRegex.exec(href);
1822
+ if (!matches || matches.length !== 4) {
1823
+ return;
1824
+ }
1825
+ const mimeType = matches[1];
1826
+ const encodedData = matches[3];
1827
+ const bundle: nbformat.IMimeBundle = { [mimeType]: encodedData };
1828
+ const URI = this._generateURI(blob.name);
1829
+
1830
+ if (mimeType.startsWith('image/')) {
1831
+ this.model.attachments.set(URI, bundle);
1832
+ this.updateCellSourceWithAttachment(blob.name, URI);
1833
+ }
1834
+ };
1835
+ reader.onerror = evt => {
1836
+ console.error(`Failed to attach ${blob.name}` + evt);
1837
+ };
1838
+ reader.readAsDataURL(blob);
1839
+ }
1840
+
1841
+ /**
1842
+ * Generates a unique URI for a file
1843
+ * while preserving the file extension.
1844
+ */
1845
+ private _generateURI(name = ''): string {
1846
+ const lastIndex = name.lastIndexOf('.');
1847
+ return lastIndex !== -1
1848
+ ? UUID.uuid4().concat(name.substring(lastIndex))
1849
+ : UUID.uuid4();
1850
+ }
1851
+ }
1852
+
1853
+ /** ****************************************************************************
1854
+ * MarkdownCell
1855
+ ******************************************************************************/
1856
+
1857
+ /**
1858
+ * A widget for a Markdown cell.
1859
+ *
1860
+ * #### Notes
1861
+ * Things get complicated if we want the rendered text to update
1862
+ * any time the text changes, the text editor model changes,
1863
+ * or the input area model changes. We don't support automatically
1864
+ * updating the rendered text in all of these cases.
1865
+ */
1866
+ export class MarkdownCell extends AttachmentsCell<IMarkdownCellModel> {
1867
+ /**
1868
+ * Construct a Markdown cell widget.
1869
+ */
1870
+ constructor(options: MarkdownCell.IOptions) {
1871
+ super({ ...options, placeholder: true });
1872
+ this.addClass(MARKDOWN_CELL_CLASS);
1873
+ this.model.contentChanged.connect(this.onContentChanged, this);
1874
+ const trans = this.translator.load('jupyterlab');
1875
+ this.node.setAttribute('aria-label', trans.__('Markdown Cell Content'));
1876
+ // Ensure we can resolve attachments:
1877
+ this._rendermime = options.rendermime.clone({
1878
+ resolver: new AttachmentsResolver({
1879
+ parent: options.rendermime.resolver ?? undefined,
1880
+ model: this.model.attachments
1881
+ })
1882
+ });
1883
+
1884
+ this._renderer = this._rendermime.createRenderer('text/markdown');
1885
+ this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1886
+
1887
+ // Check if heading cell is set to be collapsed
1888
+ this._headingCollapsed = (this.model.getMetadata(
1889
+ MARKDOWN_HEADING_COLLAPSED
1890
+ ) ?? false) as boolean;
1891
+
1892
+ this._showEditorForReadOnlyMarkdown =
1893
+ options.showEditorForReadOnlyMarkdown ??
1894
+ MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1895
+
1896
+ // Defer setting placeholder as the renderer must be instantiated before initializing the DOM
1897
+ this.placeholder = options.placeholder ?? true;
1898
+
1899
+ this._monitor = new ActivityMonitor({
1900
+ signal: this.model.contentChanged,
1901
+ timeout: RENDER_TIMEOUT
1902
+ });
1903
+
1904
+ // Throttle the rendering rate of the widget.
1905
+ this.ready
1906
+ .then(() => {
1907
+ if (this.isDisposed) {
1908
+ // Bail early
1909
+ return;
1910
+ }
1911
+ this._monitor.activityStopped.connect(() => {
1912
+ if (this._rendered) {
1913
+ this.update();
1914
+ }
1915
+ }, this);
1916
+ })
1917
+ .catch(reason => {
1918
+ console.error('Failed to be ready', reason);
1919
+ });
1920
+ }
1921
+
1922
+ /**
1923
+ * Text that represents the highest heading (i.e. lowest level) if cell is a heading.
1924
+ * Returns empty string if not a heading.
1925
+ */
1926
+ get headingInfo(): { text: string; level: number } {
1927
+ // Use table of content algorithm for consistency
1928
+ const headings = this.headings;
1929
+
1930
+ if (headings.length > 0) {
1931
+ // Return the highest level
1932
+ const { text, level } = headings.reduce(
1933
+ (prev, curr) => (prev.level <= curr.level ? prev : curr),
1934
+ headings[0]
1935
+ );
1936
+ return { text, level };
1937
+ } else {
1938
+ return { text: '', level: -1 };
1939
+ }
1940
+ }
1941
+
1942
+ get headings(): Cell.IHeading[] {
1943
+ if (!this._headingsCache) {
1944
+ // Use table of content algorithm for consistency
1945
+ const headings = TableOfContentsUtils.Markdown.getHeadings(
1946
+ this.model.sharedModel.getSource()
1947
+ );
1948
+ this._headingsCache = headings.map(h => {
1949
+ return { ...h, type: Cell.HeadingType.Markdown };
1950
+ });
1951
+ }
1952
+
1953
+ return [...this._headingsCache!];
1954
+ }
1955
+
1956
+ /**
1957
+ * Whether the heading is collapsed or not.
1958
+ */
1959
+ get headingCollapsed(): boolean {
1960
+ return this._headingCollapsed;
1961
+ }
1962
+ set headingCollapsed(value: boolean) {
1963
+ if (this._headingCollapsed !== value) {
1964
+ this._headingCollapsed = value;
1965
+ if (value) {
1966
+ this.model.setMetadata(MARKDOWN_HEADING_COLLAPSED, value);
1967
+ } else if (
1968
+ this.model.getMetadata(MARKDOWN_HEADING_COLLAPSED) !== 'undefined'
1969
+ ) {
1970
+ this.model.deleteMetadata(MARKDOWN_HEADING_COLLAPSED);
1971
+ }
1972
+ const collapseButton = this.inputArea?.promptNode.getElementsByClassName(
1973
+ HEADING_COLLAPSER_CLASS
1974
+ )[0];
1975
+ if (collapseButton) {
1976
+ if (value) {
1977
+ collapseButton.classList.add('jp-mod-collapsed');
1978
+ } else {
1979
+ collapseButton.classList.remove('jp-mod-collapsed');
1980
+ }
1981
+ }
1982
+ this.renderCollapseButtons(this._renderer);
1983
+ this._headingCollapsedChanged.emit(this._headingCollapsed);
1984
+ }
1985
+ }
1986
+
1987
+ /**
1988
+ * Number of collapsed sub cells.
1989
+ */
1990
+ get numberChildNodes(): number {
1991
+ return this._numberChildNodes;
1992
+ }
1993
+ set numberChildNodes(value: number) {
1994
+ this._numberChildNodes = value;
1995
+ this.renderCollapseButtons(this._renderer);
1996
+ }
1997
+
1998
+ /**
1999
+ * Signal emitted when the cell collapsed state changes.
2000
+ */
2001
+ get headingCollapsedChanged(): ISignal<MarkdownCell, boolean> {
2002
+ return this._headingCollapsedChanged;
2003
+ }
2004
+
2005
+ /**
2006
+ * Whether the cell is rendered.
2007
+ */
2008
+ get rendered(): boolean {
2009
+ return this._rendered;
2010
+ }
2011
+ set rendered(value: boolean) {
2012
+ // Show cell as rendered when cell is not editable
2013
+ if (this.readOnly && this._showEditorForReadOnlyMarkdown === false) {
2014
+ value = true;
2015
+ }
2016
+ if (value === this._rendered) {
2017
+ return;
2018
+ }
2019
+ this._rendered = value;
2020
+ this._handleRendered()
2021
+ .then(() => {
2022
+ // If the rendered state changed, raise an event.
2023
+ this._displayChanged.emit();
2024
+ this._renderedChanged.emit(this._rendered);
2025
+ })
2026
+ .catch(reason => {
2027
+ console.error('Failed to render', reason);
2028
+ });
2029
+ }
2030
+
2031
+ /**
2032
+ * Signal emitted when the markdown cell rendered state changes
2033
+ */
2034
+ get renderedChanged(): ISignal<MarkdownCell, boolean> {
2035
+ return this._renderedChanged;
2036
+ }
2037
+
2038
+ /*
2039
+ * Whether the Markdown editor is visible in read-only mode.
2040
+ */
2041
+ get showEditorForReadOnly(): boolean {
2042
+ return this._showEditorForReadOnlyMarkdown;
2043
+ }
2044
+ set showEditorForReadOnly(value: boolean) {
2045
+ this._showEditorForReadOnlyMarkdown = value;
2046
+ if (value === false) {
2047
+ this.rendered = true;
2048
+ }
2049
+ }
2050
+
2051
+ /**
2052
+ * Renderer
2053
+ */
2054
+ get renderer(): IRenderMime.IRenderer {
2055
+ return this._renderer;
2056
+ }
2057
+
2058
+ /**
2059
+ * Dispose of the resources held by the widget.
2060
+ */
2061
+ dispose(): void {
2062
+ if (this.isDisposed) {
2063
+ return;
2064
+ }
2065
+ this._monitor.dispose();
2066
+ super.dispose();
2067
+ }
2068
+
2069
+ /**
2070
+ * Create children widgets.
2071
+ */
2072
+ protected initializeDOM(): void {
2073
+ if (!this.placeholder) {
2074
+ return;
2075
+ }
2076
+
2077
+ super.initializeDOM();
2078
+
2079
+ this.renderCollapseButtons(this._renderer!);
2080
+
2081
+ this._handleRendered().catch(reason => {
2082
+ console.error('Failed to render', reason);
2083
+ });
2084
+ }
2085
+
2086
+ protected maybeCreateCollapseButton(): void {
2087
+ const { level } = this.headingInfo;
2088
+ if (
2089
+ level > 0 &&
2090
+ this.inputArea?.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)
2091
+ .length == 0
2092
+ ) {
2093
+ let collapseButton = this.inputArea.promptNode.appendChild(
2094
+ document.createElement('button')
2095
+ );
2096
+ collapseButton.className = `jp-Button ${HEADING_COLLAPSER_CLASS}`;
2097
+ collapseButton.setAttribute('data-heading-level', level.toString());
2098
+ if (this._headingCollapsed) {
2099
+ collapseButton.classList.add('jp-mod-collapsed');
2100
+ } else {
2101
+ collapseButton.classList.remove('jp-mod-collapsed');
2102
+ }
2103
+ collapseButton.onclick = (event: Event) => {
2104
+ this.headingCollapsed = !this.headingCollapsed;
2105
+ };
2106
+ }
2107
+ }
2108
+
2109
+ /**
2110
+ * Create, update or remove the hidden cells button.
2111
+ * Note that the actual visibility is controlled in Static Notebook by toggling jp-mod-showHiddenCellsButton class.
2112
+ */
2113
+ protected maybeCreateOrUpdateExpandButton(): void {
2114
+ const showHiddenCellsButtonList = this.node.getElementsByClassName(
2115
+ SHOW_HIDDEN_CELLS_CLASS
2116
+ );
2117
+ let trans = this.translator.load('jupyterlab');
2118
+ let buttonText = trans._n(
2119
+ '%1 cell hidden',
2120
+ '%1 cells hidden',
2121
+ this._numberChildNodes
2122
+ );
2123
+ let needToCreateButton =
2124
+ this.headingCollapsed &&
2125
+ this._numberChildNodes > 0 &&
2126
+ showHiddenCellsButtonList.length == 0;
2127
+ if (needToCreateButton) {
2128
+ const newShowHiddenCellsButton = document.createElement('button');
2129
+ newShowHiddenCellsButton.className = `jp-mod-minimal jp-Button ${SHOW_HIDDEN_CELLS_CLASS}`;
2130
+ addIcon.render(newShowHiddenCellsButton);
2131
+ const buttonTextElement = document.createElement('div');
2132
+ buttonTextElement.textContent = buttonText;
2133
+ newShowHiddenCellsButton.appendChild(buttonTextElement);
2134
+ newShowHiddenCellsButton.onclick = () => {
2135
+ this.headingCollapsed = false;
2136
+ };
2137
+ this.node.appendChild(newShowHiddenCellsButton);
2138
+ }
2139
+ let needToUpdateButtonText =
2140
+ this.headingCollapsed &&
2141
+ this._numberChildNodes > 0 &&
2142
+ showHiddenCellsButtonList.length == 1;
2143
+ if (needToUpdateButtonText) {
2144
+ showHiddenCellsButtonList[0].childNodes[1].textContent = buttonText;
2145
+ }
2146
+ let needToRemoveButton = !(
2147
+ this.headingCollapsed && this._numberChildNodes > 0
2148
+ );
2149
+ if (needToRemoveButton) {
2150
+ for (const button of showHiddenCellsButtonList) {
2151
+ this.node.removeChild(button);
2152
+ }
2153
+ }
2154
+ }
2155
+
2156
+ /**
2157
+ * Callback on content changed
2158
+ */
2159
+ protected onContentChanged(): void {
2160
+ super.onContentChanged();
2161
+ this._headingsCache = null;
2162
+ }
2163
+
2164
+ /**
2165
+ * Render the collapse button for heading cells,
2166
+ * and for collapsed heading cells render the "expand hidden cells"
2167
+ * button.
2168
+ */
2169
+ protected renderCollapseButtons(widget: Widget): void {
2170
+ this.node.classList.toggle(
2171
+ MARKDOWN_HEADING_COLLAPSED,
2172
+ this._headingCollapsed
2173
+ );
2174
+ this.maybeCreateCollapseButton();
2175
+ this.maybeCreateOrUpdateExpandButton();
2176
+ }
2177
+
2178
+ /**
2179
+ * Render an input instead of the text editor.
2180
+ */
2181
+ protected renderInput(widget: Widget): void {
2182
+ this.addClass(RENDERED_CLASS);
2183
+ if (!this.placeholder && !this.isDisposed) {
2184
+ this.renderCollapseButtons(widget);
2185
+ this.inputArea!.renderInput(widget);
2186
+ }
2187
+ }
2188
+
2189
+ /**
2190
+ * Show the text editor instead of rendered input.
2191
+ */
2192
+ protected showEditor(): void {
2193
+ this.removeClass(RENDERED_CLASS);
2194
+ if (!this.placeholder && !this.isDisposed) {
2195
+ this.inputArea!.showEditor();
2196
+ // if this is going to be a heading, place the cursor accordingly
2197
+ let numHashAtStart = (this.model.sharedModel
2198
+ .getSource()
2199
+ .match(/^#+/g) || [''])[0].length;
2200
+ if (numHashAtStart > 0) {
2201
+ this.inputArea!.editor.setCursorPosition({
2202
+ column: numHashAtStart + 1,
2203
+ line: 0
2204
+ });
2205
+ }
2206
+ }
2207
+ }
2208
+
2209
+ /*
2210
+ * Handle `update-request` messages.
2211
+ */
2212
+ protected onUpdateRequest(msg: Message): void {
2213
+ // Make sure we are properly rendered.
2214
+ this._handleRendered().catch(reason => {
2215
+ console.error('Failed to render', reason);
2216
+ });
2217
+ super.onUpdateRequest(msg);
2218
+ }
2219
+
2220
+ /**
2221
+ * Modify the cell source to include a reference to the attachment.
2222
+ */
2223
+ protected updateCellSourceWithAttachment(
2224
+ attachmentName: string,
2225
+ URI?: string
2226
+ ): void {
2227
+ const textToBeAppended = `![${attachmentName}](attachment:${
2228
+ URI ?? attachmentName
2229
+ })`;
2230
+ // TODO this should be done on the model...
2231
+ this.editor?.replaceSelection?.(textToBeAppended);
2232
+ }
2233
+
2234
+ /**
2235
+ * Handle the rendered state.
2236
+ */
2237
+ private async _handleRendered(): Promise<void> {
2238
+ if (!this._rendered) {
2239
+ this.showEditor();
2240
+ } else {
2241
+ // TODO: It would be nice for the cell to provide a way for
2242
+ // its consumers to hook into when the rendering is done.
2243
+ await this._updateRenderedInput();
2244
+ if (this._rendered) {
2245
+ // The rendered flag may be updated in the mean time
2246
+ this.renderInput(this._renderer);
2247
+ }
2248
+ }
2249
+ }
2250
+
2251
+ /**
2252
+ * Update the rendered input.
2253
+ */
2254
+ private _updateRenderedInput(): Promise<void> {
2255
+ if (this.placeholder) {
2256
+ return Promise.resolve();
2257
+ }
2258
+
2259
+ const model = this.model;
2260
+ const text =
2261
+ (model && model.sharedModel.getSource()) || DEFAULT_MARKDOWN_TEXT;
2262
+ // Do not re-render if the text has not changed.
2263
+ if (text !== this._prevText) {
2264
+ const mimeModel = new MimeModel({ data: { 'text/markdown': text } });
2265
+ this._prevText = text;
2266
+ return this._renderer.renderModel(mimeModel);
2267
+ }
2268
+ return Promise.resolve();
2269
+ }
2270
+
2271
+ /**
2272
+ * Clone the cell, using the same model.
2273
+ */
2274
+ clone(): MarkdownCell {
2275
+ const constructor = this.constructor as typeof MarkdownCell;
2276
+ return new constructor({
2277
+ model: this.model,
2278
+ contentFactory: this.contentFactory,
2279
+ rendermime: this._rendermime,
2280
+ placeholder: false,
2281
+ translator: this.translator
2282
+ });
2283
+ }
2284
+
2285
+ private _headingsCache: Cell.IHeading[] | null = null;
2286
+ private _headingCollapsed: boolean;
2287
+ private _headingCollapsedChanged = new Signal<MarkdownCell, boolean>(this);
2288
+ private _monitor: ActivityMonitor<ICellModel, void>;
2289
+ private _numberChildNodes: number;
2290
+ private _prevText = '';
2291
+ private _renderer: IRenderMime.IRenderer;
2292
+ private _rendermime: IRenderMimeRegistry;
2293
+ private _rendered = true;
2294
+ private _renderedChanged = new Signal<this, boolean>(this);
2295
+ private _showEditorForReadOnlyMarkdown = true;
2296
+ }
2297
+
2298
+ /**
2299
+ * The namespace for the `CodeCell` class statics.
2300
+ */
2301
+ export namespace MarkdownCell {
2302
+ /**
2303
+ * An options object for initializing a base cell widget.
2304
+ */
2305
+ export interface IOptions extends Cell.IOptions<IMarkdownCellModel> {
2306
+ /**
2307
+ * The mime renderer for the cell widget.
2308
+ */
2309
+ rendermime: IRenderMimeRegistry;
2310
+
2311
+ /**
2312
+ * Show editor for read-only Markdown cells.
2313
+ */
2314
+ showEditorForReadOnlyMarkdown?: boolean;
2315
+ }
2316
+
2317
+ /**
2318
+ * Default value for showEditorForReadOnlyMarkdown.
2319
+ */
2320
+ export const defaultShowEditorForReadOnlyMarkdown = true;
2321
+ }
2322
+
2323
+ /** ****************************************************************************
2324
+ * RawCell
2325
+ ******************************************************************************/
2326
+
2327
+ /**
2328
+ * A widget for a raw cell.
2329
+ */
2330
+ export class RawCell extends Cell<IRawCellModel> {
2331
+ /**
2332
+ * Construct a raw cell widget.
2333
+ */
2334
+ constructor(options: RawCell.IOptions) {
2335
+ super(options);
2336
+ this.addClass(RAW_CELL_CLASS);
2337
+ const trans = this.translator.load('jupyterlab');
2338
+ this.node.setAttribute('aria-label', trans.__('Raw Cell Content'));
2339
+ }
2340
+
2341
+ /**
2342
+ * Clone the cell, using the same model.
2343
+ */
2344
+ clone(): RawCell {
2345
+ const constructor = this.constructor as typeof RawCell;
2346
+ return new constructor({
2347
+ model: this.model,
2348
+ contentFactory: this.contentFactory,
2349
+ placeholder: false,
2350
+ translator: this.translator
2351
+ });
2352
+ }
2353
+ }
2354
+
2355
+ /**
2356
+ * The namespace for the `RawCell` class statics.
2357
+ */
2358
+ export namespace RawCell {
2359
+ /**
2360
+ * An options object for initializing a base cell widget.
2361
+ */
2362
+ export interface IOptions extends Cell.IOptions<IRawCellModel> {}
2363
+ }