main.js 14.5 KB
Newer Older
M
Matt Bierner 已提交
1 2 3 4
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
5
// @ts-check
6 7 8 9 10 11 12

/**
 * @typedef {{
 *   postMessage: (channel: string, data?: any) => void,
 *   onMessage: (channel: string, handler: any) => void,
 *   focusIframeOnCreate?: boolean,
 *   ready?: Promise<void>,
13 14
 *   onIframeLoaded?: (iframe: HTMLIFrameElement) => void,
 *   fakeLoad: boolean
15 16 17
 * }} WebviewHost
 */

M
Matt Bierner 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
(function () {
	'use strict';

	/**
	 * Use polling to track focus of main webview and iframes within the webview
	 *
	 * @param {Object} handlers
	 * @param {() => void} handlers.onFocus
	 * @param {() => void} handlers.onBlur
	 */
	const trackFocus = ({ onFocus, onBlur }) => {
		const interval = 50;
		let isFocused = document.hasFocus();
		setInterval(() => {
			const isCurrentlyFocused = document.hasFocus();
			if (isCurrentlyFocused === isFocused) {
				return;
			}
			isFocused = isCurrentlyFocused;
			if (isCurrentlyFocused) {
				onFocus();
			} else {
				onBlur();
			}
		}, interval);
	};

	const getActiveFrame = () => {
		return /** @type {HTMLIFrameElement} */ (document.getElementById('active-frame'));
	};

	const getPendingFrame = () => {
		return /** @type {HTMLIFrameElement} */ (document.getElementById('pending-frame'));
	};

	const defaultCssRules = `
54 55 56
	body {
		background-color: var(--vscode-editor-background);
		color: var(--vscode-editor-foreground);
57 58 59
		font-family: var(--vscode-font-family);
		font-weight: var(--vscode-font-weight);
		font-size: var(--vscode-font-size);
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
		margin: 0;
		padding: 0 20px;
	}

	img {
		max-width: 100%;
		max-height: 100%;
	}

	a {
		color: var(--vscode-textLink-foreground);
	}

	a:hover {
		color: var(--vscode-textLink-activeForeground);
	}

	a:focus,
	input:focus,
	select:focus,
	textarea:focus {
		outline: 1px solid -webkit-focus-ring-color;
		outline-offset: -1px;
	}

	code {
		color: var(--vscode-textPreformat-foreground);
	}

	blockquote {
		background: var(--vscode-textBlockQuote-background);
		border-color: var(--vscode-textBlockQuote-border);
	}

	::-webkit-scrollbar {
		width: 10px;
		height: 10px;
	}

	::-webkit-scrollbar-thumb {
		background-color: var(--vscode-scrollbarSlider-background);
	}
	::-webkit-scrollbar-thumb:hover {
		background-color: var(--vscode-scrollbarSlider-hoverBackground);
	}
	::-webkit-scrollbar-thumb:active {
		background-color: var(--vscode-scrollbarSlider-activeBackground);
	}`;

M
Matt Bierner 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	/**
	 * @param {*} [state]
	 * @return {string}
	 */
	function getVsCodeApiScript(state) {
		return `
			const acquireVsCodeApi = (function() {
				const originalPostMessage = window.parent.postMessage.bind(window.parent);
				const targetOrigin = '*';
				let acquired = false;

				let state = ${state ? `JSON.parse(${JSON.stringify(state)})` : undefined};

				return () => {
					if (acquired) {
						throw new Error('An instance of the VS Code API has already been acquired');
					}
					acquired = true;
					return Object.freeze({
						postMessage: function(msg) {
							return originalPostMessage({ command: 'onmessage', data: msg }, targetOrigin);
						},
						setState: function(newState) {
							state = newState;
							originalPostMessage({ command: 'do-update-state', data: JSON.stringify(newState) }, targetOrigin);
							return newState;
						},
						getState: function() {
							return state;
						}
					});
				};
			})();
			delete window.parent;
			delete window.top;
			delete window.frameElement;
		`;
	}

M
Matt Bierner 已提交
148
	/**
149
	 * @param {WebviewHost} host
150
	 */
M
Matt Bierner 已提交
151 152 153 154 155 156 157 158 159 160
	function createWebviewManager(host) {
		// state
		let firstLoad = true;
		let loadTimeout;
		let pendingMessages = [];

		const initData = {
			initialScrollProgress: undefined
		};

161

M
Matt Bierner 已提交
162 163 164 165 166 167 168
		/**
		 * @param {HTMLDocument?} document
		 * @param {HTMLElement?} body
		 */
		const applyStyles = (document, body) => {
			if (!document) {
				return;
169
			}
M
Matt Bierner 已提交
170

M
Matt Bierner 已提交
171 172 173 174
			if (body) {
				body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast');
				body.classList.add(initData.activeTheme);
			}
M
Matt Bierner 已提交
175

M
Matt Bierner 已提交
176 177 178 179
			if (initData.styles) {
				for (const variable of Object.keys(initData.styles)) {
					document.documentElement.style.setProperty(`--${variable}`, initData.styles[variable]);
				}
180
			}
M
Matt Bierner 已提交
181
		};
M
Matt Bierner 已提交
182

M
Matt Bierner 已提交
183 184 185 186 187 188 189
		/**
		 * @param {MouseEvent} event
		 */
		const handleInnerClick = (event) => {
			if (!event || !event.view || !event.view.document) {
				return;
			}
190

M
Matt Bierner 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
			let baseElement = event.view.document.getElementsByTagName('base')[0];
			/** @type {any} */
			let node = event.target;
			while (node) {
				if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
					if (node.getAttribute('href') === '#') {
						event.view.scrollTo(0, 0);
					} else if (node.hash && (node.getAttribute('href') === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) {
						let scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1));
						if (scrollTarget) {
							scrollTarget.scrollIntoView();
						}
					} else {
						host.postMessage('did-click-link', node.href.baseVal || node.href);
					}
					event.preventDefault();
					break;
				}
				node = node.parentNode;
			}
		};

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
		/**
		 * @param {MouseEvent} event
		 */
		const handleAuxClick = (event) => {
			// Prevent middle clicks opening a broken link in the browser
			if (!event.view || !event.view.document) {
				return;
			}

			if (event.button === 1) {
				let node = /** @type {any} */ (event.target);
				while (node) {
					if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
						event.preventDefault();
						break;
					}
					node = node.parentNode;
				}
			}
		};

