dom.ts 30.1 KB
Newer Older
E
Erich Gamma 已提交
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.
 *--------------------------------------------------------------------------------------------*/
'use strict';

J
Johannes Rieken 已提交
7 8 9 10 11 12
import { TPromise } from 'vs/base/common/winjs.base';
import { TimeoutTimer } from 'vs/base/common/async';
import { onUnexpectedError } from 'vs/base/common/errors';
import { EventEmitter } from 'vs/base/common/eventEmitter';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { isObject } from 'vs/base/common/types';
A
Alex Dima 已提交
13
import * as browser from 'vs/base/browser/browser';
J
Johannes Rieken 已提交
14 15 16
import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { CharCode } from 'vs/base/common/charCode';
E
Erich Gamma 已提交
17

B
Benjamin Pasero 已提交
18
export function clearNode(node: HTMLElement) {
E
Erich Gamma 已提交
19 20 21 22 23 24 25 26 27 28
	while (node.firstChild) {
		node.removeChild(node.firstChild);
	}
}

/**
 * Calls JSON.Stringify with a replacer to break apart any circular references.
 * This prevents JSON.stringify from throwing the exception
 *  "Uncaught TypeError: Converting circular structure to JSON"
 */
B
Benjamin Pasero 已提交
29 30
export function safeStringifyDOMAware(obj: any): string {
	let seen: any[] = [];
E
Erich Gamma 已提交
31 32 33
	return JSON.stringify(obj, (key, value) => {

		// HTML elements are never going to serialize nicely
B
Benjamin Pasero 已提交
34
		if (value instanceof Element) {
E
Erich Gamma 已提交
35 36 37
			return '[Element]';
		}

A
Alex Dima 已提交
38
		if (isObject(value) || Array.isArray(value)) {
B
Benjamin Pasero 已提交
39
			if (seen.indexOf(value) !== -1) {
E
Erich Gamma 已提交
40 41 42 43 44 45 46 47 48
				return '[Circular]';
			} else {
				seen.push(value);
			}
		}
		return value;
	});
}

B
Benjamin Pasero 已提交
49
export function isInDOM(node: Node): boolean {
E
Erich Gamma 已提交
50 51 52 53 54 55 56 57 58
	while (node) {
		if (node === document.body) {
			return true;
		}
		node = node.parentNode;
	}
	return false;
}

59
const _manualClassList = new class {
E
Erich Gamma 已提交
60

61 62
	private _lastStart: number;
	private _lastEnd: number;
E
Erich Gamma 已提交
63

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

66 67 68 69 70
		let classes = node.className;
		if (!classes) {
			this._lastStart = -1;
			return;
		}
E
Erich Gamma 已提交
71

72
		className = className.trim();
E
Erich Gamma 已提交
73

74 75
		let classesLen = classes.length,
			classLen = className.length;
E
Erich Gamma 已提交
76

77 78
		if (classLen === 0) {
			this._lastStart = -1;
E
Erich Gamma 已提交
79 80 81
			return;
		}

82 83
		if (classesLen < classLen) {
			this._lastStart = -1;
E
Erich Gamma 已提交
84 85 86
			return;
		}

87 88 89
		if (classes === className) {
			this._lastStart = 0;
			this._lastEnd = classesLen;
E
Erich Gamma 已提交
90 91
			return;
		}
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

		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 已提交
123 124
	}

125 126 127 128
	hasClass(node: HTMLElement, className: string): boolean {
		this._findClassName(node, className);
		return this._lastStart !== -1;
	}
E
Erich Gamma 已提交
129

130 131 132 133 134 135 136 137 138 139
	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 已提交
140

141 142 143 144 145 146
	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 已提交
147 148 149
		}
	}

150 151 152 153 154 155 156 157
	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 已提交
158
	}
159
};
E
Erich Gamma 已提交
160

