cellRenderer.ts 42.7 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.
 *--------------------------------------------------------------------------------------------*/

R
rebornix 已提交
6
import { getZoomLevel } from 'vs/base/browser/browser';
P
Peng Lyu 已提交
7
import * as DOM from 'vs/base/browser/dom';
8
import { domEvent } from 'vs/base/browser/event';
R
rebornix 已提交
9
import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
R
Rob Lourens 已提交
10
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
11
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
12
import { IAction } from 'vs/base/common/actions';
13
import { Delayer } from 'vs/base/common/async';
14
import { renderCodicons } from 'vs/base/common/codicons';
15
import { Color } from 'vs/base/common/color';
16
import { Emitter, Event } from 'vs/base/common/event';
17
import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
P
Peng Lyu 已提交
18
import { deepClone } from 'vs/base/common/objects';
19
import * as platform from 'vs/base/common/platform';
20
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
R
rebornix 已提交
21
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
22
import { EditorOption, EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
P
Peng Lyu 已提交
23
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
24
import { Range } from 'vs/editor/common/core/range';
C
Christopher Maynard 已提交
25
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
26 27 28 29
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';
30
import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
R
Rob Lourens 已提交
31
import { IMenu, MenuItemAction } from 'vs/platform/actions/common/actions';
R
rebornix 已提交
32
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
33
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
P
Peng Lyu 已提交
34
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
R
rebornix 已提交
35
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
C
Christopher Maynard 已提交
36
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
R
Rob Lourens 已提交
37 38
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { INotificationService } from 'vs/platform/notification/common/notification';
39
import { BOTTOM_CELL_TOOLBAR_HEIGHT, EDITOR_BOTTOM_PADDING, EDITOR_TOOLBAR_HEIGHT, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING, CELL_BOTTOM_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants';
40
import { CancelCellAction, ChangeCellLanguageAction, ExecuteCellAction, INotebookCellActionContext, CELL_TITLE_GROUP_ID } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';
41
import { BaseCellRenderTemplate, CellEditState, CodeCellRenderTemplate, ICellViewModel, INotebookCellList, INotebookEditor, MarkdownCellRenderTemplate, isCodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
42
import { CellMenus } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellMenus';
R
rebornix 已提交
43 44
import { CodeCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/codeCell';
import { StatefullMarkdownCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/markdownCell';
45 46 47
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';
48
import { CellKind, NotebookCellRunState, NotebookCellMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon';
49
import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys';
50

R
Rob Lourens 已提交
51 52 53
const $ = DOM.$;

export class NotebookCellListDelegate implements IListVirtualDelegate<CellViewModel> {
54
	private readonly lineHeight: number;
55

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

R
rebornix 已提交
63
	getHeight(element: CellViewModel): number {
64
		return element.getHeight(this.lineHeight);
P
Peng Lyu 已提交
65 66
	}

R
rebornix 已提交
67
	hasDynamicHeight(element: CellViewModel): boolean {
P
Peng Lyu 已提交
68 69 70
		return element.hasDynamicHeight();
	}

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

80
export class CodiconActionViewItem extends MenuEntryActionViewItem {
R
rebornix 已提交
81 82
	constructor(
		readonly _action: MenuItemAction,
83 84 85
		keybindingService: IKeybindingService,
		notificationService: INotificationService,
		contextMenuService: IContextMenuService
R
rebornix 已提交
86
	) {
87
		super(_action, keybindingService, notificationService, contextMenuService);
R
rebornix 已提交
88 89 90 91 92 93 94 95
	}
	updateLabel(): void {
		if (this.options.label && this.label) {
			this.label.innerHTML = renderCodicons(this._commandAction.label ?? '');
		}
	}
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
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,
118
		fixedOverflowWidgets: true,
119
		minimap: { enabled: false },
J
Johannes Rieken 已提交
120
		renderValidationDecorations: 'on'
121 122 123
	};

	private _value: IEditorOptions;
124
	private disposable: IDisposable;
125 126 127 128 129 130

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

	constructor(configurationService: IConfigurationService, language: string) {

131
		this.disposable = configurationService.onDidChangeConfiguration(e => {
132 133 134 135 136 137 138 139
			if (e.affectsConfiguration('editor')) {
				this._value = computeEditorOptions();
				this._onDidChange.fire(this.value);
			}
		});

		const computeEditorOptions = () => {
			const editorOptions = deepClone(configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: language }));
140
			const computed = {
141 142 143
				...editorOptions,
				...CellEditorOptions.fixedEditorOptions
			};
144 145 146 147 148 149

			if (!computed.folding) {
				computed.lineDecorationsWidth = 16;
			}

			return computed;
150 151 152 153 154 155 156
		};

		this._value = computeEditorOptions();
	}

	dispose(): void {
		this._onDidChange.dispose();
157
		this.disposable.dispose();
158 159 160 161 162
	}

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

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

172
abstract class AbstractCellRenderer {
173 174
	protected readonly editorOptions: CellEditorOptions;
	protected readonly cellMenus: CellMenus;
P
Peng Lyu 已提交
175 176

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

	dispose() {
		this.editorOptions.dispose();
P
Peng Lyu 已提交
193 194
	}

195
	protected createBetweenCellToolbar(container: HTMLElement, disposables: DisposableStore, contextKeyService: IContextKeyService): ToolBar {
R
rebornix 已提交
196 197 198 199 200 201 202 203 204 205 206 207
		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`;
R
rebornix 已提交
208 209
		container.style.height = `${BOTTOM_CELL_TOOLBAR_HEIGHT}px`;

210 211
		const cellMenu = this.instantiationService.createInstance(CellMenus);
		const menu = disposables.add(cellMenu.getCellInsertionMenu(contextKeyService));
R
rebornix 已提交
212

213
		const actions = this.getCellToolbarActions(menu);
J
João Moreno 已提交
214
		toolbar.setActions(actions.primary, actions.secondary);
R
rebornix 已提交
215

216 217
		return toolbar;
	}
218

219 220
	protected setBetweenCellToolbarContext(templateData: BaseCellRenderTemplate, element: CodeCellViewModel | MarkdownCellViewModel, context: INotebookCellActionContext): void {
		templateData.betweenCellToolbar.context = context;
R
rebornix 已提交
221

222
		const container = templateData.bottomCellContainer;
R
rebornix 已提交
223 224 225 226
		if (element instanceof CodeCellViewModel) {
			const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
			container.style.top = `${bottomToolbarOffset}px`;

227
			templateData.elementDisposables.add(element.onDidChangeLayout(() => {
R
rebornix 已提交
228 229 230 231 232 233
				const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
				container.style.top = `${bottomToolbarOffset}px`;
			}));
		}
	}

234 235 236 237
	protected createToolbar(container: HTMLElement): ToolBar {
		const toolbar = new ToolBar(container, this.contextMenuService, {
			actionViewItemProvider: action => {
				if (action instanceof MenuItemAction) {
238
					const item = new MenuEntryActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService);
239 240 241 242 243 244 245 246 247 248
					return item;
				}

				return undefined;
			}
		});

		return toolbar;
	}

R
Rob Lourens 已提交
249 250 251 252 253 254 255 256 257 258
	private getCellToolbarActions(menu: IMenu): { primary: IAction[], secondary: IAction[] } {
		const primary: IAction[] = [];
		const secondary: IAction[] = [];
		const actions = menu.getActions({ shouldForwardArgs: true });
		for (let [id, menuActions] of actions) {
			if (id === CELL_TITLE_GROUP_ID) {
				primary.push(...menuActions);
			} else {
				secondary.push(...menuActions);
			}
259
		}
260

R
Rob Lourens 已提交
261
		return { primary, secondary };
262
	}
263

264
	protected setupCellToolbarActions(templateData: BaseCellRenderTemplate, disposables: DisposableStore): void {
265
		const updateActions = () => {
266
			const actions = this.getCellToolbarActions(templateData.titleMenu);
267

268
			const hadFocus = DOM.isAncestor(document.activeElement, templateData.toolbar.getContainer());
J
João Moreno 已提交
269
			templateData.toolbar.setActions(actions.primary, actions.secondary);
270 271 272
			if (hadFocus) {
				this.notebookEditor.focus();
			}
273

274 275 276
			if (actions.primary.length || actions.secondary.length) {
				templateData.container.classList.add('cell-has-toolbar-actions');
				if (isCodeCellRenderTemplate(templateData)) {
R
rebornix 已提交
277
					templateData.focusIndicator.style.top = `${EDITOR_TOOLBAR_HEIGHT + EDITOR_TOP_MARGIN}px`;
278 279 280 281 282
					templateData.focusIndicatorRight.style.top = `${EDITOR_TOOLBAR_HEIGHT + EDITOR_TOP_MARGIN}px`;
				}
			} else {
				templateData.container.classList.remove('cell-has-toolbar-actions');
				if (isCodeCellRenderTemplate(templateData)) {
R
rebornix 已提交
283
					templateData.focusIndicator.style.top = `${EDITOR_TOP_MARGIN}px`;
284
					templateData.focusIndicatorRight.style.top = `${EDITOR_TOP_MARGIN}px`;
285 286 287 288 289
				}
			}
		};

		updateActions();
290
		disposables.add(templateData.titleMenu.onDidChange(() => {
291 292 293 294
			if (this.notebookEditor.isDisposed) {
				return;
			}

295 296 297
			updateActions();
		}));
	}
298

R
Rob Lourens 已提交
299
	protected commonRenderTemplate(templateData: BaseCellRenderTemplate): void {
300
		templateData.disposables.add(DOM.addDisposableListener(templateData.container, DOM.EventType.FOCUS, () => {
R
Rob Lourens 已提交
301 302 303
			if (templateData.currentRenderedCell) {
				this.notebookEditor.selectElement(templateData.currentRenderedCell);
			}
304
		}, true));
R
Rob Lourens 已提交
305
	}
306

R
Rob Lourens 已提交
307
	protected commonRenderElement(element: ICellViewModel, index: number, templateData: BaseCellRenderTemplate): void {
308 309 310 311 312 313
		if (element.dragging) {
			templateData.container.classList.add(DRAGGING_CLASS);
		} else {
			templateData.container.classList.remove(DRAGGING_CLASS);
		}
	}
P
Peng Lyu 已提交
314 315
}

316
export class MarkdownCellRenderer extends AbstractCellRenderer implements IListRenderer<MarkdownCellViewModel, MarkdownCellRenderTemplate> {
P
Peng Lyu 已提交
317 318 319
	static readonly TEMPLATE_ID = 'markdown_cell';

	constructor(
320
		notebookEditor: INotebookEditor,
R
Rob Lourens 已提交
321
		dndController: CellDragAndDropController,
322
		private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>,
323
		contextKeyServiceProvider: (container?: HTMLElement) => IContextKeyService,
324
		@IInstantiationService instantiationService: IInstantiationService,
P
Peng Lyu 已提交
325
		@IConfigurationService configurationService: IConfigurationService,
326 327 328
		@IContextMenuService contextMenuService: IContextMenuService,
		@IKeybindingService keybindingService: IKeybindingService,
		@INotificationService notificationService: INotificationService,
P
Peng Lyu 已提交
329
	) {
330
		super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, 'markdown', dndController);
P
Peng Lyu 已提交
331 332 333 334 335 336
	}

	get templateId() {
		return MarkdownCellRenderer.TEMPLATE_ID;
	}

337
	renderTemplate(container: HTMLElement): MarkdownCellRenderTemplate {
R
Rob Lourens 已提交
338
		container.classList.add('markdown-cell-row');
R
Rob Lourens 已提交
339
		const disposables = new DisposableStore();
R
Rob Lourens 已提交
340
		const contextKeyService = disposables.add(this.contextKeyServiceProvider(container));
R
Rob Lourens 已提交
341
		const toolbar = disposables.add(this.createToolbar(container));
342
		const focusIndicator = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left'));
R
Rob Lourens 已提交
343
		focusIndicator.setAttribute('draggable', 'true');
R
Rob Lourens 已提交
344

R
Rob Lourens 已提交
345
		const codeInnerContent = DOM.append(container, $('.cell.code'));
346
		const editorPart = DOM.append(codeInnerContent, $('.cell-editor-part'));
R
Rob Lourens 已提交
347
		const editorContainer = DOM.append(editorPart, $('.cell-editor-container'));
348
		editorPart.style.display = 'none';
P
Peng Lyu 已提交
349

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

R
rebornix 已提交
353
		const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container'));
354 355 356
		DOM.append(bottomCellContainer, $('.separator'));
		const betweenCellToolbar = disposables.add(this.createBetweenCellToolbar(bottomCellContainer, disposables, contextKeyService));
		DOM.append(bottomCellContainer, $('.separator'));
357

358
		const statusBar = this.instantiationService.createInstance(CellEditorStatusBar, editorPart);
359
		const titleMenu = disposables.add(this.cellMenus.getCellTitleMenu(contextKeyService));
360

R
Rob Lourens 已提交
361
		const templateData: MarkdownCellRenderTemplate = {
362
			contextKeyService,
363
			container,
P
Peng Lyu 已提交
364
			cellContainer: innerContent,
365 366
			editorPart,
			editorContainer,
367
			focusIndicator,
R
rebornix 已提交
368
			foldingIndicator,
369
			disposables,
370
			elementDisposables: new DisposableStore(),
371
			toolbar,
372
			betweenCellToolbar,
R
Rob Lourens 已提交
373
			bottomCellContainer,
374 375
			statusBarContainer: statusBar.statusBarContainer,
			languageStatusBarItem: statusBar.languageStatusBarItem,
376
			titleMenu,
R
rebornix 已提交
377
			toJSON: () => { return {}; }
P
Peng Lyu 已提交
378
		};
379
		this.dndController.registerDragHandle(templateData, () => this.getDragImage(templateData));
R
Rob Lourens 已提交
380
		this.commonRenderTemplate(templateData);
R
Rob Lourens 已提交
381
		return templateData;
P
Peng Lyu 已提交
382 383
	}

384
	private getDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
R
Rob Lourens 已提交
385
		if (templateData.currentRenderedCell!.editState === CellEditState.Editing) {
386
			return this.getEditDragImage(templateData);
R
Rob Lourens 已提交
387
		} else {
388
			return this.getMarkdownDragImage(templateData);
R
Rob Lourens 已提交
389 390 391
		}
	}

392
	private getMarkdownDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
393 394
		const dragImageContainer = DOM.$('.cell-drag-image.monaco-list-row.focused.markdown-cell-row');
		dragImageContainer.innerHTML = templateData.container.innerHTML;
R
Rob Lourens 已提交
395 396 397 398 399 400 401 402

		// 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();
		}

403 404 405
		return dragImageContainer;
	}

406
	private getEditDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
R
Rob Lourens 已提交
407 408
		return new CodeCellDragImageRenderer().getDragImage(templateData, templateData.currentEditor!, 'markdown');
	}
409

410
	renderElement(element: MarkdownCellViewModel, index: number, templateData: MarkdownCellRenderTemplate, height: number | undefined): void {
411 412
		this.commonRenderElement(element, index, templateData);

R
Rob Lourens 已提交
413
		templateData.currentRenderedCell = element;
R
Rob Lourens 已提交
414
		templateData.currentEditor = undefined;
415
		templateData.editorPart!.style.display = 'none';
R
rebornix 已提交
416 417 418 419 420
		templateData.cellContainer.innerHTML = '';
		let renderedHTML = element.getHTML();
		if (renderedHTML) {
			templateData.cellContainer.appendChild(renderedHTML);
		}
P
Peng Lyu 已提交
421

422 423 424
		if (height === undefined) {
			return;
		}
P
Peng Lyu 已提交
425

426
		const elementDisposables = templateData.elementDisposables;
427

428
		elementDisposables.add(new CellContextKeyManager(templateData.contextKeyService, this.notebookEditor.viewModel?.notebookDocument!, element));
R
rebornix 已提交
429

430
		// render toolbar first
431
		this.setupCellToolbarActions(templateData, elementDisposables);
R
rebornix 已提交
432

433 434 435 436 437 438
		const toolbarContext = <INotebookCellActionContext>{
			cell: element,
			notebookEditor: this.notebookEditor,
			$mid: 12
		};
		templateData.toolbar.context = toolbarContext;
R
rebornix 已提交
439

440
		this.setBetweenCellToolbarContext(templateData, element, toolbarContext);
441

442 443 444
		const markdownCell = this.instantiationService.createInstance(StatefullMarkdownCell, this.notebookEditor, element, templateData, this.editorOptions.value, this.renderedEditors);
		elementDisposables.add(this.editorOptions.onDidChange(newValue => markdownCell.updateEditorOptions(newValue)));
		elementDisposables.add(markdownCell);
445

446
		templateData.languageStatusBarItem.update(element, this.notebookEditor);
447 448
	}

449 450
	disposeTemplate(templateData: MarkdownCellRenderTemplate): void {
		templateData.disposables.clear();
P
Peng Lyu 已提交
451 452
	}

453 454 455 456 457 458 459
	disposeElement(element: ICellViewModel, _index: number, templateData: MarkdownCellRenderTemplate): void {
		templateData.elementDisposables.clear();
		element.getCellDecorations().forEach(e => {
			if (e.className) {
				templateData.container.classList.remove(e.className);
			}
		});
P
Peng Lyu 已提交
460 461 462
	}
}

463
const DRAGGING_CLASS = 'cell-dragging';
R
Rob Lourens 已提交
464 465
const GLOBAL_DRAG_CLASS = 'global-drag-active';

466 467
type DragImageProvider = () => HTMLElement;

468 469 470 471 472 473 474 475
interface CellDragEvent {
	browserEvent: DragEvent;
	draggedOverCell: ICellViewModel;
	cellTop: number;
	cellHeight: number;
	dragPosRatio: number;
}

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

481 482 483 484 485 486 487
	private listInsertionIndicator: HTMLElement;

	private list!: INotebookCellList;

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

R
Rob Lourens 已提交
488
	constructor(
489 490
		private readonly notebookEditor: INotebookEditor,
		insertionIndicatorContainer: HTMLElement
R
Rob Lourens 已提交
491 492 493
	) {
		super();

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

R
Rob Lourens 已提交
496 497
		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)));
498 499

		const addCellDragListener = (eventType: string, handler: (e: CellDragEvent) => void) => {
R
Rob Lourens 已提交
500 501 502 503 504 505 506 507 508
			this._register(DOM.addDisposableListener(
				notebookEditor.getDomNode(),
				eventType,
				e => {
					const cellDragEvent = this.toCellDragEvent(e);
					if (cellDragEvent) {
						handler(cellDragEvent);
					}
				}));
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
		};

		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;

530 531 532 533 534
		this.list.onWillScroll(e => {
			if (!e.scrollTopChanged) {
				return;
			}

535 536 537 538 539 540 541 542 543 544 545 546
			this.setInsertIndicatorVisibility(false);
			this.isScrolling = true;
			this.scrollingDelayer.trigger(() => {
				this.isScrolling = false;
			});
		});
	}

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

R
Rob Lourens 已提交
547
	private toCellDragEvent(event: DragEvent): CellDragEvent | undefined {
548 549 550
		const targetTop = this.notebookEditor.getDomNode().getBoundingClientRect().top;
		const dragOffset = this.list.scrollTop + event.clientY - targetTop;
		const draggedOverCell = this.list.elementAt(dragOffset);
R
Rob Lourens 已提交
551 552 553 554
		if (!draggedOverCell) {
			return undefined;
		}

555 556 557 558 559 560 561 562 563 564 565 566 567
		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 已提交
568 569
	}

570 571 572 573
	clearGlobalDragState() {
		this.notebookEditor.getDomNode().classList.remove(GLOBAL_DRAG_CLASS);
	}

R
Rob Lourens 已提交
574 575 576 577 578 579 580
	private onGlobalDragStart() {
		this.notebookEditor.getDomNode().classList.add(GLOBAL_DRAG_CLASS);
	}

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

582
	private onCellDragover(event: CellDragEvent): void {
583 584 585 586
		if (!event.browserEvent.dataTransfer) {
			return;
		}

R
Rob Lourens 已提交
587
		if (!this.currentDraggedCell) {
588 589 590 591
			event.browserEvent.dataTransfer.dropEffect = 'none';
			return;
		}

592 593 594 595 596 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
		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 已提交
650
		const container = templateData.container;
R
Rob Lourens 已提交
651
		const dragHandle = templateData.focusIndicator;
R
Rob Lourens 已提交
652

653
		templateData.disposables.add(domEvent(dragHandle, DOM.EventType.DRAG_END)(() => {
654 655
			// Note, templateData may have a different element rendered into it by now
			container.classList.remove(DRAGGING_CLASS);
656
			this.dragCleanup();
R
Rob Lourens 已提交
657 658
		}));

659
		templateData.disposables.add(domEvent(dragHandle, DOM.EventType.DRAG_START)(event => {
R
Rob Lourens 已提交
660 661 662 663
			if (!event.dataTransfer) {
				return;
			}

664 665
			this.currentDraggedCell = templateData.currentRenderedCell!;
			this.currentDraggedCell.dragging = true;
666 667

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

672
			container.classList.add(DRAGGING_CLASS);
673
		}));
R
Rob Lourens 已提交
674
	}
R
Rob Lourens 已提交
675

R
Rob Lourens 已提交
676 677
	private async moveCell(draggedCell: ICellViewModel, ontoCell: ICellViewModel, direction: 'above' | 'below') {
		await this.notebookEditor.moveCell(draggedCell, ontoCell, direction);
678 679
	}

R
Rob Lourens 已提交
680 681 682 683
	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 已提交
684
			this.notebookEditor.focusNotebookCell(newCell, editState === CellEditState.Editing ? 'editor' : 'container');
R
Rob Lourens 已提交
685 686
		}
	}
687 688
}

689
export class CellLanguageStatusBarItem extends Disposable {
690
	private readonly labelElement: HTMLElement;
691

692 693
	private cell: ICellViewModel | undefined;
	private editor: INotebookEditor | undefined;
694 695 696 697 698 699

	private cellDisposables: DisposableStore;

	constructor(
		readonly container: HTMLElement,
		@IModeService private readonly modeService: IModeService,
700
		@IInstantiationService private readonly instantiationService: IInstantiationService
701 702
	) {
		super();
703
		this.labelElement = DOM.append(container, $('.cell-language-picker'));
704
		this.labelElement.tabIndex = 0;
705

706 707
		this._register(DOM.addDisposableListener(this.labelElement, DOM.EventType.CLICK, () => {
			this.instantiationService.invokeFunction(accessor => {
708
				new ChangeCellLanguageAction().run(accessor, { notebookEditor: this.editor!, cell: this.cell! });
709 710
			});
		}));
711 712 713
		this._register(this.cellDisposables = new DisposableStore());
	}

714
	update(cell: ICellViewModel, editor: INotebookEditor): void {
715
		this.cellDisposables.clear();
716 717
		this.cell = cell;
		this.editor = editor;
718 719

		this.render();
720
		this.cellDisposables.add(this.cell.model.onDidChangeLanguage(() => this.render()));
721 722 723
	}

	private render(): void {
724 725
		const modeId = this.modeService.getModeIdForLanguageName(this.cell!.language) || this.cell!.language;
		this.labelElement.textContent = this.modeService.getLanguageName(modeId) || this.modeService.getLanguageName('plaintext');
726 727 728
	}
}

729 730 731 732 733 734 735 736
class EditorTextRenderer {

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

737
		const colorMap = this.getDefaultColorMap();
738 739 740 741 742 743 744 745 746 747 748 749
		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;`
			+ `">`
750
			+ this.getRichTextLines(model, modelRange, colorMap)
751 752 753
			+ '</div>';
	}

754
	private getRichTextLines(model: ITextModel, modelRange: Range, colorMap: string[]): string {
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
		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;
	}

780
	private getDefaultColorMap(): string[] {
781 782 783 784 785 786 787 788 789 790
		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 已提交
791

792
class CodeCellDragImageRenderer {
R
Rob Lourens 已提交
793
	getDragImage(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement {
794
		let dragImage = this.getDragImageImpl(templateData, editor, type);
795
		if (!dragImage) {
796
			// TODO@roblourens I don't think this can happen
797 798 799 800 801 802 803
			dragImage = document.createElement('div');
			dragImage.textContent = '1 cell';
		}

		return dragImage;
	}

804
	private getDragImageImpl(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement | null {
R
Rob Lourens 已提交
805
		const dragImageContainer = DOM.$(`.cell-drag-image.monaco-list-row.focused.${type}-cell-row`);
806 807 808 809 810 811 812
		dragImageContainer.innerHTML = templateData.container.innerHTML;

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

R
Rob Lourens 已提交
813
		const richEditorText = new EditorTextRenderer().getRichText(editor, new Range(1, 1, 1, 1000));
814 815 816 817 818 819 820
		if (!richEditorText) {
			return null;
		}

		editorContainer.innerHTML = richEditorText;

		return dragImageContainer;
R
Rob Lourens 已提交
821 822 823
	}
}

824 825 826 827 828
class CellEditorStatusBar {
	readonly cellStatusMessageContainer: HTMLElement;
	readonly cellRunStatusContainer: HTMLElement;
	readonly statusBarContainer: HTMLElement;
	readonly languageStatusBarItem: CellLanguageStatusBarItem;
829
	readonly durationContainer: HTMLElement;
830 831 832 833 834 835 836 837 838

	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'));
839
		this.durationContainer = DOM.append(leftStatusBarItems, $('.cell-run-duration'));
840 841 842 843 844
		this.cellStatusMessageContainer = DOM.append(leftStatusBarItems, $('.cell-status-message'));
		this.languageStatusBarItem = instantiationService.createInstance(CellLanguageStatusBarItem, rightStatusBarItems);
	}
}

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

P
Peng Lyu 已提交
848
	constructor(
R
rebornix 已提交
849
		protected notebookEditor: INotebookEditor,
R
rebornix 已提交
850
		private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>,
R
Rob Lourens 已提交
851
		dndController: CellDragAndDropController,
852
		contextKeyServiceProvider: (container?: HTMLElement) => IContextKeyService,
P
Peng Lyu 已提交
853 854
		@IContextMenuService contextMenuService: IContextMenuService,
		@IConfigurationService configurationService: IConfigurationService,
855
		@IInstantiationService instantiationService: IInstantiationService,
856 857
		@IKeybindingService keybindingService: IKeybindingService,
		@INotificationService notificationService: INotificationService,
P
Peng Lyu 已提交
858
	) {
859
		super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, 'python', dndController);
P
Peng Lyu 已提交
860 861 862 863 864 865
	}

	get templateId() {
		return CodeCellRenderer.TEMPLATE_ID;
	}

866
	renderTemplate(container: HTMLElement): CodeCellRenderTemplate {
R
Rob Lourens 已提交
867
		container.classList.add('code-cell-row');
868
		const disposables = new DisposableStore();
R
Rob Lourens 已提交
869
		const contextKeyService = disposables.add(this.contextKeyServiceProvider(container));
870

R
Rob Lourens 已提交
871
		DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-top'));
R
Rob Lourens 已提交
872
		const toolbar = disposables.add(this.createToolbar(container));
873
		const focusIndicator = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left'));
R
Rob Lourens 已提交
874
		focusIndicator.setAttribute('draggable', 'true');
875

R
Rob Lourens 已提交
876 877 878 879 880
		const cellContainer = DOM.append(container, $('.cell.code'));
		const runButtonContainer = DOM.append(cellContainer, $('.run-button-container'));
		const runToolbar = this.createToolbar(runButtonContainer);
		disposables.add(runToolbar);

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

883
		// create a special context key service that set the inCompositeEditor-contextkey
R
Rob Lourens 已提交
884
		const editorContextKeyService = disposables.add(this.contextKeyServiceProvider(container));
885 886 887
		const editorInstaService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, editorContextKeyService]));
		EditorContextKeys.inCompositeEditor.bindTo(editorContextKeyService).set(true);

R
Rob Lourens 已提交
888 889
		const editorPart = DOM.append(cellContainer, $('.cell-editor-part'));
		const editorContainer = DOM.append(editorPart, $('.cell-editor-container'));
890
		const editor = editorInstaService.createInstance(CodeEditorWidget, editorContainer, {
891
			...this.editorOptions.value,
P
Peng Lyu 已提交
892 893 894 895 896 897
			dimension: {
				width: 0,
				height: 0
			}
		}, {});

898 899
		disposables.add(this.editorOptions.onDidChange(newValue => editor.updateOptions(newValue)));

R
Rob Lourens 已提交
900
		const progressBar = new ProgressBar(editorPart);
R
Rob Lourens 已提交
901 902 903
		progressBar.hide();
		disposables.add(progressBar);

904
		const statusBar = this.instantiationService.createInstance(CellEditorStatusBar, editorPart);
905
		const timer = new TimerRenderer(statusBar.durationContainer);
R
Rob Lourens 已提交
906 907

		const outputContainer = DOM.append(container, $('.output'));
908 909 910 911

		const focusIndicatorRight = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-right'));
		focusIndicatorRight.setAttribute('draggable', 'true');

912 913
		const focusSinkElement = DOM.append(container, $('.cell-editor-focus-sink'));
		focusSinkElement.setAttribute('tabindex', '0');
914
		const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container'));
915 916 917
		DOM.append(bottomCellContainer, $('.separator'));
		const betweenCellToolbar = this.createBetweenCellToolbar(bottomCellContainer, disposables, contextKeyService);
		DOM.append(bottomCellContainer, $('.separator'));
918

919 920
		const focusIndicatorBottom = DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-bottom'));

921 922
		const titleMenu = disposables.add(this.cellMenus.getCellTitleMenu(contextKeyService));

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

951
		this.dndController.registerDragHandle(templateData, () => new CodeCellDragImageRenderer().getDragImage(templateData, templateData.editor, 'code'));
952

953 954
		disposables.add(DOM.addDisposableListener(focusSinkElement, DOM.EventType.FOCUS, () => {
			if (templateData.currentRenderedCell && (templateData.currentRenderedCell as CodeCellViewModel).outputs.length) {
955 956 957 958
				this.notebookEditor.focusNotebookCell(templateData.currentRenderedCell, 'output');
			}
		}));

R
Rob Lourens 已提交
959 960
		this.commonRenderTemplate(templateData);

R
Rob Lourens 已提交
961
		return templateData;
P
Peng Lyu 已提交
962 963
	}

964 965 966 967 968 969
	private updateForRunState(runState: NotebookCellRunState | undefined, templateData: CodeCellRenderTemplate): void {
		if (typeof runState === 'undefined') {
			runState = NotebookCellRunState.Idle;
		}

		if (runState === NotebookCellRunState.Running) {
970 971 972 973
			templateData.progressBar.infinite().show(500);

			templateData.runToolbar.setActions([
				this.instantiationService.createInstance(CancelCellAction)
J
João Moreno 已提交
974
			]);
975 976 977 978 979
		} else {
			templateData.progressBar.hide();

			templateData.runToolbar.setActions([
				this.instantiationService.createInstance(ExecuteCellAction)
J
João Moreno 已提交
980
			]);
981 982 983
		}
	}

984 985 986 987 988 989 990 991
	private updateForOutputs(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
		if (element.outputs.length) {
			DOM.show(templateData.focusSinkElement);
		} else {
			DOM.hide(templateData.focusSinkElement);
		}
	}

992
	private updateForMetadata(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
R
Rob Lourens 已提交
993 994
		const metadata = element.getEvaluatedMetadata(this.notebookEditor.viewModel!.notebookDocument.metadata);
		DOM.toggleClass(templateData.cellContainer, 'runnable', !!metadata.runnable);
995
		this.updateExecutionOrder(metadata, templateData);
R
Rob Lourens 已提交
996 997 998 999 1000 1001
		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 已提交
1002
		} else if (metadata.runState === NotebookCellRunState.Running) {
1003
			templateData.cellRunStatusContainer.innerHTML = renderCodicons('$(sync~spin)');
R
Rob Lourens 已提交
1004 1005 1006
		} else {
			templateData.cellRunStatusContainer.innerHTML = '';
		}
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

		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();
		}
1019 1020 1021 1022

		if (typeof metadata.breakpointMargin === 'boolean') {
			this.editorOptions.setGlyphMargin(metadata.breakpointMargin);
		}
1023 1024

		this.updateForRunState(metadata.runState, templateData);
R
Rob Lourens 已提交
1025 1026
	}

1027 1028 1029 1030
	private updateExecutionOrder(metadata: NotebookCellMetadata, templateData: CodeCellRenderTemplate): void {
		if (metadata.hasExecutionOrder) {
			const executionOrderLabel = typeof metadata.executionOrder === 'number' ?
				`[${metadata.executionOrder}]` :
1031
				'[ ]';
1032
			templateData.executionOrderLabel.innerText = executionOrderLabel;
R
Rob Lourens 已提交
1033 1034 1035 1036 1037
		} else {
			templateData.executionOrderLabel.innerText = '';
		}
	}

1038 1039 1040 1041
	private updateForHover(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
		DOM.toggleClass(templateData.container, 'cell-output-hover', element.outputIsHovered);
	}

1042 1043 1044 1045 1046 1047 1048
	private updateForLayout(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
		templateData.focusIndicator.style.height = `${element.layoutInfo.indicatorHeight}px`;
		templateData.focusIndicatorRight.style.height = `${element.layoutInfo.indicatorHeight}px`;
		templateData.focusIndicatorBottom.style.top = `${element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_HEIGHT - CELL_BOTTOM_MARGIN}px`;
		templateData.outputContainer.style.top = `${element.layoutInfo.outputContainerOffset}px`;
	}

1049
	renderElement(element: CodeCellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void {
R
rebornix 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
		const removedClassNames: string[] = [];
		templateData.container.classList.forEach(className => {
			if (/^nb\-.*$/.test(className)) {
				removedClassNames.push(className);
			}
		});

		removedClassNames.forEach(className => {
			templateData.container.classList.remove(className);
		});

1061 1062
		this.commonRenderElement(element, index, templateData);

R
Rob Lourens 已提交
1063 1064
		templateData.currentRenderedCell = element;

R
rebornix 已提交
1065 1066 1067 1068
		if (height === undefined) {
			return;
		}

1069
		templateData.outputContainer.innerHTML = '';
1070

1071
		const elementDisposables = templateData.elementDisposables;
R
rebornix 已提交
1072

1073
		elementDisposables.add(this.instantiationService.createInstance(CodeCell, this.notebookEditor, element, templateData));
J
Johannes Rieken 已提交
1074
		this.renderedEditors.set(element, templateData.editor);
1075

1076 1077
		elementDisposables.add(new CellContextKeyManager(templateData.contextKeyService, this.notebookEditor.viewModel?.notebookDocument!, element));

1078
		this.updateForLayout(element, templateData);
1079
		elementDisposables.add(element.onDidChangeLayout(() => {
1080
			this.updateForLayout(element, templateData);
1081 1082
		}));

1083
		this.updateForMetadata(element, templateData);
1084
		this.updateForHover(element, templateData);
1085
		elementDisposables.add(element.onDidChangeState((e) => {
1086
			if (e.metadataChanged) {
1087
				this.updateForMetadata(element, templateData);
1088
			}
1089 1090 1091 1092

			if (e.outputIsHoveredChanged) {
				this.updateForHover(element, templateData);
			}
1093
		}));
1094

1095 1096 1097
		this.updateForOutputs(element, templateData);
		elementDisposables.add(element.onDidChangeOutputs(_e => this.updateForOutputs(element, templateData)));

1098
		this.setupCellToolbarActions(templateData, elementDisposables);
1099 1100 1101 1102 1103 1104 1105

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

1109
		this.setBetweenCellToolbarContext(templateData, element, toolbarContext);
1110 1111

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

1114
	disposeTemplate(templateData: CodeCellRenderTemplate): void {
1115
		templateData.disposables.clear();
P
Peng Lyu 已提交
1116 1117
	}

1118
	disposeElement(element: ICellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void {
1119
		templateData.elementDisposables.clear();
J
Johannes Rieken 已提交
1120
		this.renderedEditors.delete(element);
P
Peng Lyu 已提交
1121 1122
	}
}
1123 1124 1125 1126 1127 1128

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

R
Rob Lourens 已提交
1129
	private intervalTimer: number | undefined;
1130 1131 1132 1133 1134 1135 1136 1137 1138

	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
rebornix 已提交
1139
		this.intervalTimer = intervalTimer as unknown as number | undefined;
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

		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`;
	}
}