cellRenderer.ts 42.8 KB
Newer Older
P
Peng Lyu 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6 7
// eslint-disable-next-line code-import-patterns
import 'vs/css!vs/workbench/contrib/notebook/browser/media/notebook';
R
rebornix 已提交
8
import { getZoomLevel } from 'vs/base/browser/browser';
P
Peng Lyu 已提交
9
import * as DOM from 'vs/base/browser/dom';
10 11
import { domEvent } from 'vs/base/browser/event';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
R
rebornix 已提交
12
import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
R
Rob Lourens 已提交
13
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
14
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
15
import { ActionRunner, IAction } from 'vs/base/common/actions';
16
import { Delayer } from 'vs/base/common/async';
17
import { renderCodicons } from 'vs/base/common/codicons';
18
import { Color } from 'vs/base/common/color';
19 20
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
21
import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
P
Peng Lyu 已提交
22
import { deepClone } from 'vs/base/common/objects';
23 24
import * as platform from 'vs/base/common/platform';
import { escape } from 'vs/base/common/strings';
25
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
R
rebornix 已提交
26
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
27
import { EditorOption, EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
P
Peng Lyu 已提交
28
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
29
import { Range } from 'vs/editor/common/core/range';
C
Christopher Maynard 已提交
30
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
31 32 33 34
import { ITextModel } from 'vs/editor/common/model';
import * as modes from 'vs/editor/common/modes';
import { tokenizeLineToHTML } from 'vs/editor/common/modes/textToHtmlTokenizer';
import { IModeService } from 'vs/editor/common/services/modeService';
R
Rob Lourens 已提交
35
import { ContextAwareMenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
R
Rob Lourens 已提交
36
import { IMenu, MenuItemAction } from 'vs/platform/actions/common/actions';
R
rebornix 已提交
37
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
38
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
P
Peng Lyu 已提交
39
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
R
rebornix 已提交
40
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
C
Christopher Maynard 已提交
41
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
R
Rob Lourens 已提交
42 43
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { INotificationService } from 'vs/platform/notification/common/notification';
44
import { BOTTOM_CELL_TOOLBAR_HEIGHT, EDITOR_BOTTOM_PADDING, EDITOR_TOOLBAR_HEIGHT, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
45
import { CancelCellAction, ChangeCellLanguageAction, ExecuteCellAction, INotebookCellActionContext, InsertCodeCellAction, InsertMarkdownCellAction } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';
46
import { BaseCellRenderTemplate, CellEditState, CellRunState, CodeCellRenderTemplate, ICellViewModel, INotebookCellList, INotebookEditor, MarkdownCellRenderTemplate, NOTEBOOK_CELL_EDITABLE, NOTEBOOK_CELL_HAS_OUTPUTS, NOTEBOOK_CELL_MARKDOWN_EDIT_MODE, NOTEBOOK_CELL_RUNNABLE, NOTEBOOK_CELL_RUN_STATE, NOTEBOOK_CELL_TYPE, NOTEBOOK_VIEW_TYPE } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
47
import { CellMenus } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellMenus';
R
rebornix 已提交
48 49
import { CodeCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/codeCell';
import { StatefullMarkdownCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/markdownCell';
50 51 52
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
R
Rob Lourens 已提交
53
import { CellKind, NotebookCellRunState } from 'vs/workbench/contrib/notebook/common/notebookCommon';
54

R
Rob Lourens 已提交
55 56 57
const $ = DOM.$;

export class NotebookCellListDelegate implements IListVirtualDelegate<CellViewModel> {
P
Peng Lyu 已提交
58
	private _lineHeight: number;
59

P
Peng Lyu 已提交
60 61 62 63 64 65 66
	constructor(
		@IConfigurationService private readonly configurationService: IConfigurationService
	) {
		const editorOptions = this.configurationService.getValue<IEditorOptions>('editor');
		this._lineHeight = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()).lineHeight;
	}

R
rebornix 已提交
67
	getHeight(element: CellViewModel): number {
R
rebornix 已提交
68
		return element.getHeight(this._lineHeight);
P
Peng Lyu 已提交
69 70
	}

R
rebornix 已提交
71
	hasDynamicHeight(element: CellViewModel): boolean {
P
Peng Lyu 已提交
72 73 74
		return element.hasDynamicHeight();
	}

R
rebornix 已提交
75
	getTemplateId(element: CellViewModel): string {
R
rebornix 已提交
76
		if (element.cellKind === CellKind.Markdown) {
P
Peng Lyu 已提交
77 78 79 80 81 82 83
			return MarkdownCellRenderer.TEMPLATE_ID;
		} else {
			return CodeCellRenderer.TEMPLATE_ID;
		}
	}
}

R
rebornix 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
export class CodiconActionViewItem extends ContextAwareMenuEntryActionViewItem {
	constructor(
		readonly _action: MenuItemAction,
		_keybindingService: IKeybindingService,
		_notificationService: INotificationService,
		_contextMenuService: IContextMenuService
	) {
		super(_action, _keybindingService, _notificationService, _contextMenuService);
	}
	updateLabel(): void {
		if (this.options.label && this.label) {
			this.label.innerHTML = renderCodicons(this._commandAction.label ?? '');
		}
	}
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
export class CellEditorOptions {

	private static fixedEditorOptions: IEditorOptions = {
		padding: {
			top: EDITOR_TOP_PADDING,
			bottom: EDITOR_BOTTOM_PADDING
		},
		scrollBeyondLastLine: false,
		scrollbar: {
			verticalScrollbarSize: 14,
			horizontal: 'auto',
			useShadows: true,
			verticalHasArrows: false,
			horizontalHasArrows: false,
			alwaysConsumeMouseWheel: false
		},
		renderLineHighlightOnlyWhenFocus: true,
		overviewRulerLanes: 0,
		selectOnLineNumbers: false,
		lineNumbers: 'off',
		lineDecorationsWidth: 0,
		glyphMargin: false,
122
		fixedOverflowWidgets: true,
123
		minimap: { enabled: false },
J
Johannes Rieken 已提交
124
		renderValidationDecorations: 'on'
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	};

	private _value: IEditorOptions;
	private _disposable: IDisposable;

	private readonly _onDidChange = new Emitter<IEditorOptions>();
	readonly onDidChange: Event<IEditorOptions> = this._onDidChange.event;

	constructor(configurationService: IConfigurationService, language: string) {

		this._disposable = configurationService.onDidChangeConfiguration(e => {
			if (e.affectsConfiguration('editor')) {
				this._value = computeEditorOptions();
				this._onDidChange.fire(this.value);
			}
		});

		const computeEditorOptions = () => {
			const editorOptions = deepClone(configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: language }));
			return {
				...editorOptions,
				...CellEditorOptions.fixedEditorOptions
			};
		};

		this._value = computeEditorOptions();
	}

	dispose(): void {
		this._onDidChange.dispose();
		this._disposable.dispose();
	}

	get value(): IEditorOptions {
		return this._value;
	}
161 162 163 164 165 166 167

	setGlyphMargin(gm: boolean): void {
		if (gm !== this._value.glyphMargin) {
			this._value.glyphMargin = gm;
			this._onDidChange.fire(this.value);
		}
	}
168 169
}

170
abstract class AbstractCellRenderer {
171
	protected editorOptions: CellEditorOptions;
R
rebornix 已提交
172
	private actionRunner = new ActionRunner();
P
Peng Lyu 已提交
173 174

	constructor(
175 176 177
		protected readonly instantiationService: IInstantiationService,
		protected readonly notebookEditor: INotebookEditor,
		protected readonly contextMenuService: IContextMenuService,
178
		configurationService: IConfigurationService,
179 180
		private readonly keybindingService: IKeybindingService,
		private readonly notificationService: INotificationService,
181
		protected readonly contextKeyService: IContextKeyService,
182
		language: string,
R
Rob Lourens 已提交
183
		protected readonly dndController: CellDragAndDropController
P
Peng Lyu 已提交
184
	) {
185 186 187 188 189
		this.editorOptions = new CellEditorOptions(configurationService, language);
	}

	dispose() {
		this.editorOptions.dispose();
P
Peng Lyu 已提交
190 191
	}

R
rebornix 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
	protected createBottomCellToolbar(container: HTMLElement): ToolBar {
		const toolbar = new ToolBar(container, this.contextMenuService, {
			actionViewItemProvider: action => {
				if (action instanceof MenuItemAction) {
					const item = new CodiconActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService);
					return item;
				}

				return undefined;
			}
		});

		toolbar.getContainer().style.height = `${BOTTOM_CELL_TOOLBAR_HEIGHT}px`;
		return toolbar;
	}

R
rebornix 已提交
208 209 210 211 212 213 214 215
	protected setupBetweenCellToolbarActions(element: CodeCellViewModel | MarkdownCellViewModel, templateData: BaseCellRenderTemplate, disposables: DisposableStore, context: INotebookCellActionContext): void {
		const container = templateData.bottomCellContainer;
		container.innerHTML = '';
		container.style.height = `${BOTTOM_CELL_TOOLBAR_HEIGHT}px`;

		DOM.append(container, $('.seperator'));
		const addCodeCell = DOM.append(container, $('span.button'));
		addCodeCell.innerHTML = renderCodicons(escape(`$(add) Code `));
216
		addCodeCell.tabIndex = 0;
R
rebornix 已提交
217 218
		const insertCellBelow = this.instantiationService.createInstance(InsertCodeCellAction);

R
rebornix 已提交
219 220 221 222 223
		const toolbarContext = {
			...context,
			ui: true
		};

224
		disposables.add(DOM.addDisposableListener(addCodeCell, DOM.EventType.CLICK, e => {
R
rebornix 已提交
225
			this.actionRunner.run(insertCellBelow, toolbarContext);
226
			e.stopPropagation();
R
rebornix 已提交
227 228
		}));

229 230 231 232 233
		disposables.add((DOM.addDisposableListener(addCodeCell, DOM.EventType.KEY_DOWN, async e => {
			const event = new StandardKeyboardEvent(e);
			if ((event.equals(KeyCode.Enter) || event.equals(KeyCode.Space))) {
				e.preventDefault();
				e.stopPropagation();
R
rebornix 已提交
234
				this.actionRunner.run(insertCellBelow, toolbarContext);
235 236 237
			}
		})));

R
rebornix 已提交
238 239 240
		DOM.append(container, $('.seperator-short'));
		const addMarkdownCell = DOM.append(container, $('span.button'));
		addMarkdownCell.innerHTML = renderCodicons(escape('$(add) Markdown '));
241
		addMarkdownCell.tabIndex = 0;
R
rebornix 已提交
242
		const insertMarkdownBelow = this.instantiationService.createInstance(InsertMarkdownCellAction);
243
		disposables.add(DOM.addDisposableListener(addMarkdownCell, DOM.EventType.CLICK, e => {
R
rebornix 已提交
244
			this.actionRunner.run(insertMarkdownBelow, toolbarContext);
245
			e.stopPropagation();
R
rebornix 已提交
246 247
		}));

248 249 250 251 252
		disposables.add((DOM.addDisposableListener(addMarkdownCell, DOM.EventType.KEY_DOWN, async e => {
			const event = new StandardKeyboardEvent(e);
			if ((event.equals(KeyCode.Enter) || event.equals(KeyCode.Space))) {
				e.preventDefault();
				e.stopPropagation();
R
rebornix 已提交
253
				this.actionRunner.run(insertMarkdownBelow, toolbarContext);
254 255 256
			}
		})));

R
rebornix 已提交
257 258 259 260 261 262 263 264 265 266 267 268
		DOM.append(container, $('.seperator'));

		if (element instanceof CodeCellViewModel) {
			const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
			container.style.top = `${bottomToolbarOffset}px`;

			disposables.add(element.onDidChangeLayout(() => {
				const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
				container.style.top = `${bottomToolbarOffset}px`;
			}));
		} else {
			container.style.position = 'static';
269
			container.style.height = `${BOTTOM_CELL_TOOLBAR_HEIGHT}`;
R
rebornix 已提交
270 271 272
		}
	}

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
	protected createToolbar(container: HTMLElement): ToolBar {
		const toolbar = new ToolBar(container, this.contextMenuService, {
			actionViewItemProvider: action => {
				if (action instanceof MenuItemAction) {
					const item = new ContextAwareMenuEntryActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService);
					return item;
				}

				return undefined;
			}
		});

		return toolbar;
	}

288
	private getCellToolbarActions(menu: IMenu): IAction[] {
289 290 291 292
		const actions: IAction[] = [];
		for (let [, menuActions] of menu.getActions({ shouldForwardArgs: true })) {
			actions.push(...menuActions);
		}
293

294 295
		return actions;
	}
296

297
	protected setupCellToolbarActions(scopedContextKeyService: IContextKeyService, templateData: BaseCellRenderTemplate, disposables: DisposableStore): void {
298 299 300 301 302 303 304 305 306 307
		const cellMenu = this.instantiationService.createInstance(CellMenus);
		const menu = disposables.add(cellMenu.getCellTitleMenu(scopedContextKeyService));

		const updateActions = () => {
			const actions = this.getCellToolbarActions(menu);

			templateData.toolbar.setActions(actions)();

			if (templateData.focusIndicator) {
				if (actions.length) {
308
					templateData.container.classList.add('cell-has-toolbar-actions');
R
rebornix 已提交
309
					templateData.focusIndicator.style.top = `${EDITOR_TOOLBAR_HEIGHT + EDITOR_TOP_MARGIN}px`;
310
				} else {
311
					templateData.container.classList.remove('cell-has-toolbar-actions');
R
rebornix 已提交
312
					templateData.focusIndicator.style.top = `${EDITOR_TOP_MARGIN}px`;
313 314 315 316 317 318 319 320 321
				}
			}
		};

		updateActions();
		disposables.add(menu.onDidChange(() => {
			updateActions();
		}));
	}
322

323 324 325 326 327
	protected commonRenderElement(element: ICellViewModel, index: number, templateData: BaseCellRenderTemplate): void {
		templateData.disposables.add(DOM.addDisposableListener(templateData.container, DOM.EventType.FOCUS, () => {
			this.notebookEditor.selectElement(element);
		}, true));

328 329 330 331 332 333
		if (element.dragging) {
			templateData.container.classList.add(DRAGGING_CLASS);
		} else {
			templateData.container.classList.remove(DRAGGING_CLASS);
		}
	}
P
Peng Lyu 已提交
334 335
}

336
export class MarkdownCellRenderer extends AbstractCellRenderer implements IListRenderer<MarkdownCellViewModel, MarkdownCellRenderTemplate> {
P
Peng Lyu 已提交
337 338 339
	static readonly TEMPLATE_ID = 'markdown_cell';

	constructor(
R
rebornix 已提交
340
		contextKeyService: IContextKeyService,
341
		notebookEditor: INotebookEditor,
R
Rob Lourens 已提交
342
		dndController: CellDragAndDropController,
343
		private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>,
344
		@IInstantiationService instantiationService: IInstantiationService,
P
Peng Lyu 已提交
345
		@IConfigurationService configurationService: IConfigurationService,
346 347 348
		@IContextMenuService contextMenuService: IContextMenuService,
		@IKeybindingService keybindingService: IKeybindingService,
		@INotificationService notificationService: INotificationService,
P
Peng Lyu 已提交
349
	) {
350
		super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyService, 'markdown', dndController);
P
Peng Lyu 已提交
351 352 353 354 355 356
	}

	get templateId() {
		return MarkdownCellRenderer.TEMPLATE_ID;
	}

357
	renderTemplate(container: HTMLElement): MarkdownCellRenderTemplate {
R
Rob Lourens 已提交
358
		container.classList.add('markdown-cell-row');
R
Rob Lourens 已提交
359 360
		const disposables = new DisposableStore();
		const toolbar = disposables.add(this.createToolbar(container));
R
Rob Lourens 已提交
361 362
		const focusIndicator = DOM.append(container, DOM.$('.notebook-cell-focus-indicator'));
		focusIndicator.setAttribute('draggable', 'true');
R
Rob Lourens 已提交
363

R
Rob Lourens 已提交
364
		const codeInnerContent = DOM.append(container, $('.cell.code'));
365
		const editorPart = DOM.append(codeInnerContent, $('.cell-editor-part'));
R
Rob Lourens 已提交
366
		const editorContainer = DOM.append(editorPart, $('.cell-editor-container'));
367
		editorPart.style.display = 'none';
P
Peng Lyu 已提交
368

R
Rob Lourens 已提交
369
		const innerContent = DOM.append(container, $('.cell.markdown'));
370
		const foldingIndicator = DOM.append(focusIndicator, DOM.$('.notebook-folding-indicator'));
R
rebornix 已提交
371

R
rebornix 已提交
372
		const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container'));
373

374 375
		const statusBar = this.instantiationService.createInstance(CellEditorStatusBar, editorPart);

R
Rob Lourens 已提交
376
		const templateData: MarkdownCellRenderTemplate = {
377
			container,
P
Peng Lyu 已提交
378
			cellContainer: innerContent,
379 380
			editorPart,
			editorContainer,
381
			focusIndicator,
R
rebornix 已提交
382
			foldingIndicator,
383
			disposables,
384
			elementDisposables: new DisposableStore(),
385
			toolbar,
R
Rob Lourens 已提交
386
			bottomCellContainer,
387 388
			statusBarContainer: statusBar.statusBarContainer,
			languageStatusBarItem: statusBar.languageStatusBarItem,
R
rebornix 已提交
389
			toJSON: () => { return {}; }
P
Peng Lyu 已提交
390
		};
391
		this.dndController.registerDragHandle(templateData, () => this.getDragImage(templateData));
R
Rob Lourens 已提交
392
		return templateData;
P
Peng Lyu 已提交
393 394
	}

395
	private getDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
R
Rob Lourens 已提交
396 397 398 399 400 401 402 403
		if (templateData.currentRenderedCell!.editState === CellEditState.Editing) {
			return this._getEditDragImage(templateData);
		} else {
			return this._getMarkdownDragImage(templateData);
		}
	}

	private _getMarkdownDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
