dom.ts 30.5 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';

7
import {TPromise} from 'vs/base/common/winjs.base';
A
Alex Dima 已提交
8 9
import {TimeoutTimer} from 'vs/base/common/async';
import {onUnexpectedError} from 'vs/base/common/errors';
B
Benjamin Pasero 已提交
10
import {EventEmitter} from 'vs/base/common/eventEmitter';
11
import {Disposable, IDisposable} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
12 13 14 15
import {isObject} from 'vs/base/common/types';
import {isChrome, isWebKit} from 'vs/base/browser/browser';
import {IKeyboardEvent, StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent';
import {IMouseEvent, StandardMouseEvent} from 'vs/base/browser/mouseEvent';
16
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;
}

B
Benjamin Pasero 已提交
59
let lastStart: number, lastEnd: number;
E
Erich Gamma 已提交
60

B
Benjamin Pasero 已提交
61
function _findClassName(node: HTMLElement, className: string): void {
E
Erich Gamma 已提交
62

B
Benjamin Pasero 已提交
63 64
	let classes = node.className;
	if (!classes) {
E
Erich Gamma 已提交
65 66 67 68 69 70
		lastStart = -1;
		return;
	}

	className = className.trim();

B
Benjamin Pasero 已提交
71
	let classesLen = classes.length,
E
Erich Gamma 已提交
72 73
		classLen = className.length;

B
Benjamin Pasero 已提交
74
	if (classLen === 0) {
E
Erich Gamma 已提交
75 76 77 78
		lastStart = -1;
		return;
	}

B
Benjamin Pasero 已提交
79
	if (classesLen < classLen) {
E
Erich Gamma 已提交
80 81 82 83
		lastStart = -1;
		return;
	}

B
Benjamin Pasero 已提交
84
	if (classes === className) {
E
Erich Gamma 已提交
85 86 87 88 89
		lastStart = 0;
		lastEnd = classesLen;
		return;
	}

B
Benjamin Pasero 已提交
90 91
	let idx = -1,
		idxEnd: number;
E
Erich Gamma 已提交
92 93 94 95 96 97

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

		idxEnd = idx + classLen;

		// a class that is followed by another class
98
		if ((idx === 0 || classes.charCodeAt(idx - 1) === CharCode.Space) && classes.charCodeAt(idxEnd) === CharCode.Space) {
E
Erich Gamma 已提交
99 100 101 102 103 104
			lastStart = idx;
			lastEnd = idxEnd + 1;
			return;
		}

		// last class
105
		if (idx > 0 && classes.charCodeAt(idx - 1) === CharCode.Space && idxEnd === classesLen) {
E
Erich Gamma 已提交
106 107 108 109 110 111
			lastStart = idx - 1;
			lastEnd = idxEnd;
			return;
		}

		// equal - duplicate of cmp above
B
Benjamin Pasero 已提交
112
		if (idx === 0 && idxEnd === classesLen) {
E
Erich Gamma 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126
			lastStart = 0;
			lastEnd = idxEnd;
			return;
		}
	}

	lastStart = -1;
}

/**
 * @param node a dom node
 * @param className a class name
 * @return true if the className attribute of the provided node contains the provided className
 */
B
Benjamin Pasero 已提交
127
export function hasClass(node: HTMLElement, className: string): boolean {
E
Erich Gamma 已提交
128 129 130 131 132 133 134 135 136 137
	_findClassName(node, className);
	return lastStart !== -1;
}

/**
 * Adds the provided className to the provided node. This is a no-op
 * if the class is already set.
 * @param node a dom node
 * @param className a class name
 */
B
Benjamin Pasero 已提交
138 139
export function addClass(node: HTMLElement, className: string): void {
	if (!node.className) { // doesn't have it for sure
E
Erich Gamma 已提交
140 141 142
		node.className = className;
	} else {
		_findClassName(node, className); // see if it's already there
B
Benjamin Pasero 已提交
143
		if (lastStart === -1) {
E
Erich Gamma 已提交
144 145 146 147 148 149 150 151 152 153 154
			node.className = node.className + ' ' + className;
		}
	}
}