M
Matt Bierner 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
		/**
		 * @param {KeyboardEvent} e
		 */
		const handleInnerKeydown = (e) => {
			host.postMessage('did-keydown', {
				key: e.key,
				keyCode: e.keyCode,
				code: e.code,
				shiftKey: e.shiftKey,
				altKey: e.altKey,
				ctrlKey: e.ctrlKey,
				metaKey: e.metaKey,
				repeat: e.repeat
			});
		};
M
Matt Bierner 已提交
249

M
Matt Bierner 已提交
250 251 252 253 254 255
		let isHandlingScroll = false;
		const handleInnerScroll = (event) => {
			if (!event.target || !event.target.body) {
				return;
			}
			if (isHandlingScroll) {
256 257
				return;
			}
M
Matt Bierner 已提交
258

M
Matt Bierner 已提交
259 260 261
			const progress = event.currentTarget.scrollY / event.target.body.clientHeight;
			if (isNaN(progress)) {
				return;
262
			}
M
Matt Bierner 已提交
263

M
Matt Bierner 已提交
264 265 266 267 268 269 270 271 272 273 274
			isHandlingScroll = true;
			window.requestAnimationFrame(() => {
				try {
					host.postMessage('did-scroll', progress);
				} catch (e) {
					// noop
				}
				isHandlingScroll = false;
			});
		};

M
Matt Bierner 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
		/**
		 * @return {string}
		 */
		function toContentHtml(data) {
			const options = data.options;
			const text = data.contents;
			const newDocument = new DOMParser().parseFromString(text, 'text/html');

			newDocument.querySelectorAll('a').forEach(a => {
				if (!a.title) {
					a.title = a.getAttribute('href');
				}
			});

			// apply default script
			if (options.allowScripts) {
				const defaultScript = newDocument.createElement('script');
				defaultScript.textContent = getVsCodeApiScript(data.state);
				newDocument.head.prepend(defaultScript);
			}

			// apply default styles
			const defaultStyles = newDocument.createElement('style');
			defaultStyles.id = '_defaultStyles';
			defaultStyles.innerHTML = defaultCssRules;
			newDocument.head.prepend(defaultStyles);

			applyStyles(newDocument, newDocument.body);

304 305 306 307
			// Check for CSP
			const csp = newDocument.querySelector('meta[http-equiv="Content-Security-Policy"]');
			if (!csp) {
				host.postMessage('no-csp-found');
308 309 310 311 312
			} else {
				// Rewrite vscode-resource in csp
				if (data.endpoint) {
					csp.setAttribute('content', csp.getAttribute('content').replace(/vscode-resource:/g, data.endpoint));
				}
313 314
			}

M
Matt Bierner 已提交
315 316 317 318 319
			// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off
			// and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden
			return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML;
		}

