-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
color.js
88 lines (78 loc) · 1.92 KB
/
color.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict'
const { fromString } = require('css-color-converter')
// When updating these, be sure also to update the list in `badge-maker/README.md`.
const namedColors = {
brightgreen: '#4c1',
green: '#97ca00',
yellow: '#dfb317',
yellowgreen: '#a4a61d',
orange: '#fe7d37',
red: '#e05d44',
blue: '#007ec6',
grey: '#555',
lightgrey: '#9f9f9f',
}
const aliases = {
gray: 'grey',
lightgray: 'lightgrey',
critical: 'red',
important: 'orange',
success: 'brightgreen',
informational: 'blue',
inactive: 'lightgrey',
}
const resolvedAliases = {}
Object.entries(aliases).forEach(([alias, original]) => {
resolvedAliases[alias] = namedColors[original]
})
// This function returns false for `#ccc`. However `isCSSColor('#ccc')` is
// true.
const hexColorRegex = /^([\da-f]{3}){1,2}$/i
function isHexColor(s = '') {
return hexColorRegex.test(s)
}
function isCSSColor(color) {
return typeof color === 'string' && fromString(color.trim())
}
function normalizeColor(color) {
if (color === undefined) {
return undefined
} else if (color in namedColors) {
return color
} else if (color in aliases) {
return aliases[color]
} else if (isHexColor(color)) {
return `#${color.toString().toLowerCase()}`
} else if (isCSSColor(color)) {
return color.toLowerCase()
} else {
return undefined
}
}
function toSvgColor(color) {
const normalized = normalizeColor(color)
if (normalized in namedColors) {
return namedColors[normalized]
} else if (normalized in resolvedAliases) {
return resolvedAliases[normalized]
} else {
return normalized
}
}
function brightness(color) {
if (color) {
const cssColor = fromString(color)
if (cssColor) {
const rgb = cssColor.toRgbaArray()
return +((rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 255000).toFixed(2)
}
}
return 0
}
module.exports = {
namedColors,
isHexColor,
normalizeColor,
toSvgColor,
brightness,
}