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.
 *--------------------------------------------------------------------------------------------*/

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';
R
Rob Lourens 已提交
30
import { ContextAwareMenuEntryActionViewItem } 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
import { CodeCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/codeCell';
44
import { StatefulMarkdownCell } 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;
		}
	}
}

R
rebornix 已提交
80 81 82
export class CodiconActionViewItem extends ContextAwareMenuEntryActionViewItem {
	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 238 239 240 241 242 243 244 245 246 247 248
	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;
	}

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
		const scopedInstaService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, templateData.contextKeyService]));
		const markdownCell = scopedInstaService.createInstance(StatefulMarkdownCell, this.notebookEditor, element, templateData, this.editorOptions.value, this.renderedEditors);
444 445
		elementDisposables.add(this.editorOptions.onDidChange(newValue => markdownCell.updateEditorOptions(newValue)));
		elementDisposables.add(markdownCell);
446

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

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

454 455 456 457 458 459 460
	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 已提交
461 462 463
	}
}

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

467 468
type DragImageProvider = () => HTMLElement;

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

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

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

	private list!: INotebookCellList;

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

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

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

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

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

		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;

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

536 537 538 539 540 541 542 543 544 545 546 547
			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 已提交
548
	private toCellDragEvent(event: DragEvent): CellDragEvent | undefined {
549 550 551
		const targetTop = this.notebookEditor.getDomNode().getBoundingClientRect().top;
		const dragOffset = this.list.scrollTop + event.clientY - targetTop;
		const draggedOverCell = this.list.elementAt(dragOffset);
R
Rob Lourens 已提交
552 553 554 555
		if (!draggedOverCell) {
			return undefined;
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	private cellDisposables: DisposableStore;

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

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

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

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

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

730 731 732 733 734 735 736 737
class EditorTextRenderer {

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

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

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

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

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

		return dragImage;
	}

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

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

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

		editorContainer.innerHTML = richEditorText;

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

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

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

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

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

	get templateId() {
		return CodeCellRenderer.TEMPLATE_ID;
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1043 1044 1045 1046 1047 1048 1049
	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`;
	}

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

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

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

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

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

1070
		templateData.outputContainer.innerHTML = '';
1071

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	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 已提交
1140
		this.intervalTimer = intervalTimer as unknown as number | undefined;
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 1172

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