@jupyterlab/cells 4.0.0-alpha.9 → 4.0.0-beta.0

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