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

import 'vs/css!./notebook';
import * as DOM from 'vs/base/browser/dom';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { IStorageService } from 'vs/platform/storage/common/storage';
12
import { NotebookEditorInput, ICell, NotebookEditorModel } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
P
Peng Lyu 已提交
13 14 15 16
import { EditorOptions } from 'vs/workbench/common/editor';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
P
Peng Lyu 已提交
17
import { CodeEditorWidget, ICodeEditorWidgetOptions } from 'vs/editor/browser/widget/codeEditorWidget';
P
Peng Lyu 已提交
18 19 20 21
import * as marked from 'vs/base/common/marked/marked';
import { IModelService } from 'vs/editor/common/services/modelService';
import { URI } from 'vs/base/common/uri';
import { deepClone } from 'vs/base/common/objects';
P
Peng Lyu 已提交
22
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
P
Peng Lyu 已提交
23
import { getExtraColor } from 'vs/workbench/contrib/welcome/walkThrough/common/walkThroughUtils';
P
Peng Lyu 已提交
24 25 26
import { textLinkForeground, textLinkActiveForeground, focusBorder, textPreformatForeground, contrastBorder, textBlockQuoteBackground, textBlockQuoteBorder, editorBackground, foreground } from 'vs/platform/theme/common/colorRegistry';
import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
27 28
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { getZoomLevel } from 'vs/base/browser/browser';
P
Peng Lyu 已提交
29 30 31 32
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { Action } from 'vs/base/common/actions';
import { IDisposable } from 'vs/base/common/lifecycle';
import { IEditorContributionDescription } from 'vs/editor/browser/editorExtensions';
P
Peng Lyu 已提交
33 34 35 36
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SuggestController } from 'vs/editor/contrib/suggest/suggestController';
import { SnippetController2 } from 'vs/editor/contrib/snippet/snippetController2';
import { TabCompletionController } from 'vs/workbench/contrib/snippets/browser/tabCompletion';
P
Peng Lyu 已提交
37
import { MimeTypeRenderer } from 'vs/workbench/contrib/notebook/browser/output';
38
import { ElementSizeObserver } from 'vs/editor/browser/config/elementSizeObserver';
P
Peng Lyu 已提交
39
import { ITextModel } from 'vs/editor/common/model';
P
Peng Lyu 已提交
40
import { IModeService } from 'vs/editor/common/services/modeService';
P
Peng Lyu 已提交
41 42 43

const $ = DOM.$;

P
Peng Lyu 已提交
44 45 46 47
class ViewCell {
	private _textModel: ITextModel | null = null;
	private _mdRenderer: marked.Renderer | null = null;
	private _html: string | null = null;
P
Peng Lyu 已提交
48
	private _dynamicHeight: number | null = null;
P
Peng Lyu 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

	get cellType() {
		return this.cell.cell_type;
	}

	get lineCount() {
		return this.cell.source.length;
	}

	get outputs() {
		return this.cell.outputs;
	}

	constructor(
		public cell: ICell,
		public isEditing: boolean,
		private readonly modelService: IModelService,
		private readonly modeService: IModeService
	) {

	}

	hasDynamicHeight() {
P
Peng Lyu 已提交
72 73 74 75
		if (this._dynamicHeight !== null) {
			return false;
		}

P
Peng Lyu 已提交
76 77 78
		return true;
	}

P
Peng Lyu 已提交
79 80 81 82
	setDynamicHeight(height: number) {
		this._dynamicHeight = height;
	}

P
Peng Lyu 已提交
83
	getHeight(lineHeight: number) {
P
Peng Lyu 已提交
84 85 86 87
		if (this._dynamicHeight) {
			return this._dynamicHeight;
		}

P
Peng Lyu 已提交
88 89 90 91 92 93 94
		if (this.cellType === 'markdown') {
			return 100;
		} else {
			return Math.max(this.lineCount + 1, 5) * lineHeight + 16;
		}
	}

P
Peng Lyu 已提交
95 96 97 98 99 100 101 102 103 104 105
	setText(strs: string[]) {
		this.cell.source = strs.map(str => str + '\n');
		this._html = null;
	}