404 405
		const dragImageContainer = DOM.$('.cell-drag-image.monaco-list-row.focused.markdown-cell-row');
		dragImageContainer.innerHTML = templateData.container.innerHTML;
R
Rob Lourens 已提交
406 407 408 409 410 411 412 413

		// Remove all rendered content nodes after the
		const markdownContent = dragImageContainer.querySelector('.cell.markdown')!;
		const contentNodes = markdownContent.children[0].children;
		for (let i = contentNodes.length - 1; i >= 1; i--) {
			contentNodes.item(i)!.remove();
		}

414 415 416
		return dragImageContainer;
	}

R
Rob Lourens 已提交
417 418 419
	private _getEditDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
		return new CodeCellDragImageRenderer().getDragImage(templateData, templateData.currentEditor!, 'markdown');
	}
420

421
	renderElement(element: MarkdownCellViewModel, index: number, templateData: MarkdownCellRenderTemplate, height: number | undefined): void {
422 423
		this.commonRenderElement(element, index, templateData);

R
Rob Lourens 已提交
424
		templateData.currentRenderedCell = element;
R
Rob Lourens 已提交
425
		templateData.currentEditor = undefined;
426
		templateData.editorPart!.style.display = 'none';
R
rebornix 已提交
427 428 429 430 431
		templateData.cellContainer.innerHTML = '';
		let renderedHTML = element.getHTML();
		if (renderedHTML) {
			templateData.cellContainer.appendChild(renderedHTML);
		}
P
Peng Lyu 已提交
432 433

		if (height) {
434
			const elementDisposables = templateData.elementDisposables;
P
Peng Lyu 已提交
435

R
rebornix 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448
			// render toolbar first
			const contextKeyService = this.contextKeyService.createScoped(templateData.container);
			this.setupCellToolbarActions(contextKeyService, templateData, elementDisposables);

			const toolbarContext = <INotebookCellActionContext>{
				cell: element,
				notebookEditor: this.notebookEditor,
				$mid: 12
			};
			templateData.toolbar.context = toolbarContext;

			this.setupBetweenCellToolbarActions(element, templateData, elementDisposables, toolbarContext);

449
			const markdownCell = this.instantiationService.createInstance(StatefullMarkdownCell, this.notebookEditor, element, templateData, this.editorOptions.value, this.renderedEditors);
450 451
			elementDisposables.add(this.editorOptions.onDidChange(newValue => markdownCell.updateEditorOptions(newValue)));
			elementDisposables.add(markdownCell);
452

453 454
			NOTEBOOK_CELL_TYPE.bindTo(contextKeyService).set('markdown');
			NOTEBOOK_VIEW_TYPE.bindTo(contextKeyService).set(element.viewType);
455
			const metadata = element.getEvaluatedMetadata(this.notebookEditor.viewModel!.notebookDocument.metadata);
456 457
			const cellEditableKey = NOTEBOOK_CELL_EDITABLE.bindTo(contextKeyService);
			cellEditableKey.set(!!metadata.editable);
458 459 460 461 462 463
			const updateForMetadata = () => {
				const metadata = element.getEvaluatedMetadata(this.notebookEditor.viewModel!.notebookDocument.metadata);
				cellEditableKey.set(!!metadata.editable);
			};

			updateForMetadata();
464
			elementDisposables.add(element.onDidChangeState((e) => {
465 466 467
				if (e.metadataChanged) {
					updateForMetadata();
				}
468 469
			}));

470 471
			const editModeKey = NOTEBOOK_CELL_MARKDOWN_EDIT_MODE.bindTo(contextKeyService);
			editModeKey.set(element.editState === CellEditState.Editing);
472
			elementDisposables.add(element.onDidChangeState((e) => {
473 474 475
				if (e.editStateChanged) {
					editModeKey.set(element.editState === CellEditState.Editing);
				}
476
			}));
477

R
rebornix 已提交
478
			element.totalHeight = height;
479

480 481
			templateData.languageStatusBarItem.update(element, this.notebookEditor);
		}
482 483
	}

