@jupyterlab/cells 4.0.0-alpha.2 → 4.0.0-alpha.20

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.
Files changed (46) hide show
  1. package/lib/celldragutils.d.ts +1 -7
  2. package/lib/celldragutils.js +12 -13
  3. package/lib/celldragutils.js.map +1 -1
  4. package/lib/index.d.ts +1 -0
  5. package/lib/index.js +1 -0
  6. package/lib/index.js.map +1 -1
  7. package/lib/inputarea.d.ts +9 -19
  8. package/lib/inputarea.js +16 -29
  9. package/lib/inputarea.js.map +1 -1
  10. package/lib/model.d.ts +121 -79
  11. package/lib/model.js +179 -392
  12. package/lib/model.js.map +1 -1
  13. package/lib/placeholder.d.ts +23 -19
  14. package/lib/placeholder.js +30 -35
  15. package/lib/placeholder.js.map +1 -1
  16. package/lib/resizeHandle.d.ts +0 -1
  17. package/lib/resizeHandle.js +9 -11
  18. package/lib/resizeHandle.js.map +1 -1
  19. package/lib/searchprovider.d.ts +31 -0
  20. package/lib/searchprovider.js +359 -0
  21. package/lib/searchprovider.js.map +1 -0
  22. package/lib/testutils.d.ts +22 -0
  23. package/lib/testutils.js +48 -0
  24. package/lib/testutils.js.map +1 -0
  25. package/lib/widget.d.ts +226 -42
  26. package/lib/widget.js +672 -270
  27. package/lib/widget.js.map +1 -1
  28. package/package.json +36 -33
  29. package/src/celldragutils.ts +214 -0
  30. package/src/collapser.tsx +150 -0
  31. package/src/headerfooter.ts +52 -0
  32. package/src/index.ts +17 -0
  33. package/src/inputarea.ts +292 -0
  34. package/src/model.ts +845 -0
  35. package/src/placeholder.ts +125 -0
  36. package/src/resizeHandle.ts +96 -0
  37. package/src/searchprovider.ts +433 -0
  38. package/src/testutils.ts +57 -0
  39. package/src/widget.ts +2290 -0
  40. package/style/collapser.css +5 -4
  41. package/style/headerfooter.css +3 -3
  42. package/style/index.css +4 -2
  43. package/style/index.js +4 -2
  44. package/style/inputarea.css +19 -17
  45. package/style/placeholder.css +1 -1
  46. package/style/widget.css +85 -7
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,54 +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
- let editorOptions = {};
153
- Object.keys(options.editorConfig).forEach((key) => {
154
- var _a, _b;
155
- editorOptions[key] = (_b = (_a = options.editorConfig) === null || _a === void 0 ? void 0 : _a[key]) !== null && _b !== void 0 ? _b : null;
156
- });
157
- this.editor.setOptions(editorOptions);
158
- }
159
- 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);
160
136
  }
161
137
  /**
162
138
  * Initialize view state from model.
@@ -170,10 +146,51 @@ export class Cell extends Widget {
170
146
  this.loadEditableState();
171
147
  return this;
172
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
+ }
173
187
  /**
174
188
  * Get the prompt node used by the cell.
175
189
  */
