@jupyterlab/cells 4.0.0-alpha.13 → 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
@@ -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,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,46 +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
- translator: this.translator
546
- }));
547
- output.addClass(CELL_OUTPUT_AREA_CLASS);
735
+ outputWrapper.addWidget(outputCollapser);
548
736
  // Set a CSS if there are no outputs, and connect a signal for future
549
737
  // changes to the number of outputs. This is for conditional styling
550
738
  // if there are no outputs.
551
- if (model.outputs.length === 0) {
739
+ if (this.model.outputs.length === 0) {
552
740
  this.addClass(NO_OUTPUTS_CLASS);
553
- ariaLabel = trans.__('Code Cell Content');
554
741
  }
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) {
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) {
561
748
  this.addClass(DIRTY_CLASS);
562
749
  }
563
750
  this._outputPlaceholder = new OutputPlaceholder(() => {
564
751
  this.outputHidden = !this.outputHidden;
565
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);
566
758
  }
567
- model.stateChanged.connect(this.onStateChanged, this);
568
- this.node.setAttribute('aria-label', ariaLabel);
569
759
  }
570
760
  /**
571
761
  * Initialize view state from model.
@@ -580,6 +770,47 @@ export class CodeCell extends Cell {
580
770
  this.setPrompt(`${this.model.executionCount || ''}`);
581
771
  return this;
582
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
+ }
583
814
  /**
584
815
  * Get the output area for the cell.
585
816
  */
@@ -596,20 +827,22 @@ export class CodeCell extends Cell {
596
827
  if (this._outputHidden === value) {
597
828
  return;
598
829
  }
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();
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
+ }
605
838
  }
606
- }
607
- else {
608
- if (this._outputWrapper.isHidden) {
609
- 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);
610
845
  }
611
- layout.removeWidget(this._outputPlaceholder);
612
- layout.addWidget(this._output);
613
846
  }
614
847
  this._outputHidden = value;