/**
 * Removes the className for the provided node. This is a no-op
 * if the class isn't present.
 * @param node a dom node
 * @param className a class name
 */
B
Benjamin Pasero 已提交
155
export function removeClass(node: HTMLElement, className: string): void {
E
Erich Gamma 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168
	_findClassName(node, className);
	if (lastStart === -1) {
		return; // Prevent styles invalidation if not necessary
	} else {
		node.className = node.className.substring(0, lastStart) + node.className.substring(lastEnd);
	}
}

/**
 * @param node a dom node
 * @param className a class name
 * @param shouldHaveIt
 */
B
Benjamin Pasero 已提交
169
export function toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void {
E
Erich Gamma 已提交
170
	_findClassName(node, className);
S
Sandeep Somavarapu 已提交
171
	if (lastStart !== -1 && (shouldHaveIt === void 0 || !shouldHaveIt)) {
E
Erich Gamma 已提交
172 173
		removeClass(node, className);
	}
S
Sandeep Somavarapu 已提交
174
	if (lastStart === -1 && (shouldHaveIt === void 0 || shouldHaveIt)) {
E
Erich Gamma 已提交
175 176 177 178
		addClass(node, className);
	}
}

179
class DomListener extends Disposable {
E
Erich Gamma 已提交
180

181 182 183 184 185
	private _usedAddEventListener: boolean;
	private _wrapHandler: (e: any) => void;
	private _node: any;
	private _type: string;
	private _useCapture: boolean;
E
Erich Gamma 已提交
186

187
	constructor(node: Element | Window | Document, type: string, handler: (e: any) => void, useCapture?: boolean) {
188
		super();
E
Erich Gamma 已提交
189

190 191 192
		this._node = node;
		this._type = type;
		this._useCapture = (useCapture || false);
E
Erich Gamma 已提交
193

194 195 196
		this._wrapHandler = (e) => {
			e = e || window.event;
			handler(e);
E
Erich Gamma 已提交
197
		};
198 199 200 201 202 203 204 205

		if (typeof this._node.addEventListener === 'function') {
			this._usedAddEventListener = true;
			this._node.addEventListener(this._type, this._wrapHandler, this._useCapture);
		} else {
			this._usedAddEventListener = false;
			this._node.attachEvent('on' + this._type, this._wrapHandler);
		}
E
Erich Gamma 已提交
206 207
	}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
	public dispose(): void {
		if (!this._wrapHandler) {
			// Already disposed
			return;
		}

		if (this._usedAddEventListener) {
			this._node.removeEventListener(this._type, this._wrapHandler, this._useCapture);
		} else {
			this._node.detachEvent('on' + this._type, this._wrapHandler);
		}

		// Prevent leakers from holding on to the dom or handler func
		this._node = null;
		this._wrapHandler = null;
	}
E
Erich Gamma 已提交
224 225
}

