|
| 1 | +type RGB = [number, number, number]; |
| 2 | + |
| 3 | +const int = Math.floor; |
| 4 | + |
| 5 | +export class Color { |
| 6 | + constructor( |
| 7 | + private r: number, |
| 8 | + private g: number, |
| 9 | + private b: number, |
| 10 | + ) {} |
| 11 | + |
| 12 | + toAlphaString(a: number) { |
| 13 | + return this.toCssString(a); |
| 14 | + } |
| 15 | + toString() { |
| 16 | + return this.toCssString(1); |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * Adjust the color by a multiplier to lighten (`> 1.0`) or darken (`< 1.0`) the color. Returns a new |
| 21 | + * instance. |
| 22 | + */ |
| 23 | + adjusted(mult: number) { |
| 24 | + const adjusted = Color.redistribute([ |
| 25 | + this.r * mult, |
| 26 | + this.g * mult, |
| 27 | + this.b * mult, |
| 28 | + ]); |
| 29 | + return new Color(...adjusted); |
| 30 | + } |
| 31 | + |
| 32 | + private toCssString(a: number) { |
| 33 | + return `rgba(${this.r},${this.g},${this.b},${a})`; |
| 34 | + } |
| 35 | + /** |
| 36 | + * Redistributes rgb, maintaing hue until its clamped. |
| 37 | + * https://stackoverflow.com/a/141943 |
| 38 | + */ |
| 39 | + private static redistribute([r, g, b]: RGB): RGB { |
| 40 | + const threshold = 255.999; |
| 41 | + const max = Math.max(r, g, b); |
| 42 | + if (max <= threshold) { |
| 43 | + return [int(r), int(g), int(b)]; |
| 44 | + } |
| 45 | + const total = r + g + b; |
| 46 | + if (total >= 3 * threshold) { |
| 47 | + return [int(threshold), int(threshold), int(threshold)]; |
| 48 | + } |
| 49 | + const x = (3 * threshold - total) / (3 * max - total); |
| 50 | + const gray = threshold - x * max; |
| 51 | + return [int(gray + x * r), int(gray + x * g), int(gray + x * b)]; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +export const BLACK = new Color(0, 0, 0); |
| 56 | +export const WHITE = new Color(255, 255, 255); |
| 57 | + |
| 58 | +const COLOR_POOL = [ |
| 59 | + new Color(249, 65, 68), |
| 60 | + new Color(243, 114, 44), |
| 61 | + new Color(248, 150, 30), |
| 62 | + new Color(249, 132, 74), |
| 63 | + new Color(249, 199, 79), |
| 64 | + new Color(144, 190, 109), |
| 65 | + new Color(67, 170, 139), |
| 66 | + new Color(77, 144, 142), |
| 67 | + new Color(87, 117, 144), |
| 68 | + new Color(39, 125, 161), |
| 69 | +]; |
| 70 | + |
| 71 | +export function getColorFor(index: number): Color { |
| 72 | + return COLOR_POOL[Math.abs(index) % COLOR_POOL.length]!; |
| 73 | +} |
0 commit comments