notebookEditor.ts 13.4 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';
P
Peng Lyu 已提交
12
import { NotebookEditorInput, NotebookEditorModel } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
P
Peng Lyu 已提交
13 14 15 16 17
import { EditorOptions } from 'vs/workbench/common/editor';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IModelService } from 'vs/editor/common/services/modelService';
import { getExtraColor } from 'vs/workbench/contrib/welcome/walkThrough/common/walkThroughUtils';
P
Peng Lyu 已提交
18 19
import { textLinkForeground, textLinkActiveForeground, focusBorder, textPreformatForeground, contrastBorder, textBlockQuoteBackground, textBlockQuoteBorder, editorBackground, foreground } from 'vs/platform/theme/common/colorRegistry';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
P
Peng Lyu 已提交
20
import { IModeService } from 'vs/editor/common/services/modeService';
P
Peng Lyu 已提交
21
import { NotebookHandler, ViewCell, MarkdownCellRenderer, CodeCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/cellRenderer';
22
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
P
Peng Lyu 已提交
23
import { IWebviewService } from 'vs/workbench/contrib/webview/browser/webview';
P
Peng Lyu 已提交
24
import { WebviewContentWidget, BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/contentWidget';
P
Peng Lyu 已提交
25
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
P
Peng Lyu 已提交
26 27 28

const $ = DOM.$;

P
Peng Lyu 已提交
29
export class NotebookEditor extends BaseEditor implements NotebookHandler {
P
Peng Lyu 已提交
30 31 32
	static readonly ID: string = 'workbench.editor.notebook';
	private rootElement!: HTMLElement;
	private body!: HTMLElement;
P
Peng Lyu 已提交
33 34
	private contentWidgets!: HTMLElement;
	private contentWidgetsMap: Map<ViewCell, WebviewContentWidget> = new Map();
P
Peng Lyu 已提交
35
	private contentWidgetsPool: WebviewContentWidget[] = [];
P
Peng Lyu 已提交
36
	private webview: BackLayerWebView | null = null;
P
Peng Lyu 已提交
37

P
Peng Lyu 已提交
38
	private list: WorkbenchList<ViewCell> | undefined;
P
Peng Lyu 已提交
39
	private model: NotebookEditorModel | undefined;
P
Peng Lyu 已提交
40
	private viewCells: ViewCell[] = [];
P
Peng Lyu 已提交
41 42 43 44 45

	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
		@IThemeService themeService: IThemeService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
P
Peng Lyu 已提交
46 47
		@IModelService private readonly modelService: IModelService,
		@IModeService private readonly modeService: IModeService,
P
Peng Lyu 已提交
48 49
		@IStorageService storageService: IStorageService,
		@IWebviewService private webviewService: IWebviewService
P
Peng Lyu 已提交
50 51 52
	) {
		super(NotebookEditor.ID, telemetryService, themeService, storageService);
	}
P
Peng Lyu 已提交
53

P
Peng Lyu 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67
	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 已提交
68
		this.body = document.createElement('div');
P
Peng Lyu 已提交
69 70 71
		DOM.addClass(this.body, 'cell-list-container');
		this.createCellList();
		DOM.append(parent, this.body);
P
Peng Lyu 已提交
72 73 74 75

		this.contentWidgets = document.createElement('div');
		DOM.addClass(this.contentWidgets, 'notebook-content-widgets');
		DOM.append(this.body, this.contentWidgets);
P
Peng Lyu 已提交
76 77
	}

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

P
Peng Lyu 已提交
81
		const renders = [
P
Peng Lyu 已提交
82 83
			this.instantiationService.createInstance(MarkdownCellRenderer, this),
			this.instantiationService.createInstance(CodeCellRenderer, this)
P
Peng Lyu 已提交
84 85
		];

P
Peng Lyu 已提交
86
		this.list = this.instantiationService.createInstance<typeof WorkbenchList, WorkbenchList<ViewCell>>(
P
Peng Lyu 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
			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,
109 110
					listHoverOutline: focusBorder,
					listFocusOutline: focusBorder,
111 112 113 114
					listInactiveSelectionBackground: editorBackground,
					listInactiveSelectionForeground: foreground,
					listInactiveFocusBackground: editorBackground,
					listInactiveFocusOutline: editorBackground,
P
Peng Lyu 已提交
115 116 117
				}
			}
		);
