Debian Codegraph @

closure-library/closure/goog/color/alpha.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Utilities related to alpha/transparent colors and alpha color
17 * conversion.
18 */
19
20 goog.provide('goog.color.alpha');
21
22 goog.require('goog.color');
23
24
25 /**
26 * Parses an alpha color out of a string.
27 * @param {string} str Color in some format.
28 * @return {{hex: string, type: string}} 'hex' is a string containing
29 * a hex representation of the color, and 'type' is a string
30 * containing the type of color format passed in ('hex', 'rgb', 'named').
31 */
32 goog.color.alpha.parse = function(str) {
33 var result = {};
34 str = String(str);
35
36 var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
37 if (goog.color.alpha.isValidAlphaHexColor_(maybeHex)) {
38 result.hex = goog.color.alpha.normalizeAlphaHex_(maybeHex);
39 result.type = 'hex';
40 return result;
41 } else {
42 var rgba = goog.color.alpha.isValidRgbaColor_(str);
43 if (rgba.length) {
44 result.hex = goog.color.alpha.rgbaArrayToHex(rgba);
45 result.type = 'rgba';
46 return result;
47 } else {
48 var hsla = goog.color.alpha.isValidHslaColor_(str);
49 if (hsla.length) {
50 result.hex = goog.color.alpha.hslaArrayToHex(hsla);
51 result.type = 'hsla';
52 return result;
53 }
54 }
55 }
56 throw new Error(str + ' is not a valid color string');
57 };
58
59
60 /**
61 * Converts a hex representation of a color to RGBA.
62 * @param {string} hexColor Color to convert.
63 * @return {string} string of the form 'rgba(R,G,B,A)' which can be used in
64 * styles.
65 */
66 goog.color.alpha.hexToRgbaStyle = function(hexColor) {
67 return goog.color.alpha.rgbaStyle_(goog.color.alpha.hexToRgba(hexColor));
68 };
69
70
71 /**
72 * Extracts a substring, from startIdx to endIdx, of the normalized (lowercase
73 * #rrggbbaa) form of a hex-with-alpha color.
74 * @param {string} colorWithAlpha The alpha hex color to get the hex color from.
75 * This may be four or eight digits.
76 * @param {number} startIdx The start index within the #rrggbbaa color.
77 * @param {number} endIdx The end index within the #rrggbbbaa color.
78 * @return {string} The requested startIdx-to-endIdx substring from the color.
79 * @private
80 */
81 goog.color.alpha.extractColor_ = function(colorWithAlpha, startIdx, endIdx) {
82 if (goog.color.alpha.isValidAlphaHexColor_(colorWithAlpha)) {
83 var fullColor = goog.color.prependHashIfNecessaryHelper(colorWithAlpha);
84 var normalizedColor = goog.color.alpha.normalizeAlphaHex_(fullColor);
85 return normalizedColor.substring(startIdx, endIdx);
86 } else {
87 throw new Error(colorWithAlpha + ' is not a valid 8-hex color string');
88 }
89 };
90
91
92 /**
93 * Gets the hex color part of an alpha hex color. For example, both '#abcd' and
94 * '#AABBCC12' return '#aabbcc'.
95 * @param {string} colorWithAlpha The alpha hex color to get the hex color from.
96 * @return {string} The hex color where the alpha part has been stripped off.
97 */
98 goog.color.alpha.extractHexColor = function(colorWithAlpha) {
99 return goog.color.alpha.extractColor_(colorWithAlpha, 0, 7);
100 };
101
102
103 /**
104 * Gets the alpha color part of an alpha hex color. For example, both '#123A'
105 * and '#123456aa' return 'aa'. The result is always two characters long.
106 * @param {string} colorWithAlpha The alpha hex color to get the hex color from.
107 * @return {string} The two-character alpha from the given color.
108 */
109 goog.color.alpha.extractAlpha = function(colorWithAlpha) {
110 return goog.color.alpha.extractColor_(colorWithAlpha, 7, 9);
111 };
112
113
114 /**
115 * Regular expression for extracting the digits in a hex color quadruplet.
116 * @type {RegExp}
117 * @private
118 */
119 goog.color.alpha.hexQuadrupletRe_ = /#(.)(.)(.)(.)/;
120
121
122 /**
123 * Normalize a hex representation of an alpha color.
124 * @param {string} hexColor an alpha hex color string.
125 * @return {string} hex color in the format '#rrggbbaa' with all lowercase
126 * literals.
127 * @private
128 */
129 goog.color.alpha.normalizeAlphaHex_ = function(hexColor) {
130 if (!goog.color.alpha.isValidAlphaHexColor_(hexColor)) {
131 throw new Error('\'' + hexColor + '\' is not a valid alpha hex color');
132 }
133 if (hexColor.length == 5) { // of the form #RGBA
134 hexColor = hexColor.replace(
135 goog.color.alpha.hexQuadrupletRe_, '#$1$1$2$2$3$3$4$4');
136 }
137 return hexColor.toLowerCase();
138 };
139
140
141 /**
142 * Converts an 8-hex representation of a color to RGBA.
143 * @param {string} hexColor Color to convert.
144 * @return {!Array<number>} array containing [r, g, b, a].
145 * r, g, b are ints between 0
146 * and 255, and a is a value between 0 and 1.
147 */
148 goog.color.alpha.hexToRgba = function(hexColor) {
149 // TODO(user): Enhance code sharing with goog.color, for example by
150 // adding a goog.color.genericHexToRgb method.
151 hexColor = goog.color.alpha.normalizeAlphaHex_(hexColor);
152 var r = parseInt(hexColor.substr(1, 2), 16);
153 var g = parseInt(hexColor.substr(3, 2), 16);
154 var b = parseInt(hexColor.substr(5, 2), 16);
155 var a = parseInt(hexColor.substr(7, 2), 16);
156
157 return [r, g, b, a / 255];
158 };
159
160
161 /**
162 * Converts a color from RGBA to hex representation.
163 * @param {number} r Amount of red, int between 0 and 255.
164 * @param {number} g Amount of green, int between 0 and 255.
165 * @param {number} b Amount of blue, int between 0 and 255.
166 * @param {number} a Amount of alpha, float between 0 and 1.
167 * @return {string} hex representation of the color.
168 */
169 goog.color.alpha.rgbaToHex = function(r, g, b, a) {
170 var intAlpha = Math.floor(a * 255);
171 if (isNaN(intAlpha) || intAlpha < 0 || intAlpha > 255) {
172 // TODO(user): The CSS spec says the value should be clamped.
173 throw new Error(
174 '"(' + r + ',' + g + ',' + b + ',' + a +
175 '") is not a valid RGBA color');
176 }
177 var hexA = goog.color.prependZeroIfNecessaryHelper(intAlpha.toString(16));
178 return goog.color.rgbToHex(r, g, b) + hexA;
179 };
180
181
182 /**
183 * Converts a color from HSLA to hex representation.
184 * @param {number} h Amount of hue, int between 0 and 360.
185 * @param {number} s Amount of saturation, int between 0 and 100.
186 * @param {number} l Amount of lightness, int between 0 and 100.
187 * @param {number} a Amount of alpha, float between 0 and 1.
188 * @return {string} hex representation of the color.
189 */
190 goog.color.alpha.hslaToHex = function(h, s, l, a) {
191 var intAlpha = Math.floor(a * 255);
192 if (isNaN(intAlpha) || intAlpha < 0 || intAlpha > 255) {
193 // TODO(user): The CSS spec says the value should be clamped.
194 throw new Error(
195 '"(' + h + ',' + s + ',' + l + ',' + a +
196 '") is not a valid HSLA color');
197 }
198 var hexA = goog.color.prependZeroIfNecessaryHelper(intAlpha.toString(16));
199 return goog.color.hslToHex(h, s / 100, l / 100) + hexA;
200 };
201
202
203 /**
204 * Converts a color from RGBA to hex representation.
205 * @param {Array<number>} rgba Array of [r, g, b, a], with r, g, b in [0, 255]
206 * and a in [0, 1].
207 * @return {string} hex representation of the color.
208 */
209 goog.color.alpha.rgbaArrayToHex = function(rgba) {
210 return goog.color.alpha.rgbaToHex(rgba[0], rgba[1], rgba[2], rgba[3]);
211 };
212
213
214 /**
215 * Converts a color from RGBA to an RGBA style string.
216 * @param {number} r Value of red, in [0, 255].
217 * @param {number} g Value of green, in [0, 255].
218 * @param {number} b Value of blue, in [0, 255].
219 * @param {number} a Value of alpha, in [0, 1].
220 * @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
221 */
222 goog.color.alpha.rgbaToRgbaStyle = function(r, g, b, a) {
223 if (isNaN(r) || r < 0 || r > 255 || isNaN(g) || g < 0 || g > 255 ||
224 isNaN(b) || b < 0 || b > 255 || isNaN(a) || a < 0 || a > 1) {
225 throw new Error(
226 '"(' + r + ',' + g + ',' + b + ',' + a +
227 ')" is not a valid RGBA color');
228 }
229 return goog.color.alpha.rgbaStyle_([r, g, b, a]);
230 };
231
232
233 /**
234 * Converts a color from RGBA to an RGBA style string.
235 * @param {(Array<number>|Float32Array)} rgba Array of [r, g, b, a],
236 * with r, g, b in [0, 255] and a in [0, 1].
237 * @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
238 */
239 goog.color.alpha.rgbaArrayToRgbaStyle = function(rgba) {
240 return goog.color.alpha.rgbaToRgbaStyle(rgba[0], rgba[1], rgba[2], rgba[3]);
241 };
242
243
244 /**
245 * Converts a color from HSLA to hex representation.
246 * @param {Array<number>} hsla Array of [h, s, l, a], where h is an integer in
247 * [0, 360], s and l are integers in [0, 100], and a is in [0, 1].
248 * @return {string} hex representation of the color, such as '#af457eff'.
249 */
250 goog.color.alpha.hslaArrayToHex = function(hsla) {
251 return goog.color.alpha.hslaToHex(hsla[0], hsla[1], hsla[2], hsla[3]);
252 };
253
254
255 /**
256 * Converts a color from HSLA to an RGBA style string.
257 * @param {Array<number>} hsla Array of [h, s, l, a], where h is and integer in
258 * [0, 360], s and l are integers in [0, 100], and a is in [0, 1].
259 * @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
260 */
261 goog.color.alpha.hslaArrayToRgbaStyle = function(hsla) {
262 return goog.color.alpha.hslaToRgbaStyle(hsla[0], hsla[1], hsla[2], hsla[3]);
263 };
264
265
266 /**
267 * Converts a color from HSLA to an RGBA style string.
268 * @param {number} h Amount of hue, int between 0 and 360.
269 * @param {number} s Amount of saturation, int between 0 and 100.
270 * @param {number} l Amount of lightness, int between 0 and 100.
271 * @param {number} a Amount of alpha, float between 0 and 1.
272 * @return {string} An 'rgba(r,g,b,a)' string ready for use in a CSS rule.
273 * styles.
274 */
275 goog.color.alpha.hslaToRgbaStyle = function(h, s, l, a) {
276 return goog.color.alpha.rgbaStyle_(goog.color.alpha.hslaToRgba(h, s, l, a));
277 };
278
279
280 /**
281 * Converts a color from HSLA color space to RGBA color space.
282 * @param {number} h Amount of hue, int between 0 and 360.
283 * @param {number} s Amount of saturation, int between 0 and 100.
284 * @param {number} l Amount of lightness, int between 0 and 100.
285 * @param {number} a Amount of alpha, float between 0 and 1.
286 * @return {!Array<number>} [r, g, b, a] values for the color, where r, g, b
287 * are integers in [0, 255] and a is a float in [0, 1].
288 */
289 goog.color.alpha.hslaToRgba = function(h, s, l, a) {
290 return goog.color.hslToRgb(h, s / 100, l / 100).concat(a);
291 };
292
293
294 /**
295 * Converts a color from RGBA color space to HSLA color space.
296 * Modified from {@link http://en.wikipedia.org/wiki/HLS_color_space}.
297 * @param {number} r Value of red, in [0, 255].
298 * @param {number} g Value of green, in [0, 255].
299 * @param {number} b Value of blue, in [0, 255].
300 * @param {number} a Value of alpha, in [0, 255].
301 * @return {!Array<number>} [h, s, l, a] values for the color, with h an int in
302 * [0, 360] and s, l and a in [0, 1].
303 */
304 goog.color.alpha.rgbaToHsla = function(r, g, b, a) {
305 return goog.color.rgbToHsl(r, g, b).concat(a);
306 };
307
308
309 /**
310 * Converts a color from RGBA color space to HSLA color space.
311 * @param {Array<number>} rgba [r, g, b, a] values for the color, each in
312 * [0, 255].
313 * @return {!Array<number>} [h, s, l, a] values for the color, with h in
314 * [0, 360] and s, l and a in [0, 1].
315 */
316 goog.color.alpha.rgbaArrayToHsla = function(rgba) {
317 return goog.color.alpha.rgbaToHsla(rgba[0], rgba[1], rgba[2], rgba[3]);
318 };
319
320
321 /**
322 * Helper for isValidAlphaHexColor_.
323 * @type {RegExp}
324 * @private
325 */
326 goog.color.alpha.validAlphaHexColorRe_ = /^#(?:[0-9a-f]{4}){1,2}$/i;
327
328
329 /**
330 * Checks if a string is a valid alpha hex color. We expect strings of the
331 * format #RRGGBBAA (ex: #1b3d5f5b) or #RGBA (ex: #3CAF == #33CCAAFF).
332 * @param {string} str String to check.
333 * @return {boolean} Whether the string is a valid alpha hex color.
334 * @private
335 */
336 // TODO(user): Support percentages when goog.color also supports them.
337 goog.color.alpha.isValidAlphaHexColor_ = function(str) {
338 return goog.color.alpha.validAlphaHexColorRe_.test(str);
339 };
340
341
342 /**
343 * Helper for isNormalizedAlphaHexColor_.
344 * @type {RegExp}
345 * @private
346 */
347 goog.color.alpha.normalizedAlphaHexColorRe_ = /^#[0-9a-f]{8}$/;
348
349
350 /**
351 * Checks if a string is a normalized alpha hex color.
352 * We expect strings of the format #RRGGBBAA (ex: #1b3d5f5b)
353 * using only lowercase letters.
354 * @param {string} str String to check.
355 * @return {boolean} Whether the string is a normalized hex color.
356 * @private
357 */
358 goog.color.alpha.isNormalizedAlphaHexColor_ = function(str) {
359 return goog.color.alpha.normalizedAlphaHexColorRe_.test(str);
360 };
361
362
363 /**
364 * Regular expression for matching and capturing RGBA style strings. Helper for
365 * isValidRgbaColor_.
366 * @type {RegExp}
367 * @private
368 */
369 goog.color.alpha.rgbaColorRe_ =
370 /^(?:rgba)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|1|0\.\d{0,10})\)$/i;
371
372
373 /**
374 * Regular expression for matching and capturing HSLA style strings. Helper for
375 * isValidHslaColor_.
376 * @type {RegExp}
377 * @private
378 */
379 goog.color.alpha.hslaColorRe_ =
380 /^(?:hsla)\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\%,\s?(0|[1-9]\d{0,2})\%,\s?(0|1|0\.\d{0,10})\)$/i;
381
382
383 /**
384 * Checks if a string is a valid rgba color. We expect strings of the format
385 * '(r, g, b, a)', or 'rgba(r, g, b, a)', where r, g, b are ints in [0, 255]
386 * and a is a float in [0, 1].
387 * @param {string} str String to check.
388 * @return {!Array<number>} the integers [r, g, b, a] for valid colors or the
389 * empty array for invalid colors.
390 * @private
391 */
392 goog.color.alpha.isValidRgbaColor_ = function(str) {
393 // Each component is separate (rather than using a repeater) so we can
394 // capture the match. Also, we explicitly set each component to be either 0,
395 // or start with a non-zero, to prevent octal numbers from slipping through.
396 var regExpResultArray = str.match(goog.color.alpha.rgbaColorRe_);
397 if (regExpResultArray) {
398 var r = Number(regExpResultArray[1]);
399 var g = Number(regExpResultArray[2]);
400 var b = Number(regExpResultArray[3]);
401 var a = Number(regExpResultArray[4]);
402 if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255 &&
403 a >= 0 && a <= 1) {
404 return [r, g, b, a];
405 }
406 }
407 return [];
408 };
409
410
411 /**
412 * Checks if a string is a valid hsla color. We expect strings of the format
413 * 'hsla(h, s, l, a)', where s in an int in [0, 360], s and l are percentages
414 * between 0 and 100 such as '50%' or '70%', and a is a float in [0, 1].
415 * @param {string} str String to check.
416 * @return {!Array<number>} the integers [h, s, l, a] for valid colors or the
417 * empty array for invalid colors.
418 * @private
419 */
420 goog.color.alpha.isValidHslaColor_ = function(str) {
421 // Each component is separate (rather than using a repeater) so we can
422 // capture the match. Also, we explicitly set each component to be either 0,
423 // or start with a non-zero, to prevent octal numbers from slipping through.
424 var regExpResultArray = str.match(goog.color.alpha.hslaColorRe_);
425 if (regExpResultArray) {
426 var h = Number(regExpResultArray[1]);
427 var s = Number(regExpResultArray[2]);
428 var l = Number(regExpResultArray[3]);
429 var a = Number(regExpResultArray[4]);
430 if (h >= 0 && h <= 360 && s >= 0 && s <= 100 && l >= 0 && l <= 100 &&
431 a >= 0 && a <= 1) {
432 return [h, s, l, a];
433 }
434 }
435 return [];
436 };
437
438
439 /**
440 * Takes an array of [r, g, b, a] and converts it into a string appropriate for
441 * CSS styles. The alpha channel value is rounded to 3 decimal places to make
442 * sure the produced string is not too long.
443 * @param {Array<number>} rgba [r, g, b, a] with r, g, b in [0, 255] and a
444 * in [0, 1].
445 * @return {string} string of the form 'rgba(r,g,b,a)'.
446 * @private
447 */
448 goog.color.alpha.rgbaStyle_ = function(rgba) {
449 var roundedRgba = rgba.slice(0);
450 roundedRgba[3] = Math.round(rgba[3] * 1000) / 1000;
451 return 'rgba(' + roundedRgba.join(',') + ')';
452 };
453
454
455 /**
456 * Converts from h,s,v,a values to a hex string
457 * @param {number} h Hue, in [0, 1].
458 * @param {number} s Saturation, in [0, 1].
459 * @param {number} v Value, in [0, 255].
460 * @param {number} a Alpha, in [0, 1].
461 * @return {string} hex representation of the color.
462 */
463 goog.color.alpha.hsvaToHex = function(h, s, v, a) {
464 var alpha = Math.floor(a * 255);
465 return goog.color.hsvArrayToHex([h, s, v]) +
466 goog.color.prependZeroIfNecessaryHelper(alpha.toString(16));
467 };
468
469
470 /**
471 * Converts from an HSVA array to a hex string
472 * @param {Array<number>} hsva Array of [h, s, v, a] in
473 * [[0, 1], [0, 1], [0, 255], [0, 1]].
474 * @return {string} hex representation of the color.
475 */
476 goog.color.alpha.hsvaArrayToHex = function(hsva) {
477 return goog.color.alpha.hsvaToHex(hsva[0], hsva[1], hsva[2], hsva[3]);
478 };