484 485
	disposeTemplate(templateData: MarkdownCellRenderTemplate): void {
		templateData.disposables.clear();
P
Peng Lyu 已提交
486 487
	}

488
	disposeElement(element: ICellViewModel, index: number, templateData: MarkdownCellRenderTemplate, height: number | undefined): void {
P
Peng Lyu 已提交
489
		if (height) {
490
			templateData.elementDisposables.clear();
P
Peng Lyu 已提交
491 492 493 494
		}
	}
}

495
const DRAGGING_CLASS = 'cell-dragging';
R
Rob Lourens 已提交
496 497
const GLOBAL_DRAG_CLASS = 'global-drag-active';

498 499
type DragImageProvider = () => HTMLElement;

500 501 502 503 504 505 506 507
interface CellDragEvent {
	browserEvent: DragEvent;
	draggedOverCell: ICellViewModel;
	cellTop: number;
	cellHeight: number;
	dragPosRatio: number;
}

R
Rob Lourens 已提交
508
export class CellDragAndDropController extends Disposable {
509
	// TODO@roblourens - should probably use dataTransfer here, but any dataTransfer set makes the editor think I am dropping a file, need
R
Rob Lourens 已提交
510 511 512
	// to figure out how to prevent that
	private currentDraggedCell: ICellViewModel | undefined;

513 514 515 516 517 518 519
	private listInsertionIndicator: HTMLElement;