161 162
const _nativeClassList = new class {
	hasClass(node: HTMLElement, className: string): boolean {
J
Johannes Rieken 已提交
163
		return className && node.classList && node.classList.contains(className);
E
Erich Gamma 已提交
164
	}
165 166

	addClass(node: HTMLElement, className: string): void {
J
Johannes Rieken 已提交
167 168 169
		if (className && node.classList) {
			node.classList.add(className);
		}
E
Erich Gamma 已提交
170
	}
171 172

	removeClass(node: HTMLElement, className: string): void {
J
Johannes Rieken 已提交
173 174 175
		if (className && node.classList) {
			node.classList.remove(className);
		}
176 177 178
	}

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

// 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
const _classList = browser.isIE ? _manualClassList : _nativeClassList;
export const hasClass: (node: HTMLElement, className: string) => boolean = _classList.hasClass.bind(_classList);
export const addClass: (node: HTMLElement, className: string) => void = _classList.addClass.bind(_classList);
export const removeClass: (node: HTMLElement, className: string) => void = _classList.removeClass.bind(_classList);
export const toggleClass: (node: HTMLElement, className: string, shouldHaveIt?: boolean) => void = _classList.toggleClass.bind(_classList);
E
Erich Gamma 已提交
192

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

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

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

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

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

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

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

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

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

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

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

		handler(e);
	});
}

271
const _animationFrame = (function () {
B
Benjamin Pasero 已提交
272
	let emulatedRequestAnimationFrame = (callback: (time: number) => void): number => {
E
Erich Gamma 已提交
273 274
		return setTimeout(() => callback(new Date().getTime()), 0);
	};
B
Benjamin Pasero 已提交
275 276 277 278 279 280
	let nativeRequestAnimationFrame: (callback: (time: number) => void) => number =
		self.requestAnimationFrame
		|| (<any>self).msRequestAnimationFrame
		|| (<any>self).webkitRequestAnimationFrame
		|| (<any>self).mozRequestAnimationFrame
		|| (<any>self).oRequestAnimationFrame;
E
Erich Gamma 已提交
281 282 283



B
Benjamin Pasero 已提交
284 285 286 287 288 289 290
	let emulatedCancelAnimationFrame = (id: number) => { };
	let nativeCancelAnimationFrame: (id: number) => void =
		self.cancelAnimationFrame || (<any>self).cancelRequestAnimationFrame
		|| (<any>self).msCancelAnimationFrame || (<any>self).msCancelRequestAnimationFrame
		|| (<any>self).webkitCancelAnimationFrame || (<any>self).webkitCancelRequestAnimationFrame
		|| (<any>self).mozCancelAnimationFrame || (<any>self).mozCancelRequestAnimationFrame
		|| (<any>self).oCancelAnimationFrame || (<any>self).oCancelRequestAnimationFrame;
E
Erich Gamma 已提交
291

B
Benjamin Pasero 已提交
292 293
	let isNative = !!nativeRequestAnimationFrame;
	let request = nativeRequestAnimationFrame || emulatedRequestAnimationFrame;
A
Alex Dima 已提交
294
	let cancel = nativeCancelAnimationFrame || emulatedCancelAnimationFrame;
E
Erich Gamma 已提交
295 296 297

	return {
		isNative: isNative,
B
Benjamin Pasero 已提交
298
		request: (callback: (time: number) => void): number => {
E
Erich Gamma 已提交
299 300
			return request(callback);
		},
B
Benjamin Pasero 已提交
301
		cancel: (id: number) => {
E
Erich Gamma 已提交
302 303 304 305 306 307 308 309 310 311 312
			return cancel(id);
		}
	};
})();

/**
 * 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 已提交
313
export let runAtThisOrScheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
E
Erich Gamma 已提交
314 315 316 317 318 319
/**
 * 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 已提交
320
export let scheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
E
Erich Gamma 已提交
321

B
Benjamin Pasero 已提交
322
class AnimationFrameQueueItem implements IDisposable {
E
Erich Gamma 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

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

	constructor(runner: () => void, priority: number) {
		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 已提交
346
			onUnexpectedError(e);
E
Erich Gamma 已提交
347 348 349 350 351 352 353 354 355
		}
	}

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

356
(function () {
E
Erich Gamma 已提交
357 358 359
	/**
	 * The runners scheduled at the next animation frame
	 */
B
Benjamin Pasero 已提交
360
	let NEXT_QUEUE: AnimationFrameQueueItem[] = [];
E
Erich Gamma 已提交
361 362 363
	/**
	 * The runners scheduled at the current animation frame
	 */
