@jupyterlab/cells 4.0.0-alpha.12 → 4.0.0-alpha.14

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
@@ -10,7 +10,8 @@ import { TableOfContentsUtils } from '@jupyterlab/toc';
10
10
  import { nullTranslator } from '@jupyterlab/translation';
11
11
  import { addIcon } from '@jupyterlab/ui-components';
12
12
  import { PromiseDelegate, UUID } from '@lumino/coreutils';
13
- import { filter, some, toArray } from '@lumino/algorithm';
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;
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 = options.translator || 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 = (_a = options.placeholder) !== null && _a !== void 0 ? _a : 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,73 @@ 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 (!widget.hasClass(CELL_OUTPUT_WRAPPER_CLASS)) {
670
+ // Not called in NotebookWindowedLayout for windowed notebook
671
+ MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);
672
+ this.parent.node.removeChild(widget.node);
673
+ MessageLoop.sendMessage(widget, msg);
674
+ }
675
+ }
676
+ }
677
+ }
511
678
  /**
512
679
  * A widget for a code cell.
513
680
  */
@@ -516,8 +683,12 @@ export class CodeCell extends Cell {
516
683
  * Construct a code cell widget.
517
684
  */
518
685
  constructor(options) {
519
- super(options);
686
+ var _a;
687
+ super({ layout: new CodeCellLayout(), ...options, placeholder: true });
688
+ this._headingsCache = null;
520
689
  this._outputHidden = false;
690
+ this._outputWrapper = null;
691
+ this._outputPlaceholder = null;
521
692
  this._syncScrolled = false;
522
693
  this._savingMetadata = false;
523
694
  this.addClass(CODE_CELL_CLASS);
@@ -526,45 +697,65 @@ export class CodeCell extends Cell {
526
697
  const rendermime = (this._rendermime = options.rendermime);
527
698
  const contentFactory = this.contentFactory;
528
699
  const model = this.model;
700
+ this.maxNumberOutputs = options.maxNumberOutputs;
529
701
  // Note that modifying the below label warrants one to also modify
530
702
  // the same in this._outputLengthHandler. Ideally, this label must
531
703
  // have been a constant and used in both places but it is not done
532
704
  // so because of limitations in the translation manager.
533
- let ariaLabel = trans.__('Code Cell Content with Output');
534
- if (!options.placeholder) {
705
+ const ariaLabel = model.outputs.length === 0
706
+ ? trans.__('Code Cell Content')
707
+ : trans.__('Code Cell Content with Output');
708
+ this.node.setAttribute('aria-label', ariaLabel);
709
+ const output = (this._output = new OutputArea({
710
+ model: this.model.outputs,
711
+ rendermime,
712
+ contentFactory: contentFactory,
713
+ maxNumberOutputs: this.maxNumberOutputs,
714
+ translator: this.translator
715
+ }));
716
+ output.addClass(CELL_OUTPUT_AREA_CLASS);
717
+ // Defer setting placeholder as OutputArea must be instantiated before initializing the DOM
718
+ this.placeholder = (_a = options.placeholder) !== null && _a !== void 0 ? _a : true;
719
+ model.outputs.changed.connect(this.onOutputChanged, this);
720
+ model.outputs.stateChanged.connect(this.onOutputChanged, this);
721
+ model.stateChanged.connect(this.onStateChanged, this);
722
+ }
723
+ /**
724
+ * Create children widgets.
725
+ */
726
+ initializeDOM() {
727
+ super.initializeDOM();
728
+ if (!this.placeholder) {
729
+ this.setPrompt(this.prompt);
535
730
  // Insert the output before the cell footer.
536
731
  const outputWrapper = (this._outputWrapper = new Panel());
537
732
  outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
538
733
  const outputCollapser = new OutputCollapser();
539
734
  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
- }));
546
- output.addClass(CELL_OUTPUT_AREA_CLASS);
735
+ outputWrapper.addWidget(outputCollapser);
547
736
  // Set a CSS if there are no outputs, and connect a signal for future
548
737
  // changes to the number of outputs. This is for conditional styling
549
738
  // if there are no outputs.
550
- if (model.outputs.length === 0) {
739
+ if (this.model.outputs.length === 0) {
551
740
  this.addClass(NO_OUTPUTS_CLASS);
552
- ariaLabel = trans.__('Code Cell Content');
553
741
  }
554
- output.outputLengthChanged.connect(this._outputLengthHandler, this);
555
- outputWrapper.addWidget(outputCollapser);
556
- outputWrapper.addWidget(output);
557
- this.layout.insertWidget(2, new ResizeHandle(this.node));
558
- this.layout.insertWidget(3, outputWrapper);
559
- if (model.isDirty) {
742
+ this._output.outputLengthChanged.connect(this._outputLengthHandler, this);
743
+ outputWrapper.addWidget(this._output);
744
+ const layout = this.layout;
745
+ layout.insertWidget(layout.widgets.length - 1, new ResizeHandle(this.node));
746
+ layout.insertWidget(layout.widgets.length - 1, outputWrapper);
747
+ if (this.model.isDirty) {
560
748
  this.addClass(DIRTY_CLASS);
561
749
  }
562
750
  this._outputPlaceholder = new OutputPlaceholder(() => {
563
751
  this.outputHidden = !this.outputHidden;
564
752
  });
753
+ const trans = this.translator.load('jupyterlab');
754
+ const ariaLabel = this.model.outputs.length === 0
755
+ ? trans.__('Code Cell Content')
756
+ : trans.__('Code Cell Content with Output');
757
+ this.node.setAttribute('aria-label', ariaLabel);
565
758
  }
566
- model.stateChanged.connect(this.onStateChanged, this);
567
- this.node.setAttribute('aria-label', ariaLabel);
568
759
  }
569
760
  /**
570
761
  * Initialize view state from model.
@@ -579,6 +770,47 @@ export class CodeCell extends Cell {
579
770
  this.setPrompt(`${this.model.executionCount || ''}`);
580
771
  return this;
581
772
  }
773
+ get headings() {
774
+ if (!this._headingsCache) {
775
+ const headings = [];
776
+ // Iterate over the code cell outputs to check for Markdown or HTML from which we can generate ToC headings...
777
+ const outputs = this.model.outputs;
778
+ for (let j = 0; j < outputs.length; j++) {
779
+ const m = outputs.get(j);
780
+ let htmlType = null;
781
+ let mdType = null;
782
+ Object.keys(m.data).forEach(t => {
783
+ if (!mdType && TableOfContentsUtils.Markdown.isMarkdown(t)) {
784
+ mdType = t;
785
+ }
786
+ else if (!htmlType && TableOfContentsUtils.isHTML(t)) {
787
+ htmlType = t;
788
+ }
789
+ });
790
+ // Parse HTML output
791
+ if (htmlType) {
792
+ headings.push(...TableOfContentsUtils.getHTMLHeadings(this._rendermime.sanitizer.sanitize(m.data[htmlType])).map(heading => {
793
+ return {
794
+ ...heading,
795
+ outputIndex: j,
796
+ type: Cell.HeadingType.HTML
797
+ };
798
+ }));
799
+ }
800
+ else if (mdType) {
801
+ headings.push(...TableOfContentsUtils.Markdown.getHeadings(m.data[mdType]).map(heading => {
802
+ return {
803
+ ...heading,
804
+ outputIndex: j,
805
+ type: Cell.HeadingType.Markdown
806
+ };
807
+ }));
808
+ }
809
+ }
810
+ this._headingsCache = headings;
811
+ }
812
+ return [...this._headingsCache];
813
+ }
582
814
  /**
583
815
  * Get the output area for the cell.
584
816
  */
@@ -595,20 +827,22 @@ export class CodeCell extends Cell {
595
827
  if (this._outputHidden === value) {
596
828
  return;
597
829
  }
598
- const layout = this._outputWrapper.layout;
599
- if (value) {
600
- layout.removeWidget(this._output);
601
- layout.addWidget(this._outputPlaceholder);
602
- if (this.inputHidden && !this._outputWrapper.isHidden) {
603
- this._outputWrapper.hide();
830
+ if (!this.placeholder) {
831
+ const layout = this._outputWrapper.layout;
832
+ if (value) {
833
+ layout.removeWidget(this._output);
834
+ layout.addWidget(this._outputPlaceholder);
835
+ if (this.inputHidden && !this._outputWrapper.isHidden) {
836
+ this._outputWrapper.hide();
837
+ }
604
838
  }
605
- }
606
- else {
607
- if (this._outputWrapper.isHidden) {
608
- this._outputWrapper.show();
839
+ else {
840
+ if (this._outputWrapper.isHidden) {
841
+ this._outputWrapper.show();
842
+ }
843
+ layout.removeWidget(this._outputPlaceholder);
844
+ layout.addWidget(this._output);
609
845
  }
610
- layout.removeWidget(this._outputPlaceholder);
611
- layout.addWidget(this._output);
612
846
  }
613
847
  this._outputHidden = value;
614
848
  if (this.syncCollapse) {
@@ -723,6 +957,9 @@ export class CodeCell extends Cell {
723
957
  * is hidden without accessing private state.
724
958
  */
725
959
  handleInputHidden(value) {
960
+ if (this.placeholder) {
961
+ return;
962
+ }
726
963
  if (!value && this._outputWrapper.isHidden) {
727
964
  this._outputWrapper.show();
728
965
  }
@@ -787,6 +1024,12 @@ export class CodeCell extends Cell {
787
1024
  break;
788
1025
  }
789
1026
  }
1027
+ /**
1028
+ * Callback on output changes
1029
+ */
1030
+ onOutputChanged() {
1031
+ this._headingsCache = null;
1032
+ }
790
1033
  /**
791
1034
  * Handle changes in the metadata.
792
1035
  */
@@ -834,13 +1077,17 @@ export class CodeCell extends Cell {
834
1077
  async function execute(cell, sessionContext, metadata) {
835
1078
  var _a;
836
1079
  const model = cell.model;
837
- const code = model.value.text;
1080
+ const code = model.sharedModel.getSource();
838
1081
  if (!code.trim() || !((_a = sessionContext.session) === null || _a === void 0 ? void 0 : _a.kernel)) {
839
1082
  model.clearExecution();
840
1083
  return;
841
1084
  }
842
- const cellId = { cellId: model.id };
843
- metadata = Object.assign(Object.assign(Object.assign({}, model.metadata.toJSON()), metadata), cellId);
1085
+ const cellId = { cellId: model.sharedModel.getId() };
1086
+ metadata = {
1087
+ ...model.metadata.toJSON(),
1088
+ ...metadata,
1089
+ ...cellId
1090
+ };
844
1091
  const { recordTiming } = metadata;
845
1092
  model.clearExecution();
846
1093
  cell.outputHidden = false;
@@ -970,6 +1217,7 @@ export class AttachmentsCell extends Cell {
970
1217
  node.removeEventListener('paste', this);
971
1218
  node.removeEventListener('lm-dragover', this);
972
1219
  node.removeEventListener('lm-drop', this);
1220
+ super.onBeforeDetach(msg);
973
1221
  }
974
1222
  _evtDragOver(event) {
975
1223
  const supportedMimeType = some(imageRendererFactory.mimeTypes, mimeType => {
@@ -1021,13 +1269,13 @@ export class AttachmentsCell extends Cell {
1021
1269
  * Handle the `'lm-drop'` event for the widget.
1022
1270
  */
1023
1271
  _evtDrop(event) {
1024
- const supportedMimeTypes = toArray(filter(event.mimeData.types(), mimeType => {
1272
+ const supportedMimeTypes = event.mimeData.types().filter(mimeType => {
1025
1273
  if (mimeType === CONTENTS_MIME_RICH) {
1026
1274
  const data = event.mimeData.getData(CONTENTS_MIME_RICH);
1027
1275
  return (imageRendererFactory.mimeTypes.indexOf(data.model.mimetype) !== -1);
1028
1276
  }
1029
1277
  return imageRendererFactory.mimeTypes.indexOf(mimeType) !== -1;
1030
- }));
1278
+ });
1031
1279
  if (supportedMimeTypes.length === 0) {
1032
1280
  return;
1033
1281
  }
@@ -1134,15 +1382,16 @@ export class MarkdownCell extends AttachmentsCell {
1134
1382
  * Construct a Markdown cell widget.
1135
1383
  */
1136
1384
  constructor(options) {
1137
- var _a, _b, _c;
1138
- super(options);
1385
+ var _a, _b, _c, _d;
1386
+ super({ ...options, placeholder: true });
1387
+ this._headingsCache = null;
1139
1388
  this._headingCollapsedChanged = new Signal(this);
1389
+ this._prevText = '';
1140
1390
  this._rendered = true;
1141
1391
  this._renderedChanged = new Signal(this);
1142
- this._prevText = '';
1143
- this._ready = new PromiseDelegate();
1144
1392
  this._showEditorForReadOnlyMarkdown = true;
1145
1393
  this.addClass(MARKDOWN_CELL_CLASS);
1394
+ this.model.contentChanged.connect(this.onContentChanged, this);
1146
1395
  const trans = this.translator.load('jupyterlab');
1147
1396
  this.node.setAttribute('aria-label', trans.__('Markdown Cell Content'));
1148
1397
  // Ensure we can resolve attachments:
@@ -1154,33 +1403,32 @@ export class MarkdownCell extends AttachmentsCell {
1154
1403
  });
1155
1404
  this._renderer = this._rendermime.createRenderer('text/markdown');
1156
1405
  this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1157
- // Stop codemirror handling paste
1158
- this.editor.setOption('handlePaste', false);
1159
1406
  // Check if heading cell is set to be collapsed
1160
1407
  this._headingCollapsed = ((_b = this.model.metadata.get(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1161
- // Throttle the rendering rate of the widget.
1408
+ this._showEditorForReadOnlyMarkdown =
1409
+ (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1410
+ // Defer setting placeholder as the renderer must be instantiated before initializing the DOM
1411
+ this.placeholder = (_d = options.placeholder) !== null && _d !== void 0 ? _d : true;
1162
1412
  this._monitor = new ActivityMonitor({
1163
1413
  signal: this.model.contentChanged,
1164
1414
  timeout: RENDER_TIMEOUT
1165
1415
  });
1166
- this._monitor.activityStopped.connect(() => {
1167
- if (this._rendered) {
1168
- this.update();
1416
+ // Throttle the rendering rate of the widget.
1417
+ this.ready
1418
+ .then(() => {
1419
+ if (this.isDisposed) {
1420
+ // Bail early
1421
+ return;
1169
1422
  }
1170
- }, this);
1171
- void this._updateRenderedInput().then(() => {
1172
- this._ready.resolve(void 0);
1423
+ this._monitor.activityStopped.connect(() => {
1424
+ if (this._rendered) {
1425
+ this.update();
1426
+ }
1427
+ }, this);
1428
+ })
1429
+ .catch(reason => {
1430
+ console.error('Failed to be ready', reason);
1173
1431
  });
1174
- this.renderCollapseButtons(this._renderer);
1175
- this.renderInput(this._renderer);
1176
- this._showEditorForReadOnlyMarkdown =
1177
- (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1178
- }
1179
- /**
1180
- * A promise that resolves when the widget renders for the first time.
1181
- */
1182
- get ready() {
1183
- return this._ready.promise;
1184
1432
  }
1185
1433
  /**
1186
1434
  * Text that represents the highest heading (i.e. lowest level) if cell is a heading.
@@ -1188,10 +1436,7 @@ export class MarkdownCell extends AttachmentsCell {
1188
1436
  */
1189
1437
  get headingInfo() {
1190
1438
  // Use table of content algorithm for consistency
1191
- const headings = TableOfContentsUtils.Markdown.getHeadings(this.model.value.text, {
1192
- maximalDepth: 6,
1193
- numberHeaders: false
1194
- });
1439
+ const headings = this.headings;
1195
1440
  if (headings.length > 0) {
1196
1441
  // Return the highest level
1197
1442
  const { text, level } = headings.reduce((prev, curr) => (prev.level <= curr.level ? prev : curr), headings[0]);
@@ -1201,6 +1446,16 @@ export class MarkdownCell extends AttachmentsCell {
1201
1446
  return { text: '', level: -1 };
1202
1447
  }
1203
1448
  }
1449
+ get headings() {
1450
+ if (!this._headingsCache) {
1451
+ // Use table of content algorithm for consistency
1452
+ const headings = TableOfContentsUtils.Markdown.getHeadings(this.model.sharedModel.getSource());
1453
+ this._headingsCache = headings.map(h => {
1454
+ return { ...h, type: Cell.HeadingType.Markdown };
1455
+ });
1456
+ }
1457
+ return [...this._headingsCache];
1458
+ }
1204
1459
  /**
1205
1460
  * Whether the heading is collapsed or not.
1206
1461
  */
@@ -1208,6 +1463,7 @@ export class MarkdownCell extends AttachmentsCell {
1208
1463
  return this._headingCollapsed;
1209
1464
  }
1210
1465
  set headingCollapsed(value) {
1466
+ var _a;
1211
1467
  if (this._headingCollapsed !== value) {
1212
1468
  this._headingCollapsed = value;
1213
1469
  if (value) {
@@ -1216,7 +1472,7 @@ export class MarkdownCell extends AttachmentsCell {
1216
1472
  else if (this.model.metadata.has(MARKDOWN_HEADING_COLLAPSED)) {
1217
1473
  this.model.metadata.delete(MARKDOWN_HEADING_COLLAPSED);
1218
1474
  }
1219
- const collapseButton = this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1475
+ const collapseButton = (_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1220
1476
  if (collapseButton) {
1221
1477
  if (value) {
1222
1478
  collapseButton.classList.add('jp-mod-collapsed');
@@ -1260,10 +1516,15 @@ export class MarkdownCell extends AttachmentsCell {
1260
1516
  return;
1261
1517
  }
1262
1518
  this._rendered = value;
1263
- this._handleRendered();
1264
- // If the rendered state changed, raise an event.
1265
- this._displayChanged.emit();
1266
- this._renderedChanged.emit(this._rendered);
1519
+ this._handleRendered()
1520
+ .then(() => {
1521
+ // If the rendered state changed, raise an event.
1522
+ this._displayChanged.emit();
1523
+ this._renderedChanged.emit(this._rendered);
1524
+ })
1525
+ .catch(reason => {
1526
+ console.error('Failed to render', reason);
1527
+ });
1267
1528
  }
1268
1529
  /**
1269
1530
  * Signal emitted when the markdown cell rendered state changes
@@ -1289,6 +1550,9 @@ export class MarkdownCell extends AttachmentsCell {
1289
1550
  get renderer() {
1290
1551
  return this._renderer;
1291
1552
  }
1553
+ /**
1554
+ * Dispose of the resources held by the widget.
1555
+ */
1292
1556
  dispose() {
1293
1557
  if (this.isDisposed) {
1294
1558
  return;
@@ -1296,13 +1560,26 @@ export class MarkdownCell extends AttachmentsCell {
1296
1560
  this._monitor.dispose();
1297
1561
  super.dispose();
1298
1562
  }
1563
+ /**
1564
+ * Create children widgets.
1565
+ */
1566
+ initializeDOM() {
1567
+ super.initializeDOM();
1568
+ // Stop codemirror handling paste
1569
+ this.editor.setOption('handlePaste', false);
1570
+ this.renderCollapseButtons(this._renderer);
1571
+ this._handleRendered().catch(reason => {
1572
+ console.error('Failed to render', reason);
1573
+ });
1574
+ }
1299
1575
  maybeCreateCollapseButton() {
1300
- if (this.headingInfo.level > 0 &&
1301
- this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)
1302
- .length == 0) {
1576
+ var _a;
1577
+ const { level } = this.headingInfo;
1578
+ if (level > 0 &&
1579
+ ((_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS).length) == 0) {
1303
1580
  let collapseButton = this.inputArea.promptNode.appendChild(document.createElement('button'));
1304
1581
  collapseButton.className = `jp-Button ${HEADING_COLLAPSER_CLASS}`;
1305
- collapseButton.setAttribute('data-heading-level', this.headingInfo.level.toString());
1582
+ collapseButton.setAttribute('data-heading-level', level.toString());
1306
1583
  if (this._headingCollapsed) {
1307
1584
  collapseButton.classList.add('jp-mod-collapsed');
1308
1585
  }
@@ -1350,6 +1627,12 @@ export class MarkdownCell extends AttachmentsCell {
1350
1627
  }
1351
1628
  }
1352
1629
  }
1630
+ /**
1631
+ * Callback on content changed
1632
+ */
1633
+ onContentChanged() {
1634
+ this._headingsCache = null;
1635
+ }
1353
1636
  /**
1354
1637
  * Render the collapse button for heading cells,
1355
1638
  * and for collapsed heading cells render the "expand hidden cells"
@@ -1365,23 +1648,28 @@ export class MarkdownCell extends AttachmentsCell {
1365
1648
  */
1366
1649
  renderInput(widget) {
1367
1650
  this.addClass(RENDERED_CLASS);
1368
- this.renderCollapseButtons(widget);
1369
- this.inputArea.renderInput(widget);
1651
+ if (!this.placeholder && !this.isDisposed) {
1652
+ this.renderCollapseButtons(widget);
1653
+ this.inputArea.renderInput(widget);
1654
+ }
1370
1655
  }
1371
1656
  /**
1372
1657
  * Show the text editor instead of rendered input.
1373
1658
  */
1374
1659
  showEditor() {
1375
1660
  this.removeClass(RENDERED_CLASS);
1376
- this.inputArea.showEditor();
1377
- // if this is going to be a heading, place the cursor accordingly
1378
- let numHashAtStart = (this.model.value.text.match(/^#+/g) || [''])[0]
1379
- .length;
1380
- if (numHashAtStart > 0) {
1381
- this.inputArea.editor.setCursorPosition({
1382
- column: numHashAtStart + 1,
1383
- line: 0
1384
- });
1661
+ if (!this.placeholder && !this.isDisposed) {
1662
+ this.inputArea.showEditor();
1663
+ // if this is going to be a heading, place the cursor accordingly
1664
+ let numHashAtStart = (this.model.sharedModel
1665
+ .getSource()
1666
+ .match(/^#+/g) || [''])[0].length;
1667
+ if (numHashAtStart > 0) {
1668
+ this.inputArea.editor.setCursorPosition({
1669
+ column: numHashAtStart + 1,
1670
+ line: 0
1671
+ });
1672
+ }
1385
1673
  }
1386
1674
  }
1387
1675
  /*
@@ -1389,7 +1677,9 @@ export class MarkdownCell extends AttachmentsCell {
1389
1677
  */
1390
1678
  onUpdateRequest(msg) {
1391
1679
  // Make sure we are properly rendered.
1392
- this._handleRendered();
1680
+ this._handleRendered().catch(reason => {
1681
+ console.error('Failed to render', reason);
1682
+ });
1393
1683
  super.onUpdateRequest(msg);
1394
1684
  }
1395
1685
  /**
@@ -1398,19 +1688,23 @@ export class MarkdownCell extends AttachmentsCell {
1398
1688
  updateCellSourceWithAttachment(attachmentName, URI) {
1399
1689
  var _a, _b;
1400
1690
  const textToBeAppended = `![${attachmentName}](attachment:${URI !== null && URI !== void 0 ? URI : attachmentName})`;
1401
- (_b = (_a = this.editor).replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1691
+ // TODO this should be done on the model...
1692
+ (_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1402
1693
  }
1403
1694
  /**
1404
1695
  * Handle the rendered state.
1405
1696
  */
1406
- _handleRendered() {
1697
+ async _handleRendered() {
1698
+ if (this.placeholder) {
1699
+ return Promise.resolve();
1700
+ }
1407
1701
  if (!this._rendered) {
1408
1702
  this.showEditor();
1409
1703
  }
1410
1704
  else {
1411
1705
  // TODO: It would be nice for the cell to provide a way for
1412
1706
  // its consumers to hook into when the rendering is done.
1413
- void this._updateRenderedInput();
1707
+ await this._updateRenderedInput();
1414
1708
  this.renderInput(this._renderer);
1415
1709
  }
1416
1710
  }
@@ -1419,7 +1713,7 @@ export class MarkdownCell extends AttachmentsCell {
1419
1713
  */
1420
1714
  _updateRenderedInput() {
1421
1715
  const model = this.model;
1422
- const text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
1716
+ const text = (model && model.sharedModel.getSource()) || DEFAULT_MARKDOWN_TEXT;
1423
1717
  // Do not re-render if the text has not changed.
1424
1718
  if (text !== this._prevText) {
1425
1719
  const mimeModel = new MimeModel({ data: { 'text/markdown': text } });