colors.ts 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * @module lib/colors
  3. * This module contains various functions for working with colors - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#colors)
  4. */
  5. import { clamp } from "./math.js";
  6. /**
  7. * Converts a hex color string in the format `#RRGGBB`, `#RRGGBBAA` (or even `RRGGBB` and `RGB`) to a tuple.
  8. * @returns Returns a tuple array where R, G and B are an integer from 0-255 and alpha is a float from 0 to 1, or undefined if no alpha channel exists.
  9. */
  10. export function hexToRgb(hex: string): [red: number, green: number, blue: number, alpha?: number] {
  11. hex = (hex.startsWith("#") ? hex.slice(1) : hex).trim();
  12. const a = hex.length === 8 || hex.length === 4 ? parseInt(hex.slice(-(hex.length / 4)), 16) / (hex.length === 8 ? 255 : 15) : undefined;
  13. if(!isNaN(Number(a)))
  14. hex = hex.slice(0, -(hex.length / 4));
  15. if(hex.length === 3 || hex.length === 4)
  16. hex = hex.split("").map(c => c + c).join("");
  17. const bigint = parseInt(hex, 16);
  18. const r = (bigint >> 16) & 255;
  19. const g = (bigint >> 8) & 255;
  20. const b = bigint & 255;
  21. return [clamp(r, 0, 255), clamp(g, 0, 255), clamp(b, 0, 255), typeof a === "number" ? clamp(a, 0, 1) : undefined];
  22. }
  23. /** Converts RGB or RGBA number values to a hex color string in the format `#RRGGBB` or `#RRGGBBAA` */
  24. export function rgbToHex(red: number, green: number, blue: number, alpha?: number, withHash = true, upperCase = false): string {
  25. const toHexVal = (n: number) =>
  26. clamp(Math.round(n), 0, 255).toString(16).padStart(2, "0")[(upperCase ? "toUpperCase" : "toLowerCase")]();
  27. return `${withHash ? "#" : ""}${toHexVal(red)}${toHexVal(green)}${toHexVal(blue)}${alpha ? toHexVal(alpha * 255) : ""}`;
  28. }
  29. /**
  30. * Lightens a CSS color value (in #HEX, rgb() or rgba() format) by a given percentage.
  31. * Will not exceed the maximum range (00-FF or 0-255).
  32. * @returns Returns the new color value in the same format as the input
  33. * @throws Throws if the color format is invalid or not supported
  34. */
  35. export function lightenColor(color: string, percent: number, upperCase = false): string {
  36. return darkenColor(color, percent * -1, upperCase);
  37. }
  38. /**
  39. * Darkens a CSS color value (in #HEX, rgb() or rgba() format) by a given percentage.
  40. * Will not exceed the maximum range (00-FF or 0-255).
  41. * @returns Returns the new color value in the same format as the input
  42. * @throws Throws if the color format is invalid or not supported
  43. */
  44. export function darkenColor(color: string, percent: number, upperCase = false): string {
  45. color = color.trim();
  46. const darkenRgb = (r: number, g: number, b: number, percent: number): [number, number, number] => {
  47. r = Math.max(0, Math.min(255, r - (r * percent / 100)));
  48. g = Math.max(0, Math.min(255, g - (g * percent / 100)));
  49. b = Math.max(0, Math.min(255, b - (b * percent / 100)));
  50. return [r, g, b];
  51. };
  52. let r: number, g: number, b: number, a: number | undefined;
  53. const isHexCol = color.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);
  54. if(isHexCol)
  55. [r, g, b, a] = hexToRgb(color);
  56. else if(color.startsWith("rgb")) {
  57. const rgbValues = color.match(/\d+(\.\d+)?/g)?.map(Number);
  58. if(!rgbValues)
  59. throw new Error("Invalid RGB/RGBA color format");
  60. [r, g, b, a] = rgbValues as [number, number, number, number?];
  61. }
  62. else
  63. throw new Error("Unsupported color format");
  64. [r, g, b] = darkenRgb(r, g, b, percent);
  65. if(isHexCol)
  66. return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
  67. else if(color.startsWith("rgba"))
  68. return `rgba(${r}, ${g}, ${b}, ${a ?? NaN})`;
  69. else if(color.startsWith("rgb"))
  70. return `rgb(${r}, ${g}, ${b})`;
  71. else
  72. throw new Error("Unsupported color format");
  73. }