B
Benjamin Pasero 已提交
226
export function addDisposableListener(node: Element, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
227
export function addDisposableListener(node: Element | Window, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
B
Benjamin Pasero 已提交
228 229 230
export function addDisposableListener(node: Window, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: Document, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: any, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
231
	return new DomListener(node, type, handler, useCapture);
E
Erich Gamma 已提交
232 233 234
}

export interface IAddStandardDisposableListenerSignature {
B
Benjamin Pasero 已提交
235 236 237 238 239
	(node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
	(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 已提交
240
}
B
Benjamin Pasero 已提交
241
function _wrapAsStandardMouseEvent(handler: (e: IMouseEvent) => void): (e: MouseEvent) => void {
242
	return function (e: MouseEvent) {
A
Cleanup  
Alex Dima 已提交
243
		return handler(new StandardMouseEvent(e));
E
Erich Gamma 已提交
244 245
	};
}
B
Benjamin Pasero 已提交
246
function _wrapAsStandardKeyboardEvent(handler: (e: IKeyboardEvent) => void): (e: KeyboardEvent) => void {
247
	return function (e: KeyboardEvent) {
A
Cleanup  
Alex Dima 已提交
248
		return handler(new StandardKeyboardEvent(e));
E
Erich Gamma 已提交
249 250
	};
}
B
Benjamin Pasero 已提交
251 252
export let addStandardDisposableListener: IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
	let wrapHandler = handler;
E
Erich Gamma 已提交
253 254 255 256 257 258 259 260 261

	if (type === 'click') {
		wrapHandler = _wrapAsStandardMouseEvent(handler);
	} else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
		wrapHandler = _wrapAsStandardKeyboardEvent(handler);
	}

	node.addEventListener(type, wrapHandler, useCapture || false);
	return {
262
		dispose: function () {
E
Erich Gamma 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276
			if (!wrapHandler) {
				// Already removed
				return;
			}
			node.removeEventListener(type, wrapHandler, useCapture || false);

			// Prevent leakers from holding on to the dom node or handler func
			wrapHandler = null;
			node = null;
			handler = null;
		}
	};
};

277 278
export function addDisposableNonBubblingMouseOutListener(node: Element, handler: (event: MouseEvent) => void): IDisposable {
	return addDisposableListener(node, 'mouseout', (e: MouseEvent) => {
E
Erich Gamma 已提交
279
		// Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
B
Benjamin Pasero 已提交
280
		let toElement = <Node>(e.relatedTarget || e.toElement);
E
Erich Gamma 已提交
281 282 283 284 285 286 287 288 289 290 291
		while (toElement && toElement !== node) {
			toElement = toElement.parentNode;
		}
		if (toElement === node) {
			return;
		}

		handler(e);
	});
}

292
const _animationFrame = (function () {
B
Benjamin Pasero 已提交
293
	let emulatedRequestAnimationFrame = (callback: (time: number) => void): number => {
E
Erich Gamma 已提交
294 295
		return setTimeout(() => callback(new Date().getTime()), 0);
	};
B
Benjamin Pasero 已提交
296 297 298 299 300 301
	let nativeRequestAnimationFrame: (callback: (time: number) => void) => number =
		self.requestAnimationFrame
		|| (<any>self).msRequestAnimationFrame
		|| (<any>self).webkitRequestAnimationFrame
		|| (<any>self).mozRequestAnimationFrame
		|| (<any>self).oRequestAnimationFrame;
E
Erich Gamma 已提交
302 303 304



B
Benjamin Pasero 已提交
305 306 307 308 309 310 311
	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 已提交
312

B
Benjamin Pasero 已提交
313 314
	let isNative = !!nativeRequestAnimationFrame;
	let request = nativeRequestAnimationFrame || emulatedRequestAnimationFrame;
A
Alex Dima 已提交
315
	let cancel = nativeCancelAnimationFrame || emulatedCancelAnimationFrame;
E
Erich Gamma 已提交
316 317 318

	return {
		isNative: isNative,
B
Benjamin Pasero 已提交
319
		request: (callback: (time: number) => void): number => {
E
Erich Gamma 已提交
320 321
			return request(callback);
		},
B
Benjamin Pasero 已提交
322
		cancel: (id: number) => {
E
Erich Gamma 已提交
323 324 325 326 327 328 329 330 331 332 333
			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 已提交
334
export let runAtThisOrScheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
E
Erich Gamma 已提交
335 336 337 338 339 340
/**
 * 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 已提交
341
export let scheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
E
Erich Gamma 已提交
342

B
Benjamin Pasero 已提交
343
class AnimationFrameQueueItem implements IDisposable {
E
Erich Gamma 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

	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 已提交
367
			onUnexpectedError(e);
E
Erich Gamma 已提交
368 369 370 371 372 373 374 375 376
		}
	}

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

377
(function () {
E
Erich Gamma 已提交
378 379 380
	/**
	 * The runners scheduled at the next animation frame
	 */
B
Benjamin Pasero 已提交
381
	let NEXT_QUEUE: AnimationFrameQueueItem[] = [];
E
Erich Gamma 已提交
382 383 384
	/**
	 * The runners scheduled at the current animation frame
	 */
B
Benjamin Pasero 已提交
385
	let CURRENT_QUEUE: AnimationFrameQueueItem[] = null;
E
Erich Gamma 已提交
386 387 388
	/**
	 * A flag to keep track if the native requestAnimationFrame was already called
	 */
B
Benjamin Pasero 已提交
389
	let animFrameRequested = false;
E
Erich Gamma 已提交
390 391 392
	/**
	 * A flag to indicate if currently handling a native requestAnimationFrame callback
	 */
B
Benjamin Pasero 已提交
393
	let inAnimationFrameRunner = false;
E
Erich Gamma 已提交
394

B
Benjamin Pasero 已提交
395
	let animationFrameRunner = () => {
E
Erich Gamma 已提交
396 397 398 399 400 401 402 403
		animFrameRequested = false;

		CURRENT_QUEUE = NEXT_QUEUE;
		NEXT_QUEUE = [];

		inAnimationFrameRunner = true;
		while (CURRENT_QUEUE.length > 0) {
			CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
B
Benjamin Pasero 已提交
404
			let top = CURRENT_QUEUE.shift();
E
Erich Gamma 已提交
405 406 407 408 409
			top.execute();
		}
		inAnimationFrameRunner = false;
	};

B
Benjamin Pasero 已提交
410 411
	scheduleAtNextAnimationFrame = (runner: () => void, priority: number = 0) => {
		let item = new AnimationFrameQueueItem(runner, priority);
E
Erich Gamma 已提交
412 413 414 415 416 417
		NEXT_QUEUE.push(item);

		if (!animFrameRequested) {
			animFrameRequested = true;

			// TODO@Alex: also check if it is electron
B
Benjamin Pasero 已提交
418 419
			if (isChrome) {
				let handle: number;
420
				_animationFrame.request(function () {
E
Erich Gamma 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
					clearTimeout(handle);
					animationFrameRunner();
				});
				// This is a fallback in-case chrome dropped
				// the request for an animation frame. This
				// is sick but was spotted in the wild
				handle = setTimeout(animationFrameRunner, 1000);
			} else {
				_animationFrame.request(animationFrameRunner);
			}
		}

		return item;
	};

B
Benjamin Pasero 已提交
436
	runAtThisOrScheduleAtNextAnimationFrame = (runner: () => void, priority?: number) => {
E
Erich Gamma 已提交
437
		if (inAnimationFrameRunner) {
B
Benjamin Pasero 已提交
438
			let item = new AnimationFrameQueueItem(runner, priority);
E
Erich Gamma 已提交
439 440 441 442 443 444 445 446 447 448 449 450
			CURRENT_QUEUE.push(item);
			return item;
		} else {
			return scheduleAtNextAnimationFrame(runner, priority);
		}
	};
})();

/// <summary>
/// Add a throttled listener. `handler` is fired at most every 16ms or with the next animation frame (if browser supports it).
/// </summary>
export interface IEventMerger<R> {
B
Benjamin Pasero 已提交
451
	(lastEvent: R, currentEvent: Event): R;
E
Erich Gamma 已提交
452 453
}

B
Benjamin Pasero 已提交
454
const MINIMUM_TIME_MS = 16;
455
const DEFAULT_EVENT_MERGER: IEventMerger<Event> = function (lastEvent: Event, currentEvent: Event) {
E
Erich Gamma 已提交
456 457 458
	return currentEvent;
};

459
class TimeoutThrottledDomListener<R> extends Disposable {
E
Erich Gamma 已提交
460

461 462
	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 已提交
463

464 465 466
		let lastEvent = null;
		let lastHandlerTime = 0;
		let timeout = this._register(new TimeoutTimer());
E
Erich Gamma 已提交
467

468 469 470 471 472
		let invokeHandler = () => {
			lastHandlerTime = (new Date()).getTime();
			handler(lastEvent);
			lastEvent = null;
		};
E
Erich Gamma 已提交
473

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

476 477 478 479 480 481 482 483 484 485 486
			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 已提交
487 488
}

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

B
Benjamin Pasero 已提交
493
export function getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
E
Erich Gamma 已提交
494 495 496 497 498
	return document.defaultView.getComputedStyle(el, null);
}

// Adapted from WinJS
// Converts a CSS positioning string for the specified element to pixels.
499 500
const convertToPixels: (element: HTMLElement, value: string) => number = (function () {
	return function (element: HTMLElement, value: string): number {
E
Erich Gamma 已提交
501 502 503 504
		return parseFloat(value) || 0;
	};
})();

B
Benjamin Pasero 已提交
505 506 507
function getDimension(element: HTMLElement, cssPropertyName: string, jsPropertyName: string): number {
	let computedStyle: CSSStyleDeclaration = getComputedStyle(element);
	let value = '0';
E
Erich Gamma 已提交
508 509 510 511 512 513 514 515 516 517 518
	if (computedStyle) {
		if (computedStyle.getPropertyValue) {
			value = computedStyle.getPropertyValue(cssPropertyName);
		} else {
			// IE8
			value = (<any>computedStyle).getAttribute(jsPropertyName);
		}
	}
	return convertToPixels(element, value);
}

B
Benjamin Pasero 已提交
519
const sizeUtils = {
E
Erich Gamma 已提交
520

521
	getBorderLeftWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
522 523
		return getDimension(element, 'border-left-width', 'borderLeftWidth');
	},
524
	getBorderTopWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
525 526
		return getDimension(element, 'border-top-width', 'borderTopWidth');
	},
527
	getBorderRightWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
528 529
		return getDimension(element, 'border-right-width', 'borderRightWidth');
	},
530
	getBorderBottomWidth: function (element: HTMLElement): number {
E
Erich Gamma 已提交
531 532 533
		return getDimension(element, 'border-bottom-width', 'borderBottomWidth');
	},

534
	getPaddingLeft: function (element: HTMLElement): number {
E
Erich Gamma 已提交
535 536
		return getDimension(element, 'padding-left', 'paddingLeft');
	},
537
	getPaddingTop: function (element: HTMLElement): number {
E
Erich Gamma 已提交
538 539
		return getDimension(element, 'padding-top', 'paddingTop');
	},
540
	getPaddingRight: function (element: HTMLElement): number {
E
Erich Gamma 已提交
541 542
		return getDimension(element, 'padding-right', 'paddingRight');
	},
543
	getPaddingBottom: function (element: HTMLElement): number {
E
Erich Gamma 已提交
544 545 546
		return getDimension(element, 'padding-bottom', 'paddingBottom');
	},

547
	getMarginLeft: function (element: HTMLElement): number {
E
Erich Gamma 已提交
548 549
		return getDimension(element, 'margin-left', 'marginLeft');
	},
550
	getMarginTop: function (element: HTMLElement): number {
E
Erich Gamma 已提交
551 552
		return getDimension(element, 'margin-top', 'marginTop');
	},
553
	getMarginRight: function (element: HTMLElement): number {
E
Erich Gamma 已提交
554 555
		return getDimension(element, 'margin-right', 'marginRight');
	},
556
	getMarginBottom: function (element: HTMLElement): number {
E
Erich Gamma 已提交
557 558 559 560 561 562 563 564
		return getDimension(element, 'margin-bottom', 'marginBottom');
	},
	__commaSentinel: false
};

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

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

B
Benjamin Pasero 已提交
569
	let offsetParent = element.offsetParent, top = element.offsetTop, left = element.offsetLeft;
E
Erich Gamma 已提交
570 571 572

	while ((element = <HTMLElement>element.parentNode) !== null && element !== document.body && element !== document.documentElement) {
		top -= element.scrollTop;
B
Benjamin Pasero 已提交
573
		let c = getComputedStyle(element);
E
Erich Gamma 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
		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
	};
}

593
export interface IDomNodePagePosition {
B
Benjamin Pasero 已提交
594 595 596 597
	left: number;
	top: number;
	width: number;
	height: number;
E
Erich Gamma 已提交
598 599
}

600 601 602 603 604
/**
 * 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 已提交
605
	return {
606 607
		left: bb.left + StandardWindow.scrollX,
		top: bb.top + StandardWindow.scrollY,
608 609
		width: bb.width,
		height: bb.height
E
Erich Gamma 已提交
610 611 612
	};
}

613 614 615 616 617
export interface IStandardWindow {
	scrollX: number;
	scrollY: number;
}

618
export const StandardWindow: IStandardWindow = new class {
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
	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 已提交
638 639
// 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 已提交
640 641 642
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 已提交
643 644 645 646 647
	return element.offsetWidth - border - padding;
}

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

653 654 655 656 657
export function getTotalScrollWidth(element: HTMLElement): number {
	let margin = sizeUtils.getMarginLeft(element) + sizeUtils.getMarginRight(element);
	return element.scrollWidth + margin;
}

E
Erich Gamma 已提交
658 659
// 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 已提交
660 661 662
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 已提交
663 664 665 666 667
	return element.offsetHeight - border - padding;
}

// Adapted from WinJS
// Gets the height of the element, including its margins.
B
Benjamin Pasero 已提交
668 669
export function getTotalHeight(element: HTMLElement): number {
	let margin = sizeUtils.getMarginTop(element) + sizeUtils.getMarginBottom(element);
E
Erich Gamma 已提交
670 671 672 673
	return element.offsetHeight + margin;
}

// Gets the left coordinate of the specified element relative to the specified parent.
674
function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {
E
Erich Gamma 已提交
675 676 677 678
	if (element === null) {
		return 0;
	}

M
Maxime Quandalle 已提交
679 680 681
	let elementPosition = getTopLeftOffset(element);
	let parentPosition = getTopLeftOffset(parent);
	return elementPosition.left - parentPosition.left;
E
Erich Gamma 已提交
682 683
}

M
Maxime Quandalle 已提交
684 685
export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {
	let childWidths = children.map((child) => {
686
		return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;
M
Maxime Quandalle 已提交
687 688 689
	});
	let maxWidth = Math.max(...childWidths);
	return maxWidth;
E
Erich Gamma 已提交
690 691 692 693
}

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

B
Benjamin Pasero 已提交
694 695
export function isAncestor(testChild: Node, testAncestor: Node): boolean {
	while (testChild) {
E
Erich Gamma 已提交
696 697 698 699 700 701 702 703 704
		if (testChild === testAncestor) {
			return true;
		}
		testChild = testChild.parentNode;
	}

	return false;
}

B
Benjamin Pasero 已提交
705
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazz?: string): HTMLElement {
E
Erich Gamma 已提交
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
	while (node) {
		if (hasClass(node, clazz)) {
			return node;
		}

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

		node = <HTMLElement>node.parentNode;
	}

	return null;
}

export function createStyleSheet(): HTMLStyleElement {
B
Benjamin Pasero 已提交
722
	let style = document.createElement('style');
E
Erich Gamma 已提交
723 724 725 726 727 728
	style.type = 'text/css';
	style.media = 'screen';
	document.getElementsByTagName('head')[0].appendChild(style);
	return style;
}

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

B
Benjamin Pasero 已提交
731
function getDynamicStyleSheetRules(style: any) {
E
Erich Gamma 已提交
732 733 734 735 736 737 738 739 740 741 742
	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 已提交
743
export function createCSSRule(selector: string, cssText: string, style: HTMLStyleElement = sharedStyle): void {
E
Erich Gamma 已提交
744 745 746 747 748 749 750
	if (!style || !cssText) {
		return;
	}

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

B
Benjamin Pasero 已提交
751
export function getCSSRule(selector: string, style: HTMLStyleElement = sharedStyle): any {
E
Erich Gamma 已提交
752 753 754 755
	if (!style) {
		return null;
	}

B
Benjamin Pasero 已提交
756 757 758 759
	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 已提交
760 761 762 763 764 765 766 767
		if (normalizedSelectorText === selector) {
			return rule;
		}
	}

	return null;
}

M
Martin Aeschlimann 已提交
768
export function removeCSSRulesContainingSelector(ruleName: string, style = sharedStyle): void {
E
Erich Gamma 已提交
769 770 771 772
	if (!style) {
		return;
	}

B
Benjamin Pasero 已提交
773 774 775 776 777
	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 已提交
778
		if (normalizedSelectorText.indexOf(ruleName) !== -1) {
E
Erich Gamma 已提交
779 780 781 782
			toDelete.push(i);
		}
	}

B
Benjamin Pasero 已提交
783
	for (let i = toDelete.length - 1; i >= 0; i--) {
E
Erich Gamma 已提交
784 785 786 787
		style.sheet.deleteRule(toDelete[i]);
	}
}

B
Benjamin Pasero 已提交
788
export function isHTMLElement(o: any): o is HTMLElement {
789 790 791 792
	if (typeof HTMLElement === 'object') {
		return o instanceof HTMLElement;
	}
	return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
E
Erich Gamma 已提交
793 794
}

B
Benjamin Pasero 已提交
795
export const EventType = {
E
Erich Gamma 已提交
796 797 798 799 800 801 802 803 804
	// Mouse
	CLICK: 'click',
	DBLCLICK: 'dblclick',
	MOUSE_UP: 'mouseup',
	MOUSE_DOWN: 'mousedown',
	MOUSE_OVER: 'mouseover',
	MOUSE_MOVE: 'mousemove',
	MOUSE_OUT: 'mouseout',
	CONTEXT_MENU: 'contextmenu',
B
Benjamin Pasero 已提交
805
	WHEEL: 'wheel',
E
Erich Gamma 已提交
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
	// 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
B
Benjamin Pasero 已提交
836 837 838
	ANIMATION_START: isWebKit ? 'webkitAnimationStart' : 'animationstart',
	ANIMATION_END: isWebKit ? 'webkitAnimationEnd' : 'animationend',
	ANIMATION_ITERATION: isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
E
Erich Gamma 已提交
839 840
};

A
Alex Dima 已提交
841 842 843 844 845
export interface EventLike {
	preventDefault(): void;
	stopPropagation(): void;
}

B
Benjamin Pasero 已提交
846
export const EventHelper = {
847
	stop: function (e: EventLike, cancelBubble?: boolean) {
E
Erich Gamma 已提交
848 849 850 851 852 853 854 855 856 857 858 859
		if (e.preventDefault) {
			e.preventDefault();
		} else {
			// IE8
			(<any>e).returnValue = false;
		}

		if (cancelBubble) {
			if (e.stopPropagation) {
				e.stopPropagation();
			} else {
				// IE8
A
Alex Dima 已提交
860
				(<any>e).cancelBubble = true;
E
Erich Gamma 已提交
861 862 863 864 865 866
			}
		}
	}
};

export interface IFocusTracker {
867 868
	addBlurListener(fn: () => void): IDisposable;
	addFocusListener(fn: () => void): IDisposable;
B
Benjamin Pasero 已提交
869
	dispose(): void;
E
Erich Gamma 已提交
870 871
}

B
Benjamin Pasero 已提交
872 873 874
export function saveParentsScrollTop(node: Element): number[] {
	let r: number[] = [];
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
875 876 877 878 879 880
		r[i] = node.scrollTop;
		node = <Element>node.parentNode;
	}
	return r;
}

B
Benjamin Pasero 已提交
881 882
export function restoreParentsScrollTop(node: Element, state: number[]): void {
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
883 884 885 886 887 888 889
		if (node.scrollTop !== state[i]) {
			node.scrollTop = state[i];
		}
		node = <Element>node.parentNode;
	}
}

890
class FocusTracker extends Disposable implements IFocusTracker {
E
Erich Gamma 已提交
891

892
	private _eventEmitter: EventEmitter;
E
Erich Gamma 已提交
893

894
	constructor(element: HTMLElement | Window) {
895 896 897 898 899 900 901 902 903 904 905 906
		super();

		let hasFocus = false;
		let loosingFocus = false;

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

		let onFocus = (event) => {
			loosingFocus = false;
			if (!hasFocus) {
				hasFocus = true;
				this._eventEmitter.emit('focus', {});
E
Erich Gamma 已提交
907
			}
908
		};
E
Erich Gamma 已提交
909

910 911 912 913 914 915 916 917 918 919 920 921
		let onBlur = (event) => {
			if (hasFocus) {
				loosingFocus = true;
				window.setTimeout(() => {
					if (loosingFocus) {
						loosingFocus = false;
						hasFocus = false;
						this._eventEmitter.emit('blur', {});
					}
				}, 0);
			}
		};
E
Erich Gamma 已提交
922

923 924 925
		this._register(addDisposableListener(element, EventType.FOCUS, onFocus, true));
		this._register(addDisposableListener(element, EventType.BLUR, onBlur, true));
	}
E
Erich Gamma 已提交
926

927
	public addFocusListener(fn: () => void): IDisposable {
928 929
		return this._eventEmitter.addListener2('focus', fn);
	}
E
Erich Gamma 已提交
930

931
	public addBlurListener(fn: () => void): IDisposable {
932 933 934 935
		return this._eventEmitter.addListener2('blur', fn);
	}
}

936
export function trackFocus(element: HTMLElement | Window): IFocusTracker {
937
	return new FocusTracker(element);
E
Erich Gamma 已提交
938 939
}

J
Joao Moreno 已提交
940 941 942
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 已提交
943 944
}

945 946 947 948 949
export function prepend<T extends Node>(parent: HTMLElement, child: T): T {
	parent.insertBefore(child, parent.firstChild);
	return child;
}

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

// Similar to builder, but much more lightweight
953
export function $<T extends HTMLElement>(description: string, attrs?: { [key: string]: any; }, ...children: (Node | string)[]): T {
B
Benjamin Pasero 已提交
954
	let match = SELECTOR_REGEX.exec(description);
E
Erich Gamma 已提交
955 956 957 958 959

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

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

A
Alex Dima 已提交
962 963 964 965 966 967
	if (match[3]) {
		result.id = match[3];
	}
	if (match[4]) {
		result.className = match[4].replace(/\./g, ' ').trim();
	}
E
Erich Gamma 已提交
968

J
Joao Moreno 已提交
969 970 971
	Object.keys(attrs || {}).forEach(name => {
		if (/^on\w+$/.test(name)) {
			result[name] = attrs[name];
J
Joao Moreno 已提交
972 973 974 975 976 977
		} else if (name === 'selected') {
			const value = attrs[name];
			if (value) {
				result.setAttribute(name, 'true');
			}

J
Joao Moreno 已提交
978 979 980 981
		} else {
			result.setAttribute(name, attrs[name]);
		}
	});
J
Joao Moreno 已提交
982

J
Joao Moreno 已提交
983 984 985 986 987 988 989 990 991
	children
		.filter(child => !!child)
		.forEach(child => {
			if (child instanceof Node) {
				result.appendChild(child);
			} else {
				result.appendChild(document.createTextNode(child as string));
			}
		});
J
Joao Moreno 已提交
992

J
Joao Moreno 已提交
993
	return result as T;
A
Alex Dima 已提交
994
}
995

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
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 已提交
1014
export function show(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
1015
	for (let element of elements) {
S
Sandy Armstrong 已提交
1016
		element.style.display = '';
J
Joao Moreno 已提交
1017
	}
1018 1019
}

J
Joao Moreno 已提交
1020
export function hide(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
1021
	for (let element of elements) {
J
Joao Moreno 已提交
1022 1023
		element.style.display = 'none';
	}
1024
}
1025

B
Benjamin Pasero 已提交
1026
function findParentWithAttribute(node: Node, attribute: string): HTMLElement {
1027
	while (node) {
B
Benjamin Pasero 已提交
1028
		if (node instanceof HTMLElement && node.hasAttribute(attribute)) {
1029 1030 1031
			return node;
		}

B
Benjamin Pasero 已提交
1032
		node = node.parentNode;
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
	}

	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 已提交
1054
	node.removeAttribute('tabindex');
A
Alex Dima 已提交
1055
}
1056 1057 1058

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

1061
export function finalHandler<T extends Event>(fn: (event: T) => any): (event: T) => any {
J
Joao Moreno 已提交
1062 1063 1064 1065 1066
	return e => {
		e.preventDefault();
		e.stopPropagation();
		fn(e);
	};
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
}

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);
		}
	});
1078
}