@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/lib/widget.js CHANGED
@@ -2,23 +2,25 @@
2
2
  | Copyright (c) Jupyter Development Team.
3
3
  | Distributed under the terms of the Modified BSD License.
4
4
  |----------------------------------------------------------------------------*/
5
- import { marked } from 'marked';
5
+ import { EditorView } from '@codemirror/view';
6
6
  import { AttachmentsResolver } from '@jupyterlab/attachments';
7
7
  import { ActivityMonitor, URLExt } from '@jupyterlab/coreutils';
8
8
  import { OutputArea, OutputPrompt, SimplifiedOutputArea, Stdin } from '@jupyterlab/outputarea';
9
9
  import { imageRendererFactory, MimeModel } from '@jupyterlab/rendermime';
10
+ import { TableOfContentsUtils } from '@jupyterlab/toc';
10
11
  import { nullTranslator } from '@jupyterlab/translation';
12
+ import { addIcon } from '@jupyterlab/ui-components';
11
13
  import { PromiseDelegate, UUID } from '@lumino/coreutils';
12
- import { filter, some, toArray } from '@lumino/algorithm';
14
+ import { some } from '@lumino/algorithm';
15
+ import { MessageLoop } from '@lumino/messaging';
13
16
  import { Debouncer } from '@lumino/polling';
17
+ import { Signal } from '@lumino/signaling';
14
18
  import { Panel, PanelLayout, Widget } from '@lumino/widgets';
15
19
  import { InputCollapser, OutputCollapser } from './collapser';
16
20
  import { CellFooter, CellHeader } from './headerfooter';
17
21
  import { InputArea, InputPrompt } from './inputarea';
18
22
  import { InputPlaceholder, OutputPlaceholder } from './placeholder';
19
23
  import { ResizeHandle } from './resizeHandle';
20
- import { Signal } from '@lumino/signaling';
21
- import { addIcon } from '@jupyterlab/ui-components';
22
24
  /**
23
25
  * The CSS class added to cell widgets.
24
26
  */
@@ -55,10 +57,6 @@ const CELL_INPUT_COLLAPSER_CLASS = 'jp-Cell-inputCollapser';
55
57
  * The CSS class added to the cell output collapser.
56
58
  */
57
59
  const CELL_OUTPUT_COLLAPSER_CLASS = 'jp-Cell-outputCollapser';
58
- /**
59
- * The class name added to the cell when readonly.
60
- */
61
- const READONLY_CLASS = 'jp-mod-readOnly';
62
60
  /**
63
61
  * The class name added to the cell when dirty.
64
62
  */
@@ -75,7 +73,7 @@ const MARKDOWN_CELL_CLASS = 'jp-MarkdownCell';
75
73
  * The class name added to rendered markdown output widgets.
76
74
  */
77
75
  const MARKDOWN_OUTPUT_CLASS = 'jp-MarkdownOutput';
78
- export const MARKDOWN_HEADING_COLLAPSED = 'jp-MarkdownHeadingCollapsed';
76
+ const MARKDOWN_HEADING_COLLAPSED = 'jp-MarkdownHeadingCollapsed';
79
77
  const HEADING_COLLAPSER_CLASS = 'jp-collapseHeadingButton';
80
78
  const SHOW_HIDDEN_CELLS_CLASS = 'jp-showHiddenCellsButton';
81
79
  /**
@@ -110,56 +108,31 @@ export class Cell extends Widget {
110
108
  * Construct a new base cell widget.
111
109
  */
112
110
  constructor(options) {
111
+ var _a, _b, _c, _d;
113
112
  super();
114
- /**
115
- * Signal to indicate that widget has changed visibly (in size, in type, etc)
116
- */
117
- this.displayChanged = new Signal(this);
118
- this._readOnly = false;
113
+ this.prompt = '';
114
+ this._displayChanged = new Signal(this);
115
+ this._editorConfig = {};
119
116
  this._inputHidden = false;
120
- this._syncCollapse = false;
121
- this._syncEditable = false;
117
+ this._inViewportChanged = new Signal(this);
118
+ this._readOnly = false;
119
+ this._ready = new PromiseDelegate();
122
120
  this._resizeDebouncer = new Debouncer(() => {
123
- this.displayChanged.emit();
121
+ this._displayChanged.emit();
124
122
  }, 0);
123
+ this._syncCollapse = false;
124
+ this._syncEditable = false;
125
125
  this.addClass(CELL_CLASS);
126
126
  const model = (this._model = options.model);
127
- const contentFactory = (this.contentFactory =
128
- options.contentFactory || Cell.defaultContentFactory);
129
- this.layout = new PanelLayout();
127
+ this.contentFactory = options.contentFactory;
128
+ this.layout = (_a = options.layout) !== null && _a !== void 0 ? _a : new PanelLayout();
130
129
  // Set up translator for aria labels
131
- this.translator = options.translator || nullTranslator;
132
- // Header
133
- const header = contentFactory.createCellHeader();
134
- header.addClass(CELL_HEADER_CLASS);
135
- this.layout.addWidget(header);
136
- // Input
137
- const inputWrapper = (this._inputWrapper = new Panel());
138
- inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
139
- const inputCollapser = new InputCollapser();
140
- inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
141
- const input = (this._input = new InputArea({
142
- model,
143
- contentFactory,
144
- updateOnShow: options.updateEditorOnShow,
145
- placeholder: options.placeholder
146
- }));
147
- input.addClass(CELL_INPUT_AREA_CLASS);
148
- inputWrapper.addWidget(inputCollapser);
149
- inputWrapper.addWidget(input);
150
- this.layout.addWidget(inputWrapper);
151
- this._inputPlaceholder = new InputPlaceholder(() => {
152
- this.inputHidden = !this.inputHidden;
153
- });
154
- // Footer
155
- const footer = this.contentFactory.createCellFooter();
156
- footer.addClass(CELL_FOOTER_CLASS);
157
- this.layout.addWidget(footer);
158
- // Editor settings
159
- if (options.editorConfig) {
160
- this.editor.setOptions(Object.assign({}, options.editorConfig));
161
- }
162
- model.metadata.changed.connect(this.onMetadataChanged, this);
130
+ this.translator = (_b = options.translator) !== null && _b !== void 0 ? _b : nullTranslator;
131
+ this._editorConfig = (_c = options.editorConfig) !== null && _c !== void 0 ? _c : {};
132
+ this._placeholder = true;
133
+ this._inViewport = false;
134
+ this.placeholder = (_d = options.placeholder) !== null && _d !== void 0 ? _d : true;
135
+ model.metadataChanged.connect(this.onMetadataChanged, this);
163
136
  }
164
137
  /**
165
138
  * Initialize view state from model.
@@ -173,10 +146,51 @@ export class Cell extends Widget {
173
146
  this.loadEditableState();
174
147
  return this;
175
148
  }
149
+ /**
150
+ * Signal to indicate that widget has changed visibly (in size, in type, etc)
151
+ */
152
+ get displayChanged() {
153
+ return this._displayChanged;
154
+ }
155
+ /**
156
+ * Whether the cell is in viewport or not.
157
+ */
158
+ get inViewport() {
159
+ return this._inViewport;
160
+ }
161
+ set inViewport(v) {
162
+ if (this._inViewport !== v) {
163
+ this._inViewport = v;
164
+ this._inViewportChanged.emit(this._inViewport);
165
+ }
166
+ }
167
+ /**
168
+ * Will emit true just after the node is attached to the DOM
169
+ * Will emit false just before the node is detached of the DOM
170
+ */
171
+ get inViewportChanged() {
172
+ return this._inViewportChanged;
173
+ }
174
+ /**
175
+ * Whether the cell is a placeholder not yet fully rendered or not.
176
+ */
177
+ get placeholder() {
178
+ return this._placeholder;
179
+ }
180
+ set placeholder(v) {
181
+ if (this._placeholder !== v && v === false) {
182
+ this.initializeDOM();
183
+ this._placeholder = v;
184
+ this._ready.resolve();
185
+ }
186
+ }
176
187
  /**
177
188
  * Get the prompt node used by the cell.
178
189
  */