B
Benjamin Pasero 已提交
364
	let CURRENT_QUEUE: AnimationFrameQueueItem[] = null;
E
Erich Gamma 已提交
365 366 367
	/**
	 * A flag to keep track if the native requestAnimationFrame was already called
	 */
B
Benjamin Pasero 已提交
368
	let animFrameRequested = false;
E
Erich Gamma 已提交
369 370 371
	/**
	 * A flag to indicate if currently handling a native requestAnimationFrame callback
	 */
B
Benjamin Pasero 已提交
372
	let inAnimationFrameRunner = false;
E
Erich Gamma 已提交
373

B
Benjamin Pasero 已提交
374
	let animationFrameRunner = () => {
E
Erich Gamma 已提交
375 376 377 378 379 380 381 382
		animFrameRequested = false;

		CURRENT_QUEUE = NEXT_QUEUE;
		NEXT_QUEUE = [];

		inAnimationFrameRunner = true;
		while (CURRENT_QUEUE.length > 0) {
			CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
B
Benjamin Pasero 已提交
383
			let top = CURRENT_QUEUE.shift();
E
Erich Gamma 已提交
384 385 386 387 388
			top.execute();
		}
		inAnimationFrameRunner = false;
	};

B
Benjamin Pasero 已提交
389 390
	scheduleAtNextAnimationFrame = (runner: () => void, priority: number = 0) => {
		let item = new AnimationFrameQueueItem(runner, priority);
E
Erich Gamma 已提交
391 392 393 394
		NEXT_QUEUE.push(item);

		if (!animFrameRequested) {
			animFrameRequested = true;
A
Alex Dima 已提交
395
			_animationFrame.request(animationFrameRunner);
E
Erich Gamma 已提交
396 397 398 399 400
		}

		return item;
	};

B
Benjamin Pasero 已提交
401
	runAtThisOrScheduleAtNextAnimationFrame = (runner: () => void, priority?: number) => {
E
Erich Gamma 已提交
402
		if (inAnimationFrameRunner) {
B
Benjamin Pasero 已提交
403
			let item = new AnimationFrameQueueItem(runner, priority);
E
Erich Gamma 已提交
404 405 406 407 408 409 410 411
			CURRENT_QUEUE.push(item);
			return item;
		} else {
			return scheduleAtNextAnimationFrame(runner, priority);
		}
	};
})();

A
Alex Dima 已提交
412 413 414
/**
 * Add a throttled listener. `handler` is fired at most every 16ms or with the next animation frame (if browser supports it).
 */
E
Erich Gamma 已提交
415
export interface IEventMerger<R> {
B
Benjamin Pasero 已提交
416
	(lastEvent: R, currentEvent: Event): R;
E
Erich Gamma 已提交
417 418
}

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

424
class TimeoutThrottledDomListener<R> extends Disposable {
E
Erich Gamma 已提交
425

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

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

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

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

441 442 443 444 445 446 447 448 449 450 451
			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 已提交
452 453
}

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

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

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

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

B
Benjamin Pasero 已提交
484
const sizeUtils = {
E
Erich Gamma 已提交
485

486
	getBorderLeftWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
487 488
		return getDimension(element, 'border-left-width', 'borderLeftWidth');
	},
489
	getBorderTopWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
490 491
		return getDimension(element, 'border-top-width', 'borderTopWidth');
	},
492
	getBorderRightWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
493 494
		return getDimension(element, 'border-right-width', 'borderRightWidth');
	},
495
	getBorderBottomWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
496 497 498
		return getDimension(element, 'border-bottom-width', 'borderBottomWidth');
	},

499
	getPaddingLeft: function (element: HTMLElement): number {
E
Erich Gamma 已提交
500 501
		return getDimension(element, 'padding-left', 'paddingLeft');
	},
502
	getPaddingTop: function (element: HTMLElement): number {
E
Erich Gamma 已提交
503 504
		return getDimension(element, 'padding-top', 'paddingTop');
	},
505
	getPaddingRight: function (element: HTMLElement): number {
E
Erich Gamma 已提交
506 507
		return getDimension(element, 'padding-right', 'paddingRight');
	},
