Skip to content

Instantly share code, notes, and snippets.

@StoneyEagle
Last active April 5, 2023 02:09
Show Gist options
  • Save StoneyEagle/9d8cae9f6db83bea01ecbcb9424d625a to your computer and use it in GitHub Desktop.
Save StoneyEagle/9d8cae9f6db83bea01ecbcb9424d625a to your computer and use it in GitHub Desktop.
react-palette luminocity constrained color picker
export const byte2Hex = (n: number): string => {
const nybHexString = '0123456789ABCDEF';
return String(nybHexString.substr((n >> 4) & 0x0f, 1)) + nybHexString.substr(n & 0x0f, 1);
};
export const RGBString2hex = (string: string): string => {
const newString: number[] = string
.replace('rgb(', '')
.replace(')', '')
.split(',')
.slice(0, 3)
.map(n => parseInt(n, 10));
return `#${byte2Hex(newString[0])}${byte2Hex(newString[1])}${byte2Hex(newString[2])}`;
};
const getLuminosity = function (c: any) {
c = RGBString2hex(c).substring(1);
const rgb: number = parseInt(c, 16);
const r = (rgb >> 16) & 0xff;
const g = (rgb >> 8) & 0xff;
const b = (rgb >> 0) & 0xff;
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
export const tooLight = function (c: any, max = 130) {
if (c) {
const luminosity = getLuminosity(c);
if (luminosity > max) {
return true;
}
return false;
}
return false;
};
export const tooDark = function (c: any, max = 50) {
if (c) {
const luminosity = getLuminosity(c);
if (luminosity < max) {
return true;
}
return false;
}
return false;
};
export interface PaletteColors {
primary?: string;
lightVibrant?: string;
darkVibrant?: string;
lightMuted?: string;
darkMuted?: string;
}
export const pickPaletteColor = (colorPalette: PaletteColors, dark = 50, light = 130) => {
if (!colorPalette) {
return 'rgb(var(--color-theme-400))';
}
if (!tooDark(colorPalette.darkVibrant, dark) && !tooLight(colorPalette.darkVibrant, light)) {
return colorPalette.darkVibrant;
} if (!tooDark(colorPalette.darkMuted, dark) && !tooLight(colorPalette.darkMuted, light)) {
return colorPalette.darkMuted;
} if (!tooLight(colorPalette.lightVibrant, light) && !tooDark(colorPalette.lightVibrant, dark)) {
return colorPalette.lightVibrant;
} if (!tooLight(colorPalette.lightMuted, light) && !tooDark(colorPalette.lightMuted, dark)) {
return colorPalette.lightMuted;
} if (!tooDark(colorPalette.primary, dark) && !tooLight(colorPalette.primary, light)) {
return colorPalette.primary;
}
return 'rgb(var(--color-theme-400))';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment