MCPcopy Create free account
hub / github.com/bvaughn/react-window / getContrastColor

Function getContrastColor

lib/utils/colors/getContrastColor.ts:1–47  ·  view source on GitHub ↗
(hex: string)

Source from the content-addressed store, hash-verified

1export function getContrastColor(hex: string) {
2 switch (hex.length) {
3 case 3: {
4 hex =
5 hex.charAt(0) +
6 hex.charAt(0) +
7 hex.charAt(1) +
8 hex.charAt(1) +
9 hex.charAt(2) +
10 hex.charAt(2);
11 break;
12 }
13 case 4: {
14 hex =
15 hex.charAt(1) +
16 hex.charAt(1) +
17 hex.charAt(2) +
18 hex.charAt(2) +
19 hex.charAt(3) +
20 hex.charAt(3);
21 break;
22 }
23 case 6: {
24 break;
25 }
26 case 7: {
27 hex = hex.substring(1);
28 break;
29 }
30 default: {
31 throw Error(`Invalid hex value: "${hex}"`);
32 }
33 }
34
35 const rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
36 if (!rgb) {
37 throw Error(`Invalid hex value: "${hex}"`);
38 }
39
40 const red = parseInt(rgb[1], 16);
41 const green = parseInt(rgb[2], 16);
42 const blue = parseInt(rgb[3], 16);
43
44 const brightness = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
45
46 return brightness >= 128 ? "black" : "white";
47}

Callers 1

debugFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected