@jupyterlab/cells 4.0.0-alpha.8 → 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,22 +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';
16
+ import { Debouncer } from '@lumino/polling';
17
+ import { Signal } from '@lumino/signaling';
13
18
  import { Panel, PanelLayout, Widget } from '@lumino/widgets';
14
19
  import { InputCollapser, OutputCollapser } from './collapser';
15
20
  import { CellFooter, CellHeader } from './headerfooter';
16
21
  import { InputArea, InputPrompt } from './inputarea';
17
22
  import { InputPlaceholder, OutputPlaceholder } from './placeholder';
18
23
  import { ResizeHandle } from './resizeHandle';
19
- import { Signal } from '@lumino/signaling';
20
- import { addIcon } from '@jupyterlab/ui-components';
21
24
  /**
22
25
  * The CSS class added to cell widgets.
23
26
  */
@@ -54,10 +57,6 @@ const CELL_INPUT_COLLAPSER_CLASS = 'jp-Cell-inputCollapser';
54
57
  * The CSS class added to the cell output collapser.
55
58
  */
56
59
  const CELL_OUTPUT_COLLAPSER_CLASS = 'jp-Cell-outputCollapser';
57
- /**
58
- * The class name added to the cell when readonly.
59
- */
60
- const READONLY_CLASS = 'jp-mod-readOnly';
61
60
  /**
62
61
  * The class name added to the cell when dirty.
63
62
  */
@@ -74,7 +73,7 @@ const MARKDOWN_CELL_CLASS = 'jp-MarkdownCell';
74
73
  * The class name added to rendered markdown output widgets.
75
74
  */
76
75
  const MARKDOWN_OUTPUT_CLASS = 'jp-MarkdownOutput';
77
- export const MARKDOWN_HEADING_COLLAPSED = 'jp-MarkdownHeadingCollapsed';
76
+ const MARKDOWN_HEADING_COLLAPSED = 'jp-MarkdownHeadingCollapsed';
78
77
  const HEADING_COLLAPSER_CLASS = 'jp-collapseHeadingButton';
79
78
  const SHOW_HIDDEN_CELLS_CLASS = 'jp-showHiddenCellsButton';
80
79
  /**
@@ -109,49 +108,31 @@ export class Cell extends Widget {
109
108
  * Construct a new base cell widget.
110
109
  */
111
110
  constructor(options) {
111
+ var _a, _b, _c, _d;
112
112
  super();
113
- this._readOnly = false;
113
+ this.prompt = '';
114
+ this._displayChanged = new Signal(this);
115
+ this._editorConfig = {};
114
116
  this._inputHidden = false;
117
+ this._inViewportChanged = new Signal(this);
118
+ this._readOnly = false;
119
+ this._ready = new PromiseDelegate();
120
+ this._resizeDebouncer = new Debouncer(() => {
121
+ this._displayChanged.emit();
122
+ }, 0);
115
123
  this._syncCollapse = false;
116
124
  this._syncEditable = false;
117
125
  this.addClass(CELL_CLASS);
118
126
  const model = (this._model = options.model);
119
- const contentFactory = (this.contentFactory =
120
- options.contentFactory || Cell.defaultContentFactory);
121
- this.layout = new PanelLayout();
127
+ this.contentFactory = options.contentFactory;
128
+ this.layout = (_a = options.layout) !== null && _a !== void 0 ? _a : new PanelLayout();
122
129
  // Set up translator for aria labels
123
- this.translator = options.translator || nullTranslator;
124
- // Header
125
- const header = contentFactory.createCellHeader();
126
- header.addClass(CELL_HEADER_CLASS);
127
- this.layout.addWidget(header);
128
- // Input
129
- const inputWrapper = (this._inputWrapper = new Panel());
130
- inputWrapper.addClass(CELL_INPUT_WRAPPER_CLASS);
131
- const inputCollapser = new InputCollapser();
132
- inputCollapser.addClass(CELL_INPUT_COLLAPSER_CLASS);
133
- const input = (this._input = new InputArea({
134
- model,
135
- contentFactory,
136
- updateOnShow: options.updateEditorOnShow,
137
- placeholder: options.placeholder
138
- }));
139
- input.addClass(CELL_INPUT_AREA_CLASS);
140
- inputWrapper.addWidget(inputCollapser);
141
- inputWrapper.addWidget(input);
142
- this.layout.addWidget(inputWrapper);
143
- this._inputPlaceholder = new InputPlaceholder(() => {
144
- this.inputHidden = !this.inputHidden;
145
- });
146
- // Footer
147
- const footer = this.contentFactory.createCellFooter();
148
- footer.addClass(CELL_FOOTER_CLASS);
149
- this.layout.addWidget(footer);
150
- // Editor settings
151
- if (options.editorConfig) {
152
- this.editor.setOptions(Object.assign({}, options.editorConfig));
153
- }
154
- 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);
155
136
  }