508
	getPaddingBottom: function (element: HTMLElement): number {
E
Erich Gamma 已提交
509 510 511
		return getDimension(element, 'padding-bottom', 'paddingBottom');
	},

512
	getMarginLeft: function (element: HTMLElement): number {
E
Erich Gamma 已提交
513 514
		return getDimension(element, 'margin-left', 'marginLeft');
	},
515
	getMarginTop: function (element: HTMLElement): number {
E
Erich Gamma 已提交
516 517
		return getDimension(element, 'margin-top', 'marginTop');
	},
518
	getMarginRight: function (element: HTMLElement): number {
E
Erich Gamma 已提交
519 520
		return getDimension(element, 'margin-right', 'marginRight');
	},
521
	getMarginBottom: function (element: HTMLElement): number {
E
Erich Gamma 已提交
522 523 524 525 526 527 528 529
		return getDimension(element, 'margin-bottom', 'marginBottom');
	},
	__commaSentinel: false
};

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

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

B
Benjamin Pasero 已提交
534
	let offsetParent = element.offsetParent, top = element.offsetTop, left = element.offsetLeft;
E
Erich Gamma 已提交
535 536 537

	while ((element = <HTMLElement>element.parentNode) !== null && element !== document.body && element !== document.documentElement) {
		top -= element.scrollTop;
B
Benjamin Pasero 已提交
538
		let c = getComputedStyle(element);
E
Erich Gamma 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
		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
	};
}

558
export interface IDomNodePagePosition {
B
Benjamin Pasero 已提交
559 560 561 562
	left: number;
	top: number;
	width: number;
	height: number;
E
Erich Gamma 已提交
563 564
}

