aboutsummaryrefslogtreecommitdiff
path: root/js/utils/util.js
blob: b96fe297a523bf57c9d215310d068c91b50c7278 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
 * Extend object a with the properties of object b.
 * If there's a conflict, object b takes precedence.
 *
 * @param {object} a
 * @param {object} b
 */
export const extend = ( a, b ) => {

	for( let i in b ) {
		a[ i ] = b[ i ];
	}

	return a;

}

/**
 * Converts the target object to an array.
 *
 * @param {object} o
 * @return {object[]}
 */
export const toArray = ( o ) => {

	return Array.prototype.slice.call( o );

}

/**
 * Utility for deserializing a value.
 *
 * @param {*} value
 * @return {*}
 */
export const deserialize = ( value ) => {

	if( typeof value === 'string' ) {
		if( value === 'null' ) return null;
		else if( value === 'true' ) return true;
		else if( value === 'false' ) return false;
		else if( value.match( /^-?[\d\.]+$/ ) ) return parseFloat( value );
	}

	return value;

}

/**
 * Measures the distance in pixels between point a
 * and point b.
 *
 * @param {object} a point with x/y properties
 * @param {object} b point with x/y properties
 *
 * @return {number}
 */
export const distanceBetween = ( a, b ) => {

	let dx = a.x - b.x,
		dy = a.y - b.y;

	return Math.sqrt( dx*dx + dy*dy );

}

/**
 * Applies a CSS transform to the target element.
 *
 * @param {HTMLElement} element
 * @param {string} transform
 */
export const transformElement = ( element, transform ) => {

	element.style.transform = transform;

}

/**
 * Find the closest parent that matches the given
 * selector.
 *
 * @param {HTMLElement} target The child element
 * @param {String} selector The CSS selector to match
 * the parents against
 *
 * @return {HTMLElement} The matched parent or null
 * if no matching parent was found
 */
export const closestParent = ( target, selector ) => {

	let parent = target.parentNode;

	while( parent ) {

		// There's some overhead doing this each time, we don't
		// want to rewrite the element prototype but should still
		// be enough to feature detect once at startup...
		let matchesMethod = parent.matches || parent.matchesSelector || parent.msMatchesSelector;

		// If we find a match, we're all set
		if( matchesMethod && matchesMethod.call( parent, selector ) ) {
			return parent;
		}

		// Keep searching
		parent = parent.parentNode;

	}

	return null;

}

/**
 * Converts various color input formats to an {r:0,g:0,b:0} object.
 *
 * @param {string} color The string representation of a color
 * @example
 * colorToRgb('#000');
 * @example
 * colorToRgb('#000000');
 * @example
 * colorToRgb('rgb(0,0,0)');
 * @example
 * colorToRgb('rgba(0,0,0)');
 *
 * @return {{r: number, g: number, b: number, [a]: number}|null}
 */
export const colorToRgb = ( color ) => {

	let hex3 = color.match( /^#([0-9a-f]{3})$/i );
	if( hex3 && hex3[1] ) {
		hex3 = hex3[1];
		return {
			r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11,
			g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11,
			b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11
		};
	}

	let hex6 = color.match( /^#([0-9a-f]{6})$/i );
	if( hex6 && hex6[1] ) {
		hex6 = hex6[1];
		return {
			r: parseInt( hex6.substr( 0, 2 ), 16 ),
			g: parseInt( hex6.substr( 2, 2 ), 16 ),
			b: parseInt( hex6.substr( 4, 2 ), 16 )
		};
	}

	let rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i );
	if( rgb ) {
		return {
			r: parseInt( rgb[1], 10 ),
			g: parseInt( rgb[2], 10 ),
			b: parseInt( rgb[3], 10 )
		};
	}

	let rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i );
	if( rgba ) {
		return {
			r: parseInt( rgba[1], 10 ),
			g: parseInt( rgba[2], 10 ),
			b: parseInt( rgba[3], 10 ),
			a: parseFloat( rgba[4] )
		};
	}

	return null;

}

/**
 * Calculates brightness on a scale of 0-255.
 *
 * @param {string} color See colorToRgb for supported formats.
 * @see {@link colorToRgb}
 */
export const colorBrightness = ( color ) => {

	if( typeof color === 'string' ) color = colorToRgb( color );

	if( color ) {
		return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000;
	}

	return null;

}

/**
 * Handling the fullscreen functionality via the fullscreen API
 *
 * @see http://fullscreen.spec.whatwg.org/
 * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
 */
export const enterFullscreen = () => {

	let element = document.documentElement;

	// Check which implementation is available
	let requestMethod = element.requestFullscreen ||
						element.webkitRequestFullscreen ||
						element.webkitRequestFullScreen ||
						element.mozRequestFullScreen ||
						element.msRequestFullscreen;

	if( requestMethod ) {
		requestMethod.apply( element );
	}

}

/**
 * Injects the given CSS styles into the DOM.
 *
 * @param {string} value
 */
export const injectStyleSheet = ( value ) => {

	let tag = document.createElement( 'style' );
	tag.type = 'text/css';
	if( tag.styleSheet ) {
		tag.styleSheet.cssText = value;
	}
	else {
		tag.appendChild( document.createTextNode( value ) );
	}
	document.getElementsByTagName( 'head' )[0].appendChild( tag );

}

/**
 * Loads a JavaScript file from the given URL and executes it.
 *
 * @param {string} url Address of the .js file to load
 * @param {function} callback Method to invoke when the script
 * has loaded and executed
 */
export const loadScript = ( url, callback ) => {

	const script = document.createElement( 'script' );
	script.type = 'text/javascript';
	script.async = false;
	script.defer = false;
	script.src = url;

	if( typeof callback === 'function' ) {

		// Success callback
		script.onload = script.onreadystatechange = event => {
			if( event.type === 'load' || /loaded|complete/.test( script.readyState ) ) {

				// Kill event listeners
				script.onload = script.onreadystatechange = script.onerror = null;

				callback();

			}
		};

		// Error callback
		script.onerror = err => {

			// Kill event listeners
			script.onload = script.onreadystatechange = script.onerror = null;

			callback( new Error( 'Failed loading script: ' + script.src + '\n' + err ) );

		};

	}

	// Append the script at the end of <head>
	const head = document.querySelector( 'head' );
	head.insertBefore( script, head.lastChild );

}