	save() {
		if (this._textModel && this.isEditing) {
			this.cell.source = this._textModel.getLinesContent().map(str => str + '\n');
		}
	}

P
Peng Lyu 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
	getText(): string {
		return this.cell.source.join('');
	}

	getHTML(): string | null {
		if (this.cellType === 'markdown') {
			if (this._html) {
				return this._html;
			}

			let renderer = this.getMDRenderer();
			this._html = marked(this.getText(), { renderer: renderer });
			return this._html;
		}

		return null;
	}

	getTextModel(): ITextModel {
		if (!this._textModel) {
P
Peng Lyu 已提交
126 127
			let ext = this.cellType === 'markdown' ? 'md' : 'py';
			const resource = URI.parse(`notebookcell-${Date.now()}.${ext}`);
P
Peng Lyu 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
			let content = this.cell.source.join('');
			this._textModel = this.modelService.createModel(content, this.modeService.createByFilepathOrFirstLine(resource), resource, false);
		}

		return this._textModel;
	}

	private getMDRenderer() {

		if (!this._mdRenderer) {
			this._mdRenderer = new marked.Renderer();
		}

		return this._mdRenderer;

	}
}
P
Peng Lyu 已提交
145 146

interface NotebookHandler {
P
Peng Lyu 已提交
147
	insertEmptyNotebookCell(cell: ViewCell, type: 'markdown' | 'code', direction: 'above' | 'below'): void;
P
Peng Lyu 已提交
148 149
	deleteNotebookCell(cell: ViewCell): void;
	layoutElement(cell: ViewCell, height: number): void;
P
Peng Lyu 已提交
150 151
}

P
Peng Lyu 已提交
152
interface CellRenderTemplate {
153
	container: HTMLElement;
P
Peng Lyu 已提交
154
	cellContainer: HTMLElement;
P
Peng Lyu 已提交
155
	menuContainer?: HTMLElement;
P
Peng Lyu 已提交
156
	editingContainer?: HTMLElement;
P
Peng Lyu 已提交
157
	outputContainer?: HTMLElement;
158
	editor?: CodeEditorWidget;
P
Peng Lyu 已提交
159
	model?: ITextModel;
P
Peng Lyu 已提交
160 161
}

P
Peng Lyu 已提交
162
export class NotebookCellListDelegate implements IListVirtualDelegate<ViewCell> {
163
	private _lineHeight: number;
P
Peng Lyu 已提交
164 165 166
	constructor(
		@IConfigurationService private readonly configurationService: IConfigurationService
	) {
167 168
		const editorOptions = this.configurationService.getValue<IEditorOptions>('editor');
		this._lineHeight = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()).lineHeight;
P
Peng Lyu 已提交
169 170
	}

P
Peng Lyu 已提交
171 172
	getHeight(element: ViewCell): number {
		return element.getHeight(this._lineHeight);
P
Peng Lyu 已提交
173 174
	}

P
Peng Lyu 已提交
175 176
	hasDynamicHeight(element: ViewCell): boolean {
		return element.hasDynamicHeight();
P
Peng Lyu 已提交
177 178
	}

P
Peng Lyu 已提交
179 180
	getTemplateId(element: ViewCell): string {
		if (element.cellType === 'markdown') {
P
Peng Lyu 已提交
181 182 183 184 185 186 187
			return MarkdownCellRenderer.TEMPLATE_ID;
		} else {
			return CodeCellRenderer.TEMPLATE_ID;
		}
	}
}

