2024-04-07 12:19:25 -04:00
|
|
|
import tinycolor from 'tinycolor2';
|
2024-08-10 05:46:48 -04:00
|
|
|
import type {ColorInput} from 'tinycolor2';
|
2024-04-07 12:19:25 -04:00
|
|
|
|
|
|
|
// Returns relative luminance for a SRGB color - https://en.wikipedia.org/wiki/Relative_luminance
|
|
|
|
// Keep this in sync with modules/util/color.go
|
2024-08-28 12:32:38 -04:00
|
|
|
function getRelativeLuminance(color: ColorInput): number {
|
2024-04-07 12:19:25 -04:00
|
|
|
const {r, g, b} = tinycolor(color).toRgb();
|
|
|
|
return (0.2126729 * r + 0.7151522 * g + 0.072175 * b) / 255;
|
2023-05-10 07:19:03 -04:00
|
|
|
}
|
|
|
|
|
2024-08-28 12:32:38 -04:00
|
|
|
function useLightText(backgroundColor: ColorInput): boolean {
|
2024-04-07 12:19:25 -04:00
|
|
|
return getRelativeLuminance(backgroundColor) < 0.453;
|
2023-05-10 07:19:03 -04:00
|
|
|
}
|
|
|
|
|
2024-04-07 12:19:25 -04:00
|
|
|
// Given a background color, returns a black or white foreground color that the highest
|
|
|
|
// contrast ratio. In the future, the APCA contrast function, or CSS `contrast-color` will be better.
|
|
|
|
// https://github.com/color-js/color.js/blob/eb7b53f7a13bb716ec8b28c7a56f052cd599acd9/src/contrast/APCA.js#L42
|
2024-08-28 12:32:38 -04:00
|
|
|
export function contrastColor(backgroundColor: ColorInput): string {
|
2024-04-07 12:19:25 -04:00
|
|
|
return useLightText(backgroundColor) ? '#fff' : '#000';
|
2023-05-10 07:19:03 -04:00
|
|
|
}
|
2024-02-23 18:41:24 -05:00
|
|
|
|
2024-08-28 12:32:38 -04:00
|
|
|
function resolveColors(obj: Record<string, string>): Record<string, string> {
|
2024-02-23 18:41:24 -05:00
|
|
|
const styles = window.getComputedStyle(document.documentElement);
|
2024-08-10 05:46:48 -04:00
|
|
|
const getColor = (name: string) => styles.getPropertyValue(name).trim();
|
2024-02-23 18:41:24 -05:00
|
|
|
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, getColor(value)]));
|
|
|
|
}
|
|
|
|
|
|
|
|
export const chartJsColors = resolveColors({
|
|
|
|
text: '--color-text',
|
|
|
|
border: '--color-secondary-alpha-60',
|
|
|
|
commits: '--color-primary-alpha-60',
|
|
|
|
additions: '--color-green',
|
|
|
|
deletions: '--color-red',
|
|
|
|
});
|