-
Notifications
You must be signed in to change notification settings - Fork 30
/
parse.js
65 lines (62 loc) · 1.39 KB
/
parse.js
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
import { parsers, colorProfiles, getMode } from './modes.js';
import { rx_num_per_none } from './util/regex.js';
function parseColorSyntax(color) {
const m = color.match(/^color\(\s*([a-z0-9-]+)\s*(.*?)\s*\)$/);
if (!m) {
return undefined;
}
const mode = colorProfiles[m[1]];
if (!mode) {
return undefined;
}
const res = { mode };
const [cmp_string, alpha] = m[2].split(/\s*\/\s*/);
let cm;
if (alpha !== undefined) {
cm = alpha.match(rx_num_per_none);
if (!cm) {
return undefined;
}
if (cm[1] !== undefined) {
res.alpha = cm[1] / 100;
} else if (cm[2] !== undefined) {
res.alpha = +cm[2];
}
}
const components = cmp_string.split(/\s+/);
let channels = getMode(mode).channels;
for (let i = 0, ch; i < channels.length; i++) {
ch = channels[i];
if (ch === 'alpha') {
continue;
}
if (i >= components.length || !components[i]) {
res[ch] = 0;
continue;
}
if (!(cm = components[i].match(rx_num_per_none))) {
return undefined;
}
if (cm[1] !== undefined) {
res[ch] = cm[1] / 100;
} else if (cm[2] !== undefined) {
res[ch] = +cm[2];
}
}
return res;
}
const parse = color => {
if (typeof color !== 'string') {
return undefined;
}
let result = undefined;
let i = 0;
let len = parsers.length;
while (i < len) {
if ((result = parsers[i++](color)) !== undefined) {
return result;
}
}
return parseColorSyntax(color);
};
export default parse;