dom.ts 34.0 KB
Newer Older
E
Erich Gamma 已提交
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 * as platform from 'vs/base/common/platform';
J
Johannes Rieken 已提交
7 8
import { TimeoutTimer } from 'vs/base/common/async';
import { onUnexpectedError } from 'vs/base/common/errors';
9
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
10
import * as browser from 'vs/base/browser/browser';
J
Johannes Rieken 已提交
11 12 13
import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { CharCode } from 'vs/base/common/charCode';
M
Matt Bierner 已提交
14
import { Event, Emitter } from 'vs/base/common/event';
15
import { domEvent } from 'vs/base/browser/event';
E
Erich Gamma 已提交
16

B
Benjamin Pasero 已提交
17
export function clearNode(node: HTMLElement): void {
E
Erich Gamma 已提交
18 19 20 21 22
	while (node.firstChild) {
		node.removeChild(node.firstChild);
	}
}

A
Alex Dima 已提交
23
export function isInDOM(node: Node | null): boolean {
E
Erich Gamma 已提交
24 25 26 27 28 29 30 31 32
	while (node) {
		if (node === document.body) {
			return true;
		}
		node = node.parentNode;
	}
	return false;
}

A
Alex Dima 已提交
33 34 35
interface IDomClassList {
	hasClass(node: HTMLElement, className: string): boolean;
	addClass(node: HTMLElement, className: string): void;
36
	addClasses(node: HTMLElement, ...classNames: string[]): void;
A
Alex Dima 已提交
37
	removeClass(node: HTMLElement, className: string): void;
38
	removeClasses(node: HTMLElement, ...classNames: string[]): void;
A
Alex Dima 已提交
39 40 41 42
	toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void;
}

const _manualClassList = new class implements IDomClassList {
E
Erich Gamma 已提交
43

44 45
	private _lastStart: number;
	private _lastEnd: number;
E
Erich Gamma 已提交
46

47
	private _findClassName(node: HTMLElement, className: string): void {
E
Erich Gamma 已提交
48

49 50 51 52 53
		let classes = node.className;
		if (!classes) {
			this._lastStart = -1;
			return;
		}
E
Erich Gamma 已提交
54

55
		className = className.trim();
E
Erich Gamma 已提交
56

57 58
		let classesLen = classes.length,
			classLen = className.length;
E
Erich Gamma 已提交
59

60 61
		if (classLen === 0) {
			this._lastStart = -1;
E
Erich Gamma 已提交
62 63 64
			return;
		}

65 66
		if (classesLen < classLen) {
			this._lastStart = -1;
E
Erich Gamma 已提交
67 68 69
			return;
		}

70 71 72
		if (classes === className) {
			this._lastStart = 0;
			this._lastEnd = classesLen;
E
Erich Gamma 已提交
73 74
			return;
		}
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

		let idx = -1,
			idxEnd: number;

		while ((idx = classes.indexOf(className, idx + 1)) >= 0) {

			idxEnd = idx + classLen;

			// a class that is followed by another class
			if ((idx === 0 || classes.charCodeAt(idx - 1) === CharCode.Space) && classes.charCodeAt(idxEnd) === CharCode.Space) {
				this._lastStart = idx;
				this._lastEnd = idxEnd + 1;
				return;
			}

			// last class
			if (idx > 0 && classes.charCodeAt(idx - 1) === CharCode.Space && idxEnd === classesLen) {
				this._lastStart = idx - 1;
				this._lastEnd = idxEnd;
				return;
			}

			// equal - duplicate of cmp above
			if (idx === 0 && idxEnd === classesLen) {
				this._lastStart = 0;
				this._lastEnd = idxEnd;
				return;
			}
		}

		this._lastStart = -1;
E
Erich Gamma 已提交
106 107
	}

108 109 110 111
	hasClass(node: HTMLElement, className: string): boolean {
		this._findClassName(node, className);
		return this._lastStart !== -1;
	}
E
Erich Gamma 已提交
112

113 114 115 116
	addClasses(node: HTMLElement, ...classNames: string[]): void {
		classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.addClass(node, name)));
	}

117 118 119 120 121 122 123 124 125 126
	addClass(node: HTMLElement, className: string): void {
		if (!node.className) { // doesn't have it for sure
			node.className = className;
		} else {
			this._findClassName(node, className); // see if it's already there
			if (this._lastStart === -1) {
				node.className = node.className + ' ' + className;
			}
		}
	}
E
Erich Gamma 已提交
127

128 129 130 131 132 133
	removeClass(node: HTMLElement, className: string): void {
		this._findClassName(node, className);
		if (this._lastStart === -1) {
			return; // Prevent styles invalidation if not necessary
		} else {
			node.className = node.className.substring(0, this._lastStart) + node.className.substring(this._lastEnd);
E
Erich Gamma 已提交
134 135 136
		}
	}

137 138 139 140
	removeClasses(node: HTMLElement, ...classNames: string[]): void {
		classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.removeClass(node, name)));
	}

141 142 143 144 145 146 147 148
	toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void {
		this._findClassName(node, className);
		if (this._lastStart !== -1 && (shouldHaveIt === void 0 || !shouldHaveIt)) {
			this.removeClass(node, className);
		}
		if (this._lastStart === -1 && (shouldHaveIt === void 0 || shouldHaveIt)) {
			this.addClass(node, className);
		}
E
Erich Gamma 已提交
149
	}
150
};
E
Erich Gamma 已提交
151

A
Alex Dima 已提交
152
const _nativeClassList = new class implements IDomClassList {
153
	hasClass(node: HTMLElement, className: string): boolean {
A
Alex Dima 已提交
154
		return Boolean(className) && node.classList && node.classList.contains(className);
E
Erich Gamma 已提交
155
	}
156

157 158 159 160
	addClasses(node: HTMLElement, ...classNames: string[]): void {
		classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.addClass(node, name)));
	}

161
	addClass(node: HTMLElement, className: string): void {
J
Johannes Rieken 已提交
162 163 164
		if (className && node.classList) {
			node.classList.add(className);
		}
E
Erich Gamma 已提交
165
	}
166 167

	removeClass(node: HTMLElement, className: string): void {
J
Johannes Rieken 已提交
168 169 170
		if (className && node.classList) {
			node.classList.remove(className);
		}
171 172
	}

173 174 175 176
	removeClasses(node: HTMLElement, ...classNames: string[]): void {
		classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.removeClass(node, name)));
	}

177
	toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void {
J
Johannes Rieken 已提交
178 179 180
		if (node.classList) {
			node.classList.toggle(className, shouldHaveIt);
		}
181 182 183 184 185
	}
};

// In IE11 there is only partial support for `classList` which makes us keep our
// custom implementation. Otherwise use the native implementation, see: http://caniuse.com/#search=classlist
A
Alex Dima 已提交
186
const _classList: IDomClassList = browser.isIE ? _manualClassList : _nativeClassList;
187 188
export const hasClass: (node: HTMLElement, className: string) => boolean = _classList.hasClass.bind(_classList);
export const addClass: (node: HTMLElement, className: string) => void = _classList.addClass.bind(_classList);
189
export const addClasses: (node: HTMLElement, ...classNames: string[]) => void = _classList.addClasses.bind(_classList);
190
export const removeClass: (node: HTMLElement, className: string) => void = _classList.removeClass.bind(_classList);
191
export const removeClasses: (node: HTMLElement, ...classNames: string[]) => void = _classList.removeClasses.bind(_classList);
192
export const toggleClass: (node: HTMLElement, className: string, shouldHaveIt?: boolean) => void = _classList.toggleClass.bind(_classList);
E
Erich Gamma 已提交
193

A
Alex Dima 已提交
194
class DomListener implements IDisposable {
E
Erich Gamma 已提交
195

A
Alex Dima 已提交
196 197 198 199
	private _handler: (e: any) => void;
	private _node: Element | Window | Document;
	private readonly _type: string;
	private readonly _useCapture: boolean;
E
Erich Gamma 已提交
200

A
Alex Dima 已提交
201
	constructor(node: Element | Window | Document, type: string, handler: (e: any) => void, useCapture?: boolean) {
202 203
		this._node = node;
		this._type = type;
A
Alex Dima 已提交
204
		this._handler = handler;
205
		this._useCapture = (useCapture || false);
206
		this._node.addEventListener(this._type, this._handler, this._useCapture);
E
Erich Gamma 已提交
207 208
	}

209
	public dispose(): void {
A
Alex Dima 已提交
210
		if (!this._handler) {
211 212 213 214
			// Already disposed
			return;
		}

A
Alex Dima 已提交
215
		this._node.removeEventListener(this._type, this._handler, this._useCapture);
216 217

		// Prevent leakers from holding on to the dom or handler func
A
Alex Dima 已提交
218 219
		this._node = null!;
		this._handler = null!;
220
	}
E
Erich Gamma 已提交
221 222
}

223 224
export function addDisposableListener(node: Element | Window | Document, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
	return new DomListener(node, type, handler, useCapture);
E
Erich Gamma 已提交
225 226 227
}

export interface IAddStandardDisposableListenerSignature {
B
Benjamin Pasero 已提交
228
	(node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
A
Alex Dima 已提交
229
	(node: HTMLElement, type: 'mousedown', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
B
Benjamin Pasero 已提交
230 231 232 233
	(node: HTMLElement, type: 'keydown', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
	(node: HTMLElement, type: 'keypress', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
	(node: HTMLElement, type: 'keyup', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
	(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
E
Erich Gamma 已提交
234
}
B
Benjamin Pasero 已提交
235
function _wrapAsStandardMouseEvent(handler: (e: IMouseEvent) => void): (e: MouseEvent) => void {
236
	return function (e: MouseEvent) {
A
Cleanup  
Alex Dima 已提交
237
		return handler(new StandardMouseEvent(e));
E
Erich Gamma 已提交
238 239
	};
}
B
Benjamin Pasero 已提交
240
function _wrapAsStandardKeyboardEvent(handler: (e: IKeyboardEvent) => void): (e: KeyboardEvent) => void {
241
	return function (e: KeyboardEvent) {
A
Cleanup  
Alex Dima 已提交
242
		return handler(new StandardKeyboardEvent(e));
E
Erich Gamma 已提交
243 244
	};
}
B
Benjamin Pasero 已提交
245 246
export let addStandardDisposableListener: IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
	let wrapHandler = handler;
E
Erich Gamma 已提交
247

A
Alex Dima 已提交
248
	if (type === 'click' || type === 'mousedown') {
E
Erich Gamma 已提交
249 250 251 252 253
		wrapHandler = _wrapAsStandardMouseEvent(handler);
	} else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
		wrapHandler = _wrapAsStandardKeyboardEvent(handler);
	}

254
	return addDisposableListener(node, type, wrapHandler, useCapture);
E
Erich Gamma 已提交
255 256
};

257 258
export function addDisposableNonBubblingMouseOutListener(node: Element, handler: (event: MouseEvent) => void): IDisposable {
	return addDisposableListener(node, 'mouseout', (e: MouseEvent) => {
E
Erich Gamma 已提交
259
		// Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
A
Alex Dima 已提交
260
		let toElement: Node | null = <Node>(e.relatedTarget || e.toElement);
E
Erich Gamma 已提交
261 262 263 264 265 266 267 268 269 270 271
		while (toElement && toElement !== node) {
			toElement = toElement.parentNode;
		}
		if (toElement === node) {
			return;
		}

		handler(e);
	});
}

A
Alex Dima 已提交
272 273 274
interface IRequestAnimationFrame {
	(callback: (time: number) => void): number;
}
275
let _animationFrame: IRequestAnimationFrame | null = null;
A
Alex Dima 已提交
276 277
function doRequestAnimationFrame(callback: (time: number) => void): number {
	if (!_animationFrame) {
278
		const emulatedRequestAnimationFrame = (callback: (time: number) => void): any => {
A
Alex Dima 已提交
279 280 281 282 283 284 285 286 287 288 289
			return setTimeout(() => callback(new Date().getTime()), 0);
		};
		_animationFrame = (
			self.requestAnimationFrame
			|| (<any>self).msRequestAnimationFrame
			|| (<any>self).webkitRequestAnimationFrame
			|| (<any>self).mozRequestAnimationFrame
			|| (<any>self).oRequestAnimationFrame
			|| emulatedRequestAnimationFrame
		);
	}
A
Alex Dima 已提交
290
	return _animationFrame.call(self, callback);
A
Alex Dima 已提交
291
}
E
Erich Gamma 已提交
292 293 294 295 296 297 298

/**
 * Schedule a callback to be run at the next animation frame.
 * This allows multiple parties to register callbacks that should run at the next animation frame.
 * If currently in an animation frame, `runner` will be executed immediately.
 * @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
 */
B
Benjamin Pasero 已提交
299
export let runAtThisOrScheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
E
Erich Gamma 已提交
300 301 302 303 304 305
/**
 * Schedule a callback to be run at the next animation frame.
 * This allows multiple parties to register callbacks that should run at the next animation frame.
 * If currently in an animation frame, `runner` will be executed at the next animation frame.
 * @return token that can be used to cancel the scheduled runner.
 */
B
Benjamin Pasero 已提交
306
export let scheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
E
Erich Gamma 已提交
307

B
Benjamin Pasero 已提交
308
class AnimationFrameQueueItem implements IDisposable {
E
Erich Gamma 已提交
309 310 311 312 313

	private _runner: () => void;
	public priority: number;
	private _canceled: boolean;

A
Alex Dima 已提交
314
	constructor(runner: () => void, priority: number = 0) {
E
Erich Gamma 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
		this._runner = runner;
		this.priority = priority;
		this._canceled = false;
	}

	public dispose(): void {
		this._canceled = true;
	}

	public execute(): void {
		if (this._canceled) {
			return;
		}

		try {
			this._runner();
		} catch (e) {
B
Benjamin Pasero 已提交
332
			onUnexpectedError(e);
E
Erich Gamma 已提交
333 334 335 336 337 338 339 340 341
		}
	}

	// Sort by priority (largest to lowest)
	public static sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number {
		return b.priority - a.priority;
	}
}

342
(function () {
E
Erich Gamma 已提交
343 344 345
	/**
	 * The runners scheduled at the next animation frame
	 */
B
Benjamin Pasero 已提交
346
	let NEXT_QUEUE: AnimationFrameQueueItem[] = [];
E
Erich Gamma 已提交
347 348 349
	/**
	 * The runners scheduled at the current animation frame
	 */
350
	let CURRENT_QUEUE: AnimationFrameQueueItem[] | null = null;
E
Erich Gamma 已提交
351 352 353
	/**
	 * A flag to keep track if the native requestAnimationFrame was already called
	 */
B
Benjamin Pasero 已提交
354
	let animFrameRequested = false;
E
Erich Gamma 已提交
355 356 357
	/**
	 * A flag to indicate if currently handling a native requestAnimationFrame callback
	 */
B
Benjamin Pasero 已提交
358
	let inAnimationFrameRunner = false;
E
Erich Gamma 已提交
359

B
Benjamin Pasero 已提交
360
	let animationFrameRunner = () => {
E
Erich Gamma 已提交
361 362 363 364 365 366 367 368
		animFrameRequested = false;

		CURRENT_QUEUE = NEXT_QUEUE;
		NEXT_QUEUE = [];

		inAnimationFrameRunner = true;
		while (CURRENT_QUEUE.length > 0) {
			CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
A
Alex Dima 已提交
369
			let top = CURRENT_QUEUE.shift()!;
E
Erich Gamma 已提交
370 371 372 373 374
			top.execute();
		}
		inAnimationFrameRunner = false;
	};

B
Benjamin Pasero 已提交
375 376
	scheduleAtNextAnimationFrame = (runner: () => void, priority: number = 0) => {
		let item = new AnimationFrameQueueItem(runner, priority);
E
Erich Gamma 已提交
377 378 379 380
		NEXT_QUEUE.push(item);

		if (!animFrameRequested) {
			animFrameRequested = true;
A
Alex Dima 已提交
381
			doRequestAnimationFrame(animationFrameRunner);
E
Erich Gamma 已提交
382 383 384 385 386
		}

		return item;
	};

B
Benjamin Pasero 已提交
387
	runAtThisOrScheduleAtNextAnimationFrame = (runner: () => void, priority?: number) => {
E
Erich Gamma 已提交
388
		if (inAnimationFrameRunner) {
B
Benjamin Pasero 已提交
389
			let item = new AnimationFrameQueueItem(runner, priority);
A
Alex Dima 已提交
390
			CURRENT_QUEUE!.push(item);
E
Erich Gamma 已提交
391 392 393 394 395 396 397
			return item;
		} else {
			return scheduleAtNextAnimationFrame(runner, priority);
		}
	};
})();

398 399 400 401 402 403 404 405
export function measure(callback: () => void): IDisposable {
	return scheduleAtNextAnimationFrame(callback, 10000 /* must be early */);
}

export function modify(callback: () => void): IDisposable {
	return scheduleAtNextAnimationFrame(callback, -10000 /* must be late */);
}

A
Alex Dima 已提交
406 407 408
/**
 * Add a throttled listener. `handler` is fired at most every 16ms or with the next animation frame (if browser supports it).
 */
409
export interface IEventMerger<R, E> {
A
Alex Dima 已提交
410
	(lastEvent: R | null, currentEvent: E): R;
E
Erich Gamma 已提交
411 412
}

413 414 415 416 417
export interface DOMEvent {
	preventDefault(): void;
	stopPropagation(): void;
}

B
Benjamin Pasero 已提交
418
const MINIMUM_TIME_MS = 16;
419
const DEFAULT_EVENT_MERGER: IEventMerger<DOMEvent, DOMEvent> = function (lastEvent: DOMEvent, currentEvent: DOMEvent) {
E
Erich Gamma 已提交
420 421 422
	return currentEvent;
};

423
class TimeoutThrottledDomListener<R, E extends DOMEvent> extends Disposable {
E
Erich Gamma 已提交
424

425
	constructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger<R, E> = <any>DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) {
426
		super();
E
Erich Gamma 已提交
427

428
		let lastEvent: R | null = null;
429 430
		let lastHandlerTime = 0;
		let timeout = this._register(new TimeoutTimer());
E
Erich Gamma 已提交
431

432 433
		let invokeHandler = () => {
			lastHandlerTime = (new Date()).getTime();
A
Alex Dima 已提交
434
			handler(<R>lastEvent);
435 436
			lastEvent = null;
		};
E
Erich Gamma 已提交
437

438
		this._register(addDisposableListener(node, type, (e) => {
E
Erich Gamma 已提交
439

440 441 442 443 444 445 446 447 448 449 450
			lastEvent = eventMerger(lastEvent, e);
			let elapsedTime = (new Date()).getTime() - lastHandlerTime;

			if (elapsedTime >= minimumTimeMs) {
				timeout.cancel();
				invokeHandler();
			} else {
				timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
			}
		}));
	}
E
Erich Gamma 已提交
451 452
}

453
export function addDisposableThrottledListener<R, E extends DOMEvent = DOMEvent>(node: any, type: string, handler: (event: R) => void, eventMerger?: IEventMerger<R, E>, minimumTimeMs?: number): IDisposable {
454
	return new TimeoutThrottledDomListener<R, E>(node, type, handler, eventMerger, minimumTimeMs);
E
Erich Gamma 已提交
455 456
}

B
Benjamin Pasero 已提交
457
export function getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
A
Alex Dima 已提交
458
	return document.defaultView!.getComputedStyle(el, null);
E
Erich Gamma 已提交
459 460 461 462
}

// Adapted from WinJS
// Converts a CSS positioning string for the specified element to pixels.
463 464
const convertToPixels: (element: HTMLElement, value: string) => number = (function () {
	return function (element: HTMLElement, value: string): number {
E
Erich Gamma 已提交
465 466 467 468
		return parseFloat(value) || 0;
	};
})();

B
Benjamin Pasero 已提交
469 470 471
function getDimension(element: HTMLElement, cssPropertyName: string, jsPropertyName: string): number {
	let computedStyle: CSSStyleDeclaration = getComputedStyle(element);
	let value = '0';
E
Erich Gamma 已提交
472 473 474 475 476 477 478 479 480 481 482
	if (computedStyle) {
		if (computedStyle.getPropertyValue) {
			value = computedStyle.getPropertyValue(cssPropertyName);
		} else {
			// IE8
			value = (<any>computedStyle).getAttribute(jsPropertyName);
		}
	}
	return convertToPixels(element, value);
}

483 484 485 486 487 488 489 490 491 492 493 494
export function getClientArea(element: HTMLElement): Dimension {

	// Try with DOM clientWidth / clientHeight
	if (element !== document.body) {
		return new Dimension(element.clientWidth, element.clientHeight);
	}

	// Try innerWidth / innerHeight
	if (window.innerWidth && window.innerHeight) {
		return new Dimension(window.innerWidth, window.innerHeight);
	}

495 496
	// Try with document.body.clientWidth / document.body.clientHeight
	if (document.body && document.body.clientWidth && document.body.clientHeight) {
497 498 499 500 501 502 503 504 505 506 507
		return new Dimension(document.body.clientWidth, document.body.clientHeight);
	}

	// Try with document.documentElement.clientWidth / document.documentElement.clientHeight
	if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
		return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
	}

	throw new Error('Unable to figure out browser width and height');
}

B
Benjamin Pasero 已提交
508
const sizeUtils = {
E
Erich Gamma 已提交
509

510
	getBorderLeftWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
511 512
		return getDimension(element, 'border-left-width', 'borderLeftWidth');
	},
J
Joao Moreno 已提交
513 514 515
	getBorderRightWidth: function (element: HTMLElement): number {
		return getDimension(element, 'border-right-width', 'borderRightWidth');
	},
516
	getBorderTopWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
517 518
		return getDimension(element, 'border-top-width', 'borderTopWidth');
	},
519
	getBorderBottomWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
520 521 522
		return getDimension(element, 'border-bottom-width', 'borderBottomWidth');
	},

J
Joao Moreno 已提交
523 524 525 526 527 528
	getPaddingLeft: function (element: HTMLElement): number {
		return getDimension(element, 'padding-left', 'paddingLeft');
	},
	getPaddingRight: function (element: HTMLElement): number {
		return getDimension(element, 'padding-right', 'paddingRight');
	},
529
	getPaddingTop: function (element: HTMLElement): number {
E
Erich Gamma 已提交
530 531
		return getDimension(element, 'padding-top', 'paddingTop');
	},
532
	getPaddingBottom: function (element: HTMLElement): number {
E
Erich Gamma 已提交
533 534 535
		return getDimension(element, 'padding-bottom', 'paddingBottom');
	},

536
	getMarginLeft: function (element: HTMLElement): number {
E
Erich Gamma 已提交
537 538
		return getDimension(element, 'margin-left', 'marginLeft');
	},
539
	getMarginTop: function (element: HTMLElement): number {
E
Erich Gamma 已提交
540 541
		return getDimension(element, 'margin-top', 'marginTop');
	},
542
	getMarginRight: function (element: HTMLElement): number {
E
Erich Gamma 已提交
543 544
		return getDimension(element, 'margin-right', 'marginRight');
	},
545
	getMarginBottom: function (element: HTMLElement): number {
E
Erich Gamma 已提交
546 547 548 549 550 551 552 553
		return getDimension(element, 'margin-bottom', 'marginBottom');
	},
	__commaSentinel: false
};

// ----------------------------------------------------------------------------------------
// Position & Dimension

554 555 556 557 558 559 560 561
export class Dimension {
	public width: number;
	public height: number;

	constructor(width: number, height: number) {
		this.width = width;
		this.height = height;
	}
562 563 564 565 566 567 568 569 570 571

	static equals(a: Dimension, b: Dimension): boolean {
		if (a === b) {
			return true;
		}
		if (!a || !b) {
			return false;
		}
		return a.width === b.width && a.height === b.height;
	}
572 573
}

B
Benjamin Pasero 已提交
574
export function getTopLeftOffset(element: HTMLElement): { left: number; top: number; } {
E
Erich Gamma 已提交
575 576 577
	// Adapted from WinJS.Utilities.getPosition
	// and added borders to the mix

B
Benjamin Pasero 已提交
578
	let offsetParent = element.offsetParent, top = element.offsetTop, left = element.offsetLeft;
E
Erich Gamma 已提交
579 580 581

	while ((element = <HTMLElement>element.parentNode) !== null && element !== document.body && element !== document.documentElement) {
		top -= element.scrollTop;
B
Benjamin Pasero 已提交
582
		let c = getComputedStyle(element);
E
Erich Gamma 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
		if (c) {
			left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
		}

		if (element === offsetParent) {
			left += sizeUtils.getBorderLeftWidth(element);
			top += sizeUtils.getBorderTopWidth(element);
			top += element.offsetTop;
			left += element.offsetLeft;
			offsetParent = element.offsetParent;
		}
	}

	return {
		left: left,
		top: top
	};
}

602
export interface IDomNodePagePosition {
B
Benjamin Pasero 已提交
603 604 605 606
	left: number;
	top: number;
	width: number;
	height: number;
E
Erich Gamma 已提交
607 608
}

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
export function size(element: HTMLElement, width: number, height: number): void {
	if (typeof width === 'number') {
		element.style.width = `${width}px`;
	}

	if (typeof height === 'number') {
		element.style.height = `${height}px`;
	}
}

export function position(element: HTMLElement, top: number, right?: number, bottom?: number, left?: number, position: string = 'absolute'): void {
	if (typeof top === 'number') {
		element.style.top = `${top}px`;
	}

	if (typeof right === 'number') {
		element.style.right = `${right}px`;
	}

	if (typeof bottom === 'number') {
		element.style.bottom = `${bottom}px`;
	}

	if (typeof left === 'number') {
		element.style.left = `${left}px`;
	}

	element.style.position = position;
}

639 640 641 642 643
/**
 * Returns the position of a dom node relative to the entire page.
 */
export function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePosition {
	let bb = domNode.getBoundingClientRect();
E
Erich Gamma 已提交
644
	return {
645 646
		left: bb.left + StandardWindow.scrollX,
		top: bb.top + StandardWindow.scrollY,
647 648
		width: bb.width,
		height: bb.height
E
Erich Gamma 已提交
649 650 651
	};
}

652
export interface IStandardWindow {
653 654
	readonly scrollX: number;
	readonly scrollY: number;
655 656
}

657
export const StandardWindow: IStandardWindow = new class implements IStandardWindow {
658 659 660 661 662
	get scrollX(): number {
		if (typeof window.scrollX === 'number') {
			// modern browsers
			return window.scrollX;
		} else {
A
Alex Dima 已提交
663
			return document.body.scrollLeft + document.documentElement!.scrollLeft;
664 665 666 667 668 669 670 671
		}
	}

	get scrollY(): number {
		if (typeof window.scrollY === 'number') {
			// modern browsers
			return window.scrollY;
		} else {
A
Alex Dima 已提交
672
			return document.body.scrollTop + document.documentElement!.scrollTop;
673 674 675 676
		}
	}
};

E
Erich Gamma 已提交
677 678
// Adapted from WinJS
// Gets the width of the element, including margins.
B
Benjamin Pasero 已提交
679 680
export function getTotalWidth(element: HTMLElement): number {
	let margin = sizeUtils.getMarginLeft(element) + sizeUtils.getMarginRight(element);
E
Erich Gamma 已提交
681 682 683
	return element.offsetWidth + margin;
}

J
Joao Moreno 已提交
684 685 686 687 688 689
export function getContentWidth(element: HTMLElement): number {
	let border = sizeUtils.getBorderLeftWidth(element) + sizeUtils.getBorderRightWidth(element);
	let padding = sizeUtils.getPaddingLeft(element) + sizeUtils.getPaddingRight(element);
	return element.offsetWidth - border - padding;
}

690 691 692 693 694
export function getTotalScrollWidth(element: HTMLElement): number {
	let margin = sizeUtils.getMarginLeft(element) + sizeUtils.getMarginRight(element);
	return element.scrollWidth + margin;
}

E
Erich Gamma 已提交
695 696
// Adapted from WinJS
// Gets the height of the content of the specified element. The content height does not include borders or padding.
B
Benjamin Pasero 已提交
697 698 699
export function getContentHeight(element: HTMLElement): number {
	let border = sizeUtils.getBorderTopWidth(element) + sizeUtils.getBorderBottomWidth(element);
	let padding = sizeUtils.getPaddingTop(element) + sizeUtils.getPaddingBottom(element);
E
Erich Gamma 已提交
700 701 702 703 704
	return element.offsetHeight - border - padding;
}

