@jupyterlab/cells 4.0.0-alpha.13 → 4.0.0-alpha.15

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
@@ -11,6 +11,7 @@ import { nullTranslator } from '@jupyterlab/translation';
11
11
  import { addIcon } from '@jupyterlab/ui-components';
12
12
  import { PromiseDelegate, UUID } from '@lumino/coreutils';
13
13
  import { some } from '@lumino/algorithm';
14
+ import { MessageLoop } from '@lumino/messaging';
14
15
  import { Debouncer } from '@lumino/polling';
15
16
  import { Signal } from '@lumino/signaling';
16
17
  import { Panel, PanelLayout, Widget } from '@lumino/widgets';
@@ -110,55 +111,30 @@ export class Cell extends Widget {
110
111
  * Construct a new base cell widget.
111
112
  */
112
113
  constructor(options) {
113
- var _a, _b;
114
+ var _a, _b, _c, _d;
114
115
  super();
116
+ this.prompt = '';
115
117
  this._displayChanged = new Signal(this);
116
- this._readOnly = false;
118
+ this._editorConfig = {};
117
119
  this._inputHidden = false;
118
- this._isPlaceholder = false;
119
- this._syncCollapse = false;
120
- this._syncEditable = false;
120
+ this._inViewportChanged = new Signal(this);
121
+ this._readOnly = false;
122
+ this._ready = new PromiseDelegate();
121
123
  this._resizeDebouncer = new Debouncer(() => {
122
124
  this._displayChanged.emit();
123
125
  }, 0);
126
+ this._syncCollapse = false;
127
+ this._syncEditable = false;
124
128
  this.addClass(CELL_CLASS);
125
129
  const model = (this._model = options.model);
126
- const contentFactory = (this.contentFactory =
127
- options.contentFactory || Cell.defaultContentFactory);
128
- this.layout = new PanelLayout();
130
+ this.contentFactory = options.contentFactory || Cell.defaultContentFactory;
131
+ this.layout = (_a = options.layout) !== null && _a !== void 0 ? _a : new PanelLayout();
129
132
  // Set up translator for aria labels
130
- this.translator = (_a = options.translator) !== null && _a !== void 0 ? _a : nullTranslator;
131
- // Header
132
- const header = contentFactory.createCellHeader();
133
- header.addClass(CELL_HEADER_CLASS);
134
- this.layout.addWidget(header);
135
- // Input
136
- const inputWrapper = (this._inputWrapper = new Panel());
137
- inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
138
- const inputCollapser = new InputCollapser();
139
- inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
140
- const input = (this._input = new InputArea({
141
- model,
142
- contentFactory,
143
- updateOnShow: options.updateEditorOnShow,
144
- placeholder: options.placeholder
145
- }));
146
- input.addClass(CELL_INPUT_AREA_CLASS);
147
- inputWrapper.addWidget(inputCollapser);
148
- inputWrapper.addWidget(input);
149
- this.layout.addWidget(inputWrapper);
150
- this._inputPlaceholder = new InputPlaceholder(() => {
151
- this.inputHidden = !this.inputHidden;
152
- });
153
- // Footer
154
- const footer = this.contentFactory.createCellFooter();
155
- footer.addClass(CELL_FOOTER_CLASS);
156
- this.layout.addWidget(footer);
157
- this._isPlaceholder = (_b = options.placeholder) !== null && _b !== void 0 ? _b : false;
158
- // Editor settings
159
- if (options.editorConfig) {
160
- this.editor.setOptions(Object.assign({}, options.editorConfig));
161
- }
133
+ this.translator = (_b = options.translator) !== null && _b !== void 0 ? _b : nullTranslator;
134
+ this._editorConfig = (_c = options.editorConfig) !== null && _c !== void 0 ? _c : {};
135
+ this._placeholder = true;
136
+ this._inViewport = false;
137
+ this.placeholder = (_d = options.placeholder) !== null && _d !== void 0 ? _d : true;
162
138
  model.metadata.changed.connect(this.onMetadataChanged, this);
163
139
  }
164
140
  /**
@@ -179,10 +155,45 @@ export class Cell extends Widget {
179
155
  get displayChanged() {
180
156
  return this._displayChanged;
181
157
  }
158
+ /**
159
+ * Whether the cell is in viewport or not.
160
+ */
161
+ get inViewport() {
162
+ return this._inViewport;
163
+ }
164
+ set inViewport(v) {
165
+ if (this._inViewport !== v) {
166
+ this._inViewport = v;
167
+ this._inViewportChanged.emit(this._inViewport);
168
+ }
169
+ }
170
+ /**
171
+ * Will emit true just after the node is attached to the DOM
172
+ * Will emit false just before the node is detached of the DOM
173
+ */
174
+ get inViewportChanged() {
175
+ return this._inViewportChanged;
176
+ }
177
+ /**
178
+ * Whether the cell is a placeholder not yet fully rendered or not.
179
+ */
180
+ get placeholder() {
181
+ return this._placeholder;
182
+ }
183
+ set placeholder(v) {
184
+ if (v === false) {
185
+ this._placeholder = v;
186
+ this.initializeDOM();
187
+ this._ready.resolve();
188
+ }
189
+ }
182
190
  /**
183
191
  * Get the prompt node used by the cell.
184
192
  */
185
193
  get promptNode() {
194
+ if (this.placeholder) {
195
+ return null;
196
+ }
186
197
  if (!this._inputHidden) {
187
198
  return this._input.promptNode;
188
199
  }
@@ -195,13 +206,33 @@ export class Cell extends Widget {
195
206
  * Get the CodeEditorWrapper used by the cell.
196
207
  */
197
208
  get editorWidget() {
198
- return this._input.editorWidget;
209
+ var _a, _b;
210
+ return (_b = (_a = this._input) === null || _a === void 0 ? void 0 : _a.editorWidget) !== null && _b !== void 0 ? _b : null;
199
211
  }
200
212
  /**
201
213
  * Get the CodeEditor used by the cell.
202
214
  */
203
215
  get editor() {
204
- return this._input.editor;
216
+ var _a, _b;
217
+ return (_b = (_a = this._input) === null || _a === void 0 ? void 0 : _a.editor) !== null && _b !== void 0 ? _b : null;
218
+ }
219
+ /**
220
+ * Editor configuration
221
+ */
222
+ get editorConfig() {
223
+ return this._editorConfig;
224
+ }
225
+ setEditorConfig(v) {
226
+ this._editorConfig = { ...this._editorConfig, ...v };
227
+ if (this.editor) {
228
+ this.editor.setOptions(this._editorConfig);
229
+ }
230
+ }
231
+ /**
232
+ * Cell headings
233
+ */
234
+ get headings() {
235
+ return new Array();
205
236
  }
206
237
  /**
207
238
  * Get the model used by the cell.
@@ -232,45 +263,53 @@ export class Cell extends Widget {
232
263
  this.update();
233
264
  }
234
265
  /**
235
- * Whether the cell is a placeholder that differ rendering
266
+ * Whether the cell is a placeholder that defer rendering
267
+ *
268
+ * #### Notes
269
+ * You can wait for the promise `Cell.ready` to wait for the
270
+ * cell to be rendered.
236
271
  */
237
272
  isPlaceholder() {
238
- return this._isPlaceholder;
273
+ return this.placeholder;
239
274
  }
240
275
  /**
241
276
  * Save view editable state to model
242
277
  */
243
278
  saveEditableState() {
244
- const { metadata } = this.model;
245
- const current = metadata.get('editable');
279
+ const { sharedModel } = this.model;
280
+ const metadata = sharedModel.getMetadata();
281
+ const current = metadata['editable'];
246
282
  if ((this.readOnly && current === false) ||
247
283
  (!this.readOnly && current === undefined)) {
248
284
  return;
249
285
  }
250
286
  if (this.readOnly) {
251
- this.model.metadata.set('editable', false);
287
+ metadata.editable = false;
252
288
  }
253
289
  else {
254
- this.model.metadata.delete('editable');
290
+ delete metadata.editable;
255
291
  }
292
+ sharedModel.setMetadata(metadata);
256
293
  }
257
294
  /**
258
295
  * Load view editable state from model.
259
296
  */
260
297
  loadEditableState() {
261
- this.readOnly = this.model.metadata.get('editable') === false;
298
+ this.readOnly = this.model.sharedModel.getMetadata().editable === false;
262
299
  }
263
300
  /**
264
301
  * A promise that resolves when the widget renders for the first time.
265
302
  */
266
303
  get ready() {
267
- return Promise.resolve(undefined);
304
+ return this._ready.promise;
268
305
  }
269
306
  /**
270
307
  * Set the prompt for the widget.
271
308
  */
272
309
  setPrompt(value) {
273
- this._input.setPrompt(value);
310
+ var _a;
311
+ this.prompt = value;
312
+ (_a = this._input) === null || _a === void 0 ? void 0 : _a.setPrompt(value);
274
313
  }
275
314
  /**
276
315
  * The view state of input being hidden.
@@ -282,14 +321,16 @@ export class Cell extends Widget {
282
321
  if (this._inputHidden === value) {
283
322
  return;
284
323
  }
285
- const layout = this._inputWrapper.layout;
286
- if (value) {
287
- this._input.parent = null;
288
- layout.addWidget(this._inputPlaceholder);
289
- }
290
- else {
291
- this._inputPlaceholder.parent = null;
292
- layout.addWidget(this._input);
324
+ if (!this.placeholder) {
325
+ const layout = this._inputWrapper.layout;
326
+ if (value) {
327
+ this._input.parent = null;
328
+ layout.addWidget(this._inputPlaceholder);
329
+ }
330
+ else {
331
+ this._inputPlaceholder.parent = null;
332
+ layout.addWidget(this._input);
333
+ }
293
334
  }
294
335
  this._inputHidden = value;
295
336
  if (this.syncCollapse) {
@@ -301,7 +342,7 @@ export class Cell extends Widget {
301
342
  * Save view collapse state to model
302
343
  */
303
344
  saveCollapseState() {
304
- const jupyter = Object.assign({}, this.model.metadata.get('jupyter'));
345
+ const jupyter = { ...this.model.metadata.get('jupyter') };
305
346
  if ((this.inputHidden && jupyter.source_hidden === true) ||
306
347
  (!this.inputHidden && jupyter.source_hidden === undefined)) {
307
348
  return;
@@ -394,6 +435,49 @@ export class Cell extends Widget {
394
435
  this._inputPlaceholder = null;
395
436
  super.dispose();
396
437
  }
438
+ /**
439
+ * Create children widgets.
440
+ */
441
+ initializeDOM() {
442
+ const contentFactory = this.contentFactory;
443
+ const model = this._model;
444
+ // Header
445
+ const header = contentFactory.createCellHeader();
446
+ header.addClass(CELL_HEADER_CLASS);
447
+ this.layout.addWidget(header);
448
+ // Input
449
+ const inputWrapper = (this._inputWrapper = new Panel());
450
+ inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
451
+ const inputCollapser = new InputCollapser();
452
+ inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
453
+ const input = (this._input = new InputArea({
454
+ model,
455
+ contentFactory
456
+ }));
457
+ input.addClass(CELL_INPUT_AREA_CLASS);
458
+ inputWrapper.addWidget(inputCollapser);
459
+ inputWrapper.addWidget(input);
460
+ this.layout.addWidget(inputWrapper);
461
+ this._inputPlaceholder = new InputPlaceholder(() => {
462
+ this.inputHidden = !this.inputHidden;
463
+ });
464
+ // Footer
465
+ const footer = this.contentFactory.createCellFooter();
466
+ footer.addClass(CELL_FOOTER_CLASS);
467
+ this.layout.addWidget(footer);
468
+ // Editor settings
469
+ if (this.editorConfig) {
470
+ this.editor.setOptions({ ...this.editorConfig });
471
+ }
472
+ }
473
+ /**
474
+ * Handle `before-attach` messages.
475
+ */
476
+ onBeforeAttach(msg) {
477
+ if (this.placeholder) {
478
+ this.placeholder = false;
479
+ }
480
+ }
397
481
  /**
398
482
  * Handle `after-attach` messages.
399
483
  */
@@ -404,7 +488,8 @@ export class Cell extends Widget {
404
488
  * Handle `'activate-request'` messages.
405
489
  */
406
490
  onActivateRequest(msg) {
407
- this.editor.focus();
491
+ var _a;
492
+ (_a = this.editor) === null || _a === void 0 ? void 0 : _a.focus();
408
493
  }
409
494
  /**
410
495
  * Handle `resize` messages.
@@ -416,12 +501,13 @@ export class Cell extends Widget {
416
501
  * Handle `update-request` messages.
417
502
  */
418
503
  onUpdateRequest(msg) {
504
+ var _a, _b;
419
505
  if (!this._model) {
420
506
  return;
421
507
  }
422
508
  // Handle read only state.
423
- if (this.editor.getOption('readOnly') !== this._readOnly) {
424
- this.editor.setOption('readOnly', this._readOnly);
509
+ if (((_a = this.editor) === null || _a === void 0 ? void 0 : _a.getOption('readOnly')) !== this._readOnly) {
510
+ (_b = this.editor) === null || _b === void 0 ? void 0 : _b.setOption('readOnly', this._readOnly);
425
511
  this.toggleClass(READONLY_CLASS, this._readOnly);
426
512
  }
427
513
  }
@@ -449,6 +535,20 @@ export class Cell extends Widget {
449
535
  * The namespace for the `Cell` class statics.
450
536
  */
451
537
  (function (Cell) {
538
+ /**
539
+ * Type of headings
540
+ */
541
+ let HeadingType;
542
+ (function (HeadingType) {
543
+ /**
544
+ * Heading from HTML output
545
+ */
546
+ HeadingType[HeadingType["HTML"] = 0] = "HTML";
547
+ /**
548
+ * Heading from Markdown cell or Markdown output
549
+ */
550
+ HeadingType[HeadingType["Markdown"] = 1] = "Markdown";
551
+ })(HeadingType = Cell.HeadingType || (Cell.HeadingType = {}));
452
552
  /**
453
553
  * The default implementation of an `IContentFactory`.
454
554
  *
@@ -508,6 +608,75 @@ export class Cell extends Widget {
508
608
  /** ****************************************************************************
509
609
  * CodeCell
510
610
  ******************************************************************************/
611
+ /**
612
+ * Code cell layout
613
+ *
614
+ * It will not detached the output area when the cell is detached.
615
+ */
616
+ export class CodeCellLayout extends PanelLayout {
617
+ /**
618
+ * A message handler invoked on a `'before-attach'` message.
619
+ *
620
+ * #### Notes
621
+ * The default implementation of this method forwards the message
622
+ * to all widgets. It assumes all widget nodes are attached to the
623
+ * parent widget node.
624
+ *
625
+ * This may be reimplemented by subclasses as needed.
626
+ */
627
+ onBeforeAttach(msg) {
628
+ let beforeOutputArea = true;
629
+ const outputAreaWrapper = this.parent.node.firstElementChild;
630
+ for (const widget of this) {
631
+ if (outputAreaWrapper) {
632
+ if (widget.node === outputAreaWrapper) {
633
+ beforeOutputArea = false;
634
+ }
635
+ else {
636
+ MessageLoop.sendMessage(widget, msg);
637
+ if (beforeOutputArea) {
638
+ this.parent.node.insertBefore(widget.node, outputAreaWrapper);
639
+ }
640
+ else {
641
+ this.parent.node.appendChild(widget.node);
642
+ }
643
+ // Force setting isVisible to true as it requires the parent widget to be
644
+ // visible. But that flag will be set only during the `onAfterAttach` call.
645
+ if (!this.parent.isHidden) {
646
+ widget.setFlag(Widget.Flag.IsVisible);
647
+ }
648
+ // Not called in NotebookWindowedLayout to avoid outputArea
649
+ // widgets unwanted update or reset.
650
+ MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);
651
+ }
652
+ }
653
+ }
654
+ }
655
+ /**
656
+ * A message handler invoked on an `'after-detach'` message.
657
+ *
658
+ * #### Notes
659
+ * The default implementation of this method forwards the message
660
+ * to all widgets. It assumes all widget nodes are attached to the
661
+ * parent widget node.
662
+ *
663
+ * This may be reimplemented by subclasses as needed.
664
+ */
665
+ onAfterDetach(msg) {
666
+ for (const widget of this) {
667
+ // TODO we could improve this further by removing outputs based
668
+ // on their mime type (for example plain/text or markdown could safely be detached)
669
+ // If the cell is out of the view port, its children are already detached -> skip detaching
670
+ if (!widget.hasClass(CELL_OUTPUT_WRAPPER_CLASS) &&
671
+ widget.node.isConnected) {
672
+ // Not called in NotebookWindowedLayout for windowed notebook
673
+ MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);
674
+ this.parent.node.removeChild(widget.node);
675
+ MessageLoop.sendMessage(widget, msg);
676
+ }
677
+ }
678
+ }
679
+ }
511
680
  /**
512
681
  * A widget for a code cell.
513
682
  */
@@ -516,8 +685,12 @@ export class CodeCell extends Cell {
516
685
  * Construct a code cell widget.
517
686
  */
518
687
  constructor(options) {
519
- super(options);
688
+ var _a;
689
+ super({ layout: new CodeCellLayout(), ...options, placeholder: true });
690
+ this._headingsCache = null;
520
691
  this._outputHidden = false;
692
+ this._outputWrapper = null;
693
+ this._outputPlaceholder = null;
521
694
  this._syncScrolled = false;
522
695
  this._savingMetadata = false;
523
696
  this.addClass(CODE_CELL_CLASS);
@@ -526,46 +699,65 @@ export class CodeCell extends Cell {
526
699
  const rendermime = (this._rendermime = options.rendermime);
527
700
  const contentFactory = this.contentFactory;
528
701
  const model = this.model;
702
+ this.maxNumberOutputs = options.maxNumberOutputs;
529
703
  // Note that modifying the below label warrants one to also modify
530
704
  // the same in this._outputLengthHandler. Ideally, this label must
531
705
  // have been a constant and used in both places but it is not done
532
706
  // so because of limitations in the translation manager.
533
- let ariaLabel = trans.__('Code Cell Content with Output');
534
- if (!options.placeholder) {
707
+ const ariaLabel = model.outputs.length === 0
708
+ ? trans.__('Code Cell Content')
709
+ : trans.__('Code Cell Content with Output');
710
+ this.node.setAttribute('aria-label', ariaLabel);
711
+ const output = (this._output = new OutputArea({
712
+ model: this.model.outputs,
713
+ rendermime,
714
+ contentFactory: contentFactory,
715
+ maxNumberOutputs: this.maxNumberOutputs,
716
+ translator: this.translator
717
+ }));
718
+ output.addClass(CELL_OUTPUT_AREA_CLASS);
719
+ // Defer setting placeholder as OutputArea must be instantiated before initializing the DOM
720
+ this.placeholder = (_a = options.placeholder) !== null && _a !== void 0 ? _a : true;
721
+ model.outputs.changed.connect(this.onOutputChanged, this);
722
+ model.outputs.stateChanged.connect(this.onOutputChanged, this);
723
+ model.stateChanged.connect(this.onStateChanged, this);
724
+ }
725
+ /**
726
+ * Create children widgets.
727
+ */
728
+ initializeDOM() {
729
+ super.initializeDOM();
730
+ if (!this.placeholder) {
731
+ this.setPrompt(this.prompt);
535
732
  // Insert the output before the cell footer.
536
733
  const outputWrapper = (this._outputWrapper = new Panel());
537
734
  outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
538
735
  const outputCollapser = new OutputCollapser();
539
736
  outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
540
- const output = (this._output = new OutputArea({
541
- model: model.outputs,
542
- rendermime,
543
- contentFactory: contentFactory,
544
- maxNumberOutputs: options.maxNumberOutputs,
545
- translator: this.translator
546
- }));
547
- output.addClass(CELL_OUTPUT_AREA_CLASS);
737
+ outputWrapper.addWidget(outputCollapser);
548
738
  // Set a CSS if there are no outputs, and connect a signal for future
549
739
  // changes to the number of outputs. This is for conditional styling
550
740
  // if there are no outputs.
551
- if (model.outputs.length === 0) {
741
+ if (this.model.outputs.length === 0) {
552
742
  this.addClass(NO_OUTPUTS_CLASS);
553
- ariaLabel = trans.__('Code Cell Content');
554
743
  }
555
- output.outputLengthChanged.connect(this._outputLengthHandler, this);
556
- outputWrapper.addWidget(outputCollapser);
557
- outputWrapper.addWidget(output);
558
- this.layout.insertWidget(2, new ResizeHandle(this.node));
559
- this.layout.insertWidget(3, outputWrapper);
560
- if (model.isDirty) {
744
+ this._output.outputLengthChanged.connect(this._outputLengthHandler, this);
745
+ outputWrapper.addWidget(this._output);
746
+ const layout = this.layout;
747
+ layout.insertWidget(layout.widgets.length - 1, new ResizeHandle(this.node));
748
+ layout.insertWidget(layout.widgets.length - 1, outputWrapper);
749
+ if (this.model.isDirty) {
561
750
  this.addClass(DIRTY_CLASS);
562
751
  }
563
752
  this._outputPlaceholder = new OutputPlaceholder(() => {
564
753
  this.outputHidden = !this.outputHidden;
565
754
  });
755
+ const trans = this.translator.load('jupyterlab');
756
+ const ariaLabel = this.model.outputs.length === 0
757
+ ? trans.__('Code Cell Content')
758
+ : trans.__('Code Cell Content with Output');
759
+ this.node.setAttribute('aria-label', ariaLabel);
566
760
  }
567
- model.stateChanged.connect(this.onStateChanged, this);
568
- this.node.setAttribute('aria-label', ariaLabel);
569
761
  }
570
762
  /**
571
763
  * Initialize view state from model.
@@ -580,6 +772,47 @@ export class CodeCell extends Cell {
580
772
  this.setPrompt(`${this.model.executionCount || ''}`);
581
773
  return this;
582
774
  }
775
+ get headings() {
776
+ if (!this._headingsCache) {
777
+ const headings = [];
778
+ // Iterate over the code cell outputs to check for Markdown or HTML from which we can generate ToC headings...
779
+ const outputs = this.model.outputs;
780
+ for (let j = 0; j < outputs.length; j++) {
781
+ const m = outputs.get(j);
782
+ let htmlType = null;
783
+ let mdType = null;
784
+ Object.keys(m.data).forEach(t => {
785
+ if (!mdType && TableOfContentsUtils.Markdown.isMarkdown(t)) {
786
+ mdType = t;
787
+ }
788
+ else if (!htmlType && TableOfContentsUtils.isHTML(t)) {
789
+ htmlType = t;
790
+ }
791
+ });
792
+ // Parse HTML output
793
+ if (htmlType) {
794
+ headings.push(...TableOfContentsUtils.getHTMLHeadings(this._rendermime.sanitizer.sanitize(m.data[htmlType])).map(heading => {
795
+ return {
796
+ ...heading,
797
+ outputIndex: j,
798
+ type: Cell.HeadingType.HTML
799
+ };
800
+ }));
801
+ }
802
+ else if (mdType) {
803
+ headings.push(...TableOfContentsUtils.Markdown.getHeadings(m.data[mdType]).map(heading => {
804
+ return {
805
+ ...heading,
806
+ outputIndex: j,
807
+ type: Cell.HeadingType.Markdown
808
+ };
809
+ }));
810
+ }
811
+ }
812
+ this._headingsCache = headings;
813
+ }
814
+ return [...this._headingsCache];
815
+ }
583
816
  /**
584
817
  * Get the output area for the cell.
585
818
  */
@@ -596,20 +829,22 @@ export class CodeCell extends Cell {
596
829
  if (this._outputHidden === value) {
597
830
  return;
598
831
  }
599
- const layout = this._outputWrapper.layout;
600
- if (value) {
601
- layout.removeWidget(this._output);
602
- layout.addWidget(this._outputPlaceholder);
603
- if (this.inputHidden && !this._outputWrapper.isHidden) {
604
- this._outputWrapper.hide();
832
+ if (!this.placeholder) {
833
+ const layout = this._outputWrapper.layout;
834
+ if (value) {
835
+ layout.removeWidget(this._output);
836
+ layout.addWidget(this._outputPlaceholder);
837
+ if (this.inputHidden && !this._outputWrapper.isHidden) {
838
+ this._outputWrapper.hide();
839
+ }
605
840
  }
606
- }
607
- else {
608
- if (this._outputWrapper.isHidden) {
609
- this._outputWrapper.show();
841
+ else {
842
+ if (this._outputWrapper.isHidden) {
843
+ this._outputWrapper.show();
844
+ }
845
+ layout.removeWidget(this._outputPlaceholder);
846
+ layout.addWidget(this._output);
610
847
  }
611
- layout.removeWidget(this._outputPlaceholder);
612
- layout.addWidget(this._output);
613
848
  }
614
849
  this._outputHidden = value;
615
850
  if (this.syncCollapse) {
@@ -724,6 +959,9 @@ export class CodeCell extends Cell {
724
959
  * is hidden without accessing private state.
725
960
  */
726
961
  handleInputHidden(value) {
962
+ if (this.placeholder) {
963
+ return;
964
+ }
727
965
  if (!value && this._outputWrapper.isHidden) {
728
966
  this._outputWrapper.show();
729
967
  }
@@ -788,6 +1026,12 @@ export class CodeCell extends Cell {
788
1026
  break;
789
1027
  }
790
1028
  }
1029
+ /**
1030
+ * Callback on output changes
1031
+ */
1032
+ onOutputChanged() {
1033
+ this._headingsCache = null;
1034
+ }
791
1035
  /**
792
1036
  * Handle changes in the metadata.
793
1037
  */
@@ -835,13 +1079,17 @@ export class CodeCell extends Cell {
835
1079
  async function execute(cell, sessionContext, metadata) {
836
1080
  var _a;
837
1081
  const model = cell.model;
838
- const code = model.value.text;
1082
+ const code = model.sharedModel.getSource();
839
1083
  if (!code.trim() || !((_a = sessionContext.session) === null || _a === void 0 ? void 0 : _a.kernel)) {
840
1084
  model.clearExecution();
841
1085
  return;
842
1086
  }
843
- const cellId = { cellId: model.id };
844
- metadata = Object.assign(Object.assign(Object.assign({}, model.metadata.toJSON()), metadata), cellId);
1087
+ const cellId = { cellId: model.sharedModel.getId() };
1088
+ metadata = {
1089
+ ...model.metadata.toJSON(),
1090
+ ...metadata,
1091
+ ...cellId
1092
+ };
845
1093
  const { recordTiming } = metadata;
846
1094
  model.clearExecution();
847
1095
  cell.outputHidden = false;
@@ -971,6 +1219,7 @@ export class AttachmentsCell extends Cell {
971
1219
  node.removeEventListener('paste', this);
972
1220
  node.removeEventListener('lm-dragover', this);
973
1221
  node.removeEventListener('lm-drop', this);
1222
+ super.onBeforeDetach(msg);
974
1223
  }
975
1224
  _evtDragOver(event) {
976
1225
  const supportedMimeType = some(imageRendererFactory.mimeTypes, mimeType => {
@@ -1135,15 +1384,16 @@ export class MarkdownCell extends AttachmentsCell {
1135
1384
  * Construct a Markdown cell widget.
1136
1385
  */
1137
1386
  constructor(options) {
1138
- var _a, _b, _c;
1139
- super(options);
1387
+ var _a, _b, _c, _d;
1388
+ super({ ...options, placeholder: true });
1389
+ this._headingsCache = null;
1140
1390
  this._headingCollapsedChanged = new Signal(this);
1391
+ this._prevText = '';
1141
1392
  this._rendered = true;
1142
1393
  this._renderedChanged = new Signal(this);
1143
- this._prevText = '';
1144
- this._ready = new PromiseDelegate();
1145
1394
  this._showEditorForReadOnlyMarkdown = true;
1146
1395
  this.addClass(MARKDOWN_CELL_CLASS);
1396
+ this.model.contentChanged.connect(this.onContentChanged, this);
1147
1397
  const trans = this.translator.load('jupyterlab');
1148
1398
  this.node.setAttribute('aria-label', trans.__('Markdown Cell Content'));
1149
1399
  // Ensure we can resolve attachments:
@@ -1155,33 +1405,32 @@ export class MarkdownCell extends AttachmentsCell {
1155
1405
  });
1156
1406
  this._renderer = this._rendermime.createRenderer('text/markdown');
1157
1407
  this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1158
- // Stop codemirror handling paste
1159
- this.editor.setOption('handlePaste', false);
1160
1408
  // Check if heading cell is set to be collapsed
1161
1409
  this._headingCollapsed = ((_b = this.model.metadata.get(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1162
- // Throttle the rendering rate of the widget.
1410
+ this._showEditorForReadOnlyMarkdown =
1411
+ (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1412
+ // Defer setting placeholder as the renderer must be instantiated before initializing the DOM
1413
+ this.placeholder = (_d = options.placeholder) !== null && _d !== void 0 ? _d : true;
1163
1414
  this._monitor = new ActivityMonitor({
1164
1415
  signal: this.model.contentChanged,
1165
1416
  timeout: RENDER_TIMEOUT
1166
1417
  });
1167
- this._monitor.activityStopped.connect(() => {
1168
- if (this._rendered) {
1169
- this.update();
1418
+ // Throttle the rendering rate of the widget.
1419
+ this.ready
1420
+ .then(() => {
1421
+ if (this.isDisposed) {
1422
+ // Bail early
1423
+ return;
1170
1424
  }
1171
- }, this);
1172
- void this._updateRenderedInput().then(() => {
1173
- this._ready.resolve(void 0);
1425
+ this._monitor.activityStopped.connect(() => {
1426
+ if (this._rendered) {
1427
+ this.update();
1428
+ }
1429
+ }, this);
1430
+ })
1431
+ .catch(reason => {
1432
+ console.error('Failed to be ready', reason);
1174
1433
  });
1175
- this.renderCollapseButtons(this._renderer);
1176
- this.renderInput(this._renderer);
1177
- this._showEditorForReadOnlyMarkdown =
1178
- (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1179
- }
1180
- /**
1181
- * A promise that resolves when the widget renders for the first time.
1182
- */
1183
- get ready() {
1184
- return this._ready.promise;
1185
1434
  }
1186
1435
  /**
1187
1436
  * Text that represents the highest heading (i.e. lowest level) if cell is a heading.
@@ -1189,10 +1438,7 @@ export class MarkdownCell extends AttachmentsCell {
1189
1438
  */
1190
1439
  get headingInfo() {
1191
1440
  // Use table of content algorithm for consistency
1192
- const headings = TableOfContentsUtils.Markdown.getHeadings(this.model.value.text, {
1193
- maximalDepth: 6,
1194
- numberHeaders: false
1195
- });
1441
+ const headings = this.headings;
1196
1442
  if (headings.length > 0) {
1197
1443
  // Return the highest level
1198
1444
  const { text, level } = headings.reduce((prev, curr) => (prev.level <= curr.level ? prev : curr), headings[0]);
@@ -1202,6 +1448,16 @@ export class MarkdownCell extends AttachmentsCell {
1202
1448
  return { text: '', level: -1 };
1203
1449
  }
1204
1450
  }
1451
+ get headings() {
1452
+ if (!this._headingsCache) {
1453
+ // Use table of content algorithm for consistency
1454
+ const headings = TableOfContentsUtils.Markdown.getHeadings(this.model.sharedModel.getSource());
1455
+ this._headingsCache = headings.map(h => {
1456
+ return { ...h, type: Cell.HeadingType.Markdown };
1457
+ });
1458
+ }
1459
+ return [...this._headingsCache];
1460
+ }
1205
1461
  /**
1206
1462
  * Whether the heading is collapsed or not.
1207
1463
  */
@@ -1209,6 +1465,7 @@ export class MarkdownCell extends AttachmentsCell {
1209
1465
  return this._headingCollapsed;
1210
1466
  }
1211
1467
  set headingCollapsed(value) {
1468
+ var _a;
1212
1469
  if (this._headingCollapsed !== value) {
1213
1470
  this._headingCollapsed = value;
1214
1471
  if (value) {
@@ -1217,7 +1474,7 @@ export class MarkdownCell extends AttachmentsCell {
1217
1474
  else if (this.model.metadata.has(MARKDOWN_HEADING_COLLAPSED)) {
1218
1475
  this.model.metadata.delete(MARKDOWN_HEADING_COLLAPSED);
1219
1476
  }
1220
- const collapseButton = this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1477
+ const collapseButton = (_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1221
1478
  if (collapseButton) {
1222
1479
  if (value) {
1223
1480
  collapseButton.classList.add('jp-mod-collapsed');
@@ -1261,10 +1518,15 @@ export class MarkdownCell extends AttachmentsCell {
1261
1518
  return;
1262
1519
  }
1263
1520
  this._rendered = value;
1264
- this._handleRendered();
1265
- // If the rendered state changed, raise an event.
1266
- this._displayChanged.emit();
1267
- this._renderedChanged.emit(this._rendered);
1521
+ this._handleRendered()
1522
+ .then(() => {
1523
+ // If the rendered state changed, raise an event.
1524
+ this._displayChanged.emit();
1525
+ this._renderedChanged.emit(this._rendered);
1526
+ })
1527
+ .catch(reason => {
1528
+ console.error('Failed to render', reason);
1529
+ });
1268
1530
  }
1269
1531
  /**
1270
1532
  * Signal emitted when the markdown cell rendered state changes
@@ -1290,6 +1552,9 @@ export class MarkdownCell extends AttachmentsCell {
1290
1552
  get renderer() {
1291
1553
  return this._renderer;
1292
1554
  }
1555
+ /**
1556
+ * Dispose of the resources held by the widget.
1557
+ */
1293
1558
  dispose() {
1294
1559
  if (this.isDisposed) {
1295
1560
  return;
@@ -1297,13 +1562,26 @@ export class MarkdownCell extends AttachmentsCell {
1297
1562
  this._monitor.dispose();
1298
1563
  super.dispose();
1299
1564
  }
1565
+ /**
1566
+ * Create children widgets.
1567
+ */
1568
+ initializeDOM() {
1569
+ super.initializeDOM();
1570
+ // Stop codemirror handling paste
1571
+ this.editor.setOption('handlePaste', false);
1572
+ this.renderCollapseButtons(this._renderer);
1573
+ this._handleRendered().catch(reason => {
1574
+ console.error('Failed to render', reason);
1575
+ });
1576
+ }
1300
1577
  maybeCreateCollapseButton() {
1301
- if (this.headingInfo.level > 0 &&
1302
- this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)
1303
- .length == 0) {
1578
+ var _a;
1579
+ const { level } = this.headingInfo;
1580
+ if (level > 0 &&
1581
+ ((_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS).length) == 0) {
1304
1582
  let collapseButton = this.inputArea.promptNode.appendChild(document.createElement('button'));
1305
1583
  collapseButton.className = `jp-Button ${HEADING_COLLAPSER_CLASS}`;
1306
- collapseButton.setAttribute('data-heading-level', this.headingInfo.level.toString());
1584
+ collapseButton.setAttribute('data-heading-level', level.toString());
1307
1585
  if (this._headingCollapsed) {
1308
1586
  collapseButton.classList.add('jp-mod-collapsed');
1309
1587
  }
@@ -1351,6 +1629,12 @@ export class MarkdownCell extends AttachmentsCell {
1351
1629
  }
1352
1630
  }
1353
1631
  }
1632
+ /**
1633
+ * Callback on content changed
1634
+ */
1635
+ onContentChanged() {
1636
+ this._headingsCache = null;
1637
+ }
1354
1638
  /**
1355
1639
  * Render the collapse button for heading cells,
1356
1640
  * and for collapsed heading cells render the "expand hidden cells"
@@ -1366,23 +1650,28 @@ export class MarkdownCell extends AttachmentsCell {
1366
1650
  */
1367
1651
  renderInput(widget) {
1368
1652
  this.addClass(RENDERED_CLASS);
1369
- this.renderCollapseButtons(widget);
1370
- this.inputArea.renderInput(widget);
1653
+ if (!this.placeholder && !this.isDisposed) {
1654
+ this.renderCollapseButtons(widget);
1655
+ this.inputArea.renderInput(widget);
1656
+ }
1371
1657
  }
1372
1658
  /**
1373
1659
  * Show the text editor instead of rendered input.
1374
1660
  */
1375
1661
  showEditor() {
1376
1662
  this.removeClass(RENDERED_CLASS);
1377
- this.inputArea.showEditor();
1378
- // if this is going to be a heading, place the cursor accordingly
1379
- let numHashAtStart = (this.model.value.text.match(/^#+/g) || [''])[0]
1380
- .length;
1381
- if (numHashAtStart > 0) {
1382
- this.inputArea.editor.setCursorPosition({
1383
- column: numHashAtStart + 1,
1384
- line: 0
1385
- });
1663
+ if (!this.placeholder && !this.isDisposed) {
1664
+ this.inputArea.showEditor();
1665
+ // if this is going to be a heading, place the cursor accordingly
1666
+ let numHashAtStart = (this.model.sharedModel
1667
+ .getSource()
1668
+ .match(/^#+/g) || [''])[0].length;
1669
+ if (numHashAtStart > 0) {
1670
+ this.inputArea.editor.setCursorPosition({
1671
+ column: numHashAtStart + 1,
1672
+ line: 0
1673
+ });
1674
+ }
1386
1675
  }
1387
1676
  }
1388
1677
  /*
@@ -1390,7 +1679,9 @@ export class MarkdownCell extends AttachmentsCell {
1390
1679
  */
1391
1680
  onUpdateRequest(msg) {
1392
1681
  // Make sure we are properly rendered.
1393
- this._handleRendered();
1682
+ this._handleRendered().catch(reason => {
1683
+ console.error('Failed to render', reason);
1684
+ });
1394
1685
  super.onUpdateRequest(msg);
1395
1686
  }
1396
1687
  /**
@@ -1399,19 +1690,23 @@ export class MarkdownCell extends AttachmentsCell {
1399
1690
  updateCellSourceWithAttachment(attachmentName, URI) {
1400
1691
  var _a, _b;
1401
1692
  const textToBeAppended = `![${attachmentName}](attachment:${URI !== null && URI !== void 0 ? URI : attachmentName})`;
1402
- (_b = (_a = this.editor).replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1693
+ // TODO this should be done on the model...
1694
+ (_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1403
1695
  }
1404
1696
  /**
1405
1697
  * Handle the rendered state.
1406
1698
  */
1407
- _handleRendered() {
1699
+ async _handleRendered() {
1700
+ if (this.placeholder) {
1701
+ return Promise.resolve();
1702
+ }
1408
1703
  if (!this._rendered) {
1409
1704
  this.showEditor();
1410
1705
  }
1411
1706
  else {
1412
1707
  // TODO: It would be nice for the cell to provide a way for
1413
1708
  // its consumers to hook into when the rendering is done.
1414
- void this._updateRenderedInput();
1709
+ await this._updateRenderedInput();
1415
1710
  this.renderInput(this._renderer);
1416
1711
  }
1417
1712
  }
@@ -1420,7 +1715,7 @@ export class MarkdownCell extends AttachmentsCell {
1420
1715
  */
1421
1716
  _updateRenderedInput() {
1422
1717
  const model = this.model;
1423
- const text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
1718
+ const text = (model && model.sharedModel.getSource()) || DEFAULT_MARKDOWN_TEXT;
1424
1719
  // Do not re-render if the text has not changed.
1425
1720
  if (text !== this._prevText) {
1426
1721
  const mimeModel = new MimeModel({ data: { 'text/markdown': text } });