@jupyterlab/cells 4.0.0-alpha.2 → 4.0.0-alpha.21

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