188 189
class AbstractCellRenderer {
	constructor(
190
		protected handler: NotebookHandler,
191 192 193
		private contextMenuService: IContextMenuService
	) { }

P
Peng Lyu 已提交
194
	showContextMenu(element: ViewCell, x: number, y: number) {
195 196 197 198 199 200 201
		const actions: Action[] = [];
		const insertAbove = new Action(
			'workbench.notebook.code.insertCellAbove',
			'Insert Code Cell Above',
			undefined,
			true,
			async () => {
P
Peng Lyu 已提交
202
				this.handler.insertEmptyNotebookCell(element, 'code', 'above');
203 204 205 206 207 208 209 210 211
			}
		);

		const insertBelow = new Action(
			'workbench.notebook.code.insertCellBelow',
			'Insert Code Cell Below',
			undefined,
			true,
			async () => {
P
Peng Lyu 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
				this.handler.insertEmptyNotebookCell(element, 'code', 'below');
			}
		);

		const insertMarkdownAbove = new Action(
			'workbench.notebook.markdown.insertCellAbove',
			'Insert Markdown Cell Above',
			undefined,
			true,
			async () => {
				this.handler.insertEmptyNotebookCell(element, 'markdown', 'above');
			}
		);

		const insertMarkdownBelow = new Action(
			'workbench.notebook.markdown.insertCellBelow',
			'Insert Markdown Cell Below',
			undefined,
			true,
			async () => {
				this.handler.insertEmptyNotebookCell(element, 'markdown', 'below');
233 234 235
			}
		);

P
Peng Lyu 已提交
236 237 238 239 240 241 242 243 244 245
		const deleteCell = new Action(
			'workbench.notebook.deleteCell',
			'Delete Cell',
			undefined,
			true,
			async () => {
				this.handler.deleteNotebookCell(element);
			}
		);

P
Peng Lyu 已提交
246 247
		actions.push(insertMarkdownAbove);
		actions.push(insertMarkdownBelow);
248 249
		actions.push(insertAbove);
		actions.push(insertBelow);
P
Peng Lyu 已提交
250
		actions.push(deleteCell);
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

		this.contextMenuService.showContextMenu({
			getAnchor: () => {
				return {
					x,
					y
				};
			},
			getActions: () => {
				return actions;
			},
			autoSelectFirstItem: true
		});
	}
}

P
Peng Lyu 已提交
267
export class MarkdownCellRenderer extends AbstractCellRenderer implements IListRenderer<ViewCell, CellRenderTemplate> {
P
Peng Lyu 已提交
268
	static readonly TEMPLATE_ID = 'markdown_cell';
269
	private disposables: Map<HTMLElement, IDisposable> = new Map();
P
Peng Lyu 已提交
270
	private editorOptions: IEditorOptions;
P
Peng Lyu 已提交
271 272

	constructor(
273
		handler: NotebookHandler,
P
Peng Lyu 已提交
274 275
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
276
		@IContextMenuService contextMenuService: IContextMenuService
P
Peng Lyu 已提交
277
	) {
278
		super(handler, contextMenuService);
P
Peng Lyu 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
		const language = 'python';
		const editorOptions = deepClone(this.configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: language }));
		this.editorOptions = {
			...editorOptions,
			scrollBeyondLastLine: false,
			scrollbar: {
				verticalScrollbarSize: 14,
				horizontal: 'auto',
				useShadows: true,
				verticalHasArrows: false,
				horizontalHasArrows: false
			},
			overviewRulerLanes: 3,
			fixedOverflowWidgets: false,
			lineNumbersMinChars: 1,
			minimap: { enabled: false },
		};
P
Peng Lyu 已提交
296
	}
P
Peng Lyu 已提交
297 298 299 300 301 302

	get templateId() {
		return MarkdownCellRenderer.TEMPLATE_ID;
	}

	renderTemplate(container: HTMLElement): CellRenderTemplate {
P
Peng Lyu 已提交
303 304 305 306 307 308
		const codeInnerContent = document.createElement('div');
		DOM.addClasses(codeInnerContent, 'cell', 'code');
		codeInnerContent.style.display = 'none';

		container.appendChild(codeInnerContent);

P
Peng Lyu 已提交
309 310 311 312
		const innerContent = document.createElement('div');
		DOM.addClasses(innerContent, 'cell', 'markdown');
		container.appendChild(innerContent);

P
Peng Lyu 已提交
313 314 315 316
		const action = document.createElement('div');
		DOM.addClasses(action, 'menu', 'codicon-settings-gear', 'codicon');
		container.appendChild(action);

P
Peng Lyu 已提交
317
		return {
318
			container: container,
P
Peng Lyu 已提交
319
			cellContainer: innerContent,
P
Peng Lyu 已提交
320
			menuContainer: action,
P
Peng Lyu 已提交
321
			editingContainer: codeInnerContent
P
Peng Lyu 已提交
322 323 324
		};
	}

