Merge branch '2.1' into 3.0
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / js / WoltLabSuite / Core / ColorUtil.js
1 define([], function() {
2 "use strict";
3
4 var ColorUtil = {
5 /**
6 * Converts HEX into RGB.
7 *
8 * @param string hex hex value as #ccc or #abc123
9 * @return object r-g-b values
10 */
11 hexToRgb: function(hex) {
12 hex = hex.replace(/^#/, '');
13 if (/^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(hex)) {
14 // only convert abc and abcdef
15 hex = hex.split('');
16
17 // parse shorthand #xyz
18 if (hex.length === 3) {
19 return {
20 r: parseInt(hex[0] + '' + hex[0], 16),
21 g: parseInt(hex[1] + '' + hex[1], 16),
22 b: parseInt(hex[2] + '' + hex[2], 16)
23 };
24 }
25 else {
26 return {
27 r: parseInt(hex[0] + '' + hex[1], 16),
28 g: parseInt(hex[2] + '' + hex[3], 16),
29 b: parseInt(hex[4] + '' + hex[5], 16)
30 };
31 }
32 }
33
34 return Number.NaN;
35 },
36
37 /**
38 * Converts RGB into HEX.
39 *
40 * @see http://www.linuxtopia.org/online_books/javascript_guides/javascript_faq/rgbtohex.htm
41 *
42 * @param {(int|string)} r red or rgb(1, 2, 3) or rgba(1, 2, 3, .4)
43 * @param {int} g green
44 * @param {int} b blue
45 * @return {string} hex value #abc123
46 */
47 rgbToHex: function(r, g, b) {
48 var charList = "0123456789ABCDEF";
49
50 if (g === undefined) {
51 if (r.match(/^rgba?\((\d+), ?(\d+), ?(d\+)(?:, ?[0-9.]+)?\)$/)) {
52 r = RegExp.$1;
53 g = RegExp.$2;
54 b = RegExp.$3;
55 }
56 }
57
58 return (charList.charAt((r - r % 16) / 16) + '' + charList.charAt(r % 16)) + '' + (charList.charAt((g - g % 16) / 16) + '' + charList.charAt(g % 16)) + '' + (charList.charAt((b - b % 16) / 16) + '' + charList.charAt(b % 16));
59 }
60 };
61
62 return ColorUtil;
63 });