	private list!: INotebookCellList;

	private isScrolling = false;
	private scrollingDelayer: Delayer<void>;

R
Rob Lourens 已提交
520
	constructor(
521 522
		private readonly notebookEditor: INotebookEditor,
		insertionIndicatorContainer: HTMLElement
R
Rob Lourens 已提交
523 524 525
	) {
		super();

526 527
		this.listInsertionIndicator = DOM.append(insertionIndicatorContainer, $('.cell-list-insertion-indicator'));

R
Rob Lourens 已提交
528 529
		this._register(domEvent(document.body, DOM.EventType.DRAG_START, true)(this.onGlobalDragStart.bind(this)));
		this._register(domEvent(document.body, DOM.EventType.DRAG_END, true)(this.onGlobalDragEnd.bind(this)));
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

		const addCellDragListener = (eventType: string, handler: (e: CellDragEvent) => void) => {
			this._register(
				Event.map(
					domEvent(notebookEditor.getDomNode(), eventType),
					this.toCellDragEvent.bind(this))
					(handler));
		};

		addCellDragListener(DOM.EventType.DRAG_OVER, event => {
			event.browserEvent.preventDefault();
			this.onCellDragover(event);
		});
		addCellDragListener(DOM.EventType.DROP, event => {
			event.browserEvent.preventDefault();
			this.onCellDrop(event);
		});
		addCellDragListener(DOM.EventType.DRAG_LEAVE, event => {
			event.browserEvent.preventDefault();
			this.onCellDragLeave(event);
		});

		this.scrollingDelayer = new Delayer(200);
	}

	setList(value: INotebookCellList) {
		this.list = value;

		this.list.onWillScroll(() => {
			this.setInsertIndicatorVisibility(false);
			this.isScrolling = true;
			this.scrollingDelayer.trigger(() => {
				this.isScrolling = false;
			});
		});
	}

	private setInsertIndicatorVisibility(visible: boolean) {
		this.listInsertionIndicator.style.opacity = visible ? '1' : '0';
	}

	private toCellDragEvent(event: DragEvent): CellDragEvent {
		const targetTop = this.notebookEditor.getDomNode().getBoundingClientRect().top;
		const dragOffset = this.list.scrollTop + event.clientY - targetTop;
		const draggedOverCell = this.list.elementAt(dragOffset);
		const cellTop = this.list.getAbsoluteTopOfElement(draggedOverCell);
		const cellHeight = this.list.elementHeight(draggedOverCell);

		const dragPosInElement = dragOffset - cellTop;
		const dragPosRatio = dragPosInElement / cellHeight;

		return <CellDragEvent>{
			browserEvent: event,
			draggedOverCell,
			cellTop,
			cellHeight,
			dragPosRatio
		};
R
Rob Lourens 已提交
588 589 590 591 592 593 594 595 596
	}