P
Peng Lyu 已提交
325
	renderElement(element: ViewCell, index: number, templateData: CellRenderTemplate, height: number | undefined): void {
P
Peng Lyu 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
		if (element.isEditing) {
			templateData.editingContainer!.style.display = 'block';
			const width = templateData.container.clientWidth;
			const lineNum = element.lineCount;
			const totalHeight = Math.max(lineNum + 1, 5) * 21;

			templateData.editingContainer!.innerHTML = '';
			const editor = this.instantiationService.createInstance(CodeEditorWidget, templateData.editingContainer!, {
				...this.editorOptions,
				dimension: {
					width: width,
					height: totalHeight
				}
			}, {});
			const model = element.getTextModel();
			editor.setModel(model);
			templateData.cellContainer.innerHTML = element.getHTML() || '';

			if (height) {
				model.onDidChangeContent(e => {
					element.setText(model.getLinesContent());
					templateData.cellContainer.innerHTML = element.getHTML() || '';

					const clientHeight = templateData.cellContainer.clientHeight;
					this.handler.layoutElement(element, totalHeight + 32 + clientHeight);
				});
			}
		} else {
			templateData.editingContainer!.style.display = 'none';
			templateData.editingContainer!.innerHTML = '';
			templateData.cellContainer.innerHTML = element.getHTML() || '';
		}

P
Peng Lyu 已提交
359
		let disposable = this.disposables.get(templateData.menuContainer!);
360 361 362

		if (disposable) {
			disposable.dispose();
P
Peng Lyu 已提交
363
			this.disposables.delete(templateData.menuContainer!);
364
		}
P
Peng Lyu 已提交
365

P
Peng Lyu 已提交
366 367
		let listener = DOM.addStandardDisposableListener(templateData.menuContainer!, 'mousedown', e => {
			const { top, height } = DOM.getDomNodePagePosition(templateData.menuContainer!);
P
Peng Lyu 已提交
368 369
			e.preventDefault();

370
			this.showContextMenu(element, e.posx, top + height);
P
Peng Lyu 已提交
371 372
		});

P
Peng Lyu 已提交
373
		this.disposables.set(templateData.menuContainer!, listener);
P
Peng Lyu 已提交
374 375 376 377 378 379 380
	}

	disposeTemplate(templateData: CellRenderTemplate): void {
		// throw nerendererw Error('Method not implemented.');
	}
}

P
Peng Lyu 已提交
381
export class CodeCellRenderer extends AbstractCellRenderer implements IListRenderer<ViewCell, CellRenderTemplate> {
P
Peng Lyu 已提交
382 383
	static readonly TEMPLATE_ID = 'code_cell';
	private editorOptions: IEditorOptions;
384
	private disposables: Map<HTMLElement, IDisposable> = new Map();
P
Peng Lyu 已提交
385 386

	constructor(
387 388
		handler: NotebookHandler,
		@IContextMenuService contextMenuService: IContextMenuService,
P
Peng Lyu 已提交
389 390
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
P
Peng Lyu 已提交
391
		@IThemeService private readonly themeService: IThemeService
P
Peng Lyu 已提交
392
	) {
393 394
		super(handler, contextMenuService);

P
Peng Lyu 已提交
395
		const language = 'python';
P
Peng Lyu 已提交
396 397 398 399 400 401 402 403 404 405 406 407
		const editorOptions = deepClone(this.configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: language }));
		this.editorOptions = {
			...editorOptions,
			scrollBeyondLastLine: false,
			scrollbar: {
				verticalScrollbarSize: 14,
				horizontal: 'auto',
				useShadows: true,
				verticalHasArrows: false,
				horizontalHasArrows: false
			},
			overviewRulerLanes: 3,
P
Peng Lyu 已提交
408
			fixedOverflowWidgets: false,
P
Peng Lyu 已提交
409 410 411
			lineNumbersMinChars: 1,
			minimap: { enabled: false },
		};
