46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
export function getColorFromPubkey(pubkey: string): string {
|
|
let hash = 0;
|
|
for (let i = 0; i < pubkey.length; i++) hash = ((hash << 5) - hash + pubkey.charCodeAt(i)) & 0xffffffff;
|
|
hash = Math.abs(hash);
|
|
|
|
const hue = hash % 360;
|
|
|
|
const saturation = hue >= 216 && hue <= 273 ? 0.8 : 0.9;
|
|
const lightness = hue >= 32 && hue <= 212 ? 0.85 : 0.65;
|
|
|
|
const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
|
|
const huePrime = hue / 60;
|
|
const secondComponent = chroma * (1 - Math.abs((huePrime % 2) - 1));
|
|
const lightnessAdjustment = lightness - chroma / 2;
|
|
|
|
let [r, g, b] = [0, 0, 0];
|
|
|
|
const sector = Math.floor(huePrime);
|
|
switch (sector) {
|
|
case 0:
|
|
[r, g, b] = [chroma, secondComponent, 0];
|
|
break;
|
|
case 1:
|
|
[r, g, b] = [secondComponent, chroma, 0];
|
|
break;
|
|
case 2:
|
|
[r, g, b] = [0, chroma, secondComponent];
|
|
break;
|
|
case 3:
|
|
[r, g, b] = [0, secondComponent, chroma];
|
|
break;
|
|
case 4:
|
|
[r, g, b] = [secondComponent, 0, chroma];
|
|
break;
|
|
default:
|
|
[r, g, b] = [chroma, 0, secondComponent];
|
|
break;
|
|
}
|
|
|
|
const toHex = (value: number): string =>
|
|
Math.round((value + lightnessAdjustment) * 255)
|
|
.toString(16)
|
|
.padStart(2, "0");
|
|
|
|
return `${toHex(r)}${toHex(g)}${toHex(b)}`;
|
|
}
|