	private onGlobalDragStart() {
		this.notebookEditor.getDomNode().classList.add(GLOBAL_DRAG_CLASS);
	}

	private onGlobalDragEnd() {
		this.notebookEditor.getDomNode().classList.remove(GLOBAL_DRAG_CLASS);
	}
R
Rob Lourens 已提交
597

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
	private onCellDragover(event: CellDragEvent): void {
		if (this.isScrolling || this.currentDraggedCell === event.draggedOverCell) {
			this.setInsertIndicatorVisibility(false);
			return;
		}

		const dropDirection = this.getDropInsertDirection(event);
		const insertionIndicatorAbsolutePos = dropDirection === 'above' ? event.cellTop : event.cellTop + event.cellHeight;
		const insertionIndicatorTop = insertionIndicatorAbsolutePos - this.list.scrollTop;
		if (insertionIndicatorTop >= 0) {
			this.listInsertionIndicator.style.top = `${insertionIndicatorAbsolutePos - this.list.scrollTop}px`;
			this.setInsertIndicatorVisibility(true);
		} else {
			this.setInsertIndicatorVisibility(false);
		}
	}

	private getDropInsertDirection(event: CellDragEvent): 'above' | 'below' {
		return event.dragPosRatio < 0.5 ? 'above' : 'below';
	}

	private onCellDrop(event: CellDragEvent): void {
		const draggedCell = this.currentDraggedCell!;
		this.dragCleanup();

		const isCopy = (event.browserEvent.ctrlKey && !platform.isMacintosh) || (event.browserEvent.altKey && platform.isMacintosh);

		const dropDirection = this.getDropInsertDirection(event);
		const insertionIndicatorAbsolutePos = dropDirection === 'above' ? event.cellTop : event.cellTop + event.cellHeight;
		const insertionIndicatorTop = insertionIndicatorAbsolutePos - this.list.scrollTop;
		const editorHeight = this.notebookEditor.getDomNode().getBoundingClientRect().height;
		if (insertionIndicatorTop < 0 || insertionIndicatorTop > editorHeight) {
			// Ignore drop, insertion point is off-screen
			return;
		}

		if (isCopy) {
			this.copyCell(draggedCell, event.draggedOverCell, dropDirection);
		} else {
			this.moveCell(draggedCell, event.draggedOverCell, dropDirection);
		}
	}

	private onCellDragLeave(event: CellDragEvent): void {
		if (!event.browserEvent.relatedTarget || !DOM.isAncestor(event.browserEvent.relatedTarget as HTMLElement, this.notebookEditor.getDomNode())) {
			this.setInsertIndicatorVisibility(false);
		}
	}

	private dragCleanup(): void {
		if (this.currentDraggedCell) {
			this.currentDraggedCell.dragging = false;
			this.currentDraggedCell = undefined;
		}

		this.setInsertIndicatorVisibility(false);
	}

	registerDragHandle(templateData: BaseCellRenderTemplate, dragImageProvider: DragImageProvider): void {
R
Rob Lourens 已提交
657
		const container = templateData.container;
R
Rob Lourens 已提交
658
		const dragHandle = templateData.focusIndicator;
R
Rob Lourens 已提交
659

660
		templateData.disposables.add(domEvent(dragHandle, DOM.EventType.DRAG_END)(() => {
661 662
			// Note, templateData may have a different element rendered into it by now
			container.classList.remove(DRAGGING_CLASS);
663
			this.dragCleanup();
R
Rob Lourens 已提交
664 665
		}));

666
		templateData.disposables.add(domEvent(dragHandle, DOM.EventType.DRAG_START)(event => {
R
Rob Lourens 已提交
667 668 669 670
			if (!event.dataTransfer) {
				return;
			}

671 672
			this.currentDraggedCell = templateData.currentRenderedCell!;
			this.currentDraggedCell.dragging = true;
673 674

			const dragImage = dragImageProvider();
R
Rob Lourens 已提交
675 676
			container.parentElement!.appendChild(dragImage);
			event.dataTransfer.setDragImage(dragImage, 0, 0);
677
			setTimeout(() => container.parentElement!.removeChild(dragImage!), 0); // Comment this out to debug drag image layout
R
Rob Lourens 已提交
678

679
			container.classList.add(DRAGGING_CLASS);
680
		}));
R
Rob Lourens 已提交
681
	}
R
Rob Lourens 已提交
682

R
Rob Lourens 已提交
683
	private moveCell(draggedCell: ICellViewModel, ontoCell: ICellViewModel, direction: 'above' | 'below') {
684
		const editState = draggedCell.editState;
R
Rob Lourens 已提交
685
		this.notebookEditor.moveCell(draggedCell, ontoCell, direction);
C
Christopher Maynard 已提交
686
		this.notebookEditor.focusNotebookCell(draggedCell, editState === CellEditState.Editing ? 'editor' : 'container');
687 688
	}

R
Rob Lourens 已提交
689 690 691 692
	private copyCell(draggedCell: ICellViewModel, ontoCell: ICellViewModel, direction: 'above' | 'below') {
		const editState = draggedCell.editState;
		const newCell = this.notebookEditor.insertNotebookCell(ontoCell, draggedCell.cellKind, direction, draggedCell.getText());
		if (newCell) {
C
Christopher Maynard 已提交
693
			this.notebookEditor.focusNotebookCell(newCell, editState === CellEditState.Editing ? 'editor' : 'container');
R
Rob Lourens 已提交
694 695
		}
	}
696 697
}

698 699 700
export class CellLanguageStatusBarItem extends Disposable {
	private labelElement: HTMLElement;

701
	private _cell: ICellViewModel | undefined;
702 703 704 705 706 707 708
	private _editor: INotebookEditor | undefined;

	private cellDisposables: DisposableStore;

	constructor(
		readonly container: HTMLElement,
		@IModeService private readonly modeService: IModeService,
709
		@IInstantiationService private readonly instantiationService: IInstantiationService
710 711
	) {
		super();
712
		this.labelElement = DOM.append(container, $('.cell-language-picker'));
713
		this.labelElement.tabIndex = 0;
714

715 716 717 718 719
		this._register(DOM.addDisposableListener(this.labelElement, DOM.EventType.CLICK, () => {
			this.instantiationService.invokeFunction(accessor => {
				new ChangeCellLanguageAction().run(accessor, { notebookEditor: this._editor!, cell: this._cell! });
			});
		}));
720 721 722
		this._register(this.cellDisposables = new DisposableStore());
	}

723
	update(cell: ICellViewModel, editor: INotebookEditor): void {
724 725 726 727 728 729 730 731 732 733 734 735 736
		this.cellDisposables.clear();
		this._cell = cell;
		this._editor = editor;

		this.render();
		this.cellDisposables.add(this._cell.model.onDidChangeLanguage(() => this.render()));
	}