P
Peng Lyu 已提交
412 413 414 415 416 417 418 419 420 421
	}

	get templateId() {
		return CodeCellRenderer.TEMPLATE_ID;
	}

	renderTemplate(container: HTMLElement): CellRenderTemplate {
		const innerContent = document.createElement('div');
		DOM.addClasses(innerContent, 'cell', 'code');
		container.appendChild(innerContent);
422 423 424 425 426 427
		const editor = this.instantiationService.createInstance(CodeEditorWidget, innerContent, {
			...this.editorOptions,
			dimension: {
				width: 0,
				height: 0
			}
P
Peng Lyu 已提交
428
		}, {});
P
Peng Lyu 已提交
429 430 431
		const action = document.createElement('div');
		DOM.addClasses(action, 'menu', 'codicon-settings-gear', 'codicon');
		container.appendChild(action);
P
Peng Lyu 已提交
432

P
Peng Lyu 已提交
433 434 435 436
		const outputContainer = document.createElement('div');
		DOM.addClasses(outputContainer, 'output');
		container.appendChild(outputContainer);

P
Peng Lyu 已提交
437
		return {
438
			container: container,
439
			cellContainer: innerContent,
P
Peng Lyu 已提交
440
			menuContainer: action,
P
Peng Lyu 已提交
441
			outputContainer: outputContainer,
442
			editor
P
Peng Lyu 已提交
443 444 445
		};
	}

P
Peng Lyu 已提交
446
	renderElement(element: ViewCell, index: number, templateData: CellRenderTemplate, height: number | undefined): void {
P
Peng Lyu 已提交
447 448
		const innerContent = templateData.cellContainer;
		const width = innerContent.clientWidth;
P
Peng Lyu 已提交
449
		const lineNum = element.lineCount;
P
Peng Lyu 已提交
450
		const totalHeight = Math.max(lineNum + 1, 5) * 21;
P
Peng Lyu 已提交
451
		const model = element.getTextModel();
452 453 454 455 456
		templateData.editor?.setModel(model);
		templateData.editor?.layout(
			{
				width: width,
				height: totalHeight
P
Peng Lyu 已提交
457
			}
458
		);
P
Peng Lyu 已提交
459

P
Peng Lyu 已提交
460 461
		let listener = DOM.addStandardDisposableListener(templateData.menuContainer!, 'mousedown', e => {
			const { top, height } = DOM.getDomNodePagePosition(templateData.menuContainer!);
P
Peng Lyu 已提交
462 463
			e.preventDefault();

464
			this.showContextMenu(element, e.posx, top + height);
P
Peng Lyu 已提交
465 466
		});

467
		this.disposables.set(templateData.cellContainer, listener);
P
Peng Lyu 已提交
468

P
Peng Lyu 已提交
469 470 471 472 473
		if (templateData.outputContainer) {
			templateData.outputContainer!.innerHTML = '';
		}

		if (element.outputs.length > 0) {
P
Peng Lyu 已提交
474
			let hasDynamicHeight = false;
P
Peng Lyu 已提交
475
			for (let i = 0; i < element.outputs.length; i++) {
P
Peng Lyu 已提交
476 477 478 479
				let result = MimeTypeRenderer.render(element.outputs[i], this.themeService);
				if (result) {
					hasDynamicHeight = result?.hasDynamicHeight;
					templateData.outputContainer?.appendChild(result.element);
P
Peng Lyu 已提交
480 481
				}
			}
482

P
Peng Lyu 已提交
483
			if (element.hasDynamicHeight() && height !== undefined) {
484 485
				let dimensions = DOM.getClientArea(templateData.outputContainer!);
				const elementSizeObserver = new ElementSizeObserver(templateData.outputContainer!, dimensions, () => {
P
Peng Lyu 已提交
486 487
					if (templateData.outputContainer && document.body.contains(templateData.outputContainer!)) {
						let height = elementSizeObserver.getHeight();
P
Peng Lyu 已提交
488
						if (dimensions.height !== height) {
P
Peng Lyu 已提交
489
							element.setDynamicHeight(totalHeight + 32 + height);
P
Peng Lyu 已提交
490 491
							this.handler.layoutElement(element, totalHeight + 32 + height);
						}
P
Peng Lyu 已提交
492
					}
493 494
				});
				elementSizeObserver.startObserving();
P
Peng Lyu 已提交
495 496 497 498
				if (!hasDynamicHeight && dimensions.height !== 0) {
					element.setDynamicHeight(totalHeight + 32 + dimensions.height);
					this.handler.layoutElement(element, totalHeight + 32 + dimensions.height);
				}
499 500 501 502 503 504 505 506

				this.disposables.set(templateData.outputContainer!, {
					dispose: () => {
						elementSizeObserver.stopObserving();
						elementSizeObserver.dispose();
					}
				});
			}
P
Peng Lyu 已提交
507 508
		}

P
Peng Lyu 已提交
509 510 511 512 513
	}

	disposeTemplate(templateData: CellRenderTemplate): void {
		// throw nerendererw Error('Method not implemented.');
	}