// Adapted from WinJS
// Gets the height of the element, including its margins.
B
Benjamin Pasero 已提交
705 706
export function getTotalHeight(element: HTMLElement): number {
	let margin = sizeUtils.getMarginTop(element) + sizeUtils.getMarginBottom(element);
E
Erich Gamma 已提交
707 708 709 710
	return element.offsetHeight + margin;
}

// Gets the left coordinate of the specified element relative to the specified parent.
711
function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {
E
Erich Gamma 已提交
712 713 714 715
	if (element === null) {
		return 0;
	}

M
Maxime Quandalle 已提交
716 717 718
	let elementPosition = getTopLeftOffset(element);
	let parentPosition = getTopLeftOffset(parent);
	return elementPosition.left - parentPosition.left;
E
Erich Gamma 已提交
719 720
}

M
Maxime Quandalle 已提交
721 722
export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {
	let childWidths = children.map((child) => {
723
		return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;
M
Maxime Quandalle 已提交
724 725 726
	});
	let maxWidth = Math.max(...childWidths);
	return maxWidth;
E
Erich Gamma 已提交
727 728 729 730
}

// ----------------------------------------------------------------------------------------

A
Alex Dima 已提交
731
export function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean {
B
Benjamin Pasero 已提交
732
	while (testChild) {
E
Erich Gamma 已提交
733 734 735 736 737 738 739 740 741
		if (testChild === testAncestor) {
			return true;
		}
		testChild = testChild.parentNode;
	}

	return false;
}

A
Alex Dima 已提交
742
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null {
E
Erich Gamma 已提交
743 744 745 746 747
	while (node) {
		if (hasClass(node, clazz)) {
			return node;
		}

B
Benjamin Pasero 已提交
748 749 750 751 752 753 754 755 756 757
		if (stopAtClazzOrNode) {
			if (typeof stopAtClazzOrNode === 'string') {
				if (hasClass(node, stopAtClazzOrNode)) {
					return null;
				}
			} else {
				if (node === stopAtClazzOrNode) {
					return null;
				}
			}
E
Erich Gamma 已提交
758 759 760 761 762 763 764 765
		}

		node = <HTMLElement>node.parentNode;
	}

	return null;
}

766
export function createStyleSheet(container: HTMLElement = document.getElementsByTagName('head')[0]): HTMLStyleElement {
B
Benjamin Pasero 已提交
767
	let style = document.createElement('style');
E
Erich Gamma 已提交
768 769
	style.type = 'text/css';
	style.media = 'screen';
770
	container.appendChild(style);
E
Erich Gamma 已提交
771 772 773
	return style;
}

774
let _sharedStyleSheet: HTMLStyleElement | null = null;
A
Alex Dima 已提交
775 776 777 778 779 780
function getSharedStyleSheet(): HTMLStyleElement {
	if (!_sharedStyleSheet) {
		_sharedStyleSheet = createStyleSheet();
	}
	return _sharedStyleSheet;
}
E
Erich Gamma 已提交
781

B
Benjamin Pasero 已提交
782
function getDynamicStyleSheetRules(style: any) {
E
Erich Gamma 已提交
783 784 785 786 787 788 789 790 791 792 793
	if (style && style.sheet && style.sheet.rules) {
		// Chrome, IE
		return style.sheet.rules;
	}
	if (style && style.sheet && style.sheet.cssRules) {
		// FF
		return style.sheet.cssRules;
	}
	return [];
}

A
Alex Dima 已提交
794
export function createCSSRule(selector: string, cssText: string, style: HTMLStyleElement = getSharedStyleSheet()): void {
E
Erich Gamma 已提交
795 796 797 798
	if (!style || !cssText) {
		return;
	}

799
	(<CSSStyleSheet>style.sheet).insertRule(selector + '{' + cssText + '}', 0);
E
Erich Gamma 已提交
800 801
}

A
Alex Dima 已提交
802
export function removeCSSRulesContainingSelector(ruleName: string, style: HTMLStyleElement = getSharedStyleSheet()): void {
E
Erich Gamma 已提交
803 804 805 806
	if (!style) {
		return;
	}

B
Benjamin Pasero 已提交
807 808 809 810
	let rules = getDynamicStyleSheetRules(style);
	let toDelete: number[] = [];
	for (let i = 0; i < rules.length; i++) {
		let rule = rules[i];
811
		if (rule.selectorText.indexOf(ruleName) !== -1) {
E
Erich Gamma 已提交
812 813 814 815
			toDelete.push(i);
		}
	}

B
Benjamin Pasero 已提交
816
	for (let i = toDelete.length - 1; i >= 0; i--) {
A
Alex Dima 已提交
817
		(<any>style.sheet).deleteRule(toDelete[i]);
E
Erich Gamma 已提交
818 819 820
	}
}

B
Benjamin Pasero 已提交
821
export function isHTMLElement(o: any): o is HTMLElement {
822 823 824 825
	if (typeof HTMLElement === 'object') {
		return o instanceof HTMLElement;
	}
	return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
E
Erich Gamma 已提交
826 827
}

