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

A
Alex Dima 已提交
7 8
import {TimeoutTimer} from 'vs/base/common/async';
import {onUnexpectedError} from 'vs/base/common/errors';
B
Benjamin Pasero 已提交
9
import {EventEmitter} from 'vs/base/common/eventEmitter';
10
import {Disposable, IDisposable} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
11 12 13 14
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';
E
Erich Gamma 已提交
15

B
Benjamin Pasero 已提交
16
export function clearNode(node: HTMLElement) {
E
Erich Gamma 已提交
17 18 19 20 21 22 23 24 25 26
	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 已提交
27 28
export function safeStringifyDOMAware(obj: any): string {
	let seen: any[] = [];
E
Erich Gamma 已提交
29 30 31
	return JSON.stringify(obj, (key, value) => {

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

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

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

B
Benjamin Pasero 已提交
57 58
const _blank = ' '.charCodeAt(0);
let lastStart: number, lastEnd: number;
E
Erich Gamma 已提交
59

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

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

	className = className.trim();

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

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

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

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

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

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

		idxEnd = idx + classLen;

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

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

		// equal - duplicate of cmp above
B
Benjamin Pasero 已提交
111
		if (idx === 0 && idxEnd === classesLen) {
E
Erich Gamma 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125
			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 已提交
126
export function hasClass(node: HTMLElement, className: string): boolean {
E
Erich Gamma 已提交
127 128 129 130 131 132 133 134 135 136
	_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 已提交
137 138
export function addClass(node: HTMLElement, className: string): void {
	if (!node.className) { // doesn't have it for sure
E
Erich Gamma 已提交
139 140 141
		node.className = className;
	} else {
		_findClassName(node, className); // see if it's already there
B
Benjamin Pasero 已提交
142
		if (lastStart === -1) {
E
Erich Gamma 已提交
143 144 145 146 147 148 149 150 151 152 153
			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 已提交
154
export function removeClass(node: HTMLElement, className: string): void {
E
Erich Gamma 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167
	_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 已提交
168
export function toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void {
E
Erich Gamma 已提交
169
	_findClassName(node, className);
S
Sandeep Somavarapu 已提交
170
	if (lastStart !== -1 && (shouldHaveIt === void 0 || !shouldHaveIt)) {
E
Erich Gamma 已提交
171 172
		removeClass(node, className);
	}
S
Sandeep Somavarapu 已提交
173
	if (lastStart === -1 && (shouldHaveIt === void 0 || shouldHaveIt)) {
E
Erich Gamma 已提交
174 175 176 177
		addClass(node, className);
	}
}

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

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

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

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

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

		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 已提交
205 206
	}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
	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 已提交
223 224
}

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

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

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

	node.addEventListener(type, wrapHandler, useCapture || false);
	return {
B
Benjamin Pasero 已提交
261
		dispose: function() {
E
Erich Gamma 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275
			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;
		}
	};
};

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

		handler(e);
	});
}

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



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

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

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

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

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

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

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

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

		CURRENT_QUEUE = NEXT_QUEUE;
		NEXT_QUEUE = [];

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

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

		if (!animFrameRequested) {
			animFrameRequested = true;

			// TODO@Alex: also check if it is electron
B
Benjamin Pasero 已提交
417 418 419
			if (isChrome) {
				let handle: number;
				_animationFrame.request(function() {
E
Erich Gamma 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
					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 已提交
435
	runAtThisOrScheduleAtNextAnimationFrame = (runner: () => void, priority?: number) => {
E
Erich Gamma 已提交
436
		if (inAnimationFrameRunner) {
B
Benjamin Pasero 已提交
437
			let item = new AnimationFrameQueueItem(runner, priority);
E
Erich Gamma 已提交
438 439 440 441 442 443 444 445 446 447 448 449
			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 已提交
450
	(lastEvent: R, currentEvent: Event): R;
E
Erich Gamma 已提交
451 452
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

export const StandardWindow:IStandardWindow = new class {
	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 已提交
637 638
// 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 已提交
639 640 641
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 已提交
642 643 644 645 646
	return element.offsetWidth - border - padding;
}

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

// 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 已提交
654 655 656
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 已提交
657 658 659 660 661
	return element.offsetHeight - border - padding;
}

// Adapted from WinJS
// Gets the height of the element, including its margins.
B
Benjamin Pasero 已提交
662 663
export function getTotalHeight(element: HTMLElement): number {
	let margin = sizeUtils.getMarginTop(element) + sizeUtils.getMarginBottom(element);
E
Erich Gamma 已提交
664 665 666 667
	return element.offsetHeight + margin;
}

// Gets the left coordinate of the specified element relative to the specified parent.
668
function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {
E
Erich Gamma 已提交
669 670 671 672
	if (element === null) {
		return 0;
	}

M
Maxime Quandalle 已提交
673 674 675
	let elementPosition = getTopLeftOffset(element);
	let parentPosition = getTopLeftOffset(parent);
	return elementPosition.left - parentPosition.left;
E
Erich Gamma 已提交
676 677
}

M
Maxime Quandalle 已提交
678 679 680 681 682 683
export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {
	let childWidths = children.map((child) => {
		return getTotalWidth(child) + getRelativeLeft(child, parent) || 0;
	});
	let maxWidth = Math.max(...childWidths);
	return maxWidth;
E
Erich Gamma 已提交
684 685 686 687
}

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

B
Benjamin Pasero 已提交
688 689
export function isAncestor(testChild: Node, testAncestor: Node): boolean {
	while (testChild) {
E
Erich Gamma 已提交
690 691 692 693 694 695 696 697 698
		if (testChild === testAncestor) {
			return true;
		}
		testChild = testChild.parentNode;
	}

	return false;
}

B
Benjamin Pasero 已提交
699
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazz?: string): HTMLElement {
E
Erich Gamma 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
	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 已提交
716
	let style = document.createElement('style');
E
Erich Gamma 已提交
717 718 719 720 721 722
	style.type = 'text/css';
	style.media = 'screen';
	document.getElementsByTagName('head')[0].appendChild(style);
	return style;
}

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

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

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

B
Benjamin Pasero 已提交
745
export function getCSSRule(selector: string, style: HTMLStyleElement = sharedStyle): any {
E
Erich Gamma 已提交
746 747 748 749
	if (!style) {
		return null;
	}

B
Benjamin Pasero 已提交
750 751 752 753
	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 已提交
754 755 756 757 758 759 760 761
		if (normalizedSelectorText === selector) {
			return rule;
		}
	}

	return null;
}

M
Martin Aeschlimann 已提交
762
export function removeCSSRulesContainingSelector(ruleName: string, style = sharedStyle): void {
E
Erich Gamma 已提交
763 764 765 766
	if (!style) {
		return;
	}

B
Benjamin Pasero 已提交
767 768 769 770 771
	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 已提交
772
		if (normalizedSelectorText.indexOf(ruleName) !== -1) {
E
Erich Gamma 已提交
773 774 775 776
			toDelete.push(i);
		}
	}

B
Benjamin Pasero 已提交
777
	for (let i = toDelete.length - 1; i >= 0; i--) {
E
Erich Gamma 已提交
778 779 780 781
		style.sheet.deleteRule(toDelete[i]);
	}
}

B
Benjamin Pasero 已提交
782
export function isHTMLElement(o: any): o is HTMLElement {
783 784 785 786
	if (typeof HTMLElement === 'object') {
		return o instanceof HTMLElement;
	}
	return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
E
Erich Gamma 已提交
787 788
}

B
Benjamin Pasero 已提交
789
export const EventType = {
E
Erich Gamma 已提交
790 791 792 793 794 795 796 797 798
	// 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 已提交
799
	WHEEL: 'wheel',
E
Erich Gamma 已提交
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
	// 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 已提交
830 831 832
	ANIMATION_START: isWebKit ? 'webkitAnimationStart' : 'animationstart',
	ANIMATION_END: isWebKit ? 'webkitAnimationEnd' : 'animationend',
	ANIMATION_ITERATION: isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
E
Erich Gamma 已提交
833 834
};

A
Alex Dima 已提交
835 836 837 838 839
export interface EventLike {
	preventDefault(): void;
	stopPropagation(): void;
}

B
Benjamin Pasero 已提交
840 841
export const EventHelper = {
	stop: function(e: EventLike, cancelBubble?: boolean) {
E
Erich Gamma 已提交
842 843 844 845 846 847 848 849 850 851 852 853
		if (e.preventDefault) {
			e.preventDefault();
		} else {
			// IE8
			(<any>e).returnValue = false;
		}

		if (cancelBubble) {
			if (e.stopPropagation) {
				e.stopPropagation();
			} else {
				// IE8
A
Alex Dima 已提交
854
				(<any>e).cancelBubble = true;
E
Erich Gamma 已提交
855 856 857 858 859 860
			}
		}
	}
};

export interface IFocusTracker {
861 862
	addBlurListener(fn:()=>void): IDisposable;
	addFocusListener(fn:()=>void): IDisposable;
B
Benjamin Pasero 已提交
863
	dispose(): void;
E
Erich Gamma 已提交
864 865
}

B
Benjamin Pasero 已提交
866 867 868
export function saveParentsScrollTop(node: Element): number[] {
	let r: number[] = [];
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
869 870 871 872 873 874
		r[i] = node.scrollTop;
		node = <Element>node.parentNode;
	}
	return r;
}

B
Benjamin Pasero 已提交
875 876
export function restoreParentsScrollTop(node: Element, state: number[]): void {
	for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
E
Erich Gamma 已提交
877 878 879 880 881 882 883
		if (node.scrollTop !== state[i]) {
			node.scrollTop = state[i];
		}
		node = <Element>node.parentNode;
	}
}

884
class FocusTracker extends Disposable implements IFocusTracker {
E
Erich Gamma 已提交
885

886
	private _eventEmitter: EventEmitter;
E
Erich Gamma 已提交
887

888
	constructor(element: HTMLElement|Window) {
889 890 891 892 893 894 895 896 897 898 899 900
		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 已提交
901
			}
902
		};
E
Erich Gamma 已提交
903

904 905 906 907 908 909 910 911 912 913 914 915
		let onBlur = (event) => {
			if (hasFocus) {
				loosingFocus = true;
				window.setTimeout(() => {
					if (loosingFocus) {
						loosingFocus = false;
						hasFocus = false;
						this._eventEmitter.emit('blur', {});
					}
				}, 0);
			}
		};
E
Erich Gamma 已提交
916

917 918 919
		this._register(addDisposableListener(element, EventType.FOCUS, onFocus, true));
		this._register(addDisposableListener(element, EventType.BLUR, onBlur, true));
	}
E
Erich Gamma 已提交
920

921 922 923
	public addFocusListener(fn:()=>void): IDisposable {
		return this._eventEmitter.addListener2('focus', fn);
	}
E
Erich Gamma 已提交
924

925 926 927 928 929
	public addBlurListener(fn:()=>void): IDisposable {
		return this._eventEmitter.addListener2('blur', fn);
	}
}

930
export function trackFocus(element: HTMLElement|Window): IFocusTracker {
931
	return new FocusTracker(element);
E
Erich Gamma 已提交
932 933 934 935 936 937 938
}

export function append<T extends Node>(parent: HTMLElement, child: T): T {
	parent.appendChild(child);
	return child;
}

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

// Similar to builder, but much more lightweight
J
Joao Moreno 已提交
942
export function emmet<T extends HTMLElement>(description: string): T {
B
Benjamin Pasero 已提交
943
	let match = SELECTOR_REGEX.exec(description);
E
Erich Gamma 已提交
944 945 946 947 948

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

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

A
Alex Dima 已提交
951 952 953 954 955 956
	if (match[3]) {
		result.id = match[3];
	}
	if (match[4]) {
		result.className = match[4].replace(/\./g, ' ').trim();
	}
E
Erich Gamma 已提交
957

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

J
Joao Moreno 已提交
961
export function show(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
962
	for (let element of elements) {
J
Joao Moreno 已提交
963 964
		element.style.display = null;
	}
965 966
}

J
Joao Moreno 已提交
967
export function hide(...elements: HTMLElement[]): void {
J
Johannes Rieken 已提交
968
	for (let element of elements) {
J
Joao Moreno 已提交
969 970
		element.style.display = 'none';
	}
971
}
972

B
Benjamin Pasero 已提交
973
function findParentWithAttribute(node: Node, attribute: string): HTMLElement {
974
	while (node) {
B
Benjamin Pasero 已提交
975
		if (node instanceof HTMLElement && node.hasAttribute(attribute)) {
976 977 978
			return node;
		}

B
Benjamin Pasero 已提交
979
		node = node.parentNode;
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
	}

	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 已提交
1001
	node.removeAttribute('tabindex');
A
Alex Dima 已提交
1002
}
1003 1004 1005

export function getElementsByTagName(tag: string): HTMLElement[] {
	return Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
J
Joao Moreno 已提交
1006 1007 1008 1009 1010 1011 1012 1013
}

export function finalHandler<T extends Event>(fn: (event: T)=>any): (event: T)=>any {
	return e => {
		e.preventDefault();
		e.stopPropagation();
		fn(e);
	};
1014
}