P
Peng Lyu 已提交
514

P
Peng Lyu 已提交
515

P
Peng Lyu 已提交
516
	disposeElement(element: ViewCell, index: number, templateData: CellRenderTemplate, height: number | undefined): void {
517
		let cellDisposable = this.disposables.get(templateData.cellContainer);
P
Peng Lyu 已提交
518

519 520 521 522 523 524 525 526 527 528 529 530
		if (cellDisposable) {
			cellDisposable.dispose();
			this.disposables.delete(templateData.cellContainer);
		}

		if (templateData.outputContainer) {
			let outputDisposable = this.disposables.get(templateData.outputContainer!);

			if (outputDisposable) {
				outputDisposable.dispose();
				this.disposables.delete(templateData.outputContainer!);
			}
P
Peng Lyu 已提交
531 532 533
		}
	}

P
Peng Lyu 已提交
534 535 536
	getSimpleCodeEditorWidgetOptions(): ICodeEditorWidgetOptions {
		return {
			isSimpleWidget: false,
P
Peng Lyu 已提交
537 538 539 540 541 542 543
			contributions: <IEditorContributionDescription[]>[
				{ id: MenuPreventer.ID, ctor: MenuPreventer },
				{ id: SuggestController.ID, ctor: SuggestController },
				// { id: ModesHoverController.ID, ctor: ModesHoverController },
				{ id: SnippetController2.ID, ctor: SnippetController2 },
				{ id: TabCompletionController.ID, ctor: TabCompletionController },
			]
P
Peng Lyu 已提交
544 545
		};
	}
P
Peng Lyu 已提交
546 547
}

P
Peng Lyu 已提交
548 549

export class NotebookEditor extends BaseEditor implements NotebookHandler {
P
Peng Lyu 已提交
550 551 552
	static readonly ID: string = 'workbench.editor.notebook';
	private rootElement!: HTMLElement;
	private body!: HTMLElement;
P
Peng Lyu 已提交
553
	private list: WorkbenchList<ViewCell> | undefined;
P
Peng Lyu 已提交
554
	private model: NotebookEditorModel | undefined;
P
Peng Lyu 已提交
555
	private viewCells: ViewCell[] = [];
P
Peng Lyu 已提交
556 557 558 559 560

	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
		@IThemeService themeService: IThemeService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
P
Peng Lyu 已提交
561 562
		@IModelService private readonly modelService: IModelService,
		@IModeService private readonly modeService: IModeService,
P
Peng Lyu 已提交
563
		@IStorageService storageService: IStorageService
P
Peng Lyu 已提交
564 565 566
	) {
		super(NotebookEditor.ID, telemetryService, themeService, storageService);
	}
