index.ts 7.8 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import { getSettings } from './settings';
7
import { postCommand, postMessage } from './messaging';
8

9 10 11 12 13 14 15 16 17 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 54 55 56 57 58 59 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 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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
// From https://remysharp.com/2010/07/21/throttling-function-calls
function throttle(fn: (x: any) => any, threshhold: any, scope?: any) {
	threshhold = threshhold || (threshhold = 250);
	var last: any, deferTimer: any;
	return function (...x: any[]) {
		var context = scope || this;

		var now = +new Date,
			args = arguments;
		if (last && now < last + threshhold) {
			// hold on to it
			clearTimeout(deferTimer);
			deferTimer = setTimeout(function () {
				last = now;
				fn.apply(context, args);
			}, threshhold + last - now);
		} else {
			last = now;
			fn.apply(context, args);
		}
	};
}

function clamp(min: number, max: number, value: number) {
	return Math.min(max, Math.max(min, value));
}

function clampLine(line: number) {
	return clamp(0, settings.lineCount - 1, line);
}


interface CodeLineElement {
	element: HTMLElement;
	line: number;
}

const getCodeLineElements = (() => {
	let elements: CodeLineElement[];
	return () => {
		if (!elements) {
			elements = Array.prototype.map.call(
				document.getElementsByClassName('code-line'),
				(element: any) => {
					const line = +element.getAttribute('data-line');
					return { element, line };
				})
				.filter((x: any) => !isNaN(x.line));
		}
		return elements;
	};
})();

/**
 * Find the html elements that map to a specific target line in the editor.
 *
 * If an exact match, returns a single element. If the line is between elements,
 * returns the element prior to and the element after the given line.
 */
function getElementsForSourceLine(targetLine: number): { previous: CodeLineElement; next?: CodeLineElement; } {
	const lineNumber = Math.floor(targetLine);
	const lines = getCodeLineElements();
	let previous = lines[0] || null;
	for (const entry of lines) {
		if (entry.line === lineNumber) {
			return { previous: entry, next: null };
		}
		else if (entry.line > lineNumber) {
			return { previous, next: entry };
		}
		previous = entry;
	}
	return { previous };
}

/**
 * Find the html elements that are at a specific pixel offset on the page.
 */
function getLineElementsAtPageOffset(offset: number): { previous: CodeLineElement; next?: CodeLineElement; } {
	const lines = getCodeLineElements();
	const position = offset - window.scrollY;
	let lo = -1;
	let hi = lines.length - 1;
	while (lo + 1 < hi) {
		const mid = Math.floor((lo + hi) / 2);
		const bounds = lines[mid].element.getBoundingClientRect();
		if (bounds.top + bounds.height >= position) {
			hi = mid;
		}
		else {
			lo = mid;
		}
	}
	const hiElement = lines[hi];
	const hiBounds = hiElement.element.getBoundingClientRect();
	if (hi >= 1 && hiBounds.top > position) {
		const loElement = lines[lo];
		return { previous: loElement, next: hiElement };
	}
	return { previous: hiElement };
}

/**
 * Attempt to reveal the element for a source line in the editor.
 */
function scrollToRevealSourceLine(line: number) {
	const { previous, next } = getElementsForSourceLine(line);
	if (previous && settings.scrollPreviewWithEditor) {
		let scrollTo = 0;
		const rect = previous.element.getBoundingClientRect();
		const previousTop = rect.top;
		if (next && next.line !== previous.line) {
			// Between two elements. Go to percentage offset between them.
			const betweenProgress = (line - previous.line) / (next.line - previous.line);
			const elementOffset = next.element.getBoundingClientRect().top - previousTop;
			scrollTo = previousTop + betweenProgress * elementOffset;
		}
		else {
			scrollTo = previousTop;
		}
		window.scroll(0, Math.max(1, window.scrollY + scrollTo));
	}
}