176
190
  get promptNode() {
191
+ if (this.placeholder) {
192
+ return null;
193
+ }
177
194
  if (!this._inputHidden) {
178
195
  return this._input.promptNode;
179
196
  }
@@ -186,13 +203,27 @@ export class Cell extends Widget {
186
203
  * Get the CodeEditorWrapper used by the cell.
187
204
  */
188
205
  get editorWidget() {
189
- 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;
190
208
  }
191
209
  /**
192
210
  * Get the CodeEditor used by the cell.
193
211
  */
194
212
  get editor() {
195
- 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();
196
227
  }
197
228
  /**
198
229
  * Get the model used by the cell.
@@ -222,40 +253,54 @@ export class Cell extends Widget {
222
253
  }
223
254
  this.update();
224
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
+ }
225
266
  /**
226
267
  * Save view editable state to model
227
268
  */
228
269
  saveEditableState() {
229
- const { metadata } = this.model;
230
- const current = metadata.get('editable');
270
+ const { sharedModel } = this.model;
271
+ const current = sharedModel.getMetadata('editable');
231
272
  if ((this.readOnly && current === false) ||
232
273
  (!this.readOnly && current === undefined)) {
233
274
  return;
234
275
  }
235
276
  if (this.readOnly) {
236
- this.model.metadata.set('editable', false);
277
+ sharedModel.setMetadata('editable', false);
237
278
  }
238
279
  else {
239
- this.model.metadata.delete('editable');
280
+ sharedModel.deleteMetadata('editable');
240
281
  }
241
282
  }
242
283
  /**
243
284
  * Load view editable state from model.
244
285
  */
245
286
  loadEditableState() {
246
- this.readOnly = this.model.metadata.get('editable') === false;
287
+ this.readOnly =
288
+ this.model.sharedModel.getMetadata('editable') ===
289
+ false;
247
290
  }
248
291
  /**
249
292
  * A promise that resolves when the widget renders for the first time.
250
293
  */
251
294
  get ready() {
252
- return Promise.resolve(undefined);
295
+ return this._ready.promise;
253
296
  }
254
297
  /**
255
298
  * Set the prompt for the widget.
256
299
  */
257
300
  setPrompt(value) {
258
- this._input.setPrompt(value);
301
+ var _a;
302
+ this.prompt = value;
303
+ (_a = this._input) === null || _a === void 0 ? void 0 : _a.setPrompt(value);
259
304
  }
260
305
  /**
261
306
  * The view state of input being hidden.
@@ -267,14 +312,16 @@ export class Cell extends Widget {
267
312
  if (this._inputHidden === value) {
268
313
  return;
269
314
  }
270
- const layout = this._inputWrapper.layout;
271
- if (value) {
272
- this._input.parent = null;
273
- layout.addWidget(this._inputPlaceholder);
274
- }
275
- else {
276
- this._inputPlaceholder.parent = null;
277
- 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
+ }
278
325
  }
279
326
  this._inputHidden = value;
280
327
  if (this.syncCollapse) {
@@ -286,7 +333,7 @@ export class Cell extends Widget {
286
333
  * Save view collapse state to model
287
334
  */
288
335
  saveCollapseState() {
289
- const jupyter = Object.assign({}, this.model.metadata.get('jupyter'));
336
+ const jupyter = { ...this.model.getMetadata('jupyter') };
290
337
  if ((this.inputHidden && jupyter.source_hidden === true) ||
291
338
  (!this.inputHidden && jupyter.source_hidden === undefined)) {
292
339
  return;
@@ -298,17 +345,18 @@ export class Cell extends Widget {
298
345
  delete jupyter.source_hidden;
299
346
  }
300
347
  if (Object.keys(jupyter).length === 0) {
301
- this.model.metadata.delete('jupyter');
348
+ this.model.deleteMetadata('jupyter');
302
349
  }
303
350
  else {
304
- this.model.metadata.set('jupyter', jupyter);
351
+ this.model.setMetadata('jupyter', jupyter);
305
352
  }
306
353
  }
307
354
  /**
308
355
  * Revert view collapse state from model.
309
356
  */
310
357
  loadCollapseState() {
311
- const jupyter = this.model.metadata.get('jupyter') || {};
358
+ var _a;
359
+ const jupyter = (_a = this.model.getMetadata('jupyter')) !== null && _a !== void 0 ? _a : {};
312
360
  this.inputHidden = !!jupyter.source_hidden;
313
361
  }
314
362
  /**
@@ -372,12 +420,79 @@ export class Cell extends Widget {
372
420
  if (this.isDisposed) {
373
421
  return;
374
422
  }
423
+ this._resizeDebouncer.dispose();
375
424
  this._input = null;
376
425
  this._model = null;
377
426
  this._inputWrapper = null;
378
427
  this._inputPlaceholder = null;
379
428
  super.dispose();
380
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
+ }
381
496
  /**
382
497
  * Handle `after-attach` messages.
383
498
  */
@@ -388,26 +503,26 @@ export class Cell extends Widget {
388
503
  * Handle `'activate-request'` messages.
389
504
  */
390
505
  onActivateRequest(msg) {
391
- this.editor.focus();
506
+ var _a;
507
+ (_a = this.editor) === null || _a === void 0 ? void 0 : _a.focus();
392
508
  }
393
509
  /**
394
- * Handle `fit-request` messages.
510
+ * Handle `resize` messages.
395
511
  */
396
- onFitRequest(msg) {
397
- // need this for for when a theme changes font size
398
- this.editor.refresh();
512
+ onResize(msg) {
513
+ void this._resizeDebouncer.invoke();
399
514
  }
400
515
  /**
401
516
  * Handle `update-request` messages.
402
517
  */
403
518
  onUpdateRequest(msg) {
519
+ var _a, _b;
404
520
  if (!this._model) {
405
521
  return;
406
522
  }
407
523
  // Handle read only state.
408
- if (this.editor.getOption('readOnly') !== this._readOnly) {
409
- this.editor.setOption('readOnly', this._readOnly);
410
- 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);
411
526
  }
412
527
  }
413
528
  /**
@@ -434,6 +549,20 @@ export class Cell extends Widget {
434
549
  * The namespace for the `Cell` class statics.
435
550
  */
436
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 = {}));
437
566
  /**
438
567
  * The default implementation of an `IContentFactory`.
439
568
  *
@@ -443,9 +572,8 @@ export class Cell extends Widget {
443
572
  /**
444
573
  * Create a content factory for a cell.
445
574
  */
446
- constructor(options = {}) {
447
- this._editorFactory =
448
- options.editorFactory || InputArea.defaultEditorFactory;
575
+ constructor(options) {
576
+ this._editorFactory = options.editorFactory;
449
577
  }
450
578
  /**
451
579
  * The readonly editor factory that create code editors
@@ -485,14 +613,79 @@ export class Cell extends Widget {
485
613
  }
486
614
  }
487
615
  Cell.ContentFactory = ContentFactory;
488
- /**
489
- * The default content factory for cells.
490
- */
491
- Cell.defaultContentFactory = new ContentFactory();
492
616
  })(Cell || (Cell = {}));
493
617
  /** ****************************************************************************
494
618
  * CodeCell
495
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
+ }
496
689
  /**
497
690
  * A widget for a code cell.
498
691
  */
@@ -501,54 +694,90 @@ export class CodeCell extends Cell {
501
694
  * Construct a code cell widget.
502
695
  */
503
696
  constructor(options) {
504
- super(options);
697
+ var _a;
698
+ super({ layout: new CodeCellLayout(), ...options, placeholder: true });
699
+ this._headingsCache = null;
505
700
  this._outputHidden = false;
701
+ this._outputWrapper = null;
702
+ this._outputPlaceholder = null;
506
703
  this._syncScrolled = false;
507
- this._savingMetadata = false;
508
704
  this.addClass(CODE_CELL_CLASS);
509
705
  const trans = this.translator.load('jupyterlab');
510
706
  // Only save options not handled by parent constructor.
511
707
  const rendermime = (this._rendermime = options.rendermime);
512
708
  const contentFactory = this.contentFactory;
513
709
  const model = this.model;
710
+ this.maxNumberOutputs = options.maxNumberOutputs;
514
711
  // Note that modifying the below label warrants one to also modify
515
712
  // the same in this._outputLengthHandler. Ideally, this label must
516
713
  // have been a constant and used in both places but it is not done
517
714
  // so because of limitations in the translation manager.
518
- let ariaLabel = trans.__('Code Cell Content with Output');
519
- if (!options.placeholder) {
520
- // Insert the output before the cell footer.
521
- const outputWrapper = (this._outputWrapper = new Panel());
522
- outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
523
- const outputCollapser = new OutputCollapser();
524
- outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
525
- const output = (this._output = new OutputArea({
526
- model: model.outputs,
527
- rendermime,
528
- contentFactory: contentFactory,
529
- maxNumberOutputs: options.maxNumberOutputs
530
- }));
531
- output.addClass(CELL_OUTPUT_AREA_CLASS);
532
- // Set a CSS if there are no outputs, and connect a signal for future
533
- // changes to the number of outputs. This is for conditional styling
534
- // if there are no outputs.
535
- if (model.outputs.length === 0) {
536
- this.addClass(NO_OUTPUTS_CLASS);
537
- ariaLabel = trans.__('Code Cell Content');
538
- }
539
- output.outputLengthChanged.connect(this._outputLengthHandler, this);
540
- outputWrapper.addWidget(outputCollapser);
541
- outputWrapper.addWidget(output);
542
- this.layout.insertWidget(2, new ResizeHandle(this.node));
543
- this.layout.insertWidget(3, outputWrapper);
544
- if (model.isDirty) {
545
- 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
+ }));
727
+ output.addClass(CELL_OUTPUT_AREA_CLASS);
728
+ output.toggleScrolling.connect(() => {
729
+ this.outputsScrolled = !this.outputsScrolled;
730
+ });
731
+ // Defer setting placeholder as OutputArea must be instantiated before initializing the DOM
732
+ this.placeholder = (_a = options.placeholder) !== null && _a !== void 0 ? _a : true;
733
+ model.outputs.changed.connect(this.onOutputChanged, this);
734
+ model.outputs.stateChanged.connect(this.onOutputChanged, this);
735
+ model.stateChanged.connect(this.onStateChanged, this);
736
+ }
737
+ /**
738
+ * Create children widgets.
739
+ */
740
+ initializeDOM() {
741
+ if (!this.placeholder) {
742
+ return;
743
+ }
744
+ super.initializeDOM();
745
+ this.setPrompt(this.prompt);
746
+ // Insert the output before the cell footer.
747
+ const outputWrapper = (this._outputWrapper = new Panel());
748
+ outputWrapper.addClass(CELL_OUTPUT_WRAPPER_CLASS);
749
+ const outputCollapser = new OutputCollapser();
750
+ outputCollapser.addClass(CELL_OUTPUT_COLLAPSER_CLASS);
751
+ outputWrapper.addWidget(outputCollapser);
752
+ // Set a CSS if there are no outputs, and connect a signal for future
753
+ // changes to the number of outputs. This is for conditional styling
754
+ // if there are no outputs.
755
+ if (this.model.outputs.length === 0) {
756
+ this.addClass(NO_OUTPUTS_CLASS);
757
+ }
758
+ this._output.outputLengthChanged.connect(this._outputLengthHandler, this);
759
+ outputWrapper.addWidget(this._output);
760
+ const layout = this.layout;
761
+ layout.insertWidget(layout.widgets.length - 1, new ResizeHandle(this.node));
762
+ layout.insertWidget(layout.widgets.length - 1, outputWrapper);
763
+ if (this.model.isDirty) {
764
+ this.addClass(DIRTY_CLASS);
765
+ }
766
+ this._outputPlaceholder = new OutputPlaceholder(() => {
767
+ this.outputHidden = !this.outputHidden;
768
+ });
769
+ const layoutWrapper = outputWrapper.layout;
770
+ if (this.outputHidden) {
771
+ layoutWrapper.removeWidget(this._output);
772
+ layoutWrapper.addWidget(this._outputPlaceholder);
773
+ if (this.inputHidden && !outputWrapper.isHidden) {
774
+ this._outputWrapper.hide();
546
775
  }
547
- this._outputPlaceholder = new OutputPlaceholder(() => {
548
- this.outputHidden = !this.outputHidden;
549
- });
550
776
  }
551
- model.stateChanged.connect(this.onStateChanged, this);
777
+ const trans = this.translator.load('jupyterlab');
778
+ const ariaLabel = this.model.outputs.length === 0
779
+ ? trans.__('Code Cell Content')
780
+ : trans.__('Code Cell Content with Output');
552
781
  this.node.setAttribute('aria-label', ariaLabel);
553
782
  }
554
783
  /**
@@ -564,6 +793,47 @@ export class CodeCell extends Cell {
564
793
  this.setPrompt(`${this.model.executionCount || ''}`);
565
794
  return this;
566
795
  }
796
+ get headings() {
797
+ if (!this._headingsCache) {
798
+ const headings = [];
799
+ // Iterate over the code cell outputs to check for Markdown or HTML from which we can generate ToC headings...
800
+ const outputs = this.model.outputs;
801
+ for (let j = 0; j < outputs.length; j++) {
802
+ const m = outputs.get(j);
803
+ let htmlType = null;
804
+ let mdType = null;
805
+ Object.keys(m.data).forEach(t => {
806
+ if (!mdType && TableOfContentsUtils.Markdown.isMarkdown(t)) {
807
+ mdType = t;
808
+ }
809
+ else if (!htmlType && TableOfContentsUtils.isHTML(t)) {
810
+ htmlType = t;
811
+ }
812
+ });
813
+ // Parse HTML output
814
+ if (htmlType) {
815
+ headings.push(...TableOfContentsUtils.getHTMLHeadings(this._rendermime.sanitizer.sanitize(m.data[htmlType])).map(heading => {
816
+ return {
817
+ ...heading,
818
+ outputIndex: j,
819
+ type: Cell.HeadingType.HTML
820
+ };
821
+ }));
822
+ }
823
+ else if (mdType) {
824
+ headings.push(...TableOfContentsUtils.Markdown.getHeadings(m.data[mdType]).map(heading => {
825
+ return {
826
+ ...heading,
827
+ outputIndex: j,
828
+ type: Cell.HeadingType.Markdown
829
+ };
830
+ }));
831
+ }
832
+ }
833
+ this._headingsCache = headings;
834
+ }
835
+ return [...this._headingsCache];
836
+ }
567
837
  /**
568
838
  * Get the output area for the cell.
569
839
  */
@@ -580,20 +850,22 @@ export class CodeCell extends Cell {
580
850
  if (this._outputHidden === value) {
581
851
  return;
582
852
  }
583
- const layout = this._outputWrapper.layout;
584
- if (value) {
585
- layout.removeWidget(this._output);
586
- layout.addWidget(this._outputPlaceholder);
587
- if (this.inputHidden && !this._outputWrapper.isHidden) {
588
- this._outputWrapper.hide();
853
+ if (!this.placeholder) {
854
+ const layout = this._outputWrapper.layout;
855
+ if (value) {
856
+ layout.removeWidget(this._output);
857
+ layout.addWidget(this._outputPlaceholder);
858
+ if (this.inputHidden && !this._outputWrapper.isHidden) {
859
+ this._outputWrapper.hide();
860
+ }
589
861
  }
590
- }
591
- else {
592
- if (this._outputWrapper.isHidden) {
593
- this._outputWrapper.show();
862
+ else {
863
+ if (this._outputWrapper.isHidden) {
864
+ this._outputWrapper.show();
865
+ }
866
+ layout.removeWidget(this._outputPlaceholder);
867
+ layout.addWidget(this._output);
594
868
  }
595
- layout.removeWidget(this._outputPlaceholder);
596
- layout.addWidget(this._output);
597
869
  }
598
870
  this._outputHidden = value;
599
871
  if (this.syncCollapse) {
@@ -609,11 +881,9 @@ export class CodeCell extends Cell {
609
881
  // to changes in metadata until we have fully committed our changes.
610
882
  // Otherwise setting one key can trigger a write to the other key to
611
883
  // maintain the synced consistency.
612
- this._savingMetadata = true;
613
- try {
884
+ this.model.sharedModel.transact(() => {
614
885
  super.saveCollapseState();
615
- const metadata = this.model.metadata;
616
- const collapsed = this.model.metadata.get('collapsed');
886
+ const collapsed = this.model.getMetadata('collapsed');
617
887
  if ((this.outputHidden && collapsed === true) ||
618
888
  (!this.outputHidden && collapsed === undefined)) {
619
889
  return;
@@ -621,15 +891,12 @@ export class CodeCell extends Cell {
621
891
  // Do not set jupyter.outputs_hidden since it is redundant. See
622
892
  // and https://github.com/jupyter/nbformat/issues/137
623
893
  if (this.outputHidden) {
624
- metadata.set('collapsed', true);
894
+ this.model.setMetadata('collapsed', true);
625
895
  }
626
896
  else {
627
- metadata.delete('collapsed');
897
+ this.model.deleteMetadata('collapsed');
628
898
  }
629
- }
630
- finally {
631
- this._savingMetadata = false;
632
- }
899
+ });
633
900
  }
634
901
  /**
635
902
  * Revert view collapse state from model.
@@ -639,7 +906,7 @@ export class CodeCell extends Cell {
639
906
  */
640
907
  loadCollapseState() {
641
908
  super.loadCollapseState();
642
- this.outputHidden = !!this.model.metadata.get('collapsed');
909
+ this.outputHidden = !!this.model.getMetadata('collapsed');
643
910
  }
644
911
  /**
645
912
  * Whether the output is in a scrolled state?
@@ -658,30 +925,28 @@ export class CodeCell extends Cell {
658
925
  * Save view collapse state to model
659
926
  */
660
927
  saveScrolledState() {
661
- const { metadata } = this.model;
662
- const current = metadata.get('scrolled');
928
+ const current = this.model.getMetadata('scrolled');
663
929
  if ((this.outputsScrolled && current === true) ||
664
930
  (!this.outputsScrolled && current === undefined)) {
665
931
  return;
666
932
  }
667
933
  if (this.outputsScrolled) {
668
- metadata.set('scrolled', true);
934
+ this.model.setMetadata('scrolled', true);
669
935
  }
670
936
  else {
671
- metadata.delete('scrolled');
937
+ this.model.deleteMetadata('scrolled');
672
938
  }
673
939
  }
674
940
  /**
675
941
  * Revert view collapse state from model.
676
942
  */
677
943
  loadScrolledState() {
678
- const metadata = this.model.metadata;
679
944
  // We don't have the notion of 'auto' scrolled, so we make it false.
680
- if (metadata.get('scrolled') === 'auto') {
945
+ if (this.model.getMetadata('scrolled') === 'auto') {
681
946
  this.outputsScrolled = false;
682
947
  }
683
948
  else {
684
- this.outputsScrolled = !!metadata.get('scrolled');
949
+ this.outputsScrolled = !!this.model.getMetadata('scrolled');
685
950
  }
686
951
  }
687
952
  /**
@@ -708,6 +973,9 @@ export class CodeCell extends Cell {
708
973
  * is hidden without accessing private state.
709
974
  */
710
975
  handleInputHidden(value) {
976
+ if (this.placeholder) {
977
+ return;
978
+ }
711
979
  if (!value && this._outputWrapper.isHidden) {
712
980
  this._outputWrapper.show();
713
981
  }
@@ -772,14 +1040,16 @@ export class CodeCell extends Cell {
772
1040
  break;
773
1041
  }
774
1042
  }
1043
+ /**
1044
+ * Callback on output changes
1045
+ */
1046
+ onOutputChanged() {
1047
+ this._headingsCache = null;
1048
+ }
775
1049
  /**
776
1050
  * Handle changes in the metadata.
777
1051
  */
778
1052
  onMetadataChanged(model, args) {
779
- if (this._savingMetadata) {
780
- // We are in middle of a metadata transaction, so don't react to it.
781
- return;
782
- }
783
1053
  switch (args.key) {
784
1054
  case 'scrolled':
785
1055
  if (this.syncScrolled) {
@@ -819,16 +1089,24 @@ export class CodeCell extends Cell {
819
1089
  async function execute(cell, sessionContext, metadata) {
820
1090
  var _a;
821
1091
  const model = cell.model;
822
- const code = model.value.text;
1092
+ const code = model.sharedModel.getSource();
823
1093
  if (!code.trim() || !((_a = sessionContext.session) === null || _a === void 0 ? void 0 : _a.kernel)) {
824
- model.clearExecution();
1094
+ model.sharedModel.transact(() => {
1095
+ model.clearExecution();
1096
+ });
825
1097
  return;
826
1098
  }
827
- const cellId = { cellId: model.id };
828
- metadata = Object.assign(Object.assign(Object.assign({}, model.metadata.toJSON()), metadata), cellId);
1099
+ const cellId = { cellId: model.sharedModel.getId() };
1100
+ metadata = {
1101
+ ...model.metadata,
1102
+ ...metadata,
1103
+ ...cellId
1104
+ };
829
1105
  const { recordTiming } = metadata;
830
- model.clearExecution();
831
- cell.outputHidden = false;
1106
+ model.sharedModel.transact(() => {
1107
+ model.clearExecution();
1108
+ cell.outputHidden = false;
1109
+ });
832
1110
  cell.setPrompt('*');
833
1111
  model.trusted = true;
834
1112
  let future;
@@ -851,22 +1129,22 @@ export class CodeCell extends Cell {
851
1129
  // If the data is missing, estimate it to now
852
1130
  // Date was added in 5.1: https://jupyter-client.readthedocs.io/en/stable/messaging.html#message-header
853
1131
  const value = msg.header.date || new Date().toISOString();
854
- const timingInfo = Object.assign({}, model.metadata.get('execution'));
1132
+ const timingInfo = Object.assign({}, model.getMetadata('execution'));
855
1133
  timingInfo[`iopub.${label}`] = value;
856
- model.metadata.set('execution', timingInfo);
1134
+ model.setMetadata('execution', timingInfo);
857
1135
  return true;
858
1136
  };
859
1137
  cell.outputArea.future.registerMessageHook(recordTimingHook);
860
1138
  }
861
1139
  else {
862
- model.metadata.delete('execution');
1140
+ model.deleteMetadata('execution');
863
1141
  }
864
1142
  // Save this execution's future so we can compare in the catch below.
865
1143
  future = cell.outputArea.future;
866
1144
  const msg = (await msgPromise);
867
1145
  model.executionCount = msg.content.execution_count;
868
1146
  if (recordTiming) {
869
- const timingInfo = Object.assign({}, model.metadata.get('execution'));
1147
+ const timingInfo = Object.assign({}, model.getMetadata('execution'));
870
1148
  const started = msg.metadata.started;
871
1149
  // Started is not in the API, but metadata IPyKernel sends
872
1150
  if (started) {
@@ -876,7 +1154,7 @@ export class CodeCell extends Cell {
876
1154
  const finished = msg.header.date;
877
1155
  timingInfo['shell.execute_reply'] =
878
1156
  finished || new Date().toISOString();
879
- model.metadata.set('execution', timingInfo);
1157
+ model.setMetadata('execution', timingInfo);
880
1158
  }
881
1159
  return msg;
882
1160
  }
@@ -908,18 +1186,6 @@ export class AttachmentsCell extends Cell {
908
1186
  */
909
1187
  handleEvent(event) {
910
1188
  switch (event.type) {
911
- case 'paste':
912
- this._evtPaste(event);
913
- break;
914
- case 'dragenter':
915
- event.preventDefault();
916
- break;
917
- case 'dragover':
918
- event.preventDefault();
919
- break;
920
- case 'drop':
921
- this._evtNativeDrop(event);
922
- break;
923
1189
  case 'lm-dragover':
924
1190
  this._evtDragOver(event);
925
1191
  break;
@@ -930,6 +1196,33 @@ export class AttachmentsCell extends Cell {
930
1196
  break;
931
1197
  }
932
1198
  }
1199
+ /**
1200
+ * Get the editor options at initialization.
1201
+ *
1202
+ * @returns Editor options
1203
+ */
1204
+ getEditorOptions() {
1205
+ var _a, _b;
1206
+ const base = (_a = super.getEditorOptions()) !== null && _a !== void 0 ? _a : {};
1207
+ base.extensions = [
1208
+ ...((_b = base.extensions) !== null && _b !== void 0 ? _b : []),
1209
+ EditorView.domEventHandlers({
1210
+ dragenter: (event) => {
1211
+ event.preventDefault();
1212
+ },
1213
+ dragover: (event) => {
1214
+ event.preventDefault();
1215
+ },
1216
+ drop: (event) => {
1217
+ this._evtNativeDrop(event);
1218
+ },
1219
+ paste: (event) => {
1220
+ this._evtPaste(event);
1221
+ }
1222
+ })
1223
+ ];
1224
+ return base;
1225
+ }
933
1226
  /**
934
1227
  * Handle `after-attach` messages for the widget.
935
1228
  */
@@ -938,10 +1231,6 @@ export class AttachmentsCell extends Cell {
938
1231
  const node = this.node;
939
1232
  node.addEventListener('lm-dragover', this);
940
1233
  node.addEventListener('lm-drop', this);
941
- node.addEventListener('dragenter', this);
942
- node.addEventListener('dragover', this);
943
- node.addEventListener('drop', this);
944
- node.addEventListener('paste', this);
945
1234
  }
946
1235
  /**
947
1236
  * A message handler invoked on a `'before-detach'`
@@ -949,12 +1238,9 @@ export class AttachmentsCell extends Cell {
949
1238
  */
950
1239
  onBeforeDetach(msg) {
951
1240
  const node = this.node;
952
- node.removeEventListener('drop', this);
953
- node.removeEventListener('dragover', this);
954
- node.removeEventListener('dragenter', this);
955
- node.removeEventListener('paste', this);
956
1241
  node.removeEventListener('lm-dragover', this);
957
1242
  node.removeEventListener('lm-drop', this);
1243
+ super.onBeforeDetach(msg);
958
1244
  }
959
1245
  _evtDragOver(event) {
960
1246
  const supportedMimeType = some(imageRendererFactory.mimeTypes, mimeType => {
@@ -1006,13 +1292,13 @@ export class AttachmentsCell extends Cell {
1006
1292
  * Handle the `'lm-drop'` event for the widget.
1007
1293
  */
1008
1294
  _evtDrop(event) {
1009
- const supportedMimeTypes = toArray(filter(event.mimeData.types(), mimeType => {
1295
+ const supportedMimeTypes = event.mimeData.types().filter(mimeType => {
1010
1296
  if (mimeType === CONTENTS_MIME_RICH) {
1011
1297
  const data = event.mimeData.getData(CONTENTS_MIME_RICH);
1012
1298
  return (imageRendererFactory.mimeTypes.indexOf(data.model.mimetype) !== -1);
1013
1299
  }
1014
1300
  return imageRendererFactory.mimeTypes.indexOf(mimeType) !== -1;
1015
- }));
1301
+ });
1016
1302
  if (supportedMimeTypes.length === 0) {
1017
1303
  return;
1018
1304
  }
@@ -1119,14 +1405,16 @@ export class MarkdownCell extends AttachmentsCell {
1119
1405
  * Construct a Markdown cell widget.
1120
1406
  */
1121
1407
  constructor(options) {
1122
- var _a, _b;
1123
- super(options);
1124
- this._toggleCollapsedSignal = new Signal(this);
1125
- this._renderer = null;
1126
- this._rendered = true;
1408
+ var _a, _b, _c, _d;
1409
+ super({ ...options, placeholder: true });
1410
+ this._headingsCache = null;
1411
+ this._headingCollapsedChanged = new Signal(this);
1127
1412
  this._prevText = '';
1128
- this._ready = new PromiseDelegate();
1413
+ this._rendered = true;
1414
+ this._renderedChanged = new Signal(this);
1415
+ this._showEditorForReadOnlyMarkdown = true;
1129
1416
  this.addClass(MARKDOWN_CELL_CLASS);
1417
+ this.model.contentChanged.connect(this.onContentChanged, this);
1130
1418
  const trans = this.translator.load('jupyterlab');
1131
1419
  this.node.setAttribute('aria-label', trans.__('Markdown Cell Content'));
1132
1420
  // Ensure we can resolve attachments:
@@ -1136,72 +1424,93 @@ export class MarkdownCell extends AttachmentsCell {
1136
1424
  model: this.model.attachments
1137
1425
  })
1138
1426
  });
1139
- // Stop codemirror handling paste
1140
- this.editor.setOption('handlePaste', false);
1427
+ this._renderer = this._rendermime.createRenderer('text/markdown');
1428
+ this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1141
1429
  // Check if heading cell is set to be collapsed
1142
- this._headingCollapsed = ((_b = this.model.metadata.get(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1143
- // Throttle the rendering rate of the widget.
1430
+ this._headingCollapsed = ((_b = this.model.getMetadata(MARKDOWN_HEADING_COLLAPSED)) !== null && _b !== void 0 ? _b : false);
1431
+ this._showEditorForReadOnlyMarkdown =
1432
+ (_c = options.showEditorForReadOnlyMarkdown) !== null && _c !== void 0 ? _c : MarkdownCell.defaultShowEditorForReadOnlyMarkdown;
1433
+ // Defer setting placeholder as the renderer must be instantiated before initializing the DOM
1434
+ this.placeholder = (_d = options.placeholder) !== null && _d !== void 0 ? _d : true;
1144
1435
  this._monitor = new ActivityMonitor({
1145
1436
  signal: this.model.contentChanged,
1146
1437
  timeout: RENDER_TIMEOUT
1147
1438
  });
1148
- this._monitor.activityStopped.connect(() => {
1149
- if (this._rendered) {
1150
- this.update();
1439
+ // Throttle the rendering rate of the widget.
1440
+ this.ready
1441
+ .then(() => {
1442
+ if (this.isDisposed) {
1443
+ // Bail early
1444
+ return;
1151
1445
  }
1152
- }, this);
1153
- void this._updateRenderedInput().then(() => {
1154
- this._ready.resolve(void 0);
1446
+ this._monitor.activityStopped.connect(() => {
1447
+ if (this._rendered) {
1448
+ this.update();
1449
+ }
1450
+ }, this);
1451
+ })
1452
+ .catch(reason => {
1453
+ console.error('Failed to be ready', reason);
1155
1454
  });
1156
- this.renderCollapseButtons(this._renderer);
1157
- this.renderInput(this._renderer);
1158
- }
1159
- /**
1160
- * A promise that resolves when the widget renders for the first time.
1161
- */
1162
- get ready() {
1163
- return this._ready.promise;
1164
1455
  }
1165
1456
  /**
1166
- * Text that represents the heading if cell is a heading.
1457
+ * Text that represents the highest heading (i.e. lowest level) if cell is a heading.
1167
1458
  * Returns empty string if not a heading.
1168
1459
  */
1169
1460
  get headingInfo() {
1170
- let text = this.model.value.text;
1171
- const lines = marked.lexer(text);
1172
- let line;
1173
- for (line of lines) {
1174
- if (line.type === 'heading') {
1175
- return { text: line.text, level: line.depth };
1176
- }
1177
- else if (line.type === 'html') {
1178
- let match = line.raw.match(/<h([1-6])(.*?)>(.*?)<\/h\1>/);
1179
- if (match === null || match === void 0 ? void 0 : match[3]) {
1180
- return { text: match[3], level: parseInt(match[1]) };
1181
- }
1182
- return { text: '', level: -1 };
1183
- }
1461
+ // Use table of content algorithm for consistency
1462
+ const headings = this.headings;
1463
+ if (headings.length > 0) {
1464
+ // Return the highest level
1465
+ const { text, level } = headings.reduce((prev, curr) => (prev.level <= curr.level ? prev : curr), headings[0]);
1466
+ return { text, level };
1467
+ }
1468
+ else {
1469
+ return { text: '', level: -1 };
1470
+ }
1471
+ }
1472
+ get headings() {
1473
+ if (!this._headingsCache) {
1474
+ // Use table of content algorithm for consistency
1475
+ const headings = TableOfContentsUtils.Markdown.getHeadings(this.model.sharedModel.getSource());
1476
+ this._headingsCache = headings.map(h => {
1477
+ return { ...h, type: Cell.HeadingType.Markdown };
1478
+ });
1184
1479
  }
1185
- return { text: '', level: -1 };
1480
+ return [...this._headingsCache];
1186
1481
  }
1482
+ /**
1483
+ * Whether the heading is collapsed or not.
1484
+ */
1187
1485
  get headingCollapsed() {
1188
1486
  return this._headingCollapsed;
1189
1487
  }
1190
1488
  set headingCollapsed(value) {
1191
- this._headingCollapsed = value;
1192
- if (value) {
1193
- this.model.metadata.set(MARKDOWN_HEADING_COLLAPSED, value);
1194
- }
1195
- else if (this.model.metadata.has(MARKDOWN_HEADING_COLLAPSED)) {
1196
- this.model.metadata.delete(MARKDOWN_HEADING_COLLAPSED);
1197
- }
1198
- const collapseButton = this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1199
- if (collapseButton) {
1200
- collapseButton.setAttribute('style', `background:
1201
- ${value ? 'var(--jp-icon-caret-right)' : 'var(--jp-icon-caret-down)'} no-repeat center`);
1489
+ var _a;
1490
+ if (this._headingCollapsed !== value) {
1491
+ this._headingCollapsed = value;
1492
+ if (value) {
1493
+ this.model.setMetadata(MARKDOWN_HEADING_COLLAPSED, value);
1494
+ }
1495
+ else if (this.model.getMetadata(MARKDOWN_HEADING_COLLAPSED) !== 'undefined') {
1496
+ this.model.deleteMetadata(MARKDOWN_HEADING_COLLAPSED);
1497
+ }
1498
+ const collapseButton = (_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)[0];
1499
+ if (collapseButton) {
1500
+ if (value) {
1501
+ collapseButton.classList.add('jp-mod-collapsed');
1502
+ }
1503
+ else {
1504
+ collapseButton.classList.remove('jp-mod-collapsed');
1505
+ }
1506
+ }
1507
+ this.renderCollapseButtons(this._renderer);
1508
+ this._headingCollapsedChanged.emit(this._headingCollapsed);
1202
1509
  }
1203
- this.renderCollapseButtons(this._renderer);
1204
1510
  }
1511
+ /**
1512
+ * Number of collapsed sub cells.
1513
+ */
1205
1514
  get numberChildNodes() {
1206
1515
  return this._numberChildNodes;
1207
1516
  }
@@ -1209,8 +1518,11 @@ export class MarkdownCell extends AttachmentsCell {
1209
1518
  this._numberChildNodes = value;
1210
1519
  this.renderCollapseButtons(this._renderer);
1211
1520
  }
1212
- get toggleCollapsedSignal() {
1213
- return this._toggleCollapsedSignal;
1521
+ /**
1522
+ * Signal emitted when the cell collapsed state changes.
1523
+ */
1524
+ get headingCollapsedChanged() {
1525
+ return this._headingCollapsedChanged;
1214
1526
  }
1215
1527
  /**
1216
1528
  * Whether the cell is rendered.
@@ -1219,30 +1531,87 @@ export class MarkdownCell extends AttachmentsCell {
1219
1531
  return this._rendered;
1220
1532
  }
1221
1533
  set rendered(value) {
1534
+ // Show cell as rendered when cell is not editable
1535
+ if (this.readOnly && this._showEditorForReadOnlyMarkdown === false) {
1536
+ value = true;
1537
+ }
1222
1538
  if (value === this._rendered) {
1223
1539
  return;
1224
1540
  }
1225
1541
  this._rendered = value;
1226
- this._handleRendered();
1227
- // Refreshing an editor can be really expensive, so we don't call it from
1228
- // _handleRendered, since _handledRendered is also called on every update
1229
- // request.
1230
- if (!this._rendered) {
1231
- this.editor.refresh();
1542
+ this._handleRendered()
1543
+ .then(() => {
1544
+ // If the rendered state changed, raise an event.
1545
+ this._displayChanged.emit();
1546
+ this._renderedChanged.emit(this._rendered);
1547
+ })
1548
+ .catch(reason => {
1549
+ console.error('Failed to render', reason);
1550
+ });
1551
+ }
1552
+ /**
1553
+ * Signal emitted when the markdown cell rendered state changes
1554
+ */
1555
+ get renderedChanged() {
1556
+ return this._renderedChanged;
1557
+ }
1558
+ /*
1559
+ * Whether the Markdown editor is visible in read-only mode.
1560
+ */
1561
+ get showEditorForReadOnly() {
1562
+ return this._showEditorForReadOnlyMarkdown;
1563
+ }
1564
+ set showEditorForReadOnly(value) {
1565
+ this._showEditorForReadOnlyMarkdown = value;
1566
+ if (value === false) {
1567
+ this.rendered = true;
1568
+ }
1569
+ }
1570
+ /**
1571
+ * Renderer
1572
+ */
1573
+ get renderer() {
1574
+ return this._renderer;
1575
+ }
1576
+ /**
1577
+ * Dispose of the resources held by the widget.
1578
+ */
1579
+ dispose() {
1580
+ if (this.isDisposed) {
1581
+ return;
1232
1582
  }
1583
+ this._monitor.dispose();
1584
+ super.dispose();
1585
+ }
1586
+ /**
1587
+ * Create children widgets.
1588
+ */
1589
+ initializeDOM() {
1590
+ if (!this.placeholder) {
1591
+ return;
1592
+ }
1593
+ super.initializeDOM();
1594
+ this.renderCollapseButtons(this._renderer);
1595
+ this._handleRendered().catch(reason => {
1596
+ console.error('Failed to render', reason);
1597
+ });
1233
1598
  }
1234
1599
  maybeCreateCollapseButton() {
1235
- if (this.headingInfo.level > 0 &&
1236
- this.inputArea.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS)
1237
- .length == 0) {
1600
+ var _a;
1601
+ const { level } = this.headingInfo;
1602
+ if (level > 0 &&
1603
+ ((_a = this.inputArea) === null || _a === void 0 ? void 0 : _a.promptNode.getElementsByClassName(HEADING_COLLAPSER_CLASS).length) == 0) {
1238
1604
  let collapseButton = this.inputArea.promptNode.appendChild(document.createElement('button'));
1239
- collapseButton.className = `jp-Button jp-mod-minimal ${HEADING_COLLAPSER_CLASS}`;
1240
- collapseButton.style.background = `${this._headingCollapsed
1241
- ? 'var(--jp-icon-caret-right)'
1242
- : 'var(--jp-icon-caret-down)'} no-repeat center`;
1605
+ collapseButton.className = `jp-Button ${HEADING_COLLAPSER_CLASS}`;
1606
+ collapseButton.setAttribute('data-heading-level', level.toString());
1607
+ if (this._headingCollapsed) {
1608
+ collapseButton.classList.add('jp-mod-collapsed');
1609
+ }
1610
+ else {
1611
+ collapseButton.classList.remove('jp-mod-collapsed');
1612
+ }
1243
1613
  collapseButton.onclick = (event) => {
1244
1614
  this.headingCollapsed = !this.headingCollapsed;
1245
- this._toggleCollapsedSignal.emit(this._headingCollapsed);
1246
1615
  };
1247
1616
  }
1248
1617
  }
@@ -1266,7 +1635,6 @@ export class MarkdownCell extends AttachmentsCell {
1266
1635
  newShowHiddenCellsButton.appendChild(buttonTextElement);
1267
1636
  newShowHiddenCellsButton.onclick = () => {
1268
1637
  this.headingCollapsed = false;
1269
- this._toggleCollapsedSignal.emit(this._headingCollapsed);
1270
1638
  };
1271
1639
  this.node.appendChild(newShowHiddenCellsButton);
1272
1640
  }
@@ -1283,6 +1651,12 @@ export class MarkdownCell extends AttachmentsCell {
1283
1651
  }
1284
1652
  }
1285
1653
  }
1654
+ /**
1655
+ * Callback on content changed
1656
+ */
1657
+ onContentChanged() {
1658
+ this._headingsCache = null;
1659
+ }
1286
1660
  /**
1287
1661
  * Render the collapse button for heading cells,
1288
1662
  * and for collapsed heading cells render the "expand hidden cells"
@@ -1298,22 +1672,38 @@ export class MarkdownCell extends AttachmentsCell {
1298
1672
  */
1299
1673
  renderInput(widget) {
1300
1674
  this.addClass(RENDERED_CLASS);
1301
- this.renderCollapseButtons(widget);
1302
- this.inputArea.renderInput(widget);
1675
+ if (!this.placeholder && !this.isDisposed) {
1676
+ this.renderCollapseButtons(widget);
1677
+ this.inputArea.renderInput(widget);
1678
+ }
1303
1679
  }
1304
1680
  /**
1305
1681
  * Show the text editor instead of rendered input.
1306
1682
  */
1307
1683
  showEditor() {
1308
1684
  this.removeClass(RENDERED_CLASS);
1309
- this.inputArea.showEditor();
1685
+ if (!this.placeholder && !this.isDisposed) {
1686
+ this.inputArea.showEditor();
1687
+ // if this is going to be a heading, place the cursor accordingly
1688
+ let numHashAtStart = (this.model.sharedModel
1689
+ .getSource()
1690
+ .match(/^#+/g) || [''])[0].length;
1691
+ if (numHashAtStart > 0) {
1692
+ this.inputArea.editor.setCursorPosition({
1693
+ column: numHashAtStart + 1,
1694
+ line: 0
1695
+ });
1696
+ }
1697
+ }
1310
1698
  }
1311
1699
  /*
1312
1700
  * Handle `update-request` messages.
1313
1701
  */
1314
1702
  onUpdateRequest(msg) {
1315
1703
  // Make sure we are properly rendered.
1316
- this._handleRendered();
1704
+ this._handleRendered().catch(reason => {
1705
+ console.error('Failed to render', reason);
1706
+ });
1317
1707
  super.onUpdateRequest(msg);
1318
1708
  }
1319
1709
  /**
@@ -1322,39 +1712,42 @@ export class MarkdownCell extends AttachmentsCell {
1322
1712
  updateCellSourceWithAttachment(attachmentName, URI) {
1323
1713
  var _a, _b;
1324
1714
  const textToBeAppended = `![${attachmentName}](attachment:${URI !== null && URI !== void 0 ? URI : attachmentName})`;
1325
- (_b = (_a = this.editor).replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1715
+ // TODO this should be done on the model...
1716
+ (_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.replaceSelection) === null || _b === void 0 ? void 0 : _b.call(_a, textToBeAppended);
1326
1717
  }
1327
1718
  /**
1328
1719
  * Handle the rendered state.
1329
1720
  */
1330
- _handleRendered() {
1721
+ async _handleRendered() {
1331
1722
  if (!this._rendered) {
1332
1723
  this.showEditor();
1333
1724
  }
1334
1725
  else {
1335
1726
  // TODO: It would be nice for the cell to provide a way for
1336
1727
  // its consumers to hook into when the rendering is done.
1337
- void this._updateRenderedInput();
1338
- this.renderInput(this._renderer);
1728
+ await this._updateRenderedInput();
1729
+ if (this._rendered) {
1730
+ // The rendered flag may be updated in the mean time
1731
+ this.renderInput(this._renderer);
1732
+ }
1339
1733
  }
1340
1734
  }
1341
1735
  /**
1342
1736
  * Update the rendered input.
1343
1737
  */
1344
1738
  _updateRenderedInput() {
1739
+ if (this.placeholder) {
1740
+ return Promise.resolve();
1741
+ }
1345
1742
  const model = this.model;
1346
- const text = (model && model.value.text) || DEFAULT_MARKDOWN_TEXT;
1743
+ const text = (model && model.sharedModel.getSource()) || DEFAULT_MARKDOWN_TEXT;
1347
1744
  // Do not re-render if the text has not changed.
1348
1745
  if (text !== this._prevText) {
1349
1746
  const mimeModel = new MimeModel({ data: { 'text/markdown': text } });
1350
- if (!this._renderer) {
1351
- this._renderer = this._rendermime.createRenderer('text/markdown');
1352
- this._renderer.addClass(MARKDOWN_OUTPUT_CLASS);
1353
- }
1354
1747
  this._prevText = text;
1355
1748
  return this._renderer.renderModel(mimeModel);
1356
1749
  }
1357
- return Promise.resolve(void 0);
1750
+ return Promise.resolve();
1358
1751
  }
1359
1752
  /**
1360
1753
  * Clone the cell, using the same model.
@@ -1370,6 +1763,15 @@ export class MarkdownCell extends AttachmentsCell {
1370
1763
  });
1371
1764
  }
1372
1765
  }
1766
+ /**
1767
+ * The namespace for the `CodeCell` class statics.
1768
+ */
1769
+ (function (MarkdownCell) {
1770
+ /**
1771
+ * Default value for showEditorForReadOnlyMarkdown.
1772
+ */
1773
+ MarkdownCell.defaultShowEditorForReadOnlyMarkdown = true;
1774
+ })(MarkdownCell || (MarkdownCell = {}));
1373
1775
  /** ****************************************************************************
1374
1776
  * RawCell
1375
1777
  ******************************************************************************/