B
Benjamin Pasero 已提交
828
export const EventType = {
E
Erich Gamma 已提交
829 830 831 832 833 834 835 836
	// Mouse
	CLICK: 'click',
	DBLCLICK: 'dblclick',
	MOUSE_UP: 'mouseup',
	MOUSE_DOWN: 'mousedown',
	MOUSE_OVER: 'mouseover',
	MOUSE_MOVE: 'mousemove',
	MOUSE_OUT: 'mouseout',
837
	MOUSE_ENTER: 'mouseenter',
838
	MOUSE_LEAVE: 'mouseleave',
E
Erich Gamma 已提交
839
	CONTEXT_MENU: 'contextmenu',
B
Benjamin Pasero 已提交
840
	WHEEL: 'wheel',
E
Erich Gamma 已提交
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
	// Keyboard
	KEY_DOWN: 'keydown',
	KEY_PRESS: 'keypress',
	KEY_UP: 'keyup',
	// HTML Document
	LOAD: 'load',
	UNLOAD: 'unload',
	ABORT: 'abort',
	ERROR: 'error',
	RESIZE: 'resize',
	SCROLL: 'scroll',
	// Form
	SELECT: 'select',
	CHANGE: 'change',
	SUBMIT: 'submit',
	RESET: 'reset',
	FOCUS: 'focus',
858 859
	FOCUS_IN: 'focusin',
	FOCUS_OUT: 'focusout',
E
Erich Gamma 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872
	BLUR: 'blur',
	INPUT: 'input',
	// Local Storage
	STORAGE: 'storage',
	// Drag
	DRAG_START: 'dragstart',
	DRAG: 'drag',
	DRAG_ENTER: 'dragenter',
	DRAG_LEAVE: 'dragleave',
	DRAG_OVER: 'dragover',
	DROP: 'drop',
	DRAG_END: 'dragend',
	// Animation
A
Alex Dima 已提交
873 874 875
	ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',
	ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',
	ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
E
Erich Gamma 已提交
876 877
};

A
Alex Dima 已提交
878 879 880 881 882
export interface EventLike {
	preventDefault(): void;
	stopPropagation(): void;
}

B
Benjamin Pasero 已提交
883
export const EventHelper = {
884
	stop: function (e: EventLike, cancelBubble?: boolean) {
E
Erich Gamma 已提交
885 886 887 888 889 890 891 892 893 894 895 896
		if (e.preventDefault) {
			e.preventDefault();
		} else {
			// IE8
			(<any>e).returnValue = false;
		}

		if (cancelBubble) {
			if (e.stopPropagation) {
				e.stopPropagation();
			} else {
				// IE8
A
Alex Dima 已提交
897
				(<any>e).cancelBubble = true;
E
Erich Gamma 已提交
898 899 900 901 902 903
			}
		}
	}
};

export interface IFocusTracker {
904 905
	onDidFocus: Event<void>;
	onDidBlur: Event<void>;
B
Benjamin Pasero 已提交
906
	dispose(): void;
E
Erich Gamma 已提交
907 908
}

B
Benjamin Pasero 已提交
909 910 911
export function saveParentsScrollTop(node: Element): number[] {
	let r: number[] = [];
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
912 913 914 915 916 917
		r[i] = node.scrollTop;
		node = <Element>node.parentNode;
	}
	return r;
}

B
Benjamin Pasero 已提交
918 919
export function restoreParentsScrollTop(node: Element, state: number[]): void {
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
920 921 922 923 924 925 926
		if (node.scrollTop !== state[i]) {
			node.scrollTop = state[i];
		}
		node = <Element>node.parentNode;
	}
}

927
class FocusTracker implements IFocusTracker {
E
Erich Gamma 已提交
928

929 930
	private _onDidFocus = new Emitter<void>();
	readonly onDidFocus: Event<void> = this._onDidFocus.event;
E
Erich Gamma 已提交
931

932 933
	private _onDidBlur = new Emitter<void>();
	readonly onDidBlur: Event<void> = this._onDidBlur.event;
934

935 936 937
	private disposables: IDisposable[] = [];

	constructor(element: HTMLElement | Window) {
938
		let hasFocus = isAncestor(document.activeElement, <HTMLElement>element);
939 940
		let loosingFocus = false;

941
		let onFocus = () => {
942 943 944
			loosingFocus = false;
			if (!hasFocus) {
				hasFocus = true;
945
				this._onDidFocus.fire();
E
Erich Gamma 已提交
946
			}
947
		};
E
Erich Gamma 已提交
948

949
		let onBlur = () => {
950 951 952 953 954 955
			if (hasFocus) {
				loosingFocus = true;
				window.setTimeout(() => {
					if (loosingFocus) {
						loosingFocus = false;
						hasFocus = false;
956
						this._onDidBlur.fire();
957 958 959 960
					}
				}, 0);
			}
		};
E
Erich Gamma 已提交
961

962 963
		domEvent(element, EventType.FOCUS, true)(onFocus, null, this.disposables);
		domEvent(element, EventType.BLUR, true)(onBlur, null, this.disposables);
964
	}
E
Erich Gamma 已提交
965

966 967 968 969
	dispose(): void {
		this.disposables = dispose(this.disposables);
		this._onDidFocus.dispose();
		this._onDidBlur.dispose();
970 971 972
	}
}

973
export function trackFocus(element: HTMLElement | Window): IFocusTracker {
974
	return new FocusTracker(element);
E
Erich Gamma 已提交
975 976
}

J
Joao Moreno 已提交
977 978 979
export function append<T extends Node>(parent: HTMLElement, ...children: T[]): T {
	children.forEach(child => parent.appendChild(child));
	return children[children.length - 1];
E
Erich Gamma 已提交
980 981
}

982 983 984 985 986
export function prepend<T extends Node>(parent: HTMLElement, child: T): T {
	parent.insertBefore(child, parent.firstChild);
	return child;
}

B
Benjamin Pasero 已提交
987
const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/;
E
Erich Gamma 已提交
988