P
Peng Lyu 已提交
118

P
Peng Lyu 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131
		this.webview = new BackLayerWebView(this.webviewService, this);
		this.list.view.rowsContainer.appendChild(this.webview.element);

		const updateScrollPosition = () => {
			let scrollTop = this.list?.scrollTop || 0;
			this.webview!.element.style.top = `${scrollTop}px`;
			this.webview!.mapping.forEach((item) => {
				let index = this.model!.getNotebook().cells.indexOf(item.cell.cell);
				let top = this.list?.getElementTop(index);
				if (top !== null && top !== undefined) {
					this.webview!.updateTop(item.cell.id, -scrollTop + top);
				}
			});
P
Peng Lyu 已提交
132
			this.contentWidgetsMap.forEach((value, cell) => {
P
Peng Lyu 已提交
133 134 135 136
				if (value.detachedFromViewEvents) {
					return;
				}

P
Peng Lyu 已提交
137 138 139 140 141 142 143 144
				let index = this.model!.getNotebook().cells.indexOf(cell.cell);
				let top = this.list?.getElementTop(index);
				if (top !== null && top !== undefined) {
					let domElement = value.element;
					let scrollTop = this.list?.scrollTop || 0;
					domElement.style.top = `${-scrollTop + top + value.offset}px`;
				}
			});
P
Peng Lyu 已提交
145 146 147 148
		};

		this._register(this.list.onDidScroll(() => updateScrollPosition()));
		this._register(this.list.onDidChangeContentHeight(() => updateScrollPosition()));
P
Peng Lyu 已提交
149 150 151 152 153 154

		this._register(this.list);
	}

	triggerWheel(event: IMouseWheelEvent) {
		this.list?.triggerScrollFromMouseWheelEvent(event);
P
Peng Lyu 已提交
155 156
	}

P
Peng Lyu 已提交
157
	createContentWidget(cell: ViewCell, shadowContent: string, shadowElement: HTMLElement, offset: number) {
P
Peng Lyu 已提交
158
		if (this.webview!.mapping.has(cell.id)) {
P
Peng Lyu 已提交
159
		} else {
P
Peng Lyu 已提交
160 161 162 163
			let index = this.model!.getNotebook().cells.indexOf(cell.cell);
			let top = this.list?.getElementTop(index) || 0;
			let scrollTop = this.list?.scrollTop || 0;
			this.webview!.createContentWidget(shadowElement, cell, offset, shadowContent, -scrollTop + top + offset);
P
Peng Lyu 已提交
164
		}
P
Peng Lyu 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
		// let zone = this.contentWidgetsMap.get(cell);

		// if (!zone) {
		// 	let existingContentWidget = this.contentWidgetsPool.pop();
		// 	if (existingContentWidget) {
		// 		existingContentWidget.detachedFromViewEvents = false;
		// 		existingContentWidget.updateInitialization(shadowElement, cell, offset, shadowContent);
		// 		this.contentWidgetsMap.set(cell, existingContentWidget);

		// 		let index = this.model!.getNotebook().cells.indexOf(cell.cell);
		// 		let top = this.list?.getElementTop(index);
		// 		if (top !== null && top !== undefined) {
		// 			let domElement = existingContentWidget.element;
		// 			let scrollTop = this.list?.scrollTop || 0;
		// 			domElement.style.top = `${-scrollTop + top + existingContentWidget.offset}px`;
		// 		}
		// 		return;
		// 	}

		// 	let contentWidget = new WebviewContentWidget(
		// 		shadowElement,
		// 		cell,
		// 		offset,
		// 		this.webviewService,
		// 		shadowContent,
		// 		this
		// 	);

		// 	this.contentWidgets.appendChild(contentWidget.element);
		// 	this.contentWidgetsMap.set(cell, contentWidget);
		// } else {
		// 	zone.updateShadowElement(shadowElement);
		// }
P
Peng Lyu 已提交
198
	}
P
Peng Lyu 已提交
199

P
Peng Lyu 已提交
200
	disposeViewCell(cell: ViewCell) {
P
Peng Lyu 已提交
201 202 203 204 205
		if (this.webview!.mapping.has(cell.id)) {
			this.webview!.updateTop(cell.id, -2400);
			return;
		}

P
Peng Lyu 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
		let zone = this.contentWidgetsMap.get(cell);

		if (zone) {
			// we are going to dispose a view who has a webview
			if (!zone.webview.containsScript) {
				// this view can be disposed
				zone.detachedFromViewEvents = true;
				zone.element.style.top = '-2400px';
				zone.element.style.height = '700px';

				if (this.contentWidgetsPool.length < 10) {
					this.contentWidgetsPool.push(zone);
					this.contentWidgetsMap.delete(cell);
				} else {
					this.contentWidgets.removeChild(zone.element);
					this.contentWidgetsMap.delete(cell);
				}
			}
		}
	}

P
Peng Lyu 已提交
227 228 229 230 231 232
	onHide() {
		super.onHide();

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

233 234 235 236 237 238 239
	setVisible(visible: boolean, group?: IEditorGroup): void {
		super.onHide();
		if (!visible) {
			this.viewCells.forEach(cell => cell.isEditing = false);
		}
	}

P
Peng Lyu 已提交
240
	setInput(input: NotebookEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
241 242 243 244 245
		return super.setInput(input, options, token)
			.then(() => {
				return input.resolve();
			})
			.then(model => {
P
Peng Lyu 已提交
246 247 248 249
				if (this.model !== undefined && this.model.textModel === model.textModel) {
					return;
				}

P
Peng Lyu 已提交
250 251 252 253
				this.viewCells.forEach(cell => {
					cell.save();
				});

P
Peng Lyu 已提交
254 255 256 257 258
				this.contentWidgetsMap.forEach((value, cell) => {
					this.contentWidgets.removeChild(value.element);
				});
				this.contentWidgetsMap.clear();

P
Peng Lyu 已提交
259
				this.model = model;
P
Peng Lyu 已提交
260
				this.viewCells = model.getNotebook().cells.map(cell => {
P
Peng Lyu 已提交
261 262
					return new ViewCell(cell, false, this.modelService, this.modeService);
				});
P
Peng Lyu 已提交
263
				this.list?.splice(0, this.list?.length, this.viewCells);
264 265
				this.list?.layout();
			});
P
Peng Lyu 已提交
266 267
	}

P
Peng Lyu 已提交
268
	layoutElement(cell: ViewCell, height: number) {
P
Peng Lyu 已提交
269 270 271 272
		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 已提交
273
			//. @TODO @rebornix, it should be batched.
P
Peng Lyu 已提交
274
			let index = this.model!.getNotebook().cells.indexOf(cell.cell);
P
Peng Lyu 已提交
275 276
			this.list?.updateDynamicHeight(index, cell, height);
		}, 0);
277 278
	}

P
Peng Lyu 已提交
279
	insertEmptyNotebookCell(cell: ViewCell, type: 'code' | 'markdown', direction: 'above' | 'below') {
P
Peng Lyu 已提交
280
		let newCell = new ViewCell({
P
Peng Lyu 已提交
281
			cell_type: type,
P
Peng Lyu 已提交
282
			source: [],
P
Peng Lyu 已提交
283
			outputs: []
P
Peng Lyu 已提交
284
		}, false, this.modelService, this.modeService);
P
Peng Lyu 已提交
285

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

P
Peng Lyu 已提交
289 290
		this.viewCells!.splice(insertIndex, 0, newCell);
		this.model!.insertCell(newCell.cell, insertIndex);
P
Peng Lyu 已提交
291
		this.list?.splice(insertIndex, 0, [newCell]);
P
Peng Lyu 已提交
292 293 294 295 296 297 298 299 300 301 302 303

		if (type === 'markdown') {
			newCell.isEditing = true;
		}
	}

	editNotebookCell(cell: ViewCell): void {
		cell.isEditing = true;
	}

	saveNotebookCell(cell: ViewCell): void {
		cell.isEditing = false;
P
Peng Lyu 已提交
304 305
	}

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

P
Peng Lyu 已提交
309 310
		this.viewCells!.splice(index, 1);
		this.model!.deleteCell(cell.cell);
P
Peng Lyu 已提交
311 312 313
		this.list?.splice(index, 1);
	}

P
Peng Lyu 已提交
314 315 316
	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 已提交
317 318
		DOM.size(this.body, dimension.width - 20, dimension.height);
		this.list?.layout(dimension.height, dimension.width - 20);
P
Peng Lyu 已提交
319 320 321 322 323 324 325 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
	}
}

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