179
190
  get promptNode() {
191
+ if (this.placeholder) {
192
+ return null;
193
+ }
180
194
  if (!this._inputHidden) {
181
195
  return this._input.promptNode;
182
196
  }
@@ -189,13 +203,27 @@ export class Cell extends Widget {
189
203
  * Get the CodeEditorWrapper used by the cell.
190
204
  */
191
205
  get editorWidget() {
192
- return this._input.editorWidget;
206
+ var _a, _b;
207
+ return (_b = (_a = this._input) === null || _a === void 0 ? void 0 : _a.editorWidget) !== null && _b !== void 0 ? _b : null;
193
208
  }
194
209
  /**
195
210
  * Get the CodeEditor used by the cell.
196
211
  */
197
212
  get editor() {
198
- return this._input.editor;
213
+ var _a, _b;
214
+ return (_b = (_a = this._input) === null || _a === void 0 ? void 0 : _a.editor) !== null && _b !== void 0 ? _b : null;
215
+ }
216
+ /**
217
+ * Editor configuration
218
+ */
219
+ get editorConfig() {
220
+ return this._editorConfig;
221
+ }
222
+ /**
223
+ * Cell headings
224
+ */
225
+ get headings() {
226
+ return new Array();
199
227
  }
200
228
  /**
201
229
  * Get the model used by the cell.
@@ -225,40 +253,54 @@ export class Cell extends Widget {
225
253
  }
226
254
  this.update();
227
255
  }
256
+ /**
257
+ * Whether the cell is a placeholder that defer rendering
258
+ *
259
+ * #### Notes
260
+ * You can wait for the promise `Cell.ready` to wait for the
261
+ * cell to be rendered.
262
+ */
263
+ isPlaceholder() {
264
+ return this.placeholder;
265
+ }
228
266
  /**
229
267
  * Save view editable state to model
230
268
  */
231
269
  saveEditableState() {
232
- const { metadata } = this.model;
233
- const current = metadata.get('editable');
270
+ const { sharedModel } = this.model;
271
+ const current = sharedModel.getMetadata('editable');
234
272
  if ((this.readOnly && current === false) ||
235
273
  (!this.readOnly && current === undefined)) {
236
274
  return;
237
275
  }
238
276
  if (this.readOnly) {
239
- this.model.metadata.set('editable', false);
277
+ sharedModel.setMetadata('editable', false);
240
278
  }
241
279
  else {
242
- this.model.metadata.delete('editable');
280
+ sharedModel.deleteMetadata('editable');
243
281
  }
244
282
  }
245
283
  /**
246
284
  * Load view editable state from model.
247
285
  */
248
286
  loadEditableState() {
249
- this.readOnly = this.model.metadata.get('editable') === false;
287
+ this.readOnly =
288
+ this.model.sharedModel.getMetadata('editable') ===
289
+ false;
250
290
  }
251
291
  /**
252
292
  * A promise that resolves when the widget renders for the first time.
253
293
  */
254
294
  get ready() {
255
- return Promise.resolve(undefined);
295
+ return this._ready.promise;
256
296
  }
257
297
  /**
258
298
  * Set the prompt for the widget.
259
299
  */
260
300
  setPrompt(value) {
261
- this._input.setPrompt(value);
301
+ var _a;
302
+ this.prompt = value;
303
+ (_a = this._input) === null || _a === void 0 ? void 0 : _a.setPrompt(value);
262
304
  }
263
305
  /**
264
306
  * The view state of input being hidden.
@@ -267,17 +309,25 @@ export class Cell extends Widget {
267
309
  return this._inputHidden;
268
310
  }
269
311
  set inputHidden(value) {
312
+ var _a;
270
313
  if (this._inputHidden === value) {
271
314
  return;
272
315
  }
273
- const layout = this._inputWrapper.layout;
274
- if (value) {
275
- this._input.parent = null;
276
- layout.addWidget(this._inputPlaceholder);
277
- }
278
- else {
279
- this._inputPlaceholder.parent = null;
280
- layout.addWidget(this._input);
316
+ if (!this.placeholder) {
317
+ const layout = this._inputWrapper.layout;
318
+ if (value) {
319
+ this._input.parent = null;
320
+ if (this._inputPlaceholder) {
321
+ this._inputPlaceholder.text = (_a = this.model.sharedModel
322
+ .getSource()
323
+ .split('\n')) === null || _a === void 0 ? void 0 : _a[0];
324
+ }
325
+ layout.addWidget(this._inputPlaceholder);
326
+ }
327
+ else {
328
+ this._inputPlaceholder.parent = null;
329
+ layout.addWidget(this._input);
330
+ }
281
331
  }
282
332
  this._inputHidden = value;
283
333
  if (this.syncCollapse) {
@@ -289,7 +339,7 @@ export class Cell extends Widget {
289
339
  * Save view collapse state to model
290
340
  */
291
341
  saveCollapseState() {
292
- const jupyter = Object.assign({}, this.model.metadata.get('jupyter'));
342
+ const jupyter = { ...this.model.getMetadata('jupyter') };
293
343
  if ((this.inputHidden && jupyter.source_hidden === true) ||
294
344
  (!this.inputHidden && jupyter.source_hidden === undefined)) {
295
345
  return;
@@ -301,17 +351,18 @@ export class Cell extends Widget {
301
351
  delete jupyter.source_hidden;
302
352
  }
303
353
  if (Object.keys(jupyter).length === 0) {
304
- this.model.metadata.delete('jupyter');
354
+ this.model.deleteMetadata('jupyter');
305
355
  }
306
356
  else {
307
- this.model.metadata.set('jupyter', jupyter);
357
+ this.model.setMetadata('jupyter', jupyter);
308
358
  }
309
359
  }
310
360
  /**
311
361
  * Revert view collapse state from model.
312
362
  */
313
363
  loadCollapseState() {
314
- const jupyter = this.model.metadata.get('jupyter') || {};
364
+ var _a;
365
+ const jupyter = (_a = this.model.getMetadata('jupyter')) !== null && _a !== void 0 ? _a : {};
315
366
  this.inputHidden = !!jupyter.source_hidden;
316
367
  }
317
368
  /**
@@ -375,12 +426,91 @@ export class Cell extends Widget {
375
426
  if (this.isDisposed) {
376
427
  return;
377
428
  }
429
+ this._resizeDebouncer.dispose();
378
430
  this._input = null;
379
431
  this._model = null;
380
432
  this._inputWrapper = null;
381
433
  this._inputPlaceholder = null;
382
434
  super.dispose();
383
435
  }
436
+ /**
437
+ * Update the editor configuration with the partial provided dictionary.
438
+ *
439
+ * @param v Partial editor configuration
440
+ */
441
+ updateEditorConfig(v) {
442
+ this._editorConfig = { ...this._editorConfig, ...v };
443
+ if (this.editor) {
444
+ this.editor.setOptions(this._editorConfig);
445
+ }
446
+ }
447
+ /**
448
+ * Create children widgets.
449
+ */
450
+ initializeDOM() {
451
+ if (!this.placeholder) {
452
+ return;
453
+ }
454
+ const contentFactory = this.contentFactory;
455
+ const model = this._model;
456
+ // Header
457
+ const header = contentFactory.createCellHeader();
458
+ header.addClass(CELL_HEADER_CLASS);
459
+ this.layout.addWidget(header);
460
+ // Input
461
+ const inputWrapper = (this._inputWrapper = new Panel());
462
+ inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
463
+ const inputCollapser = new InputCollapser();
464
+ inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
465
+ const input = (this._input = new InputArea({
466
+ model,
467
+ contentFactory,
468
+ editorOptions: this.getEditorOptions()
469
+ }));
470
+ input.addClass(CELL_INPUT_AREA_CLASS);
471
+ inputWrapper.addWidget(inputCollapser);
472
+ inputWrapper.addWidget(input);
473
+ this.layout.addWidget(inputWrapper);
474
+ this._inputPlaceholder = new InputPlaceholder({
475
+ callback: () => {
476
+ this.inputHidden = !this.inputHidden;
477
+ },
478
+ text: input.model.sharedModel.getSource().split('\n')[0],
479
+ translator: this.translator
480
+ });
481
+ input.model.contentChanged.connect((sender, args) => {
482
+ var _a;
483
+ if (this._inputPlaceholder && this.inputHidden) {
484
+ this._inputPlaceholder.text = (_a = sender.sharedModel
485
+ .getSource()
486
+ .split('\n')) === null || _a === void 0 ? void 0 : _a[0];
487
+ }
488
+ });
489
+ if (this.inputHidden) {
490
+ input.parent = null;
491
+ inputWrapper.layout.addWidget(this._inputPlaceholder);
492
+ }
493
+ // Footer
494
+ const footer = this.contentFactory.createCellFooter();
495
+ footer.addClass(CELL_FOOTER_CLASS);
496
+ this.layout.addWidget(footer);
497
+ }
498
+ /**
499
+ * Get the editor options at initialization.
500
+ *
501
+ * @returns Editor options
502
+ */
503
+ getEditorOptions() {
504
+ return { config: this.editorConfig };
505
+ }
506
+ /**
507
+ * Handle `before-attach` messages.
508
+ */
509
+ onBeforeAttach(msg) {
510
+ if (this.placeholder) {
511
+ this.placeholder = false;
512
+ }
513
+ }
384
514
  /**
385
515
  * Handle `after-attach` messages.
386
516
  */
@@ -391,14 +521,8 @@ export class Cell extends Widget {
391
521
  * Handle `'activate-request'` messages.
392
522
  */
393
523
  onActivateRequest(msg) {
394
- this.editor.focus();
395
- }
396
- /**
397
- * Handle `fit-request` messages.
398
- */
399
- onFitRequest(msg) {
400
- // need this for for when a theme changes font size
401
- this.editor.refresh();
524
+ var _a;
525
+ (_a = this.editor) === null || _a === void 0 ? void 0 : _a.focus();
402
526
  }
403
527
  /**
404
528
  * Handle `resize` messages.
@@ -410,13 +534,21 @@ export class Cell extends Widget {
410
534
  * Handle `update-request` messages.
411
535
  */
412
536
  onUpdateRequest(msg) {
537
+ var _a, _b;
413
538
  if (!this._model) {
414
539
  return;
415
540
  }
416
541
  // Handle read only state.
417
- if (this.editor.getOption('readOnly') !== this._readOnly) {
418
- this.editor.setOption('readOnly', this._readOnly);
419
- this.toggleClass(READONLY_CLASS, this._readOnly);
542
+ if (((_a = this.editor) === null || _a === void 0 ? void 0 : _a.getOption('readOnly')) !== this._readOnly) {
543
+ (_b = this.editor) === null || _b === void 0 ? void 0 : _b.setOption('readOnly', this._readOnly);
544
+ }
545
+ }
546
+ onContentChanged() {
547
+ var _a;
548
+ if (this.inputHidden && this._inputPlaceholder) {
549
+ this._inputPlaceholder.text = (_a = this.model.sharedModel
550
+ .getSource()
551
+ .split('\n')) === null || _a === void 0 ? void 0 : _a[0];
420
552
  }
421
553
  }
422
554
  /**
@@ -443,6 +575,20 @@ export class Cell extends Widget {
443
575
  * The namespace for the `Cell` class statics.
444
576
  */
445
577
  (function (Cell) {
578
+ /**
579
+ * Type of headings
580
+ */
581
+ let HeadingType;
582
+ (function (HeadingType) {
583
+ /**
584
+ * Heading from HTML output
585
+ */
586
+ HeadingType[HeadingType["HTML"] = 0] = "HTML";
587
+ /**
588
+ * Heading from Markdown cell or Markdown output
589
+ */
590
+ HeadingType[HeadingType["Markdown"] = 1] = "Markdown";
591
+ })(HeadingType = Cell.HeadingType || (Cell.HeadingType = {}));
446
592
  /**
447
593
  * The default implementation of an `IContentFactory`.
448
594
  *
@@ -452,9 +598,8 @@ export class Cell extends Widget {
452
598
  /**
453
599
  * Create a content factory for a cell.
454
600
  */
455
- constructor(options = {}) {
456
- this._editorFactory =
457
- options.editorFactory || InputArea.defaultEditorFactory;
601
+ constructor(options) {
602
+ this._editorFactory = options.editorFactory;
458
603
  }
459
604
  /**
460
605
  * The readonly editor factory that create code editors
@@ -494,14 +639,79 @@ export class Cell extends Widget {
494
639
  }
495
640
  }
496
641
  Cell.ContentFactory = ContentFactory;
497
- /**
498
- * The default content factory for cells.
499
- */
500
- Cell.defaultContentFactory = new ContentFactory();
501
642
  })(Cell || (Cell = {}));
502
643
  /** ****************************************************************************
503
644
  * CodeCell
504
645
  ******************************************************************************/
646
+ /**
647
+ * Code cell layout
648
+ *
649
+ * It will not detached the output area when the cell is detached.
650
+ */
651
+ export class CodeCellLayout extends PanelLayout {
652
+ /**
653
+ * A message handler invoked on a `'before-attach'` message.
654
+ *
655
+ * #### Notes
656
+ * The default implementation of this method forwards the message
657
+ * to all widgets. It assumes all widget nodes are attached to the
658
+ * parent widget node.
659
+ *
660
+ * This may be reimplemented by subclasses as needed.
661
+ */
662
+ onBeforeAttach(msg) {
663
+ let beforeOutputArea = true;
664
+ const outputAreaWrapper = this.parent.node.firstElementChild;
665
+ for (const widget of this) {
666
+ if (outputAreaWrapper) {
667
+ if (widget.node === outputAreaWrapper) {
668
+ beforeOutputArea = false;
669
+ }
670
+ else {
671
+ MessageLoop.sendMessage(widget, msg);
672
+ if (beforeOutputArea) {
673
+ this.parent.node.insertBefore(widget.node, outputAreaWrapper);
674
+ }
675
+ else {
676
+ this.parent.node.appendChild(widget.node);
677
+ }
678
+ // Force setting isVisible to true as it requires the parent widget to be
679
+ // visible. But that flag will be set only during the `onAfterAttach` call.
680
+ if (!this.parent.isHidden) {
681
+ widget.setFlag(Widget.Flag.IsVisible);
682
+ }
683
+ // Not called in NotebookWindowedLayout to avoid outputArea
684
+ // widgets unwanted update or reset.
685
+ MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);
686
+ }
687
+ }
688
+ }
689
+ }
690
+ /**
691
+ * A message handler invoked on an `'after-detach'` message.
692
+ *
693
+ * #### Notes
694
+ * The default implementation of this method forwards the message
695
+ * to all widgets. It assumes all widget nodes are attached to the
696
+ * parent widget node.
697
+ *
698
+ * This may be reimplemented by subclasses as needed.
699
+ */
700
+ onAfterDetach(msg) {
701
+ for (const widget of this) {
702
+ // TODO we could improve this further by removing outputs based
703
+ // on their mime type (for example plain/text or markdown could safely be detached)
704
+ // If the cell is out of the view port, its children are already detached -> skip detaching
705
+ if (!widget.hasClass(CELL_OUTPUT_WRAPPER_CLASS) &&
706
+ widget.node.isConnected) {
707
+ // Not called in NotebookWindowedLayout for windowed notebook
708
+ MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);
709
+ this.parent.node.removeChild(widget.node);
710
+ MessageLoop.sendMessage(widget, msg);
711
+ }
712
+ }
713
+ }
714
+ }
505
715
  /**
506
716
  * A widget for a code cell.
507
717
  */
@@ -510,56 +720,126 @@ export class CodeCell extends Cell {
510
720
  * Construct a code cell widget.
511
721
  */
512
722
  constructor(options) {
513
- super(options);
723
+ var _a;
724
+ super({ layout: new CodeCellLayout(), ...options, placeholder: true });
725
+ this._headingsCache = null;
514
726
  this._outputHidden = false;
727
+ this._outputWrapper = null;
728
+ this._outputPlaceholder = null;
515
729
  this._syncScrolled = false;
516
- this._savingMetadata = false;
517
730
  this.addClass(CODE_CELL_CLASS);
518
731
  const trans = this.translator.load('jupyterlab');
519
732
  // Only save options not handled by parent constructor.
520
733
  const rendermime = (this._rendermime = options.rendermime);
521
734
  const contentFactory = this.contentFactory;
522
735
  const model = this.model;
736
+ this.maxNumberOutputs = options.maxNumberOutputs;
523
737
  // Note that modifying the below label warrants one to also modify
524
738
  // the same in this._outputLengthHandler. Ideally, this label must
525
739
  // have been a constant and used in both places but it is not done
526
740
  // so because of limitations in the translation manager.
527
- let ariaLabel = trans.__('Code Cell Content with Output');
528
- if (!options.placeholder) {
529
- // Insert the output before the cell footer.
530
- const outputWrapper = (this._outputWrapper = new Panel());
531
- outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
532
- const outputCollapser = new OutputCollapser();
533
- outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
534
- const output = (this._output = new OutputArea({
535
- model: model.outputs,
536
- rendermime,
537
- contentFactory: contentFactory,
538
- maxNumberOutputs: options.maxNumberOutputs
539
- }));
540
- output.addClass(CELL_OUTPUT_AREA_CLASS);
541
- // Set a CSS if there are no outputs, and connect a signal for future
542
- // changes to the number of outputs. This is for conditional styling
543
- // if there are no outputs.
544
- if (model.outputs.length === 0) {
545
- this.addClass(NO_OUTPUTS_CLASS);
546
- ariaLabel = trans.__('Code Cell Content');
547
- }
548
- output.outputLengthChanged.connect(this._outputLengthHandler, this);
549
- outputWrapper.addWidget(outputCollapser);
550
- outputWrapper.addWidget(output);
551
- this.layout.insertWidget(2, new ResizeHandle(this.node));
552
- this.layout.insertWidget(3, outputWrapper);
553
- if (model.isDirty) {
554
- this.addClass(DIRTY_CLASS);
555
- }
556
- this._outputPlaceholder = new OutputPlaceholder(() => {
741
+ const ariaLabel = model.outputs.length === 0
742
+ ? trans.__('Code Cell Content')
743
+ : trans.__('Code Cell Content with Output');
744
+ this.node.setAttribute('aria-label', ariaLabel);
745
+ const output = (this._output = new OutputArea({
746
+ model: this.model.outputs,
747
+ rendermime,
748
+ contentFactory: contentFactory,
749
+ maxNumberOutputs: this.maxNumberOutputs,
750
+ translator: this.translator,
751
+ promptOverlay: true,
752
+ inputHistoryScope: options.inputHistoryScope
753
+ }));
754
+ output.addClass(CELL_OUTPUT_AREA_CLASS);
755
+ output.toggleScrolling.connect(() => {
756
+ this.outputsScrolled = !this.outputsScrolled;
757
+ });
758
+ // Defer setting placeholder as OutputArea must be instantiated before initializing the DOM
759
+ this.placeholder = (_a = options.placeholder) !== null && _a !== void 0 ? _a : true;
760
+ model.outputs.changed.connect(this.onOutputChanged, this);
761
+ model.outputs.stateChanged.connect(this.onOutputChanged, this);
762
+ model.stateChanged.connect(this.onStateChanged, this);
763
+ }
764
+ /**
765
+ * Create children widgets.
766
+ */
767
+ initializeDOM() {
768
+ if (!this.placeholder) {
769
+ return;
770
+ }
771
+ super.initializeDOM();
772
+ this.setPrompt(this.prompt);
773
+ // Insert the output before the cell footer.
774
+ const outputWrapper = (this._outputWrapper = new Panel());
775
+ outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
776
+ const outputCollapser = new OutputCollapser();
777
+ outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
778
+ outputWrapper.addWidget(outputCollapser);
779
+ // Set a CSS if there are no outputs, and connect a signal for future
780
+ // changes to the number of outputs. This is for conditional styling
781
+ // if there are no outputs.
782
+ if (this.model.outputs.length === 0) {
783
+ this.addClass(NO_OUTPUTS_CLASS);
784
+ }
785
+ this._output.outputLengthChanged.connect(this._outputLengthHandler, this);
786
+ outputWrapper.addWidget(this._output);
787
+ const layout = this.layout;
788
+ layout.insertWidget(layout.widgets.length - 1, new ResizeHandle(this.node));
789
+ layout.insertWidget(layout.widgets.length - 1, outputWrapper);
790
+ if (this.model.isDirty) {
791
+ this.addClass(DIRTY_CLASS);
792
+ }
793
+ this._outputPlaceholder = new OutputPlaceholder({
794
+ callback: () => {
557
795
  this.outputHidden = !this.outputHidden;
558
- });
796
+ },
797
+ text: this.getOutputPlaceholderText(),
798
+ translator: this.translator
799
+ });
800
+ const layoutWrapper = outputWrapper.layout;
801
+ if (this.outputHidden) {
802
+ layoutWrapper.removeWidget(this._output);
803
+ layoutWrapper.addWidget(this._outputPlaceholder);
804
+ if (this.inputHidden && !outputWrapper.isHidden) {
805
+ this._outputWrapper.hide();
806
+ }
559
807
  }
560
- model.stateChanged.connect(this.onStateChanged, this);
808
+ const trans = this.translator.load('jupyterlab');
809
+ const ariaLabel = this.model.outputs.length === 0
810
+ ? trans.__('Code Cell Content')
811
+ : trans.__('Code Cell Content with Output');
561
812
  this.node.setAttribute('aria-label', ariaLabel);
562
813
  }
814
+ getOutputPlaceholderText() {
815
+ var _a;
816
+ const firstOutput = this.model.outputs.get(0);
817
+ const outputData = firstOutput === null || firstOutput === void 0 ? void 0 : firstOutput.data;
818
+ if (!outputData) {
819
+ return undefined;
820
+ }
821
+ const supportedOutputTypes = [
822
+ 'text/html',
823
+ 'image/svg+xml',
824
+ 'application/pdf',
825
+ 'text/markdown',
826
+ 'text/plain',
827
+ 'application/vnd.jupyter.stderr',
828
+ 'application/vnd.jupyter.stdout',
829
+ 'text'
830
+ ];
831
+ const preferredOutput = supportedOutputTypes.find(mt => {
832
+ const data = firstOutput.data[mt];
833
+ return (Array.isArray(data) ? typeof data[0] : typeof data) === 'string';
834
+ });
835
+ const dataToDisplay = firstOutput.data[preferredOutput !== null && preferredOutput !== void 0 ? preferredOutput : ''];
836
+ if (dataToDisplay !== undefined) {
837
+ return (_a = (Array.isArray(dataToDisplay)
838
+ ? dataToDisplay
839
+ : dataToDisplay === null || dataToDisplay === void 0 ? void 0 : dataToDisplay.split('\n'))) === null || _a === void 0 ? void 0 : _a.find(part => part !== '');
840
+ }
841
+ return undefined;
842
+ }
563
843
  /**
564
844
  * Initialize view state from model.
565
845
  *
@@ -573,6 +853,47 @@ export class CodeCell extends Cell {
573
853
  this.setPrompt(`${this.model.executionCount || ''}`);
574
854
  return this;
575
855
  }
856
+ get headings() {
857
+ if (!this._headingsCache) {
858
+ const headings = [];
859
+ // Iterate over the code cell outputs to check for Markdown or HTML from which we can generate ToC headings...
860
+ const outputs = this.model.outputs;
861
+ for (let j = 0; j < outputs.length; j++) {
862
+ const m = outputs.get(j);
863
+ let htmlType = null;
864
+ let mdType = null;
865
+ Object.keys(m.data).forEach(t => {
866
+ if (!mdType && TableOfContentsUtils.Markdown.isMarkdown(t)) {
867
+ mdType = t;
868
+ }
869
+ else if (!htmlType && TableOfContentsUtils.isHTML(t)) {
870
+ htmlType = t;
871
+ }
872
+ });
873
+ // Parse HTML output
874
+ if (htmlType) {
875
+ headings.push(...TableOfContentsUtils.getHTMLHeadings(this._rendermime.sanitizer.sanitize(m.data[htmlType])).map(heading => {
876
+ return {
877
+ ...heading,
878
+ outputIndex: j,
879
+ type: Cell.HeadingType.HTML
880
+ };
881
+ }));
882
+ }
883
+ else if (mdType) {
884
+ headings.push(...TableOfContentsUtils.Markdown.getHeadings(m.data[mdType]).map(heading => {
885
+ return {
886
+ ...heading,
887
+ outputIndex: j,
888
+ type: Cell.HeadingType.Markdown
889
+ };
890
+ }));
891
+ }
892
+ }
893
+ this._headingsCache = headings;
894
+ }
895
+ return [...this._headingsCache];
896
+ }
576
897
  /**
577
898
  * Get the output area for the cell.
578
899
  */
@@ -586,23 +907,29 @@ export class CodeCell extends Cell {
586
907
  return this._outputHidden;
587
908
  }
588
909
  set outputHidden(value) {
910
+ var _a;
589
911
  if (this._outputHidden === value) {
590
912
  return;
591
913
  }
592
- const layout = this._outputWrapper.layout;
593
- if (value) {
594
- layout.removeWidget(this._output);
595
- layout.addWidget(this._outputPlaceholder);
596
- if (this.inputHidden && !this._outputWrapper.isHidden) {
597
- this._outputWrapper.hide();
914
+ if (!this.placeholder) {
915
+ const layout = this._outputWrapper.layout;
916
+ if (value) {
917
+ layout.removeWidget(this._output);
918
+ layout.addWidget(this._outputPlaceholder);
919
+ if (this.inputHidden && !this._outputWrapper.isHidden) {
920
+ this._outputWrapper.hide();
921
+ }
922
+ if (this._outputPlaceholder) {
923
+ this._outputPlaceholder.text = (_a = this.getOutputPlaceholderText()) !== null && _a !== void 0 ? _a : '';
924
+ }
598
925
  }
599
- }
600
- else {
601
- if (this._outputWrapper.isHidden) {
602
- this._outputWrapper.show();
926
+ else {
927
+ if (this._outputWrapper.isHidden) {
928
+ this._outputWrapper.show();
929
+ }
930
+ layout.removeWidget(this._outputPlaceholder);
931
+ layout.addWidget(this._output);
603
932
  }
604
- layout.removeWidget(this._outputPlaceholder);
605
- layout.addWidget(this._output);
606
933
  }
607
934
  this._outputHidden = value;
608
935
  if (this.syncCollapse) {
@@ -618,11 +945,9 @@ export class CodeCell extends Cell {
618
945
  // to changes in metadata until we have fully committed our changes.
619
946
  // Otherwise setting one key can trigger a write to the other key to
620
947
  // maintain the synced consistency.
621
- this._savingMetadata = true;
622
- try {
948
+ this.model.sharedModel.transact(() => {
623
949
  super.saveCollapseState();
624
- const metadata = this.model.metadata;
625
- const collapsed = this.model.metadata.get('collapsed');
950
+ const collapsed = this.model.getMetadata('collapsed');
626
951
  if ((this.outputHidden && collapsed === true) ||
627
952
  (!this.outputHidden && collapsed === undefined)) {
628
953
  return;
@@ -630,15 +955,12 @@ export class CodeCell extends Cell {
630
955
  // Do not set jupyter.outputs_hidden since it is redundant. See
631
956
  // and https://github.com/jupyter/nbformat/issues/137
632
957
  if (this.outputHidden) {
633
- metadata.set('collapsed', true);
958
+ this.model.setMetadata('collapsed', true);
634
959
  }
635
960
  else {
636
- metadata.delete('collapsed');
961
+ this.model.deleteMetadata('collapsed');
637
962
  }
638
- }
639
- finally {
640
- this._savingMetadata = false;
641
- }
963
+ }, false);
642
964
  }
643
965
  /**
644
966
  * Revert view collapse state from model.
@@ -648,7 +970,7 @@ export class CodeCell extends Cell {
648
970
  */
649
971
  loadCollapseState() {
650
972
  super.loadCollapseState();
651
- this.outputHidden = !!this.model.metadata.get('collapsed');
973
+ this.outputHidden = !!this.model.getMetadata('collapsed');
652
974
  }
653
975
  /**
654
976
  * Whether the output is in a scrolled state?
@@ -667,30 +989,28 @@ export class CodeCell extends Cell {
667
989
  * Save view collapse state to model
668
990
  */
669
991
  saveScrolledState() {
670
- const { metadata } = this.model;
671
- const current = metadata.get('scrolled');
992
+ const current = this.model.getMetadata('scrolled');
672
993
  if ((this.outputsScrolled && current === true) ||
673
994
  (!this.outputsScrolled && current === undefined)) {
674
995
  return;
675
996
  }
676
997
  if (this.outputsScrolled) {
677
- metadata.set('scrolled', true);
998
+ this.model.setMetadata('scrolled', true);
678
999
  }
679
1000
  else {
680
- metadata.delete('scrolled');
1001
+ this.model.deleteMetadata('scrolled');
681
1002
  }
682
1003
  }
683
1004
  /**
684
1005
  * Revert view collapse state from model.
685
1006
  */
686
1007
  loadScrolledState() {
687
- const metadata = this.model.metadata;
688
1008
  // We don't have the notion of 'auto' scrolled, so we make it false.
689
- if (metadata.get('scrolled') === 'auto') {
1009
+ if (this.model.getMetadata('scrolled') === 'auto') {
690
1010
  this.outputsScrolled = false;
691
1011
  }
692
1012
  else {
693
- this.outputsScrolled = !!metadata.get('scrolled');
1013
+ this.outputsScrolled = !!this.model.getMetadata('scrolled');
694
1014
  }
695
1015
  }
696
1016
  /**
@@ -717,6 +1037,9 @@ export class CodeCell extends Cell {
717
1037
  * is hidden without accessing private state.
718
1038
  */
719
1039
  handleInputHidden(value) {
1040
+ if (this.placeholder) {
1041
+ return;
1042
+ }
720
1043
  if (!value && this._outputWrapper.isHidden) {
721
1044
  this._outputWrapper.show();
722
1045
  }
@@ -781,14 +1104,20 @@ export class CodeCell extends Cell {
781
1104
  break;
782
1105
  }
783
1106
  }
1107
+ /**
1108
+ * Callback on output changes
1109
+ */
1110
+ onOutputChanged() {
1111
+ var _a;
1112
+ this._headingsCache = null;
1113
+ if (this._outputPlaceholder && this.outputHidden) {
1114
+ this._outputPlaceholder.text = (_a = this.getOutputPlaceholderText()) !== null && _a !== void 0 ? _a : '';
1115
+ }
1116
+ }
784
1117
  /**
785
1118
  * Handle changes in the metadata.
786
1119
  */
787
1120
  onMetadataChanged(model, args) {
788
- if (this._savingMetadata) {
789
- // We are in middle of a metadata transaction, so don't react to it.
790
- return;
791
- }
792
1121
  switch (args.key) {
793
1122
  case 'scrolled':
794
1123
  if (this.syncScrolled) {
@@ -828,16 +1157,24 @@ export class CodeCell extends Cell {
828
1157
  async function execute(cell, sessionContext, metadata) {
829
1158
  var _a;
830
1159
  const model = cell.model;
831
- const code = model.value.text;
1160
+ const code = model.sharedModel.getSource();
832
1161
  if (!code.trim() || !((_a = sessionContext.session) === null || _a === void 0 ? void 0 : _a.kernel)) {
833
- model.clearExecution();
1162
+ model.sharedModel.transact(() => {
1163
+ model.clearExecution();
1164
+ }, false);
834
1165
  return;
835
1166
  }
836
- const cellId = { cellId: model.id };
837
- metadata = Object.assign(Object.assign(Object.assign({}, model.metadata.toJSON()), metadata), cellId);
1167
+ const cellId = { cellId: model.sharedModel.getId() };
1168
+ metadata = {
1169
+ ...model.metadata,
1170
+ ...metadata,
1171
+ ...cellId
1172
+ };
838
1173
  const { recordTiming } = metadata;
839
- model.clearExecution();
840
- cell.outputHidden = false;
1174
+ model.sharedModel.transact(() => {
1175
+ model.clearExecution();
1176
+ cell.outputHidden = false;
1177
+ }, false);
841
1178
  cell.setPrompt('*');
842
1179
  model.trusted = true;
843
1180
  let future;
@@ -860,22 +1197,22 @@ export class CodeCell extends Cell {
860
1197
  // If the data is missing, estimate it to now
861
1198
  // Date was added in 5.1: https://jupyter-client.readthedocs.io/en/stable/messaging.html#message-header
862
1199
  const value = msg.header.date || new Date().toISOString();
863
- const timingInfo = Object.assign({}, model.metadata.get('execution'));
1200
+ const timingInfo = Object.assign({}, model.getMetadata('execution'));
864
1201
  timingInfo[`iopub.${label}`] = value;
865
- model.metadata.set('execution', timingInfo);
1202
+ model.setMetadata('execution', timingInfo);
866
1203
  return true;
867
1204
  };
868
1205
  cell.outputArea.future.registerMessageHook(recordTimingHook);
869
1206
  }
870
1207
  else {
871
- model.metadata.delete('execution');
1208
+ model.deleteMetadata('execution');
872
1209
  }
873
1210
  // Save this execution's future so we can compare in the catch below.
874
1211
  future = cell.outputArea.future;
875
1212
  const msg = (await msgPromise);
876
1213
  model.executionCount = msg.content.execution_count;
877
1214
  if (recordTiming) {
878
- const timingInfo = Object.assign({}, model.metadata.get('execution'));
1215
+ const timingInfo = Object.assign({}, model.getMetadata('execution'));
879
1216
  const started = msg.metadata.started;
880
1217
  // Started is not in the API, but metadata IPyKernel sends
881
1218
  if (started) {
@@ -885,7 +1222,7 @@ export class CodeCell extends Cell {
885
1222
  const finished = msg.header.date;
886
1223
  timingInfo['shell.execute_reply'] =
887
1224
  finished || new Date().toISOString();
888
- model.metadata.set('execution', timingInfo);
1225
+ model.setMetadata('execution', timingInfo);
889
1226
  }
890
1227
  return msg;
891
1228
  }
@@ -917,18 +1254,6 @@ export class AttachmentsCell extends Cell {
917
1254
  */
918
1255
  handleEvent(event) {
919
1256
  switch (event.type) {
920
- case 'paste':
921
- this._evtPaste(event);
922
- break;
923
- case 'dragenter':
924
- event.preventDefault();
925
- break;
926
- case 'dragover':
927
- event.preventDefault();
928
- break;
929
- case 'drop':
930
- this._evtNativeDrop(event);
931
- break;
932
1257
  case 'lm-dragover':
933
1258
  this._evtDragOver(event);
934
1259
  break;
@@ -939,6 +1264,33 @@ export class AttachmentsCell extends Cell {
939
1264
  break;
940
1265
  }
941
1266
  }
1267
+ /**
1268
+ * Get the editor options at initialization.
1269
+ *
1270
+ * @returns Editor options
1271
+ */
1272
+ getEditorOptions() {
1273
+ var _a, _b;
1274
+ const base = (_a = super.getEditorOptions()) !== null && _a !== void 0 ? _a : {};
1275
+ base.extensions = [
1276
+ ...((_b = base.extensions) !== null && _b !== void 0 ? _b : []),
1277
+ EditorView.domEventHandlers({
1278
+ dragenter: (event) => {
1279
+ event.preventDefault();
1280
+ },
1281
+ dragover: (event) => {
1282
+ event.preventDefault();
1283
+ },
1284
+ drop: (event) => {
1285
+ this._evtNativeDrop(event);
1286
+ },
1287
+ paste: (event) => {
1288
+ this._evtPaste(event);
1289
+ }
1290
+ })
1291
+ ];
1292
+ return base;
1293
+ }
942
1294
  /**
943
1295
  * Handle `after-attach` messages for the widget.
944
1296
  */
@@ -947,10 +1299,6 @@ export class AttachmentsCell extends Cell {
947
1299
  const node = this.node;
948
1300
  node.addEventListener('lm-dragover', this);
949
1301
  node.addEventListener('lm-drop', this);
950
- node.addEventListener('dragenter', this);
951
- node.addEventListener('dragover', this);
952
- node.addEventListener('drop', this);
953
- node.addEventListener('paste', this);
954
1302
  }
955
1303
  /**
956
1304
  * A message handler invoked on a `'before-detach'`
@@ -958,12 +1306,9 @@ export class AttachmentsCell extends Cell {
958
1306
  */
959
1307
  onBeforeDetach(msg) {
960
1308
  const node = this.node;
961
- node.removeEventListener('drop', this);
962
- node.removeEventListener('dragover', this);
963
- node.removeEventListener('dragenter', this);
964
- node.removeEventListener('paste', this);
965
1309
  node.removeEventListener('lm-dragover', this);
966
1310
  node.removeEventListener('lm-drop', this);
1311
+ super.onBeforeDetach(msg);
967
1312
  }
968
1313
  _evtDragOver(event) {
969
1314
  const supportedMimeType = some(imageRendererFactory.mimeTypes, mimeType => {
@@ -1015,13 +1360,13 @@ export class AttachmentsCell extends Cell {
1015
1360
  * Handle the `'lm-drop'` event for the widget.
1016
1361
  */
1017
1362
  _evtDrop(event) {
1018
- const supportedMimeTypes = toArray(filter(event.mimeData.types(), mimeType => {
1363
+ const supportedMimeTypes = event.mimeData.types().filter(mimeType => {
1019
1364
  if (mimeType === CONTENTS_MIME_RICH) {
1020
1365
  const data = event.mimeData.getData(CONTENTS_MIME_RICH);
1021
1366
  return (imageRendererFactory.mimeTypes.indexOf(data.model.mimetype) !== -1);
1022
1367
  }
1023
1368
  return imageRendererFactory.mimeTypes.indexOf(mimeType) !== -1;
1024
- }));
1369
+ });
1025
1370
  if (supportedMimeTypes.length === 0) {
1026
1371
  return;
1027
1372
  }
@@ -1128,15 +1473,16 @@ export class MarkdownCell extends AttachmentsCell {
1128
1473
  * Construct a Markdown cell widget.
1129
1474
  */
1130
1475
  constructor(options) {
1131
- var _a, _b, _c;
1132
- super(options);
1133
- this._toggleCollapsedSignal = new Signal(this);
1134
- this._renderer = null;
1135
- this._rendered = true;
1476
+ var _a, _b, _c, _d;
1477
+ super({ ...options, placeholder: true });
1478
+ this._headingsCache = null;
1479
+ this._headingCollapsedChanged = new Signal(this);
1136
1480
  this._prevText = '';
1137
- this._ready = new PromiseDelegate();
1481
+ this._rendered = true;
1482
+ this._renderedChanged = new Signal(this);
1138
1483
  this._showEditorForReadOnlyMarkdown = true;
1139
1484
  this.addClass(MARKDOWN_CELL_CLASS);
1485
+ this.model.contentChanged.connect(this.onContentChanged, this);
1140
1486
  const trans = this.translator.load('jupyterlab');
1141
1487
  this.node.setAttribute('aria-label', trans.__('Markdown Cell Content'));
1142
1488
  // Ensure we can resolve attachments:
@@ -1146,78 +1492,93 @@ export class MarkdownCell extends AttachmentsCell {
1146
1492
  model: this.model.attachments
1147
1493
  })
1148
1494
  });
1149
- // Stop codemirror handling paste
1150
- this.editor.setOption('handlePaste', false);
1495
+ this._renderer = this._rendermime.createRenderer('text/markdown');
1496
+ this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1151
1497
  // Check if heading cell is set to be collapsed
1152
- this._headingCollapsed = ((_b = this.model.metadata.get(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1153
- // Throttle the rendering rate of the widget.
1498
+ this._headingCollapsed = ((_b = this.model.getMetadata(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1499
+ this._showEditorForReadOnlyMarkdown =
1500
+ (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1501
+ // Defer setting placeholder as the renderer must be instantiated before initializing the DOM
1502
+ this.placeholder = (_d = options.placeholder) !== null && _d !== void 0 ? _d : true;
1154
1503
  this._monitor = new ActivityMonitor({
1155
1504
  signal: this.model.contentChanged,
1156
1505
  timeout: RENDER_TIMEOUT
1157
1506
  });
1158
- this._monitor.activityStopped.connect(() => {
1159
- if (this._rendered) {
1160
- this.update();
1507
+ // Throttle the rendering rate of the widget.
1508
+ this.ready
1509
+ .then(() => {
1510
+ if (this.isDisposed) {
1511
+ // Bail early
1512
+ return;
1161
1513
  }
1162
- }, this);
1163
- void this._updateRenderedInput().then(() => {
1164
- this._ready.resolve(void 0);
1514
+ this._monitor.activityStopped.connect(() => {
1515
+ if (this._rendered) {
1516
+ this.update();
1517
+ }
1518
+ }, this);
1519
+ })
1520
+ .catch(reason => {
1521
+ console.error('Failed to be ready', reason);
1165
1522
  });
1166
- this.renderCollapseButtons(this._renderer);
1167
- this.renderInput(this._renderer);
1168
- this._showEditorForReadOnlyMarkdown =
1169
- (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1170
1523
  }
1171
1524
  /**
1172
- * A promise that resolves when the widget renders for the first time.
1173
- */
1174
- get ready() {
1175
- return this._ready.promise;
1176
- }
1177
- /**
1178
- * Text that represents the heading if cell is a heading.
1525
+ * Text that represents the highest heading (i.e. lowest level) if cell is a heading.
1179
1526
  * Returns empty string if not a heading.
1180
1527
  */
1181
1528
  get headingInfo() {
1182
- let text = this.model.value.text;
1183
- const lines = marked.lexer(text);
1184
- let line;
1185
- for (line of lines) {
1186
- if (line.type === 'heading') {
1187
- return { text: line.text, level: line.depth };
1188
- }
1189
- else if (line.type === 'html') {
1190
- let match = line.raw.match(/<h([1-6])(.*?)>(.*?)<\/h\1>/);
1191
- if (match === null || match === void 0 ? void 0 : match[3]) {
1192
- return { text: match[3], level: parseInt(match[1]) };
1193
- }
1194
- return { text: '', level: -1 };
1195
- }
1529
+ // Use table of content algorithm for consistency
1530
+ const headings = this.headings;
1531
+ if (headings.length > 0) {
1532
+ // Return the highest level
1533
+ const { text, level } = headings.reduce((prev, curr) => (prev.level <= curr.level ? prev : curr), headings[0]);
1534
+ return { text, level };
1535
+ }
1536
+ else {
1537
+ return { text: '', level: -1 };
1196
1538
  }
1197
- return { text: '', level: -1 };
1198
1539
  }
1540
+ get headings() {
1541
+ if (!this._headingsCache) {
1542
+ // Use table of content algorithm for consistency
1543
+ const headings = TableOfContentsUtils.Markdown.getHeadings(this.model.sharedModel.getSource());
1544
+ this._headingsCache = headings.map(h => {
1545
+ return { ...h, type: Cell.HeadingType.Markdown };
1546
+ });
1547
+ }
1548
+ return [...this._headingsCache];
1549
+ }
1550
+ /**
1551
+ * Whether the heading is collapsed or not.
1552
+ */
1199
1553
  get headingCollapsed() {
1200
1554
  return this._headingCollapsed;
1201
1555
  }
1202
1556
  set headingCollapsed(value) {
1203
- this._headingCollapsed = value;
1204
- if (value) {
1205
- this.model.metadata.set(MARKDOWN_HEADING_COLLAPSED, value);
1206
- }
1207
- else if (this.model.metadata.has(MARKDOWN_HEADING_COLLAPSED)) {
1208
- this.model.metadata.delete(MARKDOWN_HEADING_COLLAPSED);
1209
- }
1210
- const collapseButton = this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1211
- if (collapseButton) {
1557
+ var _a;
1558
+ if (this._headingCollapsed !== value) {
1559
+ this._headingCollapsed = value;
1212
1560
  if (value) {
1213
- collapseButton.classList.add('jp-mod-collapsed');
1561
+ this.model.setMetadata(MARKDOWN_HEADING_COLLAPSED, value);
1214
1562
  }
1215
- else {
1216
- collapseButton.classList.remove('jp-mod-collapsed');
1563
+ else if (this.model.getMetadata(MARKDOWN_HEADING_COLLAPSED) !== 'undefined') {
1564
+ this.model.deleteMetadata(MARKDOWN_HEADING_COLLAPSED);
1565
+ }
1566
+ const collapseButton = (_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1567
+ if (collapseButton) {
1568
+ if (value) {
1569
+ collapseButton.classList.add('jp-mod-collapsed');
1570
+ }
1571
+ else {
1572
+ collapseButton.classList.remove('jp-mod-collapsed');
1573
+ }
1217
1574
  }
1575
+ this.renderCollapseButtons(this._renderer);
1576
+ this._headingCollapsedChanged.emit(this._headingCollapsed);
1218
1577
  }
1219
- this.renderCollapseButtons(this._renderer);
1220
1578
  }
1579
+ /**
1580
+ * Number of collapsed sub cells.
1581
+ */
1221
1582
  get numberChildNodes() {
1222
1583
  return this._numberChildNodes;
1223
1584
  }
@@ -1225,8 +1586,11 @@ export class MarkdownCell extends AttachmentsCell {
1225
1586
  this._numberChildNodes = value;
1226
1587
  this.renderCollapseButtons(this._renderer);
1227
1588
  }
1228
- get toggleCollapsedSignal() {
1229
- return this._toggleCollapsedSignal;
1589
+ /**
1590
+ * Signal emitted when the cell collapsed state changes.
1591
+ */
1592
+ get headingCollapsedChanged() {
1593
+ return this._headingCollapsedChanged;
1230
1594
  }
1231
1595
  /**
1232
1596
  * Whether the cell is rendered.
@@ -1235,7 +1599,6 @@ export class MarkdownCell extends AttachmentsCell {
1235
1599
  return this._rendered;
1236
1600
  }
1237
1601
  set rendered(value) {
1238
- const oldValue = this._rendered;
1239
1602
  // Show cell as rendered when cell is not editable
1240
1603
  if (this.readOnly && this._showEditorForReadOnlyMarkdown === false) {
1241
1604
  value = true;
@@ -1244,17 +1607,21 @@ export class MarkdownCell extends AttachmentsCell {
1244
1607
  return;
1245
1608
  }
1246
1609
  this._rendered = value;
1247
- this._handleRendered();
1248
- // Refreshing an editor can be really expensive, so we don't call it from
1249
- // _handleRendered, since _handledRendered is also called on every update
1250
- // request.
1251
- if (!this._rendered) {
1252
- this.editor.refresh();
1253
- }
1254
- // If the rendered state changed, raise an event.
1255
- if (oldValue !== value) {
1256
- this.displayChanged.emit();
1257
- }
1610
+ this._handleRendered()
1611
+ .then(() => {
1612
+ // If the rendered state changed, raise an event.
1613
+ this._displayChanged.emit();
1614
+ this._renderedChanged.emit(this._rendered);
1615
+ })
1616
+ .catch(reason => {
1617
+ console.error('Failed to render', reason);
1618
+ });
1619
+ }
1620
+ /**
1621
+ * Signal emitted when the markdown cell rendered state changes
1622
+ */
1623
+ get renderedChanged() {
1624
+ return this._renderedChanged;
1258
1625
  }
1259
1626
  /*
1260
1627
  * Whether the Markdown editor is visible in read-only mode.
@@ -1268,13 +1635,43 @@ export class MarkdownCell extends AttachmentsCell {
1268
1635
  this.rendered = true;
1269
1636
  }
1270
1637
  }
1638
+ /**
1639
+ * Renderer
1640
+ */
1641
+ get renderer() {
1642
+ return this._renderer;
1643
+ }
1644
+ /**
1645
+ * Dispose of the resources held by the widget.
1646
+ */
1647
+ dispose() {
1648
+ if (this.isDisposed) {
1649
+ return;
1650
+ }
1651
+ this._monitor.dispose();
1652
+ super.dispose();
1653
+ }
1654
+ /**
1655
+ * Create children widgets.
1656
+ */
1657
+ initializeDOM() {
1658
+ if (!this.placeholder) {
1659
+ return;
1660
+ }
1661
+ super.initializeDOM();
1662
+ this.renderCollapseButtons(this._renderer);
1663
+ this._handleRendered().catch(reason => {
1664
+ console.error('Failed to render', reason);
1665
+ });
1666
+ }
1271
1667
  maybeCreateCollapseButton() {
1272
- if (this.headingInfo.level > 0 &&
1273
- this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)
1274
- .length == 0) {
1668
+ var _a;
1669
+ const { level } = this.headingInfo;
1670
+ if (level > 0 &&
1671
+ ((_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS).length) == 0) {
1275
1672
  let collapseButton = this.inputArea.promptNode.appendChild(document.createElement('button'));
1276
1673
  collapseButton.className = `jp-Button ${HEADING_COLLAPSER_CLASS}`;
1277
- collapseButton.setAttribute('data-heading-level', this.headingInfo.level.toString());
1674
+ collapseButton.setAttribute('data-heading-level', level.toString());
1278
1675
  if (this._headingCollapsed) {
1279
1676
  collapseButton.classList.add('jp-mod-collapsed');
1280
1677
  }
@@ -1283,7 +1680,6 @@ export class MarkdownCell extends AttachmentsCell {
1283
1680
  }
1284
1681
  collapseButton.onclick = (event) => {
1285
1682
  this.headingCollapsed = !this.headingCollapsed;
1286
- this._toggleCollapsedSignal.emit(this._headingCollapsed);
1287
1683
  };
1288
1684
  }
1289
1685
  }
@@ -1307,7 +1703,6 @@ export class MarkdownCell extends AttachmentsCell {
1307
1703
  newShowHiddenCellsButton.appendChild(buttonTextElement);
1308
1704
  newShowHiddenCellsButton.onclick = () => {
1309
1705
  this.headingCollapsed = false;
1310
- this._toggleCollapsedSignal.emit(this._headingCollapsed);
1311
1706
  };
1312
1707
  this.node.appendChild(newShowHiddenCellsButton);
1313
1708
  }
@@ -1324,6 +1719,13 @@ export class MarkdownCell extends AttachmentsCell {
1324
1719
  }
1325
1720
  }
1326
1721
  }
1722
+ /**
1723
+ * Callback on content changed
1724
+ */
1725
+ onContentChanged() {
1726
+ super.onContentChanged();
1727
+ this._headingsCache = null;
1728
+ }
1327
1729
  /**
1328
1730
  * Render the collapse button for heading cells,
1329
1731
  * and for collapsed heading cells render the "expand hidden cells"
@@ -1339,23 +1741,28 @@ export class MarkdownCell extends AttachmentsCell {
1339
1741
  */
1340
1742
  renderInput(widget) {
1341
1743
  this.addClass(RENDERED_CLASS);
1342
- this.renderCollapseButtons(widget);
1343
- this.inputArea.renderInput(widget);
1744
+ if (!this.placeholder && !this.isDisposed) {
1745
+ this.renderCollapseButtons(widget);
1746
+ this.inputArea.renderInput(widget);
1747
+ }
1344
1748
  }
1345
1749
  /**
1346
1750
  * Show the text editor instead of rendered input.
1347
1751
  */
1348
1752
  showEditor() {
1349
1753
  this.removeClass(RENDERED_CLASS);
1350
- this.inputArea.showEditor();
1351
- // if this is going to be a heading, place the cursor accordingly
1352
- let numHashAtStart = (this.model.value.text.match(/^#+/g) || [''])[0]
1353
- .length;
1354
- if (numHashAtStart > 0) {
1355
- this.inputArea.editor.setCursorPosition({
1356
- column: numHashAtStart + 1,
1357
- line: 0
1358
- });
1754
+ if (!this.placeholder && !this.isDisposed) {
1755
+ this.inputArea.showEditor();
1756
+ // if this is going to be a heading, place the cursor accordingly
1757
+ let numHashAtStart = (this.model.sharedModel
1758
+ .getSource()
1759
+ .match(/^#+/g) || [''])[0].length;
1760
+ if (numHashAtStart > 0) {
1761
+ this.inputArea.editor.setCursorPosition({
1762
+ column: numHashAtStart + 1,
1763
+ line: 0
1764
+ });
1765
+ }
1359
1766
  }
1360
1767
  }
1361
1768
  /*
@@ -1363,7 +1770,9 @@ export class MarkdownCell extends AttachmentsCell {
1363
1770
  */
1364
1771
  onUpdateRequest(msg) {
1365
1772
  // Make sure we are properly rendered.
1366
- this._handleRendered();
1773
+ this._handleRendered().catch(reason => {
1774
+ console.error('Failed to render', reason);
1775
+ });
1367
1776
  super.onUpdateRequest(msg);
1368
1777
  }
1369
1778
  /**
@@ -1372,39 +1781,42 @@ export class MarkdownCell extends AttachmentsCell {
1372
1781
  updateCellSourceWithAttachment(attachmentName, URI) {
1373
1782
  var _a, _b;
1374
1783
  const textToBeAppended = `![${attachmentName}](attachment:${URI !== null && URI !== void 0 ? URI : attachmentName})`;
1375
- (_b = (_a = this.editor).replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1784
+ // TODO this should be done on the model...
1785
+ (_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1376
1786
  }
1377
1787
  /**
1378
1788
  * Handle the rendered state.
1379
1789
  */
1380
- _handleRendered() {
1790
+ async _handleRendered() {
1381
1791
  if (!this._rendered) {
1382
1792
  this.showEditor();
1383
1793
  }
1384
1794
  else {
1385
1795
  // TODO: It would be nice for the cell to provide a way for
1386
1796
  // its consumers to hook into when the rendering is done.
1387
- void this._updateRenderedInput();
1388
- this.renderInput(this._renderer);
1797
+ await this._updateRenderedInput();
1798
+ if (this._rendered) {
1799
+ // The rendered flag may be updated in the mean time
1800
+ this.renderInput(this._renderer);
1801
+ }
1389
1802
  }
1390
1803
  }
1391
1804
  /**
1392
1805
  * Update the rendered input.
1393
1806
  */
1394
1807
  _updateRenderedInput() {
1808
+ if (this.placeholder) {
1809
+ return Promise.resolve();
1810
+ }
1395
1811
  const model = this.model;
1396
- const text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
1812
+ const text = (model && model.sharedModel.getSource()) || DEFAULT_MARKDOWN_TEXT;
1397
1813
  // Do not re-render if the text has not changed.
1398
1814
  if (text !== this._prevText) {
1399
1815
  const mimeModel = new MimeModel({ data: { 'text/markdown': text } });
1400
- if (!this._renderer) {
1401
- this._renderer = this._rendermime.createRenderer('text/markdown');
1402
- this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1403
- }
1404
1816
  this._prevText = text;
1405
1817
  return this._renderer.renderModel(mimeModel);
1406
1818
  }
1407
- return Promise.resolve(void 0);
1819
+ return Promise.resolve();
1408
1820
  }
1409
1821
  /**
1410
1822
  * Clone the cell, using the same model.