	private render(): void {
		this.labelElement.textContent = this.modeService.getLanguageName(this._cell!.language!);
	}
}

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
class EditorTextRenderer {

	getRichText(editor: ICodeEditor, modelRange: Range): string | null {
		const model = editor.getModel();
		if (!model) {
			return null;
		}

		const colorMap = this._getDefaultColorMap();
		const fontInfo = editor.getOptions().get(EditorOption.fontInfo);
		const fontFamily = fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily ? fontInfo.fontFamily : `'${fontInfo.fontFamily}', ${EDITOR_FONT_DEFAULTS.fontFamily}`;

		return `<div style="`
			+ `color: ${colorMap[modes.ColorId.DefaultForeground]};`
			+ `background-color: ${colorMap[modes.ColorId.DefaultBackground]};`
			+ `font-family: ${fontFamily};`
			+ `font-weight: ${fontInfo.fontWeight};`
			+ `font-size: ${fontInfo.fontSize}px;`
			+ `line-height: ${fontInfo.lineHeight}px;`
			+ `white-space: pre;`
			+ `">`
			+ this._getRichTextLines(model, modelRange, colorMap)
			+ '</div>';
	}

	private _getRichTextLines(model: ITextModel, modelRange: Range, colorMap: string[]): string {
		const startLineNumber = modelRange.startLineNumber;
		const startColumn = modelRange.startColumn;
		const endLineNumber = modelRange.endLineNumber;
		const endColumn = modelRange.endColumn;

		const tabSize = model.getOptions().tabSize;

		let result = '';

		for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
			const lineTokens = model.getLineTokens(lineNumber);
			const lineContent = lineTokens.getLineContent();
			const startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0);
			const endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length);

			if (lineContent === '') {
				result += '<br>';
			} else {
				result += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows);
			}
		}

		return result;
	}

	private _getDefaultColorMap(): string[] {
		let colorMap = modes.TokenizationRegistry.getColorMap();
		let result: string[] = ['#000000'];
		if (colorMap) {
			for (let i = 1, len = colorMap.length; i < len; i++) {
				result[i] = Color.Format.CSS.formatHex(colorMap[i]);
			}
		}
		return result;
	}
}
R
Rob Lourens 已提交
799

800
class CodeCellDragImageRenderer {
R
Rob Lourens 已提交
801 802
	getDragImage(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement {
		let dragImage = this._getDragImage(templateData, editor, type);
803
		if (!dragImage) {
804
			// TODO@roblourens I don't think this can happen
805 806 807 808 809 810 811
			dragImage = document.createElement('div');
			dragImage.textContent = '1 cell';
		}

		return dragImage;
	}

R
Rob Lourens 已提交
812 813
	private _getDragImage(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement | null {
		const dragImageContainer = DOM.$(`.cell-drag-image.monaco-list-row.focused.${type}-cell-row`);
814 815 816 817 818 819 820 821 822 823 824 825
		dragImageContainer.innerHTML = templateData.container.innerHTML;

		const editorContainer = dragImageContainer.querySelector('.cell-editor-container');
		if (!editorContainer) {
			return null;
		}

		const focusIndicator = dragImageContainer.querySelector('.notebook-cell-focus-indicator') as HTMLElement;
		if (focusIndicator) {
			focusIndicator.style.height = '40px';
		}

R
Rob Lourens 已提交
826
		const richEditorText = new EditorTextRenderer().getRichText(editor, new Range(1, 1, 1, 1000));
827 828 829 830 831 832 833
		if (!richEditorText) {
			return null;
		}

		editorContainer.innerHTML = richEditorText;

		return dragImageContainer;
R
Rob Lourens 已提交
834 835 836
	}
}

837 838 839 840 841
class CellEditorStatusBar {
	readonly cellStatusMessageContainer: HTMLElement;
	readonly cellRunStatusContainer: HTMLElement;
	readonly statusBarContainer: HTMLElement;
	readonly languageStatusBarItem: CellLanguageStatusBarItem;
842
	readonly durationContainer: HTMLElement;
843 844 845 846 847 848 849 850 851

	constructor(
		container: HTMLElement,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		this.statusBarContainer = DOM.append(container, $('.cell-statusbar-container'));
		const leftStatusBarItems = DOM.append(this.statusBarContainer, $('.cell-status-left'));
		const rightStatusBarItems = DOM.append(this.statusBarContainer, $('.cell-status-right'));
		this.cellRunStatusContainer = DOM.append(leftStatusBarItems, $('.cell-run-status'));
852
		this.durationContainer = DOM.append(leftStatusBarItems, $('.cell-run-duration'));
853 854 855 856 857
		this.cellStatusMessageContainer = DOM.append(leftStatusBarItems, $('.cell-status-message'));
		this.languageStatusBarItem = instantiationService.createInstance(CellLanguageStatusBarItem, rightStatusBarItems);
	}
}

858
export class CodeCellRenderer extends AbstractCellRenderer implements IListRenderer<CodeCellViewModel, CodeCellRenderTemplate> {
P
Peng Lyu 已提交
859
	static readonly TEMPLATE_ID = 'code_cell';
R
rebornix 已提交
860

P
Peng Lyu 已提交
861
	constructor(
R
rebornix 已提交
862
		protected notebookEditor: INotebookEditor,
R
rebornix 已提交
863
		private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>,
R
Rob Lourens 已提交
864
		dndController: CellDragAndDropController,
865
		@IContextKeyService protected contextKeyService: IContextKeyService,
P
Peng Lyu 已提交
866 867
		@IContextMenuService contextMenuService: IContextMenuService,
		@IConfigurationService configurationService: IConfigurationService,
868
		@IInstantiationService instantiationService: IInstantiationService,
869 870
		@IKeybindingService keybindingService: IKeybindingService,
		@INotificationService notificationService: INotificationService,
P
Peng Lyu 已提交
871
	) {
R
Rob Lourens 已提交
872
		super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyService, 'python', dndController);
P
Peng Lyu 已提交
873 874 875 876 877 878
	}

	get templateId() {
		return CodeCellRenderer.TEMPLATE_ID;
	}

879
	renderTemplate(container: HTMLElement): CodeCellRenderTemplate {
R
Rob Lourens 已提交
880
		container.classList.add('code-cell-row');
R
rebornix 已提交
881
		container.tabIndex = 0;
882
		const disposables = new DisposableStore();
R
Rob Lourens 已提交
883
		const toolbar = disposables.add(this.createToolbar(container));
R
Rob Lourens 已提交
884 885
		const focusIndicator = DOM.append(container, DOM.$('.notebook-cell-focus-indicator'));
		focusIndicator.setAttribute('draggable', 'true');
886

R
Rob Lourens 已提交
887 888 889 890 891
		const cellContainer = DOM.append(container, $('.cell.code'));
		const runButtonContainer = DOM.append(cellContainer, $('.run-button-container'));
		const runToolbar = this.createToolbar(runButtonContainer);
		disposables.add(runToolbar);

892 893
		const executionOrderLabel = DOM.append(runButtonContainer, $('div.execution-count-label'));

894 895 896 897 898
		// create a special context key service that set the inCompositeEditor-contextkey
		const editorContextKeyService = this.contextKeyService.createScoped();
		const editorInstaService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, editorContextKeyService]));
		EditorContextKeys.inCompositeEditor.bindTo(editorContextKeyService).set(true);

