-
-
Notifications
You must be signed in to change notification settings - Fork 208
/
rgb.js
52 lines (48 loc) · 1.36 KB
/
rgb.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
// @flow
import reduceHexValue from '../internalHelpers/_reduceHexValue'
import toHex from '../internalHelpers/_numberToHex'
import type { RgbColor } from '../types/color'
/**
* Returns a string value for the color. The returned result is the smallest possible hex notation.
*
* @example
* // Styles as object usage
* const styles = {
* background: rgb(255, 205, 100),
* background: rgb({ red: 255, green: 205, blue: 100 }),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${rgb(255, 205, 100)};
* background: ${rgb({ red: 255, green: 205, blue: 100 })};
* `
*
* // CSS in JS Output
*
* element {
* background: "#ffcd64";
* background: "#ffcd64";
* }
*/
function rgb(value: RgbColor | number, green?: number, blue?: number): string {
if (
typeof value === 'number' &&
typeof green === 'number' &&
typeof blue === 'number'
) {
return reduceHexValue(`#${toHex(value)}${toHex(green)}${toHex(blue)}`)
} else if (
typeof value === 'object' &&
green === undefined &&
blue === undefined
) {
return reduceHexValue(
`#${toHex(value.red)}${toHex(value.green)}${toHex(value.blue)}`,
)
}
throw new Error(
'Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).',
)
}
export default rgb