615
848
  if (this.syncCollapse) {
@@ -724,6 +957,9 @@ export class CodeCell extends Cell {
724
957
  * is hidden without accessing private state.
725
958
  */
726
959
  handleInputHidden(value) {
960
+ if (this.placeholder) {
961
+ return;
962
+ }
727
963
  if (!value && this._outputWrapper.isHidden) {
728
964
  this._outputWrapper.show();
729
965
  }
@@ -788,6 +1024,12 @@ export class CodeCell extends Cell {
788
1024
  break;
789
1025
  }
790
1026
  }
1027
+ /**
1028
+ * Callback on output changes
1029
+ */
1030
+ onOutputChanged() {
1031
+ this._headingsCache = null;
1032
+ }
791
1033
  /**
792
1034
  * Handle changes in the metadata.
793
1035
  */
@@ -835,13 +1077,17 @@ export class CodeCell extends Cell {
835
1077
  async function execute(cell, sessionContext, metadata) {
836
1078
  var _a;
837
1079
  const model = cell.model;
838
- const code = model.value.text;
1080
+ const code = model.sharedModel.getSource();
839
1081
  if (!code.trim() || !((_a = sessionContext.session) === null || _a === void 0 ? void 0 : _a.kernel)) {
840
1082
  model.clearExecution();
841
1083
  return;
842
1084
  }
843
- const cellId = { cellId: model.id };
844
- 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
+ };
845
1091
  const { recordTiming } = metadata;
846
1092
  model.clearExecution();
847
1093
  cell.outputHidden = false;
@@ -971,6 +1217,7 @@ export class AttachmentsCell extends Cell {
971
1217
  node.removeEventListener('paste', this);
972
1218
  node.removeEventListener('lm-dragover', this);
973
1219
  node.removeEventListener('lm-drop', this);
1220
+ super.onBeforeDetach(msg);
974
1221
  }
975
1222
  _evtDragOver(event) {
976
1223
  const supportedMimeType = some(imageRendererFactory.mimeTypes, mimeType => {
@@ -1135,15 +1382,16 @@ export class MarkdownCell extends AttachmentsCell {
1135
1382
  * Construct a Markdown cell widget.
1136
1383
  */
1137
1384
  constructor(options) {
1138
- var _a, _b, _c;
1139
- super(options);
1385
+ var _a, _b, _c, _d;
1386
+ super({ ...options, placeholder: true });
1387
+ this._headingsCache = null;
1140
1388
  this._headingCollapsedChanged = new Signal(this);
1389
+ this._prevText = '';
1141
1390
  this._rendered = true;
1142
1391
  this._renderedChanged = new Signal(this);
1143
- this._prevText = '';
1144
- this._ready = new PromiseDelegate();
1145
1392
  this._showEditorForReadOnlyMarkdown = true;
1146
1393
  this.addClass(MARKDOWN_CELL_CLASS);
1394
+ this.model.contentChanged.connect(this.onContentChanged, this);
1147
1395
  const trans = this.translator.load('jupyterlab');
1148
1396
  this.node.setAttribute('aria-label', trans.__('Markdown Cell Content'));
1149
1397
  // Ensure we can resolve attachments:
@@ -1155,33 +1403,32 @@ export class MarkdownCell extends AttachmentsCell {
1155
1403
  });
1156
1404
  this._renderer = this._rendermime.createRenderer('text/markdown');
1157
1405
  this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1158
- // Stop codemirror handling paste
1159
- this.editor.setOption('handlePaste', false);
1160
1406
  // Check if heading cell is set to be collapsed
1161
1407
  this._headingCollapsed = ((_b = this.model.metadata.get(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1162
- // 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;
1163
1412
  this._monitor = new ActivityMonitor({
1164
1413
  signal: this.model.contentChanged,
1165
1414
  timeout: RENDER_TIMEOUT
1166
1415
  });
1167
- this._monitor.activityStopped.connect(() => {
1168
- if (this._rendered) {
1169
- this.update();
1416
+ // Throttle the rendering rate of the widget.
1417
+ this.ready
1418
+ .then(() => {
1419
+ if (this.isDisposed) {
1420
+ // Bail early
1421
+ return;
1170
1422
  }
1171
- }, this);
1172
- void this._updateRenderedInput().then(() => {
1173
- 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);
1174
1431
  });
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
1432
  }
1186
1433
  /**
1187
1434
  * Text that represents the highest heading (i.e. lowest level) if cell is a heading.
@@ -1189,10 +1436,7 @@ export class MarkdownCell extends AttachmentsCell {
1189
1436
  */
1190
1437
  get headingInfo() {
1191
1438
  // Use table of content algorithm for consistency
1192
- const headings = TableOfContentsUtils.Markdown.getHeadings(this.model.value.text, {
1193
- maximalDepth: 6,
1194
- numberHeaders: false
1195
- });
1439
+ const headings = this.headings;
1196
1440
  if (headings.length > 0) {
1197
1441
  // Return the highest level
1198
1442
  const { text, level } = headings.reduce((prev, curr) => (prev.level <= curr.level ? prev : curr), headings[0]);
@@ -1202,6 +1446,16 @@ export class MarkdownCell extends AttachmentsCell {
1202
1446
  return { text: '', level: -1 };
1203
1447
  }
1204
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
+ }
1205
1459
  /**
1206
1460
  * Whether the heading is collapsed or not.
1207
1461
  */
@@ -1209,6 +1463,7 @@ export class MarkdownCell extends AttachmentsCell {
1209
1463
  return this._headingCollapsed;
1210
1464
  }
1211
1465
  set headingCollapsed(value) {
1466
+ var _a;
1212
1467
  if (this._headingCollapsed !== value) {
1213
1468
  this._headingCollapsed = value;
1214
1469
  if (value) {
@@ -1217,7 +1472,7 @@ export class MarkdownCell extends AttachmentsCell {
1217
1472
  else if (this.model.metadata.has(MARKDOWN_HEADING_COLLAPSED)) {
1218
1473
  this.model.metadata.delete(MARKDOWN_HEADING_COLLAPSED);
1219
1474
  }
1220
- 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];
1221
1476
  if (collapseButton) {
1222
1477
  if (value) {
1223
1478
  collapseButton.classList.add('jp-mod-collapsed');
@@ -1261,10 +1516,15 @@ export class MarkdownCell extends AttachmentsCell {
1261
1516
  return;
1262
1517
  }
1263
1518
  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);
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
+ });
1268
1528
  }
1269
1529
  /**
1270
1530
  * Signal emitted when the markdown cell rendered state changes
@@ -1290,6 +1550,9 @@ export class MarkdownCell extends AttachmentsCell {
1290
1550
  get renderer() {
1291
1551
  return this._renderer;
1292
1552
  }
1553
+ /**
1554
+ * Dispose of the resources held by the widget.
1555
+ */
1293
1556
  dispose() {
1294
1557
  if (this.isDisposed) {
1295
1558
  return;
@@ -1297,13 +1560,26 @@ export class MarkdownCell extends AttachmentsCell {
1297
1560
  this._monitor.dispose();
1298
1561
  super.dispose();
1299
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
+ }
1300
1575
  maybeCreateCollapseButton() {
1301
- if (this.headingInfo.level > 0 &&
1302
- this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)
1303
- .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) {
1304
1580
  let collapseButton = this.inputArea.promptNode.appendChild(document.createElement('button'));
1305
1581
  collapseButton.className = `jp-Button ${HEADING_COLLAPSER_CLASS}`;
1306
- collapseButton.setAttribute('data-heading-level', this.headingInfo.level.toString());
1582
+ collapseButton.setAttribute('data-heading-level', level.toString());
1307
1583
  if (this._headingCollapsed) {
1308
1584
  collapseButton.classList.add('jp-mod-collapsed');
1309
1585
  }
@@ -1351,6 +1627,12 @@ export class MarkdownCell extends AttachmentsCell {
1351
1627
  }
1352
1628
  }
1353
1629
  }
1630
+ /**
1631
+ * Callback on content changed
1632
+ */
1633
+ onContentChanged() {
1634
+ this._headingsCache = null;
1635
+ }
1354
1636
  /**
1355
1637
  * Render the collapse button for heading cells,
1356
1638
  * and for collapsed heading cells render the "expand hidden cells"
@@ -1366,23 +1648,28 @@ export class MarkdownCell extends AttachmentsCell {
1366
1648
  */
1367
1649
  renderInput(widget) {
1368
1650
  this.addClass(RENDERED_CLASS);
1369
- this.renderCollapseButtons(widget);
1370
- this.inputArea.renderInput(widget);
1651
+ if (!this.placeholder && !this.isDisposed) {
1652
+ this.renderCollapseButtons(widget);
1653
+ this.inputArea.renderInput(widget);
1654
+ }
1371
1655
  }
1372
1656
  /**
1373
1657
  * Show the text editor instead of rendered input.
1374
1658
  */
1375
1659
  showEditor() {
1376
1660
  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
- });
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
+ }
1386
1673
  }
1387
1674
  }
1388
1675
  /*
@@ -1390,7 +1677,9 @@ export class MarkdownCell extends AttachmentsCell {
1390
1677
  */
1391
1678
  onUpdateRequest(msg) {
1392
1679
  // Make sure we are properly rendered.
1393
- this._handleRendered();
1680
+ this._handleRendered().catch(reason => {
1681
+ console.error('Failed to render', reason);
1682
+ });
1394
1683
  super.onUpdateRequest(msg);
1395
1684
  }
1396
1685
  /**
@@ -1399,19 +1688,23 @@ export class MarkdownCell extends AttachmentsCell {
1399
1688
  updateCellSourceWithAttachment(attachmentName, URI) {
1400
1689
  var _a, _b;
1401
1690
  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);
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);
1403
1693
  }
1404
1694
  /**
1405
1695
  * Handle the rendered state.
1406
1696
  */
1407
- _handleRendered() {
1697
+ async _handleRendered() {
1698
+ if (this.placeholder) {
1699
+ return Promise.resolve();
1700
+ }
1408
1701
  if (!this._rendered) {
1409
1702
  this.showEditor();
1410
1703
  }
1411
1704
  else {
1412
1705
  // TODO: It would be nice for the cell to provide a way for
1413
1706
  // its consumers to hook into when the rendering is done.
1414
- void this._updateRenderedInput();
1707
+ await this._updateRenderedInput();
1415
1708
  this.renderInput(this._renderer);
1416
1709
  }
1417
1710
  }
@@ -1420,7 +1713,7 @@ export class MarkdownCell extends AttachmentsCell {
1420
1713
  */
1421
1714
  _updateRenderedInput() {
1422
1715
  const model = this.model;
1423
- const text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
1716
+ const text = (model && model.sharedModel.getSource()) || DEFAULT_MARKDOWN_TEXT;
1424
1717
  // Do not re-render if the text has not changed.
1425
1718
  if (text !== this._prevText) {
1426
1719
  const mimeModel = new MimeModel({ data: { 'text/markdown': text } });