R
Rob Lourens 已提交
899 900
		const editorPart = DOM.append(cellContainer, $('.cell-editor-part'));
		const editorContainer = DOM.append(editorPart, $('.cell-editor-container'));
901
		const editor = editorInstaService.createInstance(CodeEditorWidget, editorContainer, {
902
			...this.editorOptions.value,
P
Peng Lyu 已提交
903 904 905 906 907 908
			dimension: {
				width: 0,
				height: 0
			}
		}, {});

909 910
		disposables.add(this.editorOptions.onDidChange(newValue => editor.updateOptions(newValue)));

R
Rob Lourens 已提交
911
		const progressBar = new ProgressBar(editorPart);
R
Rob Lourens 已提交
912 913 914
		progressBar.hide();
		disposables.add(progressBar);

915
		const statusBar = this.instantiationService.createInstance(CellEditorStatusBar, editorPart);
916
		const timer = new TimerRenderer(statusBar.durationContainer);
R
Rob Lourens 已提交
917 918

		const outputContainer = DOM.append(container, $('.output'));
919 920
		const focusSink = DOM.append(container, $('.cell-editor-focus-sink'));
		focusSink.setAttribute('tabindex', '0');
921 922
		const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container'));

R
Rob Lourens 已提交
923
		const templateData: CodeCellRenderTemplate = {
924 925
			container,
			cellContainer,
926 927 928 929
			statusBarContainer: statusBar.statusBarContainer,
			cellRunStatusContainer: statusBar.cellRunStatusContainer,
			cellStatusMessageContainer: statusBar.cellStatusMessageContainer,
			languageStatusBarItem: statusBar.languageStatusBarItem,
R
Rob Lourens 已提交
930
			progressBar,
931
			focusIndicator,
932
			toolbar,
R
Rob Lourens 已提交
933
			runToolbar,
R
rebornix 已提交
934
			runButtonContainer,
935
			executionOrderLabel,
936 937
			outputContainer,
			editor,
938
			disposables,
939 940
			elementDisposables: new DisposableStore(),
			bottomCellContainer,
941
			timer,
R
rebornix 已提交
942
			toJSON: () => { return {}; }
P
Peng Lyu 已提交
943
		};
R
Rob Lourens 已提交
944

945
		this.dndController.registerDragHandle(templateData, () => new CodeCellDragImageRenderer().getDragImage(templateData, templateData.editor, 'code'));
946 947 948 949 950 951 952

		disposables.add(DOM.addDisposableListener(focusSink, DOM.EventType.FOCUS, () => {
			if (templateData.currentRenderedCell) {
				this.notebookEditor.focusNotebookCell(templateData.currentRenderedCell, 'output');
			}
		}));

R
Rob Lourens 已提交
953
		return templateData;
P
Peng Lyu 已提交
954 955
	}

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
	private updateForRunState(element: CodeCellViewModel, templateData: CodeCellRenderTemplate, runStateKey: IContextKey<string>): void {
		runStateKey.set(CellRunState[element.runState]);
		if (element.runState === CellRunState.Running) {
			templateData.progressBar.infinite().show(500);

			templateData.runToolbar.setActions([
				this.instantiationService.createInstance(CancelCellAction)
			])();
		} else {
			templateData.progressBar.hide();

			templateData.runToolbar.setActions([
				this.instantiationService.createInstance(ExecuteCellAction)
			])();
		}
	}

973
	private updateForMetadata(element: CodeCellViewModel, templateData: CodeCellRenderTemplate, cellEditableKey: IContextKey<boolean>, cellRunnableKey: IContextKey<boolean>): void {
R
Rob Lourens 已提交
974 975 976 977
		const metadata = element.getEvaluatedMetadata(this.notebookEditor.viewModel!.notebookDocument.metadata);
		DOM.toggleClass(templateData.cellContainer, 'runnable', !!metadata.runnable);
		this.renderExecutionOrder(element, templateData);
		cellEditableKey.set(!!metadata.editable);
978
		cellRunnableKey.set(!!metadata.runnable);
R
Rob Lourens 已提交
979 980 981 982 983 984
		templateData.cellStatusMessageContainer.textContent = metadata?.statusMessage || '';

		if (metadata.runState === NotebookCellRunState.Success) {
			templateData.cellRunStatusContainer.innerHTML = renderCodicons('$(check)');
		} else if (metadata.runState === NotebookCellRunState.Error) {
			templateData.cellRunStatusContainer.innerHTML = renderCodicons('$(error)');
R
Rob Lourens 已提交
985
		} else if (metadata.runState === NotebookCellRunState.Running) {
986
			templateData.cellRunStatusContainer.innerHTML = renderCodicons('$(sync~spin)');
R
Rob Lourens 已提交
987 988 989
		} else {
			templateData.cellRunStatusContainer.innerHTML = '';
		}
990 991 992 993 994 995 996 997 998 999 1000 1001

		if (metadata.runState === NotebookCellRunState.Running) {
			if (metadata.runStartTime) {
				templateData.elementDisposables.add(templateData.timer.start(metadata.runStartTime));
			} else {
				templateData.timer.clear();
			}
		} else if (typeof metadata.lastRunDuration === 'number') {
			templateData.timer.show(metadata.lastRunDuration);
		} else {
			templateData.timer.clear();
		}
1002 1003 1004 1005

		if (typeof metadata.breakpointMargin === 'boolean') {
			this.editorOptions.setGlyphMargin(metadata.breakpointMargin);
		}
R
Rob Lourens 已提交
1006 1007 1008 1009 1010
	}

	private renderExecutionOrder(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
		const hasExecutionOrder = this.notebookEditor.viewModel!.notebookDocument.metadata?.hasExecutionOrder;
		if (hasExecutionOrder) {
1011 1012
			const executionOrdeerLabel = typeof element.metadata?.executionOrder === 'number' ? `[${element.metadata.executionOrder}]` :
				'[ ]';
R
Rob Lourens 已提交
1013 1014 1015 1016 1017 1018
			templateData.executionOrderLabel.innerText = executionOrdeerLabel;
		} else {
			templateData.executionOrderLabel.innerText = '';
		}
	}