P
Peng Lyu 已提交
567

P
Peng Lyu 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581
	get minimumWidth(): number { return 375; }
	get maximumWidth(): number { return Number.POSITIVE_INFINITY; }

	// these setters need to exist because this extends from BaseEditor
	set minimumWidth(value: number) { /*noop*/ }
	set maximumWidth(value: number) { /*noop*/ }


	protected createEditor(parent: HTMLElement): void {
		this.rootElement = DOM.append(parent, $('.notebook-editor'));
		this.createBody(this.rootElement);
	}

	private createBody(parent: HTMLElement): void {
P
Peng Lyu 已提交
582
		this.body = document.createElement('div');
P
Peng Lyu 已提交
583 584 585
		DOM.addClass(this.body, 'cell-list-container');
		this.createCellList();
		DOM.append(parent, this.body);
P
Peng Lyu 已提交
586 587
	}

P
Peng Lyu 已提交
588 589
	private createCellList(): void {
		DOM.addClass(this.body, 'cell-list-container');
P
Peng Lyu 已提交
590

P
Peng Lyu 已提交
591
		const renders = [
P
Peng Lyu 已提交
592 593
			this.instantiationService.createInstance(MarkdownCellRenderer, this),
			this.instantiationService.createInstance(CodeCellRenderer, this)
P
Peng Lyu 已提交
594 595
		];

P
Peng Lyu 已提交
596
		this.list = this.instantiationService.createInstance<typeof WorkbenchList, WorkbenchList<ViewCell>>(
P
Peng Lyu 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
			WorkbenchList,
			'NotebookCellList',
			this.body,
			this.instantiationService.createInstance(NotebookCellListDelegate),
			renders,
			{
				setRowLineHeight: false,
				supportDynamicHeights: true,
				horizontalScrolling: false,
				keyboardSupport: false,
				mouseSupport: false,
				multipleSelectionSupport: false,
				overrideStyles: {
					listBackground: editorBackground,
					listActiveSelectionBackground: editorBackground,
					listActiveSelectionForeground: foreground,
					listFocusAndSelectionBackground: editorBackground,
					listFocusAndSelectionForeground: foreground,
					listFocusBackground: editorBackground,
					listFocusForeground: foreground,
					listHoverForeground: foreground,
					listHoverBackground: editorBackground,
619 620
					listHoverOutline: focusBorder,
					listFocusOutline: focusBorder,
621 622 623 624
					listInactiveSelectionBackground: editorBackground,
					listInactiveSelectionForeground: foreground,
					listInactiveFocusBackground: editorBackground,
					listInactiveFocusOutline: editorBackground,
P
Peng Lyu 已提交
625 626 627 628
				}
			}
		);
	}
P
Peng Lyu 已提交
629

P
Peng Lyu 已提交
630 631 632 633 634 635
	onHide() {
		super.onHide();

		this.viewCells.forEach(cell => cell.isEditing = false);
	}

P
Peng Lyu 已提交
636
	setInput(input: NotebookEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
637 638 639 640 641
		return super.setInput(input, options, token)
			.then(() => {
				return input.resolve();
			})
			.then(model => {
P
Peng Lyu 已提交
642 643 644 645
				if (this.model !== undefined && this.model.textModel === model.textModel) {
					return;
				}

P
Peng Lyu 已提交
646 647 648 649
				this.viewCells.forEach(cell => {
					cell.save();
				});

P
Peng Lyu 已提交
650
				this.model = model;
P
Peng Lyu 已提交
651
				this.viewCells = model.getNotebook().cells.map(cell => {
P
Peng Lyu 已提交
652 653
					return new ViewCell(cell, false, this.modelService, this.modeService);
				});
P
Peng Lyu 已提交
654
				this.list?.splice(0, this.list?.length, this.viewCells);
655 656
				this.list?.layout();
			});
P
Peng Lyu 已提交
657 658
	}

