Skip to content

Commit 64d0bc6

Browse files
committed
refactor: hoist out color functions
1 parent 35e96d4 commit 64d0bc6

1 file changed

Lines changed: 21 additions & 21 deletions

File tree

app/utils/colors.ts

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
// Vue Data UI does not support CSS vars nor OKLCH for now
22

3+
/** Converts a 0-255 RGB component to a 2-digit hex string */
4+
const componentToHex = (value: number): string =>
5+
Math.round(Math.min(Math.max(0, value), 255))
6+
.toString(16)
7+
.padStart(2, '0')
8+
9+
/** Converts a 0-1 linear value to a 2-digit hex string */
10+
const linearToHex = (value: number): string =>
11+
Math.round(Math.min(Math.max(0, value), 1) * 255)
12+
.toString(16)
13+
.padStart(2, '0')
14+
15+
/** Converts linear RGB to sRGB gamma-corrected value */
16+
const linearToSrgb = (value: number): number =>
17+
value <= 0.0031308 ? 12.92 * value : 1.055 * Math.pow(value, 1 / 2.4) - 0.055
18+
319
/**
420
* Converts a hex color to RGB components
521
*/
@@ -14,11 +30,7 @@ function hexToRgb(hex: string): [number, number, number] | null {
1430
* Converts RGB components to hex color
1531
*/
1632
function rgbToHex(r: number, g: number, b: number): string {
17-
const toHex = (value: number): string =>
18-
Math.round(Math.min(Math.max(0, value), 255))
19-
.toString(16)
20-
.padStart(2, '0')
21-
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
33+
return `#${componentToHex(r)}${componentToHex(g)}${componentToHex(b)}`
2234
}
2335

2436
/**
@@ -62,21 +74,9 @@ export function oklchToHex(color: string | undefined | null): string | undefined
6274
m_ = m_ ** 3
6375
s_ = s_ ** 3
6476

65-
let r = 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_
66-
let g = -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_
67-
let bRgb = -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_
68-
69-
const toSrgb = (value: number): number =>
70-
value <= 0.0031308 ? 12.92 * value : 1.055 * Math.pow(value, 1 / 2.4) - 0.055
71-
72-
r = toSrgb(r)
73-
g = toSrgb(g)
74-
bRgb = toSrgb(bRgb)
75-
76-
const toHex = (value: number): string =>
77-
Math.round(Math.min(Math.max(0, value), 1) * 255)
78-
.toString(16)
79-
.padStart(2, '0')
77+
const r = 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_
78+
const g = -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_
79+
const bRgb = -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_
8080

81-
return `#${toHex(r)}${toHex(g)}${toHex(bRgb)}`
81+
return `#${linearToHex(linearToSrgb(r))}${linearToHex(linearToSrgb(g))}${linearToHex(linearToSrgb(bRgb))}`
8282
}

0 commit comments

Comments
 (0)