1019 1020 1021 1022
	private updateForHover(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
		DOM.toggleClass(templateData.container, 'cell-output-hover', element.outputIsHovered);
	}

1023
	renderElement(element: CodeCellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void {
1024 1025
		this.commonRenderElement(element, index, templateData);

R
Rob Lourens 已提交
1026 1027
		templateData.currentRenderedCell = element;

R
rebornix 已提交
1028 1029 1030 1031
		if (height === undefined) {
			return;
		}

1032
		templateData.outputContainer.innerHTML = '';
1033

1034
		const elementDisposables = templateData.elementDisposables;
R
rebornix 已提交
1035

1036
		elementDisposables.add(this.instantiationService.createInstance(CodeCell, this.notebookEditor, element, templateData));
J
Johannes Rieken 已提交
1037
		this.renderedEditors.set(element, templateData.editor);
1038

1039
		templateData.focusIndicator.style.height = `${element.layoutInfo.indicatorHeight}px`;
1040
		elementDisposables.add(element.onDidChangeLayout(() => {
1041
			templateData.focusIndicator.style.height = `${element.layoutInfo.indicatorHeight}px`;
1042 1043
		}));

1044 1045
		const contextKeyService = this.contextKeyService.createScoped(templateData.container);

1046 1047
		const runStateKey = NOTEBOOK_CELL_RUN_STATE.bindTo(contextKeyService);
		runStateKey.set(CellRunState[element.runState]);
1048
		this.updateForRunState(element, templateData, runStateKey);
1049
		elementDisposables.add(element.onDidChangeState((e) => {
1050 1051 1052 1053
			if (e.runStateChanged) {
				this.updateForRunState(element, templateData, runStateKey);
			}
		}));
1054

R
rebornix 已提交
1055 1056 1057 1058 1059 1060
		const cellHasOutputsContext = NOTEBOOK_CELL_HAS_OUTPUTS.bindTo(contextKeyService);
		cellHasOutputsContext.set(element.outputs.length > 0);
		elementDisposables.add(element.onDidChangeOutputs(() => {
			cellHasOutputsContext.set(element.outputs.length > 0);
		}));

1061 1062
		NOTEBOOK_CELL_TYPE.bindTo(contextKeyService).set('code');
		NOTEBOOK_VIEW_TYPE.bindTo(contextKeyService).set(element.viewType);
1063
		const metadata = element.getEvaluatedMetadata(this.notebookEditor.viewModel!.notebookDocument.metadata);
1064 1065 1066 1067
		const cellEditableKey = NOTEBOOK_CELL_EDITABLE.bindTo(contextKeyService);
		cellEditableKey.set(!!metadata.editable);
		const cellRunnableKey = NOTEBOOK_CELL_RUNNABLE.bindTo(contextKeyService);
		cellRunnableKey.set(!!metadata.runnable);
1068
		this.updateForMetadata(element, templateData, cellEditableKey, cellRunnableKey);
1069
		elementDisposables.add(element.onDidChangeState((e) => {
1070
			if (e.metadataChanged) {
1071
				this.updateForMetadata(element, templateData, cellEditableKey, cellRunnableKey);
1072
			}
1073 1074 1075 1076

			if (e.outputIsHoveredChanged) {
				this.updateForHover(element, templateData);
			}
1077
		}));
1078

1079
		this.setupCellToolbarActions(contextKeyService, templateData, elementDisposables);
1080 1081 1082 1083 1084 1085 1086

		const toolbarContext = <INotebookCellActionContext>{
			cell: element,
			cellTemplate: templateData,
			notebookEditor: this.notebookEditor,
			$mid: 12
		};
1087
		templateData.toolbar.context = toolbarContext;
1088
		templateData.runToolbar.context = toolbarContext;
R
rebornix 已提交
1089

1090
		this.setupBetweenCellToolbarActions(element, templateData, elementDisposables, toolbarContext);
1091 1092

		templateData.languageStatusBarItem.update(element, this.notebookEditor);
R
rebornix 已提交
1093 1094
	}

1095
	disposeTemplate(templateData: CodeCellRenderTemplate): void {
1096
		templateData.disposables.clear();
P
Peng Lyu 已提交
1097 1098
	}

1099
	disposeElement(element: ICellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void {
1100
		templateData.elementDisposables.clear();
J
Johannes Rieken 已提交
1101
		this.renderedEditors.delete(element);
1102
		templateData.focusIndicator.style.height = 'initial';
P
Peng Lyu 已提交
1103 1104
	}
}
1105 1106 1107 1108 1109 1110

export class TimerRenderer {
	constructor(private readonly container: HTMLElement) {
		DOM.hide(container);
	}

R
Rob Lourens 已提交
1111
	private intervalTimer: number | undefined;
1112 1113 1114 1115 1116 1117 1118 1119 1120

	start(startTime: number): IDisposable {
		this.stop();

		DOM.show(this.container);
		const intervalTimer = setInterval(() => {
			const duration = Date.now() - startTime;
			this.container.textContent = this.formatDuration(duration);
		}, 100);
R
Rob Lourens 已提交
1121
		this.intervalTimer = intervalTimer as any;
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

		return toDisposable(() => {
			clearInterval(intervalTimer);
		});
	}

	stop() {
		if (this.intervalTimer) {
			clearInterval(this.intervalTimer);
		}
	}

	show(duration: number) {
		this.stop();

		DOM.show(this.container);
		this.container.textContent = this.formatDuration(duration);
	}

	clear() {
		DOM.hide(this.container);
		this.stop();
		this.container.textContent = '';
	}

	private formatDuration(duration: number) {
		const seconds = Math.floor(duration / 1000);
		const tenths = String(duration - seconds * 1000).charAt(0);

		return `${seconds}.${tenths}s`;
	}
}