P
Peng Lyu 已提交
659
	layoutElement(cell: ViewCell, height: number) {
P
Peng Lyu 已提交
660 661 662 663
		setTimeout(() => {
			// list.splice -> renderElement -> resize -> layoutElement
			// above flow will actually break how list view renders it self as it messes up with the internal state
			// instead we run the layout update in next tick
P
Peng Lyu 已提交
664
			let index = this.model!.getNotebook().cells.indexOf(cell.cell);
P
Peng Lyu 已提交
665 666
			this.list?.updateDynamicHeight(index, cell, height);
		}, 0);
667 668
	}

P
Peng Lyu 已提交
669
	insertEmptyNotebookCell(cell: ViewCell, type: 'code' | 'markdown', direction: 'above' | 'below') {
P
Peng Lyu 已提交
670
		let newCell = new ViewCell({
P
Peng Lyu 已提交
671
			cell_type: type,
P
Peng Lyu 已提交
672
			source: [],
P
Peng Lyu 已提交
673
			outputs: []
P
Peng Lyu 已提交
674
		}, type === 'markdown', this.modelService, this.modeService);
P
Peng Lyu 已提交
675

P
Peng Lyu 已提交
676
		let index = this.model!.getNotebook().cells.indexOf(cell.cell);
P
Peng Lyu 已提交
677 678
		const insertIndex = direction === 'above' ? index : index + 1;

P
Peng Lyu 已提交
679 680
		this.viewCells!.splice(insertIndex, 0, newCell);
		this.model!.insertCell(newCell.cell, insertIndex);
P
Peng Lyu 已提交
681 682 683
		this.list?.splice(insertIndex, 0, [newCell]);
	}

P
Peng Lyu 已提交
684
	deleteNotebookCell(cell: ViewCell) {
P
Peng Lyu 已提交
685
		let index = this.model!.getNotebook().cells.indexOf(cell.cell);
P
Peng Lyu 已提交
686

P
Peng Lyu 已提交
687 688
		this.viewCells!.splice(index, 1);
		this.model!.deleteCell(cell.cell);
P
Peng Lyu 已提交
689 690 691
		this.list?.splice(index, 1);
	}

P
Peng Lyu 已提交
692

P
Peng Lyu 已提交
693 694 695
	layout(dimension: DOM.Dimension): void {
		DOM.toggleClass(this.rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
		DOM.toggleClass(this.rootElement, 'narrow-width', dimension.width < 600);
P
Peng Lyu 已提交
696 697
		DOM.size(this.body, dimension.width - 40, dimension.height);
		this.list?.layout(dimension.height, dimension.width - 40);
P
Peng Lyu 已提交
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
	}
}

const embeddedEditorBackground = 'walkThrough.embeddedEditorBackground';

registerThemingParticipant((theme, collector) => {
	const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null });
	if (color) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-editor-background,
			.monaco-workbench .part.editor > .content .notebook-editor .margin-view-overlays { background: ${color}; }`);
	}
	const link = theme.getColor(textLinkForeground);
	if (link) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor a { color: ${link}; }`);
	}
	const activeLink = theme.getColor(textLinkActiveForeground);
	if (activeLink) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor a:hover,
			.monaco-workbench .part.editor > .content .notebook-editor a:active { color: ${activeLink}; }`);
	}
	const focusColor = theme.getColor(focusBorder);
	if (focusColor) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor a:focus { outline-color: ${focusColor}; }`);
	}
	const shortcut = theme.getColor(textPreformatForeground);
	if (shortcut) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor code,
			.monaco-workbench .part.editor > .content .notebook-editor .shortcut { color: ${shortcut}; }`);
	}
	const border = theme.getColor(contrastBorder);
	if (border) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-editor { border-color: ${border}; }`);
	}
	const quoteBackground = theme.getColor(textBlockQuoteBackground);
	if (quoteBackground) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { background: ${quoteBackground}; }`);
	}
	const quoteBorder = theme.getColor(textBlockQuoteBorder);
	if (quoteBorder) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { border-color: ${quoteBorder}; }`);
	}
});