MCPcopy Create free account
hub / github.com/adobe/react-spectrum / parseHexColor

Function parseHexColor

packages/dev/s2-docs/src/searchUtils.tsx:24–49  ·  view source on GitHub ↗

* Parses a hex color string to RGB values. * Supports #RGB, #RRGGBB formats (with or without #).

(hex: string)

Source from the content-addressed store, hash-verified

22 * Supports #RGB, #RRGGBB formats (with or without #).
23 */
24function parseHexColor(hex: string): [number, number, number] | null {
25 // Remove # if present and trim whitespace
26 const cleanHex = hex.replace(/^#/, '').trim();
27
28 if (!/^[0-9A-Fa-f]+$/.test(cleanHex)) {
29 return null;
30 }
31
32 let r: number, g: number, b: number;
33
34 if (cleanHex.length === 3) {
35 // #RGB format
36 r = parseInt(cleanHex[0] + cleanHex[0], 16);
37 g = parseInt(cleanHex[1] + cleanHex[1], 16);
38 b = parseInt(cleanHex[2] + cleanHex[2], 16);
39 } else if (cleanHex.length === 6) {
40 // #RRGGBB format
41 r = parseInt(cleanHex.slice(0, 2), 16);
42 g = parseInt(cleanHex.slice(2, 4), 16);
43 b = parseInt(cleanHex.slice(4, 6), 16);
44 } else {
45 return null;
46 }
47
48 return [r, g, b];
49}
50
51/**
52 * Checks if a search string looks like a hex color code.

Callers 1

useFilteredColorsFunction · 0.85

Calls 1

sliceMethod · 0.80

Tested by

no test coverage detected