65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import { darkTheme, lightTheme } from '../theme';
|
|
|
|
const getContrastColor = (hexColor: string) => {
|
|
if (hexColor.startsWith('#')) {
|
|
hexColor = hexColor.slice(1);
|
|
}
|
|
|
|
const r = Number.parseInt(hexColor.slice(0, 2), 16);
|
|
const g = Number.parseInt(hexColor.slice(2, 4), 16);
|
|
const b = Number.parseInt(hexColor.slice(4, 6), 16);
|
|
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
|
|
|
|
return brightness > 128
|
|
? lightTheme.colors.onBackground
|
|
: darkTheme.colors.onBackground;
|
|
};
|
|
|
|
const isHexColor = (color: string) => {
|
|
return /^#([\da-f]{6})$/i.test(color);
|
|
};
|
|
|
|
const isRgbColor = (color: string) => {
|
|
return /^rgb\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)$/i.test(color);
|
|
};
|
|
|
|
const rgbToHex = (rgb: string) => {
|
|
const [r, g, b] = rgb
|
|
.replaceAll(/[^\d,]/g, '')
|
|
.split(',')
|
|
.map(value => Number.parseInt(value, 10));
|
|
|
|
return `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`;
|
|
};
|
|
|
|
const rgbToRgba = (rgb: string, alpha: number) => {
|
|
const [r, g, b] = rgb
|
|
.replaceAll(/[^\d,]/g, '')
|
|
.split(',')
|
|
.map(value => Number.parseInt(value, 10));
|
|
|
|
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
|
};
|
|
|
|
const generateRandomColor = () => {
|
|
const r = Math.floor(Math.random() * 256)
|
|
.toString(16)
|
|
.padStart(2, '0');
|
|
const g = Math.floor(Math.random() * 256)
|
|
.toString(16)
|
|
.padStart(2, '0');
|
|
const b = Math.floor(Math.random() * 256)
|
|
.toString(16)
|
|
.padStart(2, '0');
|
|
return `#${r}${g}${b}`;
|
|
};
|
|
|
|
export {
|
|
getContrastColor,
|
|
isHexColor,
|
|
isRgbColor,
|
|
rgbToHex,
|
|
rgbToRgba,
|
|
generateRandomColor,
|
|
};
|