File tree Expand file tree Collapse file tree 3 files changed +73
-0
lines changed
Expand file tree Collapse file tree 3 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ export 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+ }
Original file line number Diff line number Diff line change 1+ export function stringToColor ( string : string ) {
2+ let hash = 0 ;
3+ string . split ( "" ) . forEach ( ( char ) => {
4+ hash = char . charCodeAt ( 0 ) + ( ( hash << 5 ) - hash ) ;
5+ } ) ;
6+
7+ let color = "#" ;
8+ for ( let i = 0 ; i < 3 ; i ++ ) {
9+ const value = ( hash >> ( i * 8 ) ) & 0xff ;
10+ color += value . toString ( 16 ) . padStart ( 2 , "0" ) ;
11+ }
12+ return color ;
13+ }
Original file line number Diff line number Diff line change 1+ import { getContrastColor } from "./colors/getContrastColor" ;
2+ import { stringToColor } from "./colors/stringToColor" ;
3+
4+ export function debug ( namespace : string , ...args : unknown [ ] ) {
5+ const backgroundColor = stringToColor ( namespace ) ;
6+ const color = getContrastColor ( backgroundColor ) ;
7+
8+ console . log (
9+ `%c ${ namespace } ` ,
10+ `background-color: ${ backgroundColor } ; color: ${ color } ;` ,
11+ ...args
12+ ) ;
13+ }
You can’t perform that action at this time.
0 commit comments