function getEditorLineNumberForPageOffset(offset: number) {
	const { previous, next } = getLineElementsAtPageOffset(offset);
	if (previous) {
		const previousBounds = previous.element.getBoundingClientRect();
		const offsetFromPrevious = (offset - window.scrollY - previousBounds.top);
		if (next) {
			const progressBetweenElements = offsetFromPrevious / (next.element.getBoundingClientRect().top - previousBounds.top);
			const line = previous.line + progressBetweenElements * (next.line - previous.line);
			return clampLine(line);
		}
		else {
			const progressWithinElement = offsetFromPrevious / (previousBounds.height);
			const line = previous.line + progressWithinElement;
			return clampLine(line);
		}
	}
	return null;
}

class ActiveLineMarker {
	private _current: any;

	onDidChangeTextEditorSelection(line: number) {
		const { previous } = getElementsForSourceLine(line);
		this._update(previous && previous.element);
	}

	_update(before: HTMLElement | undefined) {
		this._unmarkActiveElement(this._current);
		this._markActiveElement(before);
		this._current = before;
	}

	_unmarkActiveElement(element: HTMLElement) {
		if (!element) {
			return;
		}
		element.className = element.className.replace(/\bcode-active-line\b/g, '');
	}

	_markActiveElement(element: HTMLElement) {
		if (!element) {
			return;
		}
		element.className += ' code-active-line';
	}
}

var scrollDisabled = true;
const marker = new ActiveLineMarker();
183
const settings = getSettings();
184 185 186 187 188 189 190 191 192 193 194 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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

function onLoad() {
	if (settings.scrollPreviewWithEditor) {
		setTimeout(() => {
			const initialLine = +settings.line;
			if (!isNaN(initialLine)) {
				scrollDisabled = true;
				scrollToRevealSourceLine(initialLine);
			}
		}, 0);
	}
}

const onUpdateView = (() => {
	const doScroll = throttle((line: number) => {
		scrollDisabled = true;
		scrollToRevealSourceLine(line);
	}, 50);

	return (line: number, settings: any) => {
		if (!isNaN(line)) {
			settings.line = line;
			doScroll(line);
		}
	};
})();


if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
	document.addEventListener('DOMContentLoaded', onLoad);
} else {
	onLoad();
}


window.addEventListener('resize', () => {
	scrollDisabled = true;
}, true);

window.addEventListener('message', event => {
	if (event.data.source !== settings.source) {
		return;
	}

	switch (event.data.type) {
		case 'onDidChangeTextEditorSelection':
			marker.onDidChangeTextEditorSelection(event.data.line);
			break;

		case 'updateView':
			onUpdateView(event.data.line, settings);
			break;
	}
}, false);

document.addEventListener('dblclick', event => {
	if (!settings.doubleClickToSwitchToEditor) {
		return;
	}

	// Ignore clicks on links
	for (let node = event.target as HTMLElement; node; node = node.parentNode as HTMLElement) {
		if (node.tagName === 'A') {
			return;
		}
	}

	const offset = event.pageY;
	const line = getEditorLineNumberForPageOffset(offset);
	if (!isNaN(line)) {
		postMessage('didClick', { line });
	}
});

document.addEventListener('click', event => {
	if (!event) {
		return;
	}

	const baseElement = document.getElementsByTagName('base')[0];

	let node: any = event.target;
	while (node) {
		if (node.tagName && node.tagName === 'A' && node.href) {
			if (node.getAttribute('href').startsWith('#')) {
				break;
			}
			if (node.href.startsWith('file://') || node.href.startsWith('vscode-workspace-resource:')) {
				const [path, fragment] = node.href.replace(/^(file:\/\/|vscode-workspace-resource:)/i, '').split('#');
				postCommand('_markdown.openDocumentLink', [{ path, fragment }]);
				event.preventDefault();
				event.stopPropagation();
				break;
			}
			break;
		}
		node = node.parentNode;
	}
}, true);

if (settings.scrollEditorWithPreview) {
	window.addEventListener('scroll', throttle(() => {
		if (scrollDisabled) {
			scrollDisabled = false;
		} else {
			const line = getEditorLineNumberForPageOffset(window.scrollY);
			if (!isNaN(line)) {
				postMessage('revealLine', { line });
			}
		}
	}, 50));
}