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

import * as DOM from 'vs/base/browser/dom';
7
import { Disposable } from 'vs/base/common/lifecycle';
R
rebornix 已提交
8 9 10
import { URI } from 'vs/base/common/uri';
import * as UUID from 'vs/base/common/uuid';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
11
import { INotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
R
rebornix 已提交
12
import { INotebookService } from 'vs/workbench/contrib/notebook/browser/notebookService';
R
rebornix 已提交
13
import { IOutput } from 'vs/workbench/contrib/notebook/common/notebookCommon';
R
rebornix 已提交
14 15
import { IWebviewService, WebviewElement } from 'vs/workbench/contrib/webview/browser/webview';
import { WebviewResourceScheme } from 'vs/workbench/contrib/webview/common/resourceLoader';
R
rebornix 已提交
16
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
17
import { CELL_MARGIN, CELL_RUN_GUTTER } from 'vs/workbench/contrib/notebook/browser/constants';
18
import { Emitter, Event } from 'vs/base/common/event';
19
import { IOpenerService } from 'vs/platform/opener/common/opener';
R
rebornix 已提交
20
import { getPathFromAmdModule } from 'vs/base/common/amd';
P
Peng Lyu 已提交
21 22

export interface IDimentionMessage {
23
	__vscode_notebook_message: boolean;
P
Peng Lyu 已提交
24 25 26 27 28
	type: 'dimension';
	id: string;
	data: DOM.Dimension;
}

29 30 31 32 33 34
export interface IWheelMessage {
	__vscode_notebook_message: boolean;
	type: 'did-scroll-wheel';
	payload: any;
}

35 36

export interface IScrollAckMessage {
37
	__vscode_notebook_message: boolean;
38 39 40 41 42
	type: 'scroll-ack';
	data: { top: number };
	version: number;
}

P
Peng Lyu 已提交
43 44 45 46 47 48 49 50
export interface IClearMessage {
	type: 'clear';
}

export interface ICreationRequestMessage {
	type: 'html';
	content: string;
	id: string;
51
	outputId: string;
P
Peng Lyu 已提交
52
	top: number;
53
	left: number;
P
Peng Lyu 已提交
54 55
}

56 57 58
export interface IContentWidgetTopRequest {
	id: string;
	top: number;
59
	left: number;
60 61 62 63 64 65 66 67 68
}

export interface IViewScrollTopRequestMessage {
	type: 'view-scroll';
	top?: number;
	widgets: IContentWidgetTopRequest[];
	version: number;
}

P
Peng Lyu 已提交
69 70 71 72
export interface IScrollRequestMessage {
	type: 'scroll';
	id: string;
	top: number;
73 74
	widgetTop?: number;
	version: number;
P
Peng Lyu 已提交
75 76
}

77 78 79 80 81
export interface IUpdatePreloadResourceMessage {
	type: 'preload';
	resources: string[];
}

82
type IMessage = IDimentionMessage | IScrollAckMessage | IWheelMessage;
P
Peng Lyu 已提交
83

84 85
let version = 0;
export class BackLayerWebView extends Disposable {
R
rebornix 已提交
86 87
	element: HTMLElement;
	webview: WebviewElement;
R
rebornix 已提交
88
	insetMapping: Map<IOutput, { outputId: string, cell: CodeCellViewModel, cacheOffset: number | undefined }> = new Map();
89
	reversedInsetMapping: Map<string, IOutput> = new Map();
R
rebornix 已提交
90
	preloadsCache: Map<string, boolean> = new Map();
91 92
	localResourceRootsCache: URI[] | undefined = undefined;
	rendererRootsCache: URI[] = [];
93 94 95
	private readonly _onMessage = this._register(new Emitter<any>());
	public readonly onMessage: Event<any> = this._onMessage.event;

P
Peng Lyu 已提交
96

97 98 99 100 101 102 103
	constructor(
		public notebookEditor: INotebookEditor,
		@IWebviewService webviewService: IWebviewService,
		@IOpenerService openerService: IOpenerService,
		@IEnvironmentService private readonly environmentSerice: IEnvironmentService,
		@INotebookService private readonly notebookService: INotebookService,
	) {
104
		super();
P
Peng Lyu 已提交
105
		this.element = document.createElement('div');
106 107

		this.element.style.width = `calc(100% - ${CELL_MARGIN * 2}px)`;
P
Peng Lyu 已提交
108 109
		this.element.style.height = '1400px';
		this.element.style.position = 'absolute';
R
rebornix 已提交
110
		this.element.style.margin = `0px 0 0px ${CELL_MARGIN}px`;
P
Peng Lyu 已提交
111

R
rebornix 已提交
112 113
		const pathsPath = getPathFromAmdModule(require, 'vs/loader.js');
		const loader = URI.file(pathsPath).with({ scheme: WebviewResourceScheme });
R
rebornix 已提交
114

R
rebornix 已提交
115
		const outputNodePadding = 8;
P
Peng Lyu 已提交
116 117 118 119
		let content = /* html */`
		<html lang="en">
			<head>
				<meta charset="UTF-8">
120
				<style>
R
rebornix 已提交
121
					#container > div > div {
122
						width: 100%;
R
rebornix 已提交
123 124
						padding: ${outputNodePadding}px;
						box-sizing: border-box;
125 126
						background-color: var(--vscode-list-inactiveSelectionBackground);
					}
R
rebornix 已提交
127 128
					body {
						padding: 0px;
R
rebornix 已提交
129 130
						height: 100%;
						width: 100%;
R
rebornix 已提交
131
					}
132
				</style>
P
Peng Lyu 已提交
133 134
			</head>
			<body style="overflow: hidden;">
R
rebornix 已提交
135 136 137 138
				<script>
					self.require = {};
				</script>
				<script src="${loader}"></script>
139
				<div id="__vscode_preloads"></div>
140
				<div id='container' class="widgetarea" style="position: absolute;width:100%;top: 0px"></div>
P
Peng Lyu 已提交
141 142
<script>
(function () {
143
	// eslint-disable-next-line no-undef
P
Peng Lyu 已提交
144
	const vscode = acquireVsCodeApi();
R
rebornix 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

	const preservedScriptAttributes = {
		type: true,
		src: true,
		nonce: true,
		noModule: true,
		async: true
	};

	// derived from https://github.com/jquery/jquery/blob/d0ce00cdfa680f1f0c38460bc51ea14079ae8b07/src/core/DOMEval.js
	const domEval = (container) => {
		var arr = Array.from(container.getElementsByTagName('script'));
		for (let n = 0; n < arr.length; n++) {
			let node = arr[n];
			let scriptTag = document.createElement('script');
			scriptTag.text = node.innerText;
			for (let key in preservedScriptAttributes ) {
				const val = node[key] || node.getAttribute && node.getAttribute(key);
				if (val) {
					scriptTag.setAttribute(key, val);
				}
			}

			// TODO: should script with src not be removed?
			container.appendChild(scriptTag).parentNode.removeChild(scriptTag);
		}
	};
P
Peng Lyu 已提交
172

R
rebornix 已提交
173 174 175 176 177 178 179
	let observers = [];

	const resizeObserve = (container, id) => {
		const resizeObserver = new ResizeObserver(entries => {
			for (let entry of entries) {
				if (entry.target.id === id && entry.contentRect) {
					vscode.postMessage({
180
							__vscode_notebook_message: true,
R
rebornix 已提交
181 182 183
							type: 'dimension',
							id: id,
							data: {
R
rebornix 已提交
184
								height: entry.contentRect.height + ${outputNodePadding} * 2
R
rebornix 已提交
185 186 187 188 189 190 191 192 193 194
							}
						});
				}
			}
		});

		resizeObserver.observe(container);
		observers.push(resizeObserver);
	}

195 196 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 230 231 232 233 234
	function scrollWillGoToParent(event) {
		for (let node = event.target; node; node = node.parentNode) {
			if (node.id === 'container') {
				return false;
			}

			console.log(node, node.parentNode, node.scrollTop, node.scrollHeight, node.clientHeight);
			if (event.deltaY < 0 && node.scrollTop > 0) {
				return true;
			}

			if (event.deltaY > 0 && node.scrollTop + node.clientHeight < node.scrollHeight) {
				return true;
			}
		}

		return false;
	}

	const handleWheel = (event) => {
		if (event.defaultPrevented || scrollWillGoToParent(event)) {
			return;
		}

		vscode.postMessage({
			__vscode_notebook_message: true,
			type: 'did-scroll-wheel',
			payload: {
				deltaMode: event.deltaMode,
				deltaX: event.deltaX,
				deltaY: event.deltaY,
				deltaZ: event.deltaZ,
				detail: event.detail,
				type: event.type
			}
		});
	};

	window.addEventListener('wheel', handleWheel);

P
Peng Lyu 已提交
235
	window.addEventListener('message', event => {
P
Peng Lyu 已提交
236 237 238 239 240
		let id = event.data.id;

		switch (event.data.type) {
			case 'html':
				{
R
rebornix 已提交
241
					let cellOutputContainer = document.getElementById(id);
242
					let outputId = event.data.outputId;
R
rebornix 已提交
243 244
					if (!cellOutputContainer) {
						let newElement = document.createElement('div');
245

R
rebornix 已提交
246 247 248
						newElement.id = id;
						document.getElementById('container').appendChild(newElement);
						cellOutputContainer = newElement;
P
Peng Lyu 已提交
249
					}
R
rebornix 已提交
250 251

					let outputNode = document.createElement('div');
252 253
					outputNode.style.position = 'absolute';
					outputNode.style.top = event.data.top + 'px';
254
					outputNode.style.left = event.data.left + 'px';
255
					outputNode.style.width = 'calc(100% - ' + event.data.left + 'px)';
R
rebornix 已提交
256
					outputNode.style.minHeight = '32px';
257 258

					outputNode.id = outputId;
R
rebornix 已提交
259 260 261 262 263 264
					let content = event.data.content;
					outputNode.innerHTML = content;
					cellOutputContainer.appendChild(outputNode);

					// eval
					domEval(outputNode);
265
					resizeObserve(outputNode, outputId);
R
rebornix 已提交
266

R
rebornix 已提交
267
					vscode.postMessage({
268
						__vscode_notebook_message: true,
R
rebornix 已提交
269
						type: 'dimension',
270
						id: outputId,
R
rebornix 已提交
271
						data: {
272
							height: outputNode.clientHeight
R
rebornix 已提交
273 274
						}
					});
P
Peng Lyu 已提交
275 276
				}
				break;
277
			case 'view-scroll':
P
Peng Lyu 已提交
278
				{
R
rebornix 已提交
279
					// const date = new Date();
R
rebornix 已提交
280
					// console.log('----- will scroll ----  ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds());
281 282 283 284 285 286

					for (let i = 0; i < event.data.widgets.length; i++) {
						let widget = document.getElementById(event.data.widgets[i].id);
						widget.style.top = event.data.widgets[i].top + 'px';
					}
					break;
P
Peng Lyu 已提交
287
				}
P
Peng Lyu 已提交
288 289
			case 'clear':
				document.getElementById('container').innerHTML = '';
R
rebornix 已提交
290
				for (let i = 0; i < observers.length; i++) {
291
					observers[i].disconnect();
R
rebornix 已提交
292 293 294
				}

				observers = [];
P
Peng Lyu 已提交
295
				break;
R
rebornix 已提交
296 297 298 299 300
			case 'clearOutput':
				let output = document.getElementById(id);
				output.parentNode.removeChild(output);
				// @TODO remove observer
				break;
301 302 303 304 305 306 307 308 309
			case 'preload':
				let resources = event.data.resources;
				let preloadsContainer = document.getElementById('__vscode_preloads');
				for (let i = 0; i < resources.length; i++) {
					let scriptTag = document.createElement('script');
					scriptTag.setAttribute('src', resources[i]);
					preloadsContainer.appendChild(scriptTag)
				}
				break;
P
Peng Lyu 已提交
310 311 312
		}
	});
}());
P
Peng Lyu 已提交
313

P
Peng Lyu 已提交
314 315 316 317 318 319 320
</script>
</body>
`;

		this.webview = this._createInset(webviewService, content);
		this.webview.mountTo(this.element);

321 322 323 324
		this._register(this.webview.onDidClickLink(link => {
			openerService.open(link, { fromUserGesture: true });
		}));

325
		this._register(this.webview.onMessage((data: IMessage) => {
326 327 328
			if (data.__vscode_notebook_message) {
				if (data.type === 'dimension') {
					let output = this.reversedInsetMapping.get(data.id);
329

330 331 332
					if (!output) {
						return;
					}
333

334 335
					let cell = this.insetMapping.get(output)!.cell;
					let height = data.data.height;
336
					let outputHeight = height;
337

338 339 340
					if (cell) {
						let outputIndex = cell.outputs.indexOf(output);
						cell.updateOutputHeight(outputIndex, outputHeight);
R
rebornix 已提交
341
						this.notebookEditor.layoutNotebookCell(cell, cell.layoutInfo.totalHeight);
342 343 344 345 346
					}
				} else if (data.type === 'scroll-ack') {
					// const date = new Date();
					// const top = data.data.top;
					// console.log('ack top ', top, ' version: ', data.version, ' - ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds());
347 348
				} else if (data.type === 'did-scroll-wheel') {
					this.notebookEditor.triggerScroll(data.payload);
P
Peng Lyu 已提交
349
				}
350
				return;
P
Peng Lyu 已提交
351
			}
352 353

			this._onMessage.fire(data);
354
		}));
P
Peng Lyu 已提交
355 356 357
	}

	private _createInset(webviewService: IWebviewService, content: string) {
358
		this.localResourceRootsCache = [...this.notebookService.getNotebookProviderResourceRoots(), URI.file(this.environmentSerice.appRoot)];
R
rebornix 已提交
359
		const webview = webviewService.createWebviewElement('' + UUID.generateUuid(), {
P
Peng Lyu 已提交
360 361
			enableFindWidget: false,
		}, {
R
rebornix 已提交
362
			allowMultipleAPIAcquire: true,
R
rebornix 已提交
363
			allowScripts: true,
364
			localResourceRoots: this.localResourceRootsCache
P
Peng Lyu 已提交
365 366 367 368 369
		});
		webview.html = content;
		return webview;
	}

R
rebornix 已提交
370
	shouldUpdateInset(cell: CodeCellViewModel, output: IOutput, cellTop: number) {
371 372
		let outputCache = this.insetMapping.get(output)!;
		let outputIndex = cell.outputs.indexOf(output);
373
		let outputOffset = cellTop + cell.getOutputOffset(outputIndex);
374 375 376

		if (outputOffset === outputCache.cacheOffset) {
			return false;
P
Peng Lyu 已提交
377
		}
378

379
		return true;
380 381
	}

R
rebornix 已提交
382
	updateViewScrollTop(top: number, items: { cell: CodeCellViewModel, output: IOutput, cellTop: number }[]) {
383 384 385 386 387
		let widgets: IContentWidgetTopRequest[] = items.map(item => {
			let outputCache = this.insetMapping.get(item.output)!;
			let id = outputCache.outputId;
			let outputIndex = item.cell.outputs.indexOf(item.output);

388
			let outputOffset = item.cellTop + item.cell.getOutputOffset(outputIndex);
389 390 391 392
			outputCache.cacheOffset = outputOffset;

			return {
				id: id,
393 394
				top: outputOffset,
				left: CELL_RUN_GUTTER
395
			};
396 397 398 399 400 401
		});

		let message: IViewScrollTopRequestMessage = {
			top,
			type: 'view-scroll',
			version: version++,
402
			widgets: widgets
403 404 405
		};

		this.webview.sendMessage(message);
P
Peng Lyu 已提交
406 407
	}

R
rebornix 已提交
408
	createInset(cell: CodeCellViewModel, output: IOutput, cellTop: number, offset: number, shadowContent: string, preloads: Set<number>) {
409
		this.updateRendererPreloads(preloads);
410 411
		let initialTop = cellTop + offset;
		let outputId = UUID.generateUuid();
412

P
Peng Lyu 已提交
413
		let message: ICreationRequestMessage = {
P
Peng Lyu 已提交
414 415 416
			type: 'html',
			content: shadowContent,
			id: cell.id,
417
			outputId: outputId,
418 419
			top: initialTop,
			left: CELL_RUN_GUTTER
P
Peng Lyu 已提交
420
		};
P
Peng Lyu 已提交
421

P
Peng Lyu 已提交
422
		this.webview.sendMessage(message);
423 424
		this.insetMapping.set(output, { outputId: outputId, cell: cell, cacheOffset: initialTop });
		this.reversedInsetMapping.set(outputId, output);
P
Peng Lyu 已提交
425
	}
P
Peng Lyu 已提交
426

R
rebornix 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	removeInset(output: IOutput) {
		let outputCache = this.insetMapping.get(output);
		if (!outputCache) {
			return;
		}

		let id = outputCache.outputId;

		this.webview.sendMessage({
			type: 'clearOutput',
			id: id
		});
		this.insetMapping.delete(output);
		this.reversedInsetMapping.delete(id);
	}

R
rebornix 已提交
443
	clearInsets() {
P
Peng Lyu 已提交
444 445
		this.webview.sendMessage({
			type: 'clear'
P
Peng Lyu 已提交
446
		});
R
rebornix 已提交
447

448 449
		this.insetMapping = new Map();
		this.reversedInsetMapping = new Map();
P
Peng Lyu 已提交
450
	}
451

R
rebornix 已提交
452
	updateRendererPreloads(preloads: Set<number>) {
453
		let resources: string[] = [];
454
		let extensionLocations: URI[] = [];
455
		preloads.forEach(preload => {
456
			let rendererInfo = this.notebookService.getRendererInfo(preload);
457 458 459 460 461 462 463 464 465 466 467

			if (rendererInfo) {
				let preloadResources = rendererInfo.preloads.map(preloadResource => preloadResource.with({ scheme: WebviewResourceScheme }));
				extensionLocations.push(rendererInfo.extensionLocation);
				preloadResources.forEach(e => {
					if (!this.preloadsCache.has(e.toString())) {
						resources.push(e.toString());
						this.preloadsCache.set(e.toString(), true);
					}
				});
			}
468 469
		});

470 471 472 473
		this.rendererRootsCache = extensionLocations;
		const mixedResourceRoots = [...(this.localResourceRootsCache || []), ...this.rendererRootsCache];

		this.webview.contentOptions = {
R
rebornix 已提交
474
			allowMultipleAPIAcquire: true,
475 476 477 478 479
			allowScripts: true,
			enableCommandUris: true,
			localResourceRoots: mixedResourceRoots
		};

480 481 482 483 484 485 486 487
		let message: IUpdatePreloadResourceMessage = {
			type: 'preload',
			resources: resources
		};

		this.webview.sendMessage(message);
	}

R
rebornix 已提交
488
	clearPreloadsCache() {
489 490
		this.preloadsCache.clear();
	}
P
Peng Lyu 已提交
491
}