notebookEditor.ts 12.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 { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/contentWidget';
P
Peng Lyu 已提交
25
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
26
import { DisposableStore } from 'vs/base/common/lifecycle';
P
Peng Lyu 已提交
27 28 29

const $ = DOM.$;

P
Peng Lyu 已提交
30
export class NotebookEditor extends BaseEditor implements NotebookHandler {
P
Peng Lyu 已提交
31 32 33
	static readonly ID: string = 'workbench.editor.notebook';
	private rootElement!: HTMLElement;
	private body!: HTMLElement;
P
Peng Lyu 已提交
34
	private contentWidgets!: HTMLElement;
P
Peng Lyu 已提交
35
	private webview: BackLayerWebView | null = null;
P
Peng Lyu 已提交
36

P
Peng Lyu 已提交
37
	private list: WorkbenchList<ViewCell> | undefined;
P
Peng Lyu 已提交
38
	private model: NotebookEditorModel | undefined;
P
Peng Lyu 已提交
39
	private viewCells: ViewCell[] = [];
40
	private localStore: DisposableStore = new DisposableStore();
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
		this.webview = new BackLayerWebView(this.webviewService, this);
		this.list.view.rowsContainer.appendChild(this.webview.element);
P
Peng Lyu 已提交
121 122 123 124 125
		this._register(this.list);
	}

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

P
Peng Lyu 已提交
128
	createContentWidget(cell: ViewCell, shadowContent: string, offset: number) {
129 130 131 132
		if (!this.webview) {
			return;
		}

P
Peng Lyu 已提交
133 134 135
		if (!this.webview!.mapping.has(cell.id)) {
			let index = this.model!.getNotebook().cells.indexOf(cell.cell);
			let top = this.list?.getElementTop(index) || 0;
136
			this.webview!.createContentWidget(cell, offset, shadowContent, top + offset);
P
Peng Lyu 已提交
137
		} else {
P
Peng Lyu 已提交
138 139 140 141
			let index = this.model!.getNotebook().cells.indexOf(cell.cell);
			let top = this.list?.getElementTop(index) || 0;
			let scrollTop = this.list?.scrollTop || 0;

142
			this.webview!.updateViewScrollTop(-scrollTop, [{ id: cell.id, top: top + offset }]);
P
Peng Lyu 已提交
143
		}
P
Peng Lyu 已提交
144
	}
P
Peng Lyu 已提交
145

P
Peng Lyu 已提交
146 147 148
	disposeViewCell(cell: ViewCell) {
	}

P
Peng Lyu 已提交
149 150
	onHide() {
		this.viewCells.forEach(cell => cell.isEditing = false);
151 152 153 154 155 156 157 158 159 160

		if (this.webview) {
			this.localStore.clear();
			this.list?.view.rowsContainer.removeChild(this.webview?.element);
			this.webview?.dispose();
			this.webview = null;
		}

		this.list?.splice(0, this.list?.length);
		super.onHide();
P
Peng Lyu 已提交
161 162
	}

163 164 165 166 167 168 169
	setVisible(visible: boolean, group?: IEditorGroup): void {
		super.onHide();
		if (!visible) {
			this.viewCells.forEach(cell => cell.isEditing = false);
		}
	}

P
Peng Lyu 已提交
170
	setInput(input: NotebookEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
171 172 173 174 175
		return super.setInput(input, options, token)
			.then(() => {
				return input.resolve();
			})
			.then(model => {
176
				if (this.model !== undefined && this.model.textModel === model.textModel && this.webview !== null) {
P
Peng Lyu 已提交
177 178 179
					return;
				}

180
				this.localStore.clear();
P
Peng Lyu 已提交
181 182 183 184
				this.viewCells.forEach(cell => {
					cell.save();
				});

185 186 187 188 189 190 191 192
				if (this.webview) {
					this.webview?.clearContentWidgets();
				} else {
					this.webview = new BackLayerWebView(this.webviewService, this);
					this.list?.view.rowsContainer.insertAdjacentElement('afterbegin', this.webview!.element);

				}

P
Peng Lyu 已提交
193
				this.model = model;
P
Peng Lyu 已提交
194
				this.viewCells = model.getNotebook().cells.map(cell => {
P
Peng Lyu 已提交
195 196
					return new ViewCell(cell, false, this.modelService, this.modeService);
				});
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

				const updateScrollPosition = () => {
					let scrollTop = this.list?.scrollTop || 0;
					this.webview!.element.style.top = `${scrollTop}px`;
					let updateItems: { top: number, id: string }[] = [];

					const date = new Date();
					this.webview?.mapping.forEach((item) => {
						let index = this.model!.getNotebook().cells.indexOf(item.cell.cell);
						let top = this.list?.getElementTop(index) || 0;
						let newTop = this.webview!.shouldRenderContentWidget(item.cell.id, top);

						if (newTop !== undefined) {
							updateItems.push({
								top: newTop,
								id: item.cell.id
							});
						}
					});

					if (updateItems.length > 0) {
						console.log('----- did scroll ----  ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds());
						this.webview?.updateViewScrollTop(-scrollTop, updateItems);
					}
				};
				this.localStore.add(this.list!.onWillScroll(e => {
					const date = new Date();
					console.log('----- will scroll ----  ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds());
					this.webview?.updateViewScrollTop(-e.scrollTop, []);
				}));
				this.localStore.add(this.list!.onDidScroll(() => updateScrollPosition()));
				this.localStore.add(this.list!.onDidChangeContentHeight(() => updateScrollPosition()));

P
Peng Lyu 已提交
230
				this.list?.splice(0, this.list?.length, this.viewCells);
231 232
				this.list?.layout();
			});
P
Peng Lyu 已提交
233 234
	}

P
Peng Lyu 已提交
235
	layoutElement(cell: ViewCell, height: number) {
P
Peng Lyu 已提交
236 237 238 239
		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 已提交
240
			//. @TODO @rebornix, it should be batched.
P
Peng Lyu 已提交
241
			let index = this.model!.getNotebook().cells.indexOf(cell.cell);
P
Peng Lyu 已提交
242 243
			this.list?.updateDynamicHeight(index, cell, height);
		}, 0);
244 245
	}

P
Peng Lyu 已提交
246
	insertEmptyNotebookCell(cell: ViewCell, type: 'code' | 'markdown', direction: 'above' | 'below') {
P
Peng Lyu 已提交
247
		let newCell = new ViewCell({
P
Peng Lyu 已提交
248
			cell_type: type,
P
Peng Lyu 已提交
249
			source: [],
P
Peng Lyu 已提交
250
			outputs: []
P
Peng Lyu 已提交
251
		}, false, this.modelService, this.modeService);
P
Peng Lyu 已提交
252

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

P
Peng Lyu 已提交
256 257
		this.viewCells!.splice(insertIndex, 0, newCell);
		this.model!.insertCell(newCell.cell, insertIndex);
P
Peng Lyu 已提交
258
		this.list?.splice(insertIndex, 0, [newCell]);
P
Peng Lyu 已提交
259 260 261 262 263 264 265 266 267 268 269 270

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

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

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

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

P
Peng Lyu 已提交
276 277
		this.viewCells!.splice(index, 1);
		this.model!.deleteCell(cell.cell);
P
Peng Lyu 已提交
278 279 280
		this.list?.splice(index, 1);
	}

P
Peng Lyu 已提交
281 282 283
	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 已提交
284 285
		DOM.size(this.body, dimension.width - 20, dimension.height);
		this.list?.layout(dimension.height, dimension.width - 20);
P
Peng Lyu 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
	}
}

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