156
137
  /**
157
138
  * Initialize view state from model.
@@ -165,10 +146,51 @@ export class Cell extends Widget {
165
146
  this.loadEditableState();
166
147
  return this;
167
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
+ }
168
187
  /**
169
188
  * Get the prompt node used by the cell.
170
189
  */
171
190
  get promptNode() {
191
+ if (this.placeholder) {
192
+ return null;
193
+ }
172
194
  if (!this._inputHidden) {
173
195
  return this._input.promptNode;
174
196
  }
@@ -181,13 +203,27 @@ export class Cell extends Widget {
181
203
  * Get the CodeEditorWrapper used by the cell.
182
204
  */
183
205
  get editorWidget() {
184
- 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;
185
208
  }
186
209
  /**
187
210
  * Get the CodeEditor used by the cell.
188
211
  */
189
212
  get editor() {
190
- 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();
191
227
  }
192
228
  /**
193
229
  * Get the model used by the cell.
@@ -217,40 +253,54 @@ export class Cell extends Widget {
217
253
  }
218
254
  this.update();
219
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
+ }
220
266
  /**
221
267
  * Save view editable state to model
222
268
  */
223
269
  saveEditableState() {
224
- const { metadata } = this.model;
225
- const current = metadata.get('editable');
270
+ const { sharedModel } = this.model;
271
+ const current = sharedModel.getMetadata('editable');
226
272
  if ((this.readOnly && current === false) ||
227
273
  (!this.readOnly && current === undefined)) {
228
274
  return;
229
275
  }
230
276
  if (this.readOnly) {
231
- this.model.metadata.set('editable', false);
277
+ sharedModel.setMetadata('editable', false);
232
278
  }
233
279
  else {
234
- this.model.metadata.delete('editable');
280
+ sharedModel.deleteMetadata('editable');
235
281
  }
236
282
  }
237
283
  /**
238
284
  * Load view editable state from model.
239
285
  */
240
286
  loadEditableState() {
241
- this.readOnly = this.model.metadata.get('editable') === false;
287
+ this.readOnly =
288
+ this.model.sharedModel.getMetadata('editable') ===
289
+ false;
242
290
  }
243
291
  /**
244
292
  * A promise that resolves when the widget renders for the first time.
245
293
  */
246
294
  get ready() {
247
- return Promise.resolve(undefined);
295
+ return this._ready.promise;
248
296
  }
249
297
  /**
250
298
  * Set the prompt for the widget.
251
299
  */
252
300
  setPrompt(value) {
253
- this._input.setPrompt(value);
301
+ var _a;
302
+ this.prompt = value;
303
+ (_a = this._input) === null || _a === void 0 ? void 0 : _a.setPrompt(value);
254
304
  }
255
305
  /**
256
306
  * The view state of input being hidden.
@@ -262,14 +312,16 @@ export class Cell extends Widget {
262
312
  if (this._inputHidden === value) {
263
313
  return;
264
314
  }
265
- const layout = this._inputWrapper.layout;
266
- if (value) {
267
- this._input.parent = null;
268
- layout.addWidget(this._inputPlaceholder);
269
- }
270
- else {
271
- this._inputPlaceholder.parent = null;
272
- 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
+ }
273
325
  }
274
326
  this._inputHidden = value;
275
327
  if (this.syncCollapse) {
@@ -281,7 +333,7 @@ export class Cell extends Widget {
281
333
  * Save view collapse state to model
282
334
  */
283
335
  saveCollapseState() {
284
- const jupyter = Object.assign({}, this.model.metadata.get('jupyter'));
336
+ const jupyter = { ...this.model.getMetadata('jupyter') };
285
337
  if ((this.inputHidden && jupyter.source_hidden === true) ||
286
338
  (!this.inputHidden && jupyter.source_hidden === undefined)) {
287
339
  return;
@@ -293,17 +345,18 @@ export class Cell extends Widget {
293
345
  delete jupyter.source_hidden;
294
346
  }
295
347
  if (Object.keys(jupyter).length === 0) {
296
- this.model.metadata.delete('jupyter');
348
+ this.model.deleteMetadata('jupyter');
297
349
  }
298
350
  else {
299
- this.model.metadata.set('jupyter', jupyter);
351
+ this.model.setMetadata('jupyter', jupyter);
300
352
  }
301
353
  }
302
354
  /**
303
355
  * Revert view collapse state from model.
304
356
  */
305
357
  loadCollapseState() {
306
- const jupyter = this.model.metadata.get('jupyter') || {};
358
+ var _a;
359
+ const jupyter = (_a = this.model.getMetadata('jupyter')) !== null && _a !== void 0 ? _a : {};
307
360
  this.inputHidden = !!jupyter.source_hidden;
308
361
  }
309
362
  /**
@@ -367,12 +420,79 @@ export class Cell extends Widget {
367
420
  if (this.isDisposed) {
368
421
  return;
369
422
  }
423
+ this._resizeDebouncer.dispose();
370
424
  this._input = null;
371
425
  this._model = null;
372
426
  this._inputWrapper = null;
373
427
  this._inputPlaceholder = null;
374
428
  super.dispose();
375
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
+ }
376
496
  /**
377
497
  * Handle `after-attach` messages.
378
498
  */
@@ -383,26 +503,26 @@ export class Cell extends Widget {
383
503
  * Handle `'activate-request'` messages.
384
504
  */
385
505
  onActivateRequest(msg) {
386
- this.editor.focus();
506
+ var _a;
507
+ (_a = this.editor) === null || _a === void 0 ? void 0 : _a.focus();
387
508
  }
388
509
  /**
389
- * Handle `fit-request` messages.
510
+ * Handle `resize` messages.
390
511
  */
391
- onFitRequest(msg) {
392
- // need this for for when a theme changes font size
393
- this.editor.refresh();
512
+ onResize(msg) {
513
+ void this._resizeDebouncer.invoke();
394
514
  }
395
515
  /**
396
516
  * Handle `update-request` messages.
397
517
  */
398
518
  onUpdateRequest(msg) {
519
+ var _a, _b;
399
520
  if (!this._model) {
400
521
  return;
401
522
  }
402
523
  // Handle read only state.
403
- if (this.editor.getOption('readOnly') !== this._readOnly) {
404
- this.editor.setOption('readOnly', this._readOnly);
405
- 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);
406
526
  }
407
527
  }
408
528
  /**
@@ -429,6 +549,20 @@ export class Cell extends Widget {
429
549
  * The namespace for the `Cell` class statics.
430
550
  */
431
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 = {}));
432
566
  /**
433
567
  * The default implementation of an `IContentFactory`.
434
568
  *
@@ -438,9 +572,8 @@ export class Cell extends Widget {
438
572
  /**
439
573
  * Create a content factory for a cell.
440
574
  */
441
- constructor(options = {}) {
442
- this._editorFactory =
443
- options.editorFactory || InputArea.defaultEditorFactory;
575
+ constructor(options) {
576
+ this._editorFactory = options.editorFactory;
444
577
  }
445
578
  /**
446
579
  * The readonly editor factory that create code editors
@@ -480,14 +613,79 @@ export class Cell extends Widget {
480
613
  }
481
614
  }
482
615
  Cell.ContentFactory = ContentFactory;
483
- /**
484
- * The default content factory for cells.
485
- */
486
- Cell.defaultContentFactory = new ContentFactory();
487
616
  })(Cell || (Cell = {}));
488
617
  /** ****************************************************************************
489
618
  * CodeCell
490
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
+ }
491
689
  /**
492
690
  * A widget for a code cell.
493
691
  */
@@ -496,54 +694,91 @@ export class CodeCell extends Cell {
496
694
  * Construct a code cell widget.
497
695
  */
498
696
  constructor(options) {
499
- super(options);
697
+ var _a;
698
+ super({ layout: new CodeCellLayout(), ...options, placeholder: true });
699
+ this._headingsCache = null;
500
700
  this._outputHidden = false;
701
+ this._outputWrapper = null;
702
+ this._outputPlaceholder = null;
501
703
  this._syncScrolled = false;
502
- this._savingMetadata = false;
503
704
  this.addClass(CODE_CELL_CLASS);
504
705
  const trans = this.translator.load('jupyterlab');
505
706
  // Only save options not handled by parent constructor.
506
707
  const rendermime = (this._rendermime = options.rendermime);
507
708
  const contentFactory = this.contentFactory;
508
709
  const model = this.model;
710
+ this.maxNumberOutputs = options.maxNumberOutputs;
509
711
  // Note that modifying the below label warrants one to also modify
510
712
  // the same in this._outputLengthHandler. Ideally, this label must
511
713
  // have been a constant and used in both places but it is not done
512
714
  // so because of limitations in the translation manager.
513
- let ariaLabel = trans.__('Code Cell Content with Output');
514
- if (!options.placeholder) {
515
- // Insert the output before the cell footer.
516
- const outputWrapper = (this._outputWrapper = new Panel());
517
- outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
518
- const outputCollapser = new OutputCollapser();
519
- outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
520
- const output = (this._output = new OutputArea({
521
- model: model.outputs,
522
- rendermime,
523
- contentFactory: contentFactory,
524
- maxNumberOutputs: options.maxNumberOutputs
525
- }));
526
- output.addClass(CELL_OUTPUT_AREA_CLASS);
527
- // Set a CSS if there are no outputs, and connect a signal for future
528
- // changes to the number of outputs. This is for conditional styling
529
- // if there are no outputs.
530
- if (model.outputs.length === 0) {
531
- this.addClass(NO_OUTPUTS_CLASS);
532
- ariaLabel = trans.__('Code Cell Content');
533
- }
534
- output.outputLengthChanged.connect(this._outputLengthHandler, this);
535
- outputWrapper.addWidget(outputCollapser);
536
- outputWrapper.addWidget(output);
537
- this.layout.insertWidget(2, new ResizeHandle(this.node));
538
- this.layout.insertWidget(3, outputWrapper);
539
- if (model.isDirty) {
540
- 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();
541
776
  }
542
- this._outputPlaceholder = new OutputPlaceholder(() => {
543
- this.outputHidden = !this.outputHidden;
544
- });
545
777
  }
546
- 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');
547
782
  this.node.setAttribute('aria-label', ariaLabel);
548
783
  }
549
784
  /**
@@ -559,6 +794,47 @@ export class CodeCell extends Cell {
559
794
  this.setPrompt(`${this.model.executionCount || ''}`);
560
795
  return this;
561
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
+ }
562
838
  /**
563
839
  * Get the output area for the cell.
564
840
  */
@@ -575,20 +851,22 @@ export class CodeCell extends Cell {
575
851
  if (this._outputHidden === value) {
576
852
  return;
577
853
  }
578
- const layout = this._outputWrapper.layout;
579
- if (value) {
580
- layout.removeWidget(this._output);
581
- layout.addWidget(this._outputPlaceholder);
582
- if (this.inputHidden && !this._outputWrapper.isHidden) {
583
- 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
+ }
584
862
  }
585
- }
586
- else {
587
- if (this._outputWrapper.isHidden) {
588
- 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);
589
869
  }
590
- layout.removeWidget(this._outputPlaceholder);
591
- layout.addWidget(this._output);
592
870
  }
593
871
  this._outputHidden = value;
594
872
  if (this.syncCollapse) {
@@ -604,11 +882,9 @@ export class CodeCell extends Cell {
604
882
  // to changes in metadata until we have fully committed our changes.
605
883
  // Otherwise setting one key can trigger a write to the other key to
606
884
  // maintain the synced consistency.
607
- this._savingMetadata = true;
608
- try {
885
+ this.model.sharedModel.transact(() => {
609
886
  super.saveCollapseState();
610
- const metadata = this.model.metadata;
611
- const collapsed = this.model.metadata.get('collapsed');
887
+ const collapsed = this.model.getMetadata('collapsed');
612
888
  if ((this.outputHidden && collapsed === true) ||
613
889
  (!this.outputHidden && collapsed === undefined)) {
614
890
  return;
@@ -616,15 +892,12 @@ export class CodeCell extends Cell {
616
892
  // Do not set jupyter.outputs_hidden since it is redundant. See
617
893
  // and https://github.com/jupyter/nbformat/issues/137
618
894
  if (this.outputHidden) {
619
- metadata.set('collapsed', true);
895
+ this.model.setMetadata('collapsed', true);
620
896
  }
621
897
  else {
622
- metadata.delete('collapsed');
898
+ this.model.deleteMetadata('collapsed');
623
899
  }
624
- }
625
- finally {
626
- this._savingMetadata = false;
627
- }
900
+ }, false);
628
901
  }
629
902
  /**
630
903
  * Revert view collapse state from model.
@@ -634,7 +907,7 @@ export class CodeCell extends Cell {
634
907
  */
635
908
  loadCollapseState() {
636
909
  super.loadCollapseState();
637
- this.outputHidden = !!this.model.metadata.get('collapsed');
910
+ this.outputHidden = !!this.model.getMetadata('collapsed');
638
911
  }
639
912
  /**
640
913
  * Whether the output is in a scrolled state?
@@ -653,30 +926,28 @@ export class CodeCell extends Cell {
653
926
  * Save view collapse state to model
654
927
  */
655
928
  saveScrolledState() {
656
- const { metadata } = this.model;
657
- const current = metadata.get('scrolled');
929
+ const current = this.model.getMetadata('scrolled');
658
930
  if ((this.outputsScrolled && current === true) ||
659
931
  (!this.outputsScrolled && current === undefined)) {
660
932
  return;
661
933
  }
662
934
  if (this.outputsScrolled) {
663
- metadata.set('scrolled', true);
935
+ this.model.setMetadata('scrolled', true);
664
936
  }
665
937
  else {
666
- metadata.delete('scrolled');
938
+ this.model.deleteMetadata('scrolled');
667
939
  }
668
940
  }
669
941
  /**
670
942
  * Revert view collapse state from model.
671
943
  */
672
944
  loadScrolledState() {
673
- const metadata = this.model.metadata;
674
945
  // We don't have the notion of 'auto' scrolled, so we make it false.
675
- if (metadata.get('scrolled') === 'auto') {
946
+ if (this.model.getMetadata('scrolled') === 'auto') {
676
947
  this.outputsScrolled = false;
677
948
  }
678
949
  else {
679
- this.outputsScrolled = !!metadata.get('scrolled');
950
+ this.outputsScrolled = !!this.model.getMetadata('scrolled');
680
951
  }
681
952
  }
682
953
  /**
@@ -703,6 +974,9 @@ export class CodeCell extends Cell {
703
974
  * is hidden without accessing private state.
704
975
  */
705
976
  handleInputHidden(value) {
977
+ if (this.placeholder) {
978
+ return;
979
+ }
706
980
  if (!value && this._outputWrapper.isHidden) {
707
981
  this._outputWrapper.show();
708
982
  }
@@ -767,14 +1041,16 @@ export class CodeCell extends Cell {
767
1041
  break;
768
1042
  }
769
1043
  }
1044
+ /**
1045
+ * Callback on output changes
1046
+ */
1047
+ onOutputChanged() {
1048
+ this._headingsCache = null;
1049
+ }
770
1050
  /**
771
1051
  * Handle changes in the metadata.
772
1052
  */
773
1053
  onMetadataChanged(model, args) {
774
- if (this._savingMetadata) {
775
- // We are in middle of a metadata transaction, so don't react to it.
776
- return;
777
- }
778
1054
  switch (args.key) {
779
1055
  case 'scrolled':
780
1056
  if (this.syncScrolled) {
@@ -814,16 +1090,24 @@ export class CodeCell extends Cell {
814
1090
  async function execute(cell, sessionContext, metadata) {
815
1091
  var _a;
816
1092
  const model = cell.model;
817
- const code = model.value.text;
1093
+ const code = model.sharedModel.getSource();
818
1094
  if (!code.trim() || !((_a = sessionContext.session) === null || _a === void 0 ? void 0 : _a.kernel)) {
819
- model.clearExecution();
1095
+ model.sharedModel.transact(() => {
1096
+ model.clearExecution();
1097
+ }, false);
820
1098
  return;
821
1099
  }
822
- const cellId = { cellId: model.id };
823
- 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
+ };
824
1106
  const { recordTiming } = metadata;
825
- model.clearExecution();
826
- cell.outputHidden = false;
1107
+ model.sharedModel.transact(() => {
1108
+ model.clearExecution();
1109
+ cell.outputHidden = false;
1110
+ }, false);
827
1111
  cell.setPrompt('*');
828
1112
  model.trusted = true;
829
1113
  let future;
@@ -846,22 +1130,22 @@ export class CodeCell extends Cell {
846
1130
  // If the data is missing, estimate it to now
847
1131
  // Date was added in 5.1: https://jupyter-client.readthedocs.io/en/stable/messaging.html#message-header
848
1132
  const value = msg.header.date || new Date().toISOString();
849
- const timingInfo = Object.assign({}, model.metadata.get('execution'));
1133
+ const timingInfo = Object.assign({}, model.getMetadata('execution'));
850
1134
  timingInfo[`iopub.${label}`] = value;
851
- model.metadata.set('execution', timingInfo);
1135
+ model.setMetadata('execution', timingInfo);
852
1136
  return true;
853
1137
  };
854
1138
  cell.outputArea.future.registerMessageHook(recordTimingHook);
855
1139
  }
856
1140
  else {
857
- model.metadata.delete('execution');
1141
+ model.deleteMetadata('execution');
858
1142
  }
859
1143
  // Save this execution's future so we can compare in the catch below.
860
1144
  future = cell.outputArea.future;
861
1145
  const msg = (await msgPromise);
862
1146
  model.executionCount = msg.content.execution_count;
863
1147
  if (recordTiming) {
864
- const timingInfo = Object.assign({}, model.metadata.get('execution'));
1148
+ const timingInfo = Object.assign({}, model.getMetadata('execution'));
865
1149
  const started = msg.metadata.started;
866
1150
  // Started is not in the API, but metadata IPyKernel sends
867
1151
  if (started) {
@@ -871,7 +1155,7 @@ export class CodeCell extends Cell {
871
1155
  const finished = msg.header.date;
872
1156
  timingInfo['shell.execute_reply'] =
873
1157
  finished || new Date().toISOString();
874
- model.metadata.set('execution', timingInfo);
1158
+ model.setMetadata('execution', timingInfo);
875
1159
  }
876
1160
  return msg;
877
1161
  }
@@ -903,18 +1187,6 @@ export class AttachmentsCell extends Cell {
903
1187
  */
904
1188
  handleEvent(event) {
905
1189
  switch (event.type) {
906
- case 'paste':
907
- this._evtPaste(event);
908
- break;
909
- case 'dragenter':
910
- event.preventDefault();
911
- break;
912
- case 'dragover':
913
- event.preventDefault();
914
- break;
915
- case 'drop':
916
- this._evtNativeDrop(event);
917
- break;
918
1190
  case 'lm-dragover':
919
1191
  this._evtDragOver(event);
920
1192
  break;
@@ -925,6 +1197,33 @@ export class AttachmentsCell extends Cell {
925
1197
  break;
926
1198
  }
927
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
+ }
928
1227
  /**
929
1228
  * Handle `after-attach` messages for the widget.
930
1229
  */
@@ -933,10 +1232,6 @@ export class AttachmentsCell extends Cell {
933
1232
  const node = this.node;
934
1233
  node.addEventListener('lm-dragover', this);
935
1234
  node.addEventListener('lm-drop', this);
936
- node.addEventListener('dragenter', this);
937
- node.addEventListener('dragover', this);
938
- node.addEventListener('drop', this);
939
- node.addEventListener('paste', this);
940
1235
  }
941
1236
  /**
942
1237
  * A message handler invoked on a `'before-detach'`
@@ -944,12 +1239,9 @@ export class AttachmentsCell extends Cell {
944
1239
  */
945
1240
  onBeforeDetach(msg) {
946
1241
  const node = this.node;
947
- node.removeEventListener('drop', this);
948
- node.removeEventListener('dragover', this);
949
- node.removeEventListener('dragenter', this);
950
- node.removeEventListener('paste', this);
951
1242
  node.removeEventListener('lm-dragover', this);
952
1243
  node.removeEventListener('lm-drop', this);
1244
+ super.onBeforeDetach(msg);
953
1245
  }
954
1246
  _evtDragOver(event) {
955
1247
  const supportedMimeType = some(imageRendererFactory.mimeTypes, mimeType => {
@@ -1001,13 +1293,13 @@ export class AttachmentsCell extends Cell {
1001
1293
  * Handle the `'lm-drop'` event for the widget.
1002
1294
  */
1003
1295
  _evtDrop(event) {
1004
- const supportedMimeTypes = toArray(filter(event.mimeData.types(), mimeType => {
1296
+ const supportedMimeTypes = event.mimeData.types().filter(mimeType => {
1005
1297
  if (mimeType === CONTENTS_MIME_RICH) {
1006
1298
  const data = event.mimeData.getData(CONTENTS_MIME_RICH);
1007
1299
  return (imageRendererFactory.mimeTypes.indexOf(data.model.mimetype) !== -1);
1008
1300
  }
1009
1301
  return imageRendererFactory.mimeTypes.indexOf(mimeType) !== -1;
1010
- }));
1302
+ });
1011
1303
  if (supportedMimeTypes.length === 0) {
1012
1304
  return;
1013
1305
  }
@@ -1114,15 +1406,16 @@ export class MarkdownCell extends AttachmentsCell {
1114
1406
  * Construct a Markdown cell widget.
1115
1407
  */
1116
1408
  constructor(options) {
1117
- var _a, _b, _c;
1118
- super(options);
1119
- this._toggleCollapsedSignal = new Signal(this);
1120
- this._renderer = null;
1121
- this._rendered = true;
1409
+ var _a, _b, _c, _d;
1410
+ super({ ...options, placeholder: true });
1411
+ this._headingsCache = null;
1412
+ this._headingCollapsedChanged = new Signal(this);
1122
1413
  this._prevText = '';
1123
- this._ready = new PromiseDelegate();
1414
+ this._rendered = true;
1415
+ this._renderedChanged = new Signal(this);
1124
1416
  this._showEditorForReadOnlyMarkdown = true;
1125
1417
  this.addClass(MARKDOWN_CELL_CLASS);
1418
+ this.model.contentChanged.connect(this.onContentChanged, this);
1126
1419
  const trans = this.translator.load('jupyterlab');
1127
1420
  this.node.setAttribute('aria-label', trans.__('Markdown Cell Content'));
1128
1421
  // Ensure we can resolve attachments:
@@ -1132,74 +1425,93 @@ export class MarkdownCell extends AttachmentsCell {
1132
1425
  model: this.model.attachments
1133
1426
  })
1134
1427
  });
1135
- // Stop codemirror handling paste
1136
- this.editor.setOption('handlePaste', false);
1428
+ this._renderer = this._rendermime.createRenderer('text/markdown');
1429
+ this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1137
1430
  // Check if heading cell is set to be collapsed
1138
- this._headingCollapsed = ((_b = this.model.metadata.get(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1139
- // 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;
1140
1436
  this._monitor = new ActivityMonitor({
1141
1437
  signal: this.model.contentChanged,
1142
1438
  timeout: RENDER_TIMEOUT
1143
1439
  });
1144
- this._monitor.activityStopped.connect(() => {
1145
- if (this._rendered) {
1146
- this.update();
1440
+ // Throttle the rendering rate of the widget.
1441
+ this.ready
1442
+ .then(() => {
1443
+ if (this.isDisposed) {
1444
+ // Bail early
1445
+ return;
1147
1446
  }
1148
- }, this);
1149
- void this._updateRenderedInput().then(() => {
1150
- 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);
1151
1455
  });
1152
- this.renderCollapseButtons(this._renderer);
1153
- this.renderInput(this._renderer);
1154
- this._showEditorForReadOnlyMarkdown =
1155
- (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1156
- }
1157
- /**
1158
- * A promise that resolves when the widget renders for the first time.
1159
- */
1160
- get ready() {
1161
- return this._ready.promise;
1162
1456
  }
1163
1457
  /**
1164
- * 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.
1165
1459
  * Returns empty string if not a heading.
1166
1460
  */
1167
1461
  get headingInfo() {
1168
- let text = this.model.value.text;
1169
- const lines = marked.lexer(text);
1170
- let line;
1171
- for (line of lines) {
1172
- if (line.type === 'heading') {
1173
- return { text: line.text, level: line.depth };
1174
- }
1175
- else if (line.type === 'html') {
1176
- let match = line.raw.match(/<h([1-6])(.*?)>(.*?)<\/h\1>/);
1177
- if (match === null || match === void 0 ? void 0 : match[3]) {
1178
- return { text: match[3], level: parseInt(match[1]) };
1179
- }
1180
- return { text: '', level: -1 };
1181
- }
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 };
1182
1471
  }
1183
- return { text: '', level: -1 };
1184
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
+ */
1185
1486
  get headingCollapsed() {
1186
1487
  return this._headingCollapsed;
1187
1488
  }
1188
1489
  set headingCollapsed(value) {
1189
- this._headingCollapsed = value;
1190
- if (value) {
1191
- this.model.metadata.set(MARKDOWN_HEADING_COLLAPSED, value);
1192
- }
1193
- else if (this.model.metadata.has(MARKDOWN_HEADING_COLLAPSED)) {
1194
- this.model.metadata.delete(MARKDOWN_HEADING_COLLAPSED);
1195
- }
1196
- const collapseButton = this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1197
- if (collapseButton) {
1198
- collapseButton.setAttribute('style', `background:
1199
- ${value ? 'var(--jp-icon-caret-right)' : 'var(--jp-icon-caret-down)'} no-repeat center`);
1490
+ var _a;
1491
+ if (this._headingCollapsed !== value) {
1492
+ this._headingCollapsed = value;
1493
+ if (value) {
1494
+ this.model.setMetadata(MARKDOWN_HEADING_COLLAPSED, value);
1495
+ }
1496
+ else if (this.model.getMetadata(MARKDOWN_HEADING_COLLAPSED) !== 'undefined') {
1497
+ this.model.deleteMetadata(MARKDOWN_HEADING_COLLAPSED);
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);
1200
1510
  }
1201
- this.renderCollapseButtons(this._renderer);
1202
1511
  }
1512
+ /**
1513
+ * Number of collapsed sub cells.
1514
+ */
1203
1515
  get numberChildNodes() {
1204
1516
  return this._numberChildNodes;
1205
1517
  }
@@ -1207,8 +1519,11 @@ export class MarkdownCell extends AttachmentsCell {
1207
1519
  this._numberChildNodes = value;
1208
1520
  this.renderCollapseButtons(this._renderer);
1209
1521
  }
1210
- get toggleCollapsedSignal() {
1211
- return this._toggleCollapsedSignal;
1522
+ /**
1523
+ * Signal emitted when the cell collapsed state changes.
1524
+ */
1525
+ get headingCollapsedChanged() {
1526
+ return this._headingCollapsedChanged;
1212
1527
  }
1213
1528
  /**
1214
1529
  * Whether the cell is rendered.
@@ -1225,13 +1540,21 @@ export class MarkdownCell extends AttachmentsCell {
1225
1540
  return;
1226
1541
  }
1227
1542
  this._rendered = value;
1228
- this._handleRendered();
1229
- // Refreshing an editor can be really expensive, so we don't call it from
1230
- // _handleRendered, since _handledRendered is also called on every update
1231
- // request.
1232
- if (!this._rendered) {
1233
- this.editor.refresh();
1234
- }
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;
1235
1558
  }
1236
1559
  /*
1237
1560
  * Whether the Markdown editor is visible in read-only mode.
@@ -1245,18 +1568,51 @@ export class MarkdownCell extends AttachmentsCell {
1245
1568
  this.rendered = true;
1246
1569
  }
1247
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
+ }
1248
1600
  maybeCreateCollapseButton() {
1249
- if (this.headingInfo.level > 0 &&
1250
- this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)
1251
- .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) {
1252
1605
  let collapseButton = this.inputArea.promptNode.appendChild(document.createElement('button'));
1253
- collapseButton.className = `jp-Button jp-mod-minimal ${HEADING_COLLAPSER_CLASS}`;
1254
- collapseButton.style.background = `${this._headingCollapsed
1255
- ? 'var(--jp-icon-caret-right)'
1256
- : 'var(--jp-icon-caret-down)'} no-repeat center`;
1606
+ collapseButton.className = `jp-Button ${HEADING_COLLAPSER_CLASS}`;
1607
+ collapseButton.setAttribute('data-heading-level', level.toString());
1608
+ if (this._headingCollapsed) {
1609
+ collapseButton.classList.add('jp-mod-collapsed');
1610
+ }
1611
+ else {
1612
+ collapseButton.classList.remove('jp-mod-collapsed');
1613
+ }
1257
1614
  collapseButton.onclick = (event) => {
1258
1615
  this.headingCollapsed = !this.headingCollapsed;
1259
- this._toggleCollapsedSignal.emit(this._headingCollapsed);
1260
1616
  };
1261
1617
  }
1262
1618
  }
@@ -1280,7 +1636,6 @@ export class MarkdownCell extends AttachmentsCell {
1280
1636
  newShowHiddenCellsButton.appendChild(buttonTextElement);
1281
1637
  newShowHiddenCellsButton.onclick = () => {
1282
1638
  this.headingCollapsed = false;
1283
- this._toggleCollapsedSignal.emit(this._headingCollapsed);
1284
1639
  };
1285
1640
  this.node.appendChild(newShowHiddenCellsButton);
1286
1641
  }
@@ -1297,6 +1652,12 @@ export class MarkdownCell extends AttachmentsCell {
1297
1652
  }
1298
1653
  }
1299
1654
  }
1655
+ /**
1656
+ * Callback on content changed
1657
+ */
1658
+ onContentChanged() {
1659
+ this._headingsCache = null;
1660
+ }
1300
1661
  /**
1301
1662
  * Render the collapse button for heading cells,
1302
1663
  * and for collapsed heading cells render the "expand hidden cells"
@@ -1312,23 +1673,28 @@ export class MarkdownCell extends AttachmentsCell {
1312
1673
  */
1313
1674
  renderInput(widget) {
1314
1675
  this.addClass(RENDERED_CLASS);
1315
- this.renderCollapseButtons(widget);
1316
- this.inputArea.renderInput(widget);
1676
+ if (!this.placeholder && !this.isDisposed) {
1677
+ this.renderCollapseButtons(widget);
1678
+ this.inputArea.renderInput(widget);
1679
+ }
1317
1680
  }
1318
1681
  /**
1319
1682
  * Show the text editor instead of rendered input.
1320
1683
  */
1321
1684
  showEditor() {
1322
1685
  this.removeClass(RENDERED_CLASS);
1323
- this.inputArea.showEditor();
1324
- // if this is going to be a heading, place the cursor accordingly
1325
- let numHashAtStart = (this.model.value.text.match(/^#+/g) || [''])[0]
1326
- .length;
1327
- if (numHashAtStart > 0) {
1328
- this.inputArea.editor.setCursorPosition({
1329
- column: numHashAtStart + 1,
1330
- line: 0
1331
- });
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
+ }
1332
1698
  }
1333
1699
  }
1334
1700
  /*
@@ -1336,7 +1702,9 @@ export class MarkdownCell extends AttachmentsCell {
1336
1702
  */
1337
1703
  onUpdateRequest(msg) {
1338
1704
  // Make sure we are properly rendered.
1339
- this._handleRendered();
1705
+ this._handleRendered().catch(reason => {
1706
+ console.error('Failed to render', reason);
1707
+ });
1340
1708
  super.onUpdateRequest(msg);
1341
1709
  }
1342
1710
  /**
@@ -1345,39 +1713,42 @@ export class MarkdownCell extends AttachmentsCell {
1345
1713
  updateCellSourceWithAttachment(attachmentName, URI) {
1346
1714
  var _a, _b;
1347
1715
  const textToBeAppended = `![${attachmentName}](attachment:${URI !== null && URI !== void 0 ? URI : attachmentName})`;
1348
- (_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);
1349
1718
  }
1350
1719
  /**
1351
1720
  * Handle the rendered state.
1352
1721
  */
1353
- _handleRendered() {
1722
+ async _handleRendered() {
1354
1723
  if (!this._rendered) {
1355
1724
  this.showEditor();
1356
1725
  }
1357
1726
  else {
1358
1727
  // TODO: It would be nice for the cell to provide a way for
1359
1728
  // its consumers to hook into when the rendering is done.
1360
- void this._updateRenderedInput();
1361
- 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
+ }
1362
1734
  }
1363
1735
  }
1364
1736
  /**
1365
1737
  * Update the rendered input.
1366
1738
  */
1367
1739
  _updateRenderedInput() {
1740
+ if (this.placeholder) {
1741
+ return Promise.resolve();
1742
+ }
1368
1743
  const model = this.model;
1369
- const text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
1744
+ const text = (model && model.sharedModel.getSource()) || DEFAULT_MARKDOWN_TEXT;
1370
1745
  // Do not re-render if the text has not changed.
1371
1746
  if (text !== this._prevText) {
1372
1747
  const mimeModel = new MimeModel({ data: { 'text/markdown': text } });
1373
- if (!this._renderer) {
1374
- this._renderer = this._rendermime.createRenderer('text/markdown');
1375
- this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1376
- }
1377
1748
  this._prevText = text;
1378
1749
  return this._renderer.renderModel(mimeModel);
1379
1750
  }
1380
- return Promise.resolve(void 0);
1751
+ return Promise.resolve();
1381
1752
  }
1382
1753
  /**
1383
1754
  * Clone the cell, using the same model.