-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.ts
More file actions
49 lines (44 loc) · 1.18 KB
/
convert.ts
File metadata and controls
49 lines (44 loc) · 1.18 KB
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
/**
* @file Color conversion helpers — `isRgbTuple()` narrows a `ColorValue` to the
* RGB-tuple branch, and `toRgb()` resolves a named color or passes through an
* existing tuple.
*/
import { ArrayIsArray } from '../primordials/array'
import { colorToRgb } from './palette'
import type { ColorRgb, ColorValue } from './types'
/**
* Type guard to check if a color value is an RGB tuple.
*
* @example
* ;```typescript
* isRgbTuple([255, 0, 0]) // true
* isRgbTuple('red') // false
* ```
*
* @param value - Color value to check.
*
* @returns `true` if value is an RGB tuple, `false` if it's a color name
*/
export function isRgbTuple(value: ColorValue): value is ColorRgb {
return ArrayIsArray(value)
}
/**
* Convert a color value to RGB tuple format. Named colors are looked up in the
* `colorToRgb` map, RGB tuples are returned as-is.
*
* @example
* ;```typescript
* toRgb('red') // [255, 0, 0]
* toRgb([0, 128, 0]) // [0, 128, 0]
* ```
*
* @param color - Color name or RGB tuple.
*
* @returns RGB tuple with values 0-255
*/
export function toRgb(color: ColorValue): ColorRgb {
if (isRgbTuple(color)) {
return color
}
return colorToRgb[color]
}