565 566 567 568 569
/**
 * 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 已提交
570
	return {
571 572
		left: bb.left + StandardWindow.scrollX,
		top: bb.top + StandardWindow.scrollY,
573 574
		width: bb.width,
		height: bb.height
E
Erich Gamma 已提交
575 576 577
	};
}

578 579 580 581 582
export interface IStandardWindow {
	scrollX: number;
	scrollY: number;
}

583
export const StandardWindow: IStandardWindow = new class {
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
	get scrollX(): number {
		if (typeof window.scrollX === 'number') {
			// modern browsers
			return window.scrollX;
		} else {
			return document.body.scrollLeft + document.documentElement.scrollLeft;
		}
	}

	get scrollY(): number {
		if (typeof window.scrollY === 'number') {
			// modern browsers
			return window.scrollY;
		} else {
			return document.body.scrollTop + document.documentElement.scrollTop;
		}
	}
};

E
Erich Gamma 已提交
603 604
// Adapted from WinJS
// Gets the width of the content of the specified element. The content width does not include borders or padding.
B
Benjamin Pasero 已提交
605 606 607
export function getContentWidth(element: HTMLElement): number {
	let border = sizeUtils.getBorderLeftWidth(element) + sizeUtils.getBorderRightWidth(element);
	let padding = sizeUtils.getPaddingLeft(element) + sizeUtils.getPaddingRight(element);
E
Erich Gamma 已提交
608 609 610 611 612
	return element.offsetWidth - border - padding;
}

// Adapted from WinJS
// Gets the width of the element, including margins.
B
Benjamin Pasero 已提交
613 614
export function getTotalWidth(element: HTMLElement): number {
	let margin = sizeUtils.getMarginLeft(element) + sizeUtils.getMarginRight(element);
E
Erich Gamma 已提交
615 616 617
	return element.offsetWidth + margin;
}

618 619 620 621 622
export function getTotalScrollWidth(element: HTMLElement): number {
	let margin = sizeUtils.getMarginLeft(element) + sizeUtils.getMarginRight(element);
	return element.scrollWidth + margin;
}

E
Erich Gamma 已提交
623 624
// 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 已提交
625 626 627
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 已提交
628 629 630 631 632
	return element.offsetHeight - border - padding;
}

// Adapted from WinJS
// Gets the height of the element, including its margins.
B
Benjamin Pasero 已提交
633 634
export function getTotalHeight(element: HTMLElement): number {
	let margin = sizeUtils.getMarginTop(element) + sizeUtils.getMarginBottom(element);
E
Erich Gamma 已提交
635 636 637 638
	return element.offsetHeight + margin;
}

// Gets the left coordinate of the specified element relative to the specified parent.
639
function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {
E
Erich Gamma 已提交
640 641 642 643
	if (element === null) {
		return 0;
	}

M
Maxime Quandalle 已提交
644 645 646
	let elementPosition = getTopLeftOffset(element);
	let parentPosition = getTopLeftOffset(parent);
	return elementPosition.left - parentPosition.left;
E
Erich Gamma 已提交
647 648
}

M
Maxime Quandalle 已提交
649 650
export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {
	let childWidths = children.map((child) => {
651
		return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;
M
Maxime Quandalle 已提交
652 653 654
	});
	let maxWidth = Math.max(...childWidths);
	return maxWidth;
E
Erich Gamma 已提交
655 656 657 658
}

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

B
Benjamin Pasero 已提交
659 660
export function isAncestor(testChild: Node, testAncestor: Node): boolean {
	while (testChild) {
E
Erich Gamma 已提交
661 662 663 664 665 666 667 668 669
		if (testChild === testAncestor) {
			return true;
		}
		testChild = testChild.parentNode;
	}

	return false;
}

B
Benjamin Pasero 已提交
670
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazz?: string): HTMLElement {
E
Erich Gamma 已提交
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
	while (node) {
		if (hasClass(node, clazz)) {
			return node;
		}

		if (stopAtClazz && hasClass(node, stopAtClazz)) {
			return null;
		}

		node = <HTMLElement>node.parentNode;
	}

	return null;
}

686
export function createStyleSheet(container: HTMLElement = document.getElementsByTagName('head')[0]): HTMLStyleElement {
B
Benjamin Pasero 已提交
687
	let style = document.createElement('style');
E
Erich Gamma 已提交
688 689
	style.type = 'text/css';
	style.media = 'screen';
690
	container.appendChild(style);
E
Erich Gamma 已提交
691 692 693
	return style;
}

B
Benjamin Pasero 已提交
694
const sharedStyle = <any>createStyleSheet();
E
Erich Gamma 已提交
695

B
Benjamin Pasero 已提交
696
function getDynamicStyleSheetRules(style: any) {
E
Erich Gamma 已提交
697 698 699 700 701 702 703 704 705 706 707
	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 [];
}

B
Benjamin Pasero 已提交
708
export function createCSSRule(selector: string, cssText: string, style: HTMLStyleElement = sharedStyle): void {
E
Erich Gamma 已提交
709 710 711 712 713 714 715
	if (!style || !cssText) {
		return;
	}

	(<any>style.sheet).insertRule(selector + '{' + cssText + '}', 0);
}

B
Benjamin Pasero 已提交
716
export function getCSSRule(selector: string, style: HTMLStyleElement = sharedStyle): any {
E
Erich Gamma 已提交
717 718 719 720
	if (!style) {
		return null;
	}

B
Benjamin Pasero 已提交
721 722 723 724
	let rules = getDynamicStyleSheetRules(style);
	for (let i = 0; i < rules.length; i++) {
		let rule = rules[i];
		let normalizedSelectorText = rule.selectorText.replace(/::/gi, ':');
E
Erich Gamma 已提交
725 726 727 728 729 730 731 732
		if (normalizedSelectorText === selector) {
			return rule;
		}
	}

	return null;
}

M
Martin Aeschlimann 已提交
733
export function removeCSSRulesContainingSelector(ruleName: string, style = sharedStyle): void {
E
Erich Gamma 已提交
734 735 736 737
	if (!style) {
		return;
	}

B
Benjamin Pasero 已提交
738 739 740 741 742
	let rules = getDynamicStyleSheetRules(style);
	let toDelete: number[] = [];
	for (let i = 0; i < rules.length; i++) {
		let rule = rules[i];
		let normalizedSelectorText = rule.selectorText.replace(/::/gi, ':');
M
Martin Aeschlimann 已提交
743
		if (normalizedSelectorText.indexOf(ruleName) !== -1) {
E
Erich Gamma 已提交
744 745 746 747
			toDelete.push(i);
		}
	}

B
Benjamin Pasero 已提交
748
	for (let i = toDelete.length - 1; i >= 0; i--) {
E
Erich Gamma 已提交
749 750 751 752
		style.sheet.deleteRule(toDelete[i]);
	}
}

B
Benjamin Pasero 已提交
753
export function isHTMLElement(o: any): o is HTMLElement {
754 755 756 757
	if (typeof HTMLElement === 'object') {
		return o instanceof HTMLElement;
	}
	return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
E
Erich Gamma 已提交
758 759
}

B
Benjamin Pasero 已提交
760
export const EventType = {
E
Erich Gamma 已提交
761 762
	// Mouse
	CLICK: 'click',
763
	AUXCLICK: 'auxclick', // >= Chrome 56
E
Erich Gamma 已提交
764 765 766 767 768 769 770
	DBLCLICK: 'dblclick',
	MOUSE_UP: 'mouseup',
	MOUSE_DOWN: 'mousedown',
	MOUSE_OVER: 'mouseover',
	MOUSE_MOVE: 'mousemove',
	MOUSE_OUT: 'mouseout',
	CONTEXT_MENU: 'contextmenu',
B
Benjamin Pasero 已提交
771
	WHEEL: 'wheel',
E
Erich Gamma 已提交
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
	// 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',
	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 已提交
802 803 804
	ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',
	ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',
	ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
E
Erich Gamma 已提交
805 806
};

A
Alex Dima 已提交
807 808 809 810 811
export interface EventLike {
	preventDefault(): void;
	stopPropagation(): void;
}

B
Benjamin Pasero 已提交
812
export const EventHelper = {
813
	stop: function (e: EventLike, cancelBubble?: boolean) {
E
Erich Gamma 已提交
814 815 816 817 818 819 820 821 822 823 824 825
		if (e.preventDefault) {
			e.preventDefault();
		} else {
			// IE8
			(<any>e).returnValue = false;
		}

		if (cancelBubble) {
			if (e.stopPropagation) {
				e.stopPropagation();
			} else {
				// IE8
A
Alex Dima 已提交
826
				(<any>e).cancelBubble = true;
E
Erich Gamma 已提交
827 828 829 830 831 832
			}
		}
	}
};

export interface IFocusTracker {
833 834
	addBlurListener(fn: () => void): IDisposable;
	addFocusListener(fn: () => void): IDisposable;
B
Benjamin Pasero 已提交
835
	dispose(): void;
E
Erich Gamma 已提交
836 837
}

B
Benjamin Pasero 已提交
838 839 840
export function saveParentsScrollTop(node: Element): number[] {
	let r: number[] = [];
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
841 842 843 844 845 846
		r[i] = node.scrollTop;
		node = <Element>node.parentNode;
	}
	return r;
}

B
Benjamin Pasero 已提交
847 848
export function restoreParentsScrollTop(node: Element, state: number[]): void {
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
849 850 851 852 853 854 855
		if (node.scrollTop !== state[i]) {
			node.scrollTop = state[i];
		}
		node = <Element>node.parentNode;
	}
}

856
class FocusTracker extends Disposable implements IFocusTracker {
E
Erich Gamma 已提交
857

858
	private _eventEmitter: EventEmitter;
E
Erich Gamma 已提交
859

860
	constructor(element: HTMLElement | Window) {
861 862 863 864 865 866 867
		super();

		let hasFocus = false;
		let loosingFocus = false;

		this._eventEmitter = this._register(new EventEmitter());

B
Benjamin Pasero 已提交
868
		let onFocus = (event: Event) => {
869 870 871 872
			loosingFocus = false;
			if (!hasFocus) {
				hasFocus = true;
				this._eventEmitter.emit('focus', {});
E
Erich Gamma 已提交
873
			}
874
		};
E
Erich Gamma 已提交
875

B
Benjamin Pasero 已提交
876
		let onBlur = (event: Event) => {
877 878 879 880 881 882 883 884 885 886 887
			if (hasFocus) {
				loosingFocus = true;
				window.setTimeout(() => {
					if (loosingFocus) {
						loosingFocus = false;
						hasFocus = false;
						this._eventEmitter.emit('blur', {});
					}
				}, 0);
			}
		};
E
Erich Gamma 已提交
888

889 890 891
		this._register(addDisposableListener(element, EventType.FOCUS, onFocus, true));
		this._register(addDisposableListener(element, EventType.BLUR, onBlur, true));
	}
E
Erich Gamma 已提交
892

893
	public addFocusListener(fn: () => void): IDisposable {
A
Alex Dima 已提交
894
		return this._eventEmitter.addListener('focus', fn);
895
	}
E
Erich Gamma 已提交
896

897
	public addBlurListener(fn: () => void): IDisposable {
A
Alex Dima 已提交
898
		return this._eventEmitter.addListener('blur', fn);
899 900 901
	}
}

902
export function trackFocus(element: HTMLElement | Window): IFocusTracker {
903
	return new FocusTracker(element);
E
Erich Gamma 已提交
904 905
}

J
Joao Moreno 已提交
906 907 908
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 已提交
909 910
}

911 912 913 914 915
export function prepend<T extends Node>(parent: HTMLElement, child: T): T {
	parent.insertBefore(child, parent.firstChild);
	return child;
}

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

// Similar to builder, but much more lightweight
919
export function $<T extends HTMLElement>(description: string, attrs?: { [key: string]: any; }, ...children: (Node | string)[]): T {
B
Benjamin Pasero 已提交
920
	let match = SELECTOR_REGEX.exec(description);
E
Erich Gamma 已提交
921 922 923 924 925

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

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

A
Alex Dima 已提交
928 929 930 931 932 933
	if (match[3]) {
		result.id = match[3];
	}
	if (match[4]) {
		result.className = match[4].replace(/\./g, ' ').trim();
	}
E
Erich Gamma 已提交
934

J
Joao Moreno 已提交
935 936 937
	Object.keys(attrs || {}).forEach(name => {
		if (/^on\w+$/.test(name)) {
			result[name] = attrs[name];
J
Joao Moreno 已提交
938 939 940 941 942 943
		} else if (name === 'selected') {
			const value = attrs[name];
			if (value) {
				result.setAttribute(name, 'true');
			}

J
Joao Moreno 已提交
944 945 946 947
		} else {
			result.setAttribute(name, attrs[name]);
		}
	});
J
Joao Moreno 已提交
948

J
Joao Moreno 已提交
949 950 951 952 953 954 955 956 957
	children
		.filter(child => !!child)
		.forEach(child => {
			if (child instanceof Node) {
				result.appendChild(child);
			} else {
				result.appendChild(document.createTextNode(child as string));
			}
		});
J
Joao Moreno 已提交
958

J
Joao Moreno 已提交
959
	return result as T;
A
Alex Dima 已提交
960
}
961

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
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 已提交
980
export function show(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
981
	for (let element of elements) {
S
Sandy Armstrong 已提交
982
		element.style.display = '';
J
Joao Moreno 已提交
983
	}
984 985
}

J
Joao Moreno 已提交
986
export function hide(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
987
	for (let element of elements) {
J
Joao Moreno 已提交
988 989
		element.style.display = 'none';
	}
990
}
991

B
Benjamin Pasero 已提交
992
function findParentWithAttribute(node: Node, attribute: string): HTMLElement {
993
	while (node) {
B
Benjamin Pasero 已提交
994
		if (node instanceof HTMLElement && node.hasAttribute(attribute)) {
995 996 997
			return node;
		}

B
Benjamin Pasero 已提交
998
		node = node.parentNode;
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	}

	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 已提交
1020
	node.removeAttribute('tabindex');
A
Alex Dima 已提交
1021
}
1022 1023 1024

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

1027
export function finalHandler<T extends Event>(fn: (event: T) => any): (event: T) => any {
J
Joao Moreno 已提交
1028 1029 1030 1031 1032
	return e => {
		e.preventDefault();
		e.stopPropagation();
		fn(e);
	};
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
}

export function domContentLoaded(): TPromise<any> {
	return new TPromise<any>((c, e) => {
		const readyState = document.readyState;
		if (readyState === 'complete' || (document && document.body !== null)) {
			window.setImmediate(c);
		} else {
			window.addEventListener('DOMContentLoaded', c, false);
		}
	});
1044
}