All files / app/utils color.ts

77.14% Statements 27/35
44.44% Branches 4/9
100% Functions 1/1
76.47% Lines 26/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 661x       2x 2x       2x 2x 2x         2x 2x 2x 2x 2x 2x 2x 2x   2x             1x 1x       1x 1x                 2x   2x       2x   2x   2x 2x         2x    
import { decomposeColor } from "@mui/system";
 
// Slightly adapted from https://github.com/Qix-/color-convert
// Using HSL (hue-saturation-lightness) values makes it easy to interpolate between colors in a natural way
export const colorStringToHsl = (colorString: string) => {
  let rgb: [number, number, number] | [number, number, number, number] = [
    0, 0, 0,
  ];
 
  try {
    const { values } = decomposeColor(colorString);
    rgb = values as [number, number, number];
  } catch {
    console.warn(`Tried to decompose invalid color string '${colorString}'`);
  }
 
  const r = rgb[0] / 255;
  const g = rgb[1] / 255;
  const b = rgb[2] / 255;
  const min = Math.min(r, g, b);
  const max = Math.max(r, g, b);
  const delta = max - min;
  let h = 0;
  let s = 0;
 
  switch (max) {
    case min: {
      h = 0;
      break;
    }
 
    case r: {
      h = (g - b) / delta;
      break;
    }
 
    case g: {
      h = 2 + (b - r) / delta;
      break;
    }
 
    case b: {
      h = 4 + (r - g) / delta;
      break;
    }
  }
 
  h = Math.min(h * 60, 360);
 
  Iif (h < 0) {
    h += 360;
  }
 
  const l = (min + max) / 2;
 
  Iif (max === min) {
    s = 0;
  } else if (l <= 0.5) {
    s = delta / (max + min);
  } else E{
    s = delta / (2 - max - min);
  }
 
  return [h, s * 100, l * 100];
};