You are here

function _olivero_hex_to_hsl in Drupal 10

Converts hex color strings to array of HSL values.

Code based on JS version. Mathematical formula for rgb-to-hsl conversion.

@internal

Parameters

string $hex_string: The 6-character hexadecimal color code, optionally with a leading hash

Return value

array Array containing hue, saturation, and lightness values. $hue: integer of value 0-360 indicating the hue on a color wheel. $saturation: string of saturation as a percentage (0% all gray, 100% full color). $lightness: string of lightness as a percentage (0% darkened to black, 50% full color, 100% lightened to white).

See also

https://css-tricks.com/converting-color-spaces-in-javascript

https://www.rapidtables.com/convert/color/rgb-to-hsl.html

2 calls to _olivero_hex_to_hsl()
OliveroHexToHslTest::testHexToHsl in core/themes/olivero/tests/src/Unit/OliveroHexToHslTest.php
Tests hex to HSL conversion.
olivero_preprocess_html in core/themes/olivero/olivero.theme
Implements hook_preprocess_HOOK() for HTML document templates.

File

core/themes/olivero/olivero.theme, line 636
Functions to support theming in the Olivero theme.

Code

function _olivero_hex_to_hsl(string $hex_string) {

  // Convert hexcode pairs to rgb values (0-255).
  $hex_val = trim($hex_string, '#');
  $r0 = hexdec($hex_val[0] . $hex_val[1]);
  $g0 = hexdec($hex_val[2] . $hex_val[3]);
  $b0 = hexdec($hex_val[4] . $hex_val[5]);

  // Convert rgb's 0-255 to decimal values.
  $r = fdiv($r0, 255);
  $g = fdiv($g0, 255);
  $b = fdiv($b0, 255);

  // Calculate Hue.
  $c_min = min($r, $g, $b);
  $c_max = max($r, $g, $b);
  $delta = $c_max - $c_min;
  if ($delta == 0) {
    $h = 0;
  }
  else {
    switch ($c_max) {
      case $r:
        $h = fmod(($g - $b) / $delta, 6);
        break;
      case $g:
        $h = ($b - $r) / $delta + 2;
        break;
      case $b:
        $h = ($r - $g) / $delta + 4;
        break;
      default:
        $h = 0;
        break;
    }
  }
  $h = round($h * 60);

  // Shift hue range from [-60 - 300] to [0 - 360].
  if ($h < 0) {
    $h += 360;
  }

  // Calculate Lightness.
  $l = ($c_max + $c_min) / 2;

  // Calculate Saturation.
  $s = $delta == 0 ? 0 : $delta / (1 - abs(2 * $l - 1));

  // Convert Saturation and Lightness to percentages.
  $s = round($s * 100);
  $l = round($l * 100);
  return [
    $h,
    $s,
    $l,
  ];
}