// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { DOMUtils } from '@jupyterlab/apputils';
import {
Cell,
CodeCell,
ICellModel,
ICodeCellModel,
IMarkdownCellModel,
IRawCellModel,
MarkdownCell,
RawCell
} from '@jupyterlab/cells';
import { CodeEditor, IEditorMimeTypeService } from '@jupyterlab/codeeditor';
import { IChangedArgs } from '@jupyterlab/coreutils';
import * as nbformat from '@jupyterlab/nbformat';
import { IObservableList } from '@jupyterlab/observables';
import { IRenderMimeRegistry } from '@jupyterlab/rendermime';
import type { IMapChange } from '@jupyter/ydoc';
import { TableOfContentsUtils } from '@jupyterlab/toc';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { WindowedList } from '@jupyterlab/ui-components';
import { ArrayExt, findIndex } from '@lumino/algorithm';
import { MimeData } from '@lumino/coreutils';
import { ElementExt } from '@lumino/domutils';
import { Drag } from '@lumino/dragdrop';
import { Message } from '@lumino/messaging';
import { AttachedProperty } from '@lumino/properties';
import { ISignal, Signal } from '@lumino/signaling';
import { h, VirtualDOM } from '@lumino/virtualdom';
import { PanelLayout, Widget } from '@lumino/widgets';
import { NotebookActions } from './actions';
import { CellList } from './celllist';
import { DROP_SOURCE_CLASS, DROP_TARGET_CLASS } from './constants';
import { INotebookHistory } from './history';
import { INotebookModel } from './model';
import { NotebookViewModel, NotebookWindowedLayout } from './windowing';
import { NotebookFooter } from './notebookfooter';
/**
* The data attribute added to a widget that has an active kernel.
*/
const KERNEL_USER = 'jpKernelUser';
/**
* The data attribute added to a widget that can run code.
*/
const CODE_RUNNER = 'jpCodeRunner';
/**
* The data attribute added to a widget that can undo.
*/
const UNDOER = 'jpUndoer';
/**
* The class name added to notebook widgets.
*/
const NB_CLASS = 'jp-Notebook';
/**
* The class name added to notebook widget cells.
*/
const NB_CELL_CLASS = 'jp-Notebook-cell';
/**
* The class name added to a notebook in edit mode.
*/
const EDIT_CLASS = 'jp-mod-editMode';
/**
* The class name added to a notebook in command mode.
*/
const COMMAND_CLASS = 'jp-mod-commandMode';
/**
* The class name added to the active cell.
*/
const ACTIVE_CLASS = 'jp-mod-active';
/**
* The class name added to selected cells.
*/
const SELECTED_CLASS = 'jp-mod-selected';
/**
* The class name added to an active cell when there are other selected cells.
*/
const OTHER_SELECTED_CLASS = 'jp-mod-multiSelected';
/**
* The class name added to unconfined images.
*/
const UNCONFINED_CLASS = 'jp-mod-unconfined';
/**
* The class name added to the notebook when an element within it is focused
* and takes keyboard input, such as focused or
.
*
* This class is also effective when the focused element is in shadow DOM.
*/
const READ_WRITE_CLASS = 'jp-mod-readWrite';
/**
* The class name added to drag images.
*/
const DRAG_IMAGE_CLASS = 'jp-dragImage';
/**
* The class name added to singular drag images
*/
const SINGLE_DRAG_IMAGE_CLASS = 'jp-dragImage-singlePrompt';
/**
* The class name added to the drag image cell content.
*/
const CELL_DRAG_CONTENT_CLASS = 'jp-dragImage-content';
/**
* The class name added to the drag image cell content.
*/
const CELL_DRAG_PROMPT_CLASS = 'jp-dragImage-prompt';
/**
* The class name added to the drag image cell content.
*/
const CELL_DRAG_MULTIPLE_BACK = 'jp-dragImage-multipleBack';
/**
* The mimetype used for Jupyter cell data.
*/
const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells';
/**
* The threshold in pixels to start a drag event.
*/
const DRAG_THRESHOLD = 5;
/**
* Maximal remaining time for idle callback
*
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API#getting_the_most_out_of_idle_callbacks
*/
const MAXIMUM_TIME_REMAINING = 50;
/*
* The rendering mode for the notebook.
*/
type RenderingLayout = 'default' | 'side-by-side';
/**
* The class attached to the heading collapser button
*/
const HEADING_COLLAPSER_CLASS = 'jp-collapseHeadingButton';
/**
* The class that controls the visibility of "heading collapser" and "show hidden cells" buttons.
*/
const HEADING_COLLAPSER_VISBILITY_CONTROL_CLASS =
'jp-mod-showHiddenCellsButton';
const SIDE_BY_SIDE_CLASS = 'jp-mod-sideBySide';
/**
* The interactivity modes for the notebook.
*/
export type NotebookMode = 'command' | 'edit';
if ((window as any).requestIdleCallback === undefined) {
// On Safari, requestIdleCallback is not available, so we use replacement functions for `idleCallbacks`
// See: https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API#falling_back_to_settimeout
// eslint-disable-next-line @typescript-eslint/ban-types
(window as any).requestIdleCallback = function (handler: Function) {
let startTime = Date.now();
return setTimeout(function () {
handler({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50.0 - (Date.now() - startTime));
}
});
}, 1);
};
(window as any).cancelIdleCallback = function (id: number) {
clearTimeout(id);
};
}
/**
* A widget which renders static non-interactive notebooks.
*
* #### Notes
* The widget model must be set separately and can be changed
* at any time. Consumers of the widget must account for a
* `null` model, and may want to listen to the `modelChanged`
* signal.
*/
export class StaticNotebook extends WindowedList {
/**
* Construct a notebook widget.
*/
constructor(options: StaticNotebook.IOptions) {
const cells = new Array();
const windowingActive =
(options.notebookConfig?.windowingMode ??
StaticNotebook.defaultNotebookConfig.windowingMode) === 'full';
super({
model: new NotebookViewModel(cells, {
overscanCount:
options.notebookConfig?.overscanCount ??
StaticNotebook.defaultNotebookConfig.overscanCount,
windowingActive
}),
layout: new NotebookWindowedLayout(),
renderer: options.renderer ?? WindowedList.defaultRenderer,
scrollbar: false
});
this.addClass(NB_CLASS);
this.cellsArray = cells;
this._idleCallBack = null;
this._editorConfig = StaticNotebook.defaultEditorConfig;
this._notebookConfig = StaticNotebook.defaultNotebookConfig;
this._mimetype = IEditorMimeTypeService.defaultMimeType;
this._notebookModel = null;
this._modelChanged = new Signal(this);
this._modelContentChanged = new Signal(this);
this.node.dataset[KERNEL_USER] = 'true';
this.node.dataset[UNDOER] = 'true';
this.node.dataset[CODE_RUNNER] = 'true';
this.rendermime = options.rendermime;
this.translator = options.translator || nullTranslator;
this.contentFactory = options.contentFactory;
this.editorConfig =
options.editorConfig || StaticNotebook.defaultEditorConfig;
this.notebookConfig =
options.notebookConfig || StaticNotebook.defaultNotebookConfig;
this._updateNotebookConfig();
this._mimetypeService = options.mimeTypeService;
this.renderingLayout = options.notebookConfig?.renderingLayout;
this.kernelHistory = options.kernelHistory;
}
get cellCollapsed(): ISignal {
return this._cellCollapsed;
}
get cellInViewportChanged(): ISignal {
return this._cellInViewportChanged;
}
/**
* A signal emitted when the model of the notebook changes.
*/
get modelChanged(): ISignal {
return this._modelChanged;
}
/**
* A signal emitted when the model content changes.
*
* #### Notes
* This is a convenience signal that follows the current model.
*/
get modelContentChanged(): ISignal {
return this._modelContentChanged;
}
/**
* A signal emitted when the rendering layout of the notebook changes.
*/
get renderingLayoutChanged(): ISignal {
return this._renderingLayoutChanged;
}
/**
* The cell factory used by the widget.
*/
readonly contentFactory: StaticNotebook.IContentFactory;
/**
* The Rendermime instance used by the widget.
*/
readonly rendermime: IRenderMimeRegistry;
/**
* Translator to be used by cell renderers
*/
readonly translator: ITranslator;
/**
* The model for the widget.
*/
get model(): INotebookModel | null {
return this._notebookModel;
}
set model(newValue: INotebookModel | null) {
newValue = newValue || null;
if (this._notebookModel === newValue) {
return;
}
const oldValue = this._notebookModel;
this._notebookModel = newValue;
// Trigger private, protected, and public changes.
this._onModelChanged(oldValue, newValue);
this.onModelChanged(oldValue, newValue);
this._modelChanged.emit(void 0);
// Trigger state change
this.viewModel.itemsList = newValue?.cells ?? null;
}
/**
* Get the mimetype for code cells.
*/
get codeMimetype(): string {
return this._mimetype;
}
/**
* A read-only sequence of the widgets in the notebook.
*/
get widgets(): ReadonlyArray {
return this.cellsArray as ReadonlyArray;
}
/**
* A configuration object for cell editor settings.
*/
get editorConfig(): StaticNotebook.IEditorConfig {
return this._editorConfig;
}
set editorConfig(value: StaticNotebook.IEditorConfig) {
this._editorConfig = value;
this._updateEditorConfig();
}
/**
* A configuration object for notebook settings.
*/
get notebookConfig(): StaticNotebook.INotebookConfig {
return this._notebookConfig;
}
set notebookConfig(value: StaticNotebook.INotebookConfig) {
this._notebookConfig = value;
this._updateNotebookConfig();
}
get renderingLayout(): RenderingLayout | undefined {
return this._renderingLayout;
}
set renderingLayout(value: RenderingLayout | undefined) {
this._renderingLayout = value;
if (this._renderingLayout === 'side-by-side') {
this.node.classList.add(SIDE_BY_SIDE_CLASS);
} else {
this.node.classList.remove(SIDE_BY_SIDE_CLASS);
}
this._renderingLayoutChanged.emit(this._renderingLayout ?? 'default');
}
/**
* Dispose of the resources held by the widget.
*/
dispose(): void {
// Do nothing if already disposed.
if (this.isDisposed) {
return;
}
this._notebookModel = null;
(this.layout as NotebookWindowedLayout).header?.dispose();
super.dispose();
}
/**
* Move cells preserving widget view state.
*
* #### Notes
* This is required because at the model level a move is a deletion
* followed by an insertion. Hence the view state is not preserved.
*
* @param from The index of the cell to move
* @param to The new index of the cell
* @param n Number of cells to move
*/
moveCell(from: number, to: number, n = 1): void {
if (!this.model) {
return;
}
const boundedTo = Math.min(this.model.cells.length - 1, Math.max(0, to));
if (boundedTo === from) {
return;
}
const viewModel: { [k: string]: any }[] = new Array(n);
for (let i = 0; i < n; i++) {
viewModel[i] = {};
const oldCell = this.widgets[from + i];
if (oldCell.model.type === 'markdown') {
for (const k of ['rendered', 'headingCollapsed']) {
// @ts-expect-error Cell has no index signature
viewModel[i][k] = oldCell[k];
}
}
}
this.model!.sharedModel.moveCells(from, boundedTo, n);
for (let i = 0; i < n; i++) {
const newCell = this.widgets[to + i];
const view = viewModel[i];
for (const state in view) {
// @ts-expect-error Cell has no index signature
newCell[state] = view[state];
}
}
}
/**
* Force rendering the cell outputs of a given cell if it is still a placeholder.
*
* #### Notes
* The goal of this method is to allow search on cell outputs (that is based
* on DOM tree introspection).
*
* @param index The cell index
*/
renderCellOutputs(index: number): void {
const cell = this.viewModel.widgetRenderer(index) as Cell;
if (cell instanceof CodeCell && cell.isPlaceholder()) {
cell.dataset.windowedListIndex = `${index}`;
this.layout.insertWidget(index, cell);
if (this.notebookConfig.windowingMode === 'full') {
// We need to delay slightly the removal to let codemirror properly initialize
requestAnimationFrame(() => {
this.layout.removeWidget(cell);
});
}
}
}
/**
* Adds a message to the notebook as a header.
*/
protected addHeader(): void {
const trans = this.translator.load('jupyterlab');
const info = new Widget();
info.node.textContent = trans.__(
'The notebook is empty. Click the + button on the toolbar to add a new cell.'
);
(this.layout as NotebookWindowedLayout).header = info;
}
/**
* Removes the header.
*/
protected removeHeader(): void {
(this.layout as NotebookWindowedLayout).header?.dispose();
(this.layout as NotebookWindowedLayout).header = null;
}
/**
* Handle a new model.
*
* #### Notes
* This method is called after the model change has been handled
* internally and before the `modelChanged` signal is emitted.
* The default implementation is a no-op.
*/
protected onModelChanged(
oldValue: INotebookModel | null,
newValue: INotebookModel | null
): void {
// No-op.
}
/**
* Handle changes to the notebook model content.
*
* #### Notes
* The default implementation emits the `modelContentChanged` signal.
*/
protected onModelContentChanged(model: INotebookModel, args: void): void {
this._modelContentChanged.emit(void 0);
}
/**
* Handle changes to the notebook model metadata.
*
* #### Notes
* The default implementation updates the mimetypes of the code cells
* when the `language_info` metadata changes.
*/
protected onMetadataChanged(sender: INotebookModel, args: IMapChange): void {
switch (args.key) {
case 'language_info':
this._updateMimetype();
break;
default:
break;
}
}
/**
* Handle a cell being inserted.
*
* The default implementation is a no-op
*/
protected onCellInserted(index: number, cell: Cell): void {
// This is a no-op.
}
/**
* Handle a cell being removed.
*
* The default implementation is a no-op
*/
protected onCellRemoved(index: number, cell: Cell): void {
// This is a no-op.
}
/**
* A message handler invoked on an `'update-request'` message.
*
* #### Notes
* The default implementation of this handler is a no-op.
*/
protected onUpdateRequest(msg: Message): void {
if (this.notebookConfig.windowingMode === 'defer') {
void this._runOnIdleTime();
} else {
super.onUpdateRequest(msg);
}
}
/**
* Handle a new model on the widget.
*/
private _onModelChanged(
oldValue: INotebookModel | null,
newValue: INotebookModel | null
): void {
if (oldValue) {
oldValue.contentChanged.disconnect(this.onModelContentChanged, this);
oldValue.metadataChanged.disconnect(this.onMetadataChanged, this);
oldValue.cells.changed.disconnect(this._onCellsChanged, this);
while (this.cellsArray.length) {
this._removeCell(0);
}
}
if (!newValue) {
this._mimetype = IEditorMimeTypeService.defaultMimeType;
return;
}
this._updateMimetype();
const cells = newValue.cells;
const collab = newValue.collaborative ?? false;
if (!collab && !cells.length) {
newValue.sharedModel.insertCell(0, {
cell_type: this.notebookConfig.defaultCell,
metadata:
this.notebookConfig.defaultCell === 'code'
? {
// This is an empty cell created in empty notebook, thus is trusted
trusted: true
}
: {}
});
}
let index = -1;
for (const cell of cells) {
this._insertCell(++index, cell);
}
newValue.cells.changed.connect(this._onCellsChanged, this);
newValue.metadataChanged.connect(this.onMetadataChanged, this);
newValue.contentChanged.connect(this.onModelContentChanged, this);
}
/**
* Handle a change cells event.
*/
protected _onCellsChanged(
sender: CellList,
args: IObservableList.IChangedArgs
): void {
this.removeHeader();
switch (args.type) {
case 'add': {
let index = 0;
index = args.newIndex;
for (const value of args.newValues) {
this._insertCell(index++, value);
}
this._updateDataWindowedListIndex(
args.newIndex,
this.model!.cells.length,
args.newValues.length
);
break;
}
case 'remove':
for (let length = args.oldValues.length; length > 0; length--) {
this._removeCell(args.oldIndex);
}
this._updateDataWindowedListIndex(
args.oldIndex,
this.model!.cells.length + args.oldValues.length,
-1 * args.oldValues.length
);
// Add default cell if there are no cells remaining.
if (!sender.length) {
const model = this.model;
// Add the cell in a new context to avoid triggering another
// cell changed event during the handling of this signal.
requestAnimationFrame(() => {
if (model && !model.isDisposed && !model.sharedModel.cells.length) {
model.sharedModel.insertCell(0, {
cell_type: this.notebookConfig.defaultCell,
metadata:
this.notebookConfig.defaultCell === 'code'
? {
// This is an empty cell created in empty notebook, thus is trusted
trusted: true
}
: {}
});
}
});
}
break;
default:
return;
}
if (!this.model!.sharedModel.cells.length) {
this.addHeader();
}
this.update();
}
/**
* Create a cell widget and insert into the notebook.
*/
private _insertCell(index: number, cell: ICellModel): void {
let widget: Cell;
switch (cell.type) {
case 'code':
widget = this._createCodeCell(cell as ICodeCellModel);
widget.model.mimeType = this._mimetype;
break;
case 'markdown':
widget = this._createMarkdownCell(cell as IMarkdownCellModel);
if (cell.sharedModel.getSource() === '') {
(widget as MarkdownCell).rendered = false;
}
break;
default:
widget = this._createRawCell(cell as IRawCellModel);
}
widget.inViewportChanged.connect(this._onCellInViewportChanged, this);
widget.addClass(NB_CELL_CLASS);
ArrayExt.insert(this.cellsArray, index, widget);
this.onCellInserted(index, widget);
this._scheduleCellRenderOnIdle();
}
/**
* Create a code cell widget from a code cell model.
*/
private _createCodeCell(model: ICodeCellModel): CodeCell {
const rendermime = this.rendermime;
const contentFactory = this.contentFactory;
const editorConfig = this.editorConfig.code;
const options: CodeCell.IOptions = {
contentFactory,
editorConfig,
inputHistoryScope: this.notebookConfig.inputHistoryScope,
maxNumberOutputs: this.notebookConfig.maxNumberOutputs,
model,
placeholder: this._notebookConfig.windowingMode !== 'none',
rendermime,
translator: this.translator
};
const cell = this.contentFactory.createCodeCell(options);
cell.syncCollapse = true;
cell.syncEditable = true;
cell.syncScrolled = true;
cell.outputArea.inputRequested.connect((_, stdin) => {
this._onInputRequested(cell).catch(reason => {
console.error('Failed to scroll to cell requesting input.', reason);
});
stdin.disposed.connect(() => {
// The input field is removed from the DOM after the user presses Enter.
// This causes focus to be lost if we don't explicitly re-focus
// somewhere else.
cell.node.focus();
});
});
return cell;
}
/**
* Create a markdown cell widget from a markdown cell model.
*/
private _createMarkdownCell(model: IMarkdownCellModel): MarkdownCell {
const rendermime = this.rendermime;
const contentFactory = this.contentFactory;
const editorConfig = this.editorConfig.markdown;
const options: MarkdownCell.IOptions = {
contentFactory,
editorConfig,
model,
placeholder: this._notebookConfig.windowingMode !== 'none',
rendermime,
showEditorForReadOnlyMarkdown:
this._notebookConfig.showEditorForReadOnlyMarkdown
};
const cell = this.contentFactory.createMarkdownCell(options);
cell.syncCollapse = true;
cell.syncEditable = true;
// Connect collapsed signal for each markdown cell widget
cell.headingCollapsedChanged.connect(this._onCellCollapsed, this);
return cell;
}
/**
* Create a raw cell widget from a raw cell model.
*/
private _createRawCell(model: IRawCellModel): RawCell {
const contentFactory = this.contentFactory;
const editorConfig = this.editorConfig.raw;
const options: RawCell.IOptions = {
editorConfig,
model,
contentFactory,
placeholder: this._notebookConfig.windowingMode !== 'none'
};
const cell = this.contentFactory.createRawCell(options);
cell.syncCollapse = true;
cell.syncEditable = true;
return cell;
}
/**
* Remove a cell widget.
*/
private _removeCell(index: number): void {
const widget = this.cellsArray[index];
widget.parent = null;
ArrayExt.removeAt(this.cellsArray, index);
this.onCellRemoved(index, widget);
widget.dispose();
}
/**
* Update the mimetype of the notebook.
*/
private _updateMimetype(): void {
const info = this._notebookModel?.getMetadata('language_info');
if (!info) {
return;
}
this._mimetype = this._mimetypeService.getMimeTypeByLanguage(info);
for (const widget of this.widgets) {
if (widget.model.type === 'code') {
widget.model.mimeType = this._mimetype;
}
}
}
/**
* Callback when a cell collapsed status changes.
*
* @param cell Cell changed
* @param collapsed New collapsed status
*/
private _onCellCollapsed(cell: Cell, collapsed: boolean): void {
NotebookActions.setHeadingCollapse(cell, collapsed, this);
this._cellCollapsed.emit(cell);
}
/**
* Callback when a cell viewport status changes.
*
* @param cell Cell changed
*/
private _onCellInViewportChanged(cell: Cell): void {
this._cellInViewportChanged.emit(cell);
}
/**
* Ensure to load in the DOM a cell requesting an user input
*
* @param cell Cell requesting an input
*/
private async _onInputRequested(cell: Cell): Promise {
if (!cell.inViewport) {
const cellIndex = this.widgets.findIndex(c => c === cell);
if (cellIndex >= 0) {
await this.scrollToItem(cellIndex);
const inputEl = cell.node.querySelector('.jp-Stdin');
if (inputEl) {
ElementExt.scrollIntoViewIfNeeded(this.node, inputEl);
(inputEl as HTMLElement).focus();
}
}
}
}
private _scheduleCellRenderOnIdle() {
if (this.notebookConfig.windowingMode !== 'none' && !this.isDisposed) {
if (!this._idleCallBack) {
this._idleCallBack = requestIdleCallback(
(deadline: IdleDeadline) => {
this._idleCallBack = null;
// In case of timeout, render for some time even if it means freezing the UI
// This avoids the cells to never be loaded.
void this._runOnIdleTime(
deadline.didTimeout
? MAXIMUM_TIME_REMAINING
: deadline.timeRemaining()
);
},
{
timeout: 3000
}
);
}
}
}
private _updateDataWindowedListIndex(
start: number,
end: number,
delta: number
): void {
for (
let cellIdx = 0;
cellIdx < this.viewportNode.childElementCount;
cellIdx++
) {
const cell = this.viewportNode.children[cellIdx];
const globalIndex = parseInt(
(cell as HTMLElement).dataset.windowedListIndex!,
10
);
if (globalIndex >= start && globalIndex < end) {
(cell as HTMLElement).dataset.windowedListIndex = `${
globalIndex + delta
}`;
}
}
}
/**
* Update editor settings for notebook cells.
*/
private _updateEditorConfig() {
for (let i = 0; i < this.widgets.length; i++) {
const cell = this.widgets[i];
let config: Record = {};
switch (cell.model.type) {
case 'code':
config = this._editorConfig.code;
break;
case 'markdown':
config = this._editorConfig.markdown;
break;
default:
config = this._editorConfig.raw;
break;
}
cell.updateEditorConfig({ ...config });
}
}
private async _runOnIdleTime(
remainingTime: number = MAXIMUM_TIME_REMAINING
): Promise {
const startTime = Date.now();
let cellIdx = 0;
while (
Date.now() - startTime < remainingTime &&
cellIdx < this.cellsArray.length
) {
const cell = this.cellsArray[cellIdx];
if (cell.isPlaceholder()) {
switch (this.notebookConfig.windowingMode) {
case 'defer':
await this._updateForDeferMode(cell, cellIdx);
break;
case 'full':
this._renderCSSAndJSOutputs(cell, cellIdx);
break;
}
}
cellIdx++;
}
// If the notebook is not fully rendered
if (cellIdx < this.cellsArray.length) {
// If we are defering the cell rendering and the rendered cells do
// not fill the viewport yet
if (
this.notebookConfig.windowingMode === 'defer' &&
this.viewportNode.clientHeight < this.node.clientHeight
) {
// Spend more time rendering cells to fill the viewport
await this._runOnIdleTime();
} else {
this._scheduleCellRenderOnIdle();
}
} else {
if (this._idleCallBack) {
window.cancelIdleCallback(this._idleCallBack);
this._idleCallBack = null;
}
}
}
private async _updateForDeferMode(
cell: Cell,
cellIdx: number
): Promise {
cell.dataset.windowedListIndex = `${cellIdx}`;
this.layout.insertWidget(cellIdx, cell);
await cell.ready;
}
private _renderCSSAndJSOutputs(
cell: Cell,
cellIdx: number
): void {
// Only render cell with text/html outputs containing scripts or/and styles
// Note:
// We don't need to render JavaScript mimetype outputs because they get
// directly evaluate without adding DOM elements (see @jupyterlab/javascript-extension)
if (cell instanceof CodeCell) {
for (
let outputIdx = 0;
outputIdx < (cell.model.outputs?.length ?? 0);
outputIdx++
) {
const output = cell.model.outputs.get(outputIdx);
const html = (output.data['text/html'] as string) ?? '';
if (
html.match(
/(