989
export function $<T extends HTMLElement>(description: string, attrs?: { [key: string]: any; }, ...children: (Node | string)[]): T {
B
Benjamin Pasero 已提交
990
	let match = SELECTOR_REGEX.exec(description);
E
Erich Gamma 已提交
991 992 993 994 995

	if (!match) {
		throw new Error('Bad use of emmet');
	}

B
Benjamin Pasero 已提交
996
	let result = document.createElement(match[1] || 'div');
J
Joao Moreno 已提交
997

A
Alex Dima 已提交
998 999 1000 1001 1002 1003
	if (match[3]) {
		result.id = match[3];
	}
	if (match[4]) {
		result.className = match[4].replace(/\./g, ' ').trim();
	}
E
Erich Gamma 已提交
1004

A
Alex Dima 已提交
1005 1006 1007
	attrs = attrs || {};
	Object.keys(attrs).forEach(name => {
		const value = attrs![name];
J
Joao Moreno 已提交
1008
		if (/^on\w+$/.test(name)) {
A
Alex Dima 已提交
1009
			(<any>result)[name] = value;
J
Joao Moreno 已提交
1010 1011 1012 1013 1014
		} else if (name === 'selected') {
			if (value) {
				result.setAttribute(name, 'true');
			}

J
Joao Moreno 已提交
1015
		} else {
A
Alex Dima 已提交
1016
			result.setAttribute(name, value);
J
Joao Moreno 已提交
1017 1018
		}
	});
J
Joao Moreno 已提交
1019

J
Joao Moreno 已提交
1020 1021 1022 1023 1024 1025 1026 1027 1028
	children
		.filter(child => !!child)
		.forEach(child => {
			if (child instanceof Node) {
				result.appendChild(child);
			} else {
				result.appendChild(document.createTextNode(child as string));
			}
		});
J
Joao Moreno 已提交
1029

J
Joao Moreno 已提交
1030
	return result as T;
A
Alex Dima 已提交
1031
}
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
export function join(nodes: Node[], separator: Node | string): Node[] {
	const result: Node[] = [];

	nodes.forEach((node, index) => {
		if (index > 0) {
			if (separator instanceof Node) {
				result.push(separator.cloneNode());
			} else {
				result.push(document.createTextNode(separator));
			}
		}

		result.push(node);
	});

	return result;
}

J
Joao Moreno 已提交
1051
export function show(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
1052
	for (let element of elements) {
S
Sandy Armstrong 已提交
1053
		element.style.display = '';
1054
		element.removeAttribute('aria-hidden');
J
Joao Moreno 已提交
1055
	}
1056 1057
}

J
Joao Moreno 已提交
1058
export function hide(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
1059
	for (let element of elements) {
J
Joao Moreno 已提交
1060
		element.style.display = 'none';
1061
		element.setAttribute('aria-hidden', 'true');
J
Joao Moreno 已提交
1062
	}
1063
}
1064

A
Alex Dima 已提交
1065
function findParentWithAttribute(node: Node | null, attribute: string): HTMLElement | null {
1066
	while (node) {
B
Benjamin Pasero 已提交
1067
		if (node instanceof HTMLElement && node.hasAttribute(attribute)) {
1068 1069 1070
			return node;
		}

B
Benjamin Pasero 已提交
1071
		node = node.parentNode;
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
	}

	return null;
}

export function removeTabIndexAndUpdateFocus(node: HTMLElement): void {
	if (!node || !node.hasAttribute('tabIndex')) {
		return;
	}

	// If we are the currently focused element and tabIndex is removed,
	// standard DOM behavior is to move focus to the <body> element. We
	// typically never want that, rather put focus to the closest element
	// in the hierarchy of the parent DOM nodes.
	if (document.activeElement === node) {
		let parentFocusable = findParentWithAttribute(node.parentElement, 'tabIndex');
		if (parentFocusable) {
			parentFocusable.focus();
		}
	}

B
fix npe  
Benjamin Pasero 已提交
1093
	node.removeAttribute('tabindex');
A
Alex Dima 已提交
1094
}
1095 1096 1097

export function getElementsByTagName(tag: string): HTMLElement[] {
	return Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
J
Joao Moreno 已提交
1098 1099
}

1100
export function finalHandler<T extends DOMEvent>(fn: (event: T) => any): (event: T) => any {
J
Joao Moreno 已提交
1101 1102 1103 1104 1105
	return e => {
		e.preventDefault();
		e.stopPropagation();
		fn(e);
	};
1106 1107
}

J
Johannes Rieken 已提交
1108 1109
export function domContentLoaded(): Promise<any> {
	return new Promise<any>(resolve => {
1110 1111
		const readyState = document.readyState;
		if (readyState === 'complete' || (document && document.body !== null)) {
J
Johannes Rieken 已提交
1112
			platform.setImmediate(resolve);
1113
		} else {
J
Johannes Rieken 已提交
1114
			window.addEventListener('DOMContentLoaded', resolve, false);
1115 1116
		}
	});
1117
}
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130

/**
 * Find a value usable for a dom node size such that the likelihood that it would be
 * displayed with constant screen pixels size is as high as possible.
 *
 * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio
 * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps"
 * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.
 */
export function computeScreenAwareSize(cssPx: number): number {
	const screenPx = window.devicePixelRatio * cssPx;
	return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
}
1131 1132 1133 1134 1135 1136 1137 1138 1139

/**
 * See https://github.com/Microsoft/monaco-editor/issues/601
 * To protect against malicious code in the linked site, particularly phishing attempts,
 * the window.opener should be set to null to prevent the linked site from having access
 * to change the location of the current page.
 * See https://mathiasbynens.github.io/rel-noopener/
 */
export function windowOpenNoOpener(url: string): void {
A
Alex Dima 已提交
1140
	if (platform.isNative || browser.isEdgeWebView) {
1141
		// In VSCode, window.open() always returns null...
A
Alex Dima 已提交
1142
		// The same is true for a WebView (see https://github.com/Microsoft/monaco-editor/issues/628)
1143 1144 1145 1146
		window.open(url);
	} else {
		let newTab = window.open();
		if (newTab) {
M
Matt Bierner 已提交
1147
			(newTab as any).opener = null;
1148 1149 1150
			newTab.location.href = url;
		}
	}
1151
}