M
Matt Bierner 已提交
320
		document.addEventListener('DOMContentLoaded', () => {
321 322
			const idMatch = document.location.search.match(/\bid=([\w-]+)/);
			const ID = idMatch ? idMatch[1] : undefined;
M
Matt Bierner 已提交
323 324
			if (!document.body) {
				return;
325
			}
M
Matt Bierner 已提交
326

M
Matt Bierner 已提交
327 328 329
			host.onMessage('styles', (_event, data) => {
				initData.styles = data.styles;
				initData.activeTheme = data.activeTheme;
M
Matt Bierner 已提交
330

M
Matt Bierner 已提交
331 332 333 334
				const target = getActiveFrame();
				if (!target) {
					return;
				}
335

M
Matt Bierner 已提交
336 337
				if (target.contentDocument) {
					applyStyles(target.contentDocument, target.contentDocument.body);
338 339 340
				}
			});

M
Matt Bierner 已提交
341 342 343 344 345 346 347 348 349
			// propagate focus
			host.onMessage('focus', () => {
				const target = getActiveFrame();
				if (target) {
					target.contentWindow.focus();
				}
			});

			// update iframe-contents
350 351 352
			let updateId = 0;
			host.onMessage('content', async (_event, data) => {
				const currentUpdateId = ++updateId;
353
				await host.ready;
354 355 356 357
				if (currentUpdateId !== updateId) {
					return;
				}

M
Matt Bierner 已提交
358
				const options = data.options;
M
Matt Bierner 已提交
359
				const newDocument = toContentHtml(data);
M
Matt Bierner 已提交
360

M
Matt Bierner 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
				const frame = getActiveFrame();
				const wasFirstLoad = firstLoad;
				// keep current scrollY around and use later
				let setInitialScrollPosition;
				if (firstLoad) {
					firstLoad = false;
					setInitialScrollPosition = (body, window) => {
						if (!isNaN(initData.initialScrollProgress)) {
							if (window.scrollY === 0) {
								window.scroll(0, body.clientHeight * initData.initialScrollProgress);
							}
						}
					};
				} else {
					const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? frame.contentWindow.scrollY : 0;
					setInitialScrollPosition = (body, window) => {
377
						if (window.scrollY === 0) {
M
Matt Bierner 已提交
378
							window.scroll(0, scrollY);
379
						}
M
Matt Bierner 已提交
380 381
					};
				}
382

M
Matt Bierner 已提交
383 384 385 386 387 388 389 390 391
				// Clean up old pending frames and set current one as new one
				const previousPendingFrame = getPendingFrame();
				if (previousPendingFrame) {
					previousPendingFrame.setAttribute('id', '');
					document.body.removeChild(previousPendingFrame);
				}
				if (!wasFirstLoad) {
					pendingMessages = [];
				}
392

M
Matt Bierner 已提交
393 394 395 396
				const newFrame = document.createElement('iframe');
				newFrame.setAttribute('id', 'pending-frame');
				newFrame.setAttribute('frameborder', '0');
				newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin' : 'allow-same-origin');
397
				if (host.fakeLoad) {
398 399 400 401
					// We should just be able to use srcdoc, but I wasn't
					// seeing the service worker applying properly.
					// Fake load an empty on the correct origin and then write real html
					// into it to get around this.
402
					newFrame.src = `./fake.html?id=${ID}`;
403
				}
M
Matt Bierner 已提交
404 405
				newFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';
				document.body.appendChild(newFrame);
406

407
				if (!host.fakeLoad) {
408 409 410
					// write new content onto iframe
					newFrame.contentDocument.open();
				}
411

M
Matt Bierner 已提交
412
				newFrame.contentWindow.addEventListener('DOMContentLoaded', e => {
M
Matt Bierner 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425
					// Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=978325
					setTimeout(() => {
						if (host.fakeLoad) {
							newFrame.contentDocument.open();
							newFrame.contentDocument.write(newDocument);
							newFrame.contentDocument.close();
							hookupOnLoadHandlers(newFrame);
						}
						const contentDocument = e.target ? (/** @type {HTMLDocument} */ (e.target)) : undefined;
						if (contentDocument) {
							applyStyles(contentDocument, contentDocument.body);
						}
					}, 0);
M
Matt Bierner 已提交
426
				});
427

M
Matt Bierner 已提交
428 429 430 431 432
				const onLoad = (contentDocument, contentWindow) => {
					if (contentDocument && contentDocument.body) {
						// Workaround for https://github.com/Microsoft/vscode/issues/12865
						// check new scrollY and reset if neccessary
						setInitialScrollPosition(contentDocument.body, contentWindow);
433
					}
434

M
Matt Bierner 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447
					const newFrame = getPendingFrame();
					if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) {
						const oldActiveFrame = getActiveFrame();
						if (oldActiveFrame) {
							document.body.removeChild(oldActiveFrame);
						}
						// Styles may have changed since we created the element. Make sure we re-style
						applyStyles(newFrame.contentDocument, newFrame.contentDocument.body);
						newFrame.setAttribute('id', 'active-frame');
						newFrame.style.visibility = 'visible';
						if (host.focusIframeOnCreate) {
							newFrame.contentWindow.focus();
						}
448

M
Matt Bierner 已提交
449 450 451 452 453 454 455 456
						contentWindow.addEventListener('scroll', handleInnerScroll);

						pendingMessages.forEach((data) => {
							contentWindow.postMessage(data, '*');
						});
						pendingMessages = [];
					}
				};
457

458 459 460
				/**
				 * @param {HTMLIFrameElement} newFrame
				 */
461
				function hookupOnLoadHandlers(newFrame) {
462 463
					clearTimeout(loadTimeout);
					loadTimeout = undefined;
464
					loadTimeout = setTimeout(() => {
M
Matt Bierner 已提交
465 466
						clearTimeout(loadTimeout);
						loadTimeout = undefined;
467 468 469 470 471 472 473 474 475 476
						onLoad(newFrame.contentDocument, newFrame.contentWindow);
					}, 200);

					newFrame.contentWindow.addEventListener('load', function (e) {
						if (loadTimeout) {
							clearTimeout(loadTimeout);
							loadTimeout = undefined;
							onLoad(e.target, this);
						}
					});
477

478
					// Bubble out various events
479 480
					newFrame.contentWindow.addEventListener('click', handleInnerClick);
					newFrame.contentWindow.addEventListener('auxclick', handleAuxClick);
481
					newFrame.contentWindow.addEventListener('keydown', handleInnerKeydown);
482
					newFrame.contentWindow.addEventListener('contextmenu', e => e.preventDefault());
483

484 485 486
					if (host.onIframeLoaded) {
						host.onIframeLoaded(newFrame);
					}
487 488
				}

489
				if (!host.fakeLoad) {
490 491
					hookupOnLoadHandlers(newFrame);
				}
492

493
				if (!host.fakeLoad) {
M
Matt Bierner 已提交
494
					newFrame.contentDocument.write(newDocument);
495 496
					newFrame.contentDocument.close();
				}
497

M
Matt Bierner 已提交
498 499
				host.postMessage('did-set-content', undefined);
			});
M
Matt Bierner 已提交
500

M
Matt Bierner 已提交
501 502 503 504 505 506 507 508 509
			// Forward message to the embedded iframe
			host.onMessage('message', (_event, data) => {
				const pending = getPendingFrame();
				if (!pending) {
					const target = getActiveFrame();
					if (target) {
						target.contentWindow.postMessage(data, '*');
						return;
					}
510
				}
M
Matt Bierner 已提交
511 512
				pendingMessages.push(data);
			});
513

M
Matt Bierner 已提交
514 515 516
			host.onMessage('initial-scroll-position', (_event, progress) => {
				initData.initialScrollProgress = progress;
			});
517

518

M
Matt Bierner 已提交
519 520 521 522
			trackFocus({
				onFocus: () => host.postMessage('did-focus'),
				onBlur: () => host.postMessage('did-blur')
			});
M
Matt Bierner 已提交
523

M
Matt Bierner 已提交
524 525 526 527
			// signal ready
			host.postMessage('webview-ready', {});
		});
	}
528

M
Matt Bierner 已提交
529 530 531 532 533
	if (typeof module !== 'undefined') {
		module.exports = createWebviewManager;
	} else {
		window.createWebviewManager = createWebviewManager;
	}
534
}());