Skip to content

Commit

Permalink
feat: add lighten() and darken() methods for hex values
Browse files Browse the repository at this point in the history
  • Loading branch information
BernhardBaumrock committed Jan 30, 2024
1 parent d6f5c76 commit 852ea50
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions RockFrontend.module.php
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,32 @@ public function addTopBar(&$html)
$html = str_replace("</body", "$topbar</body", $html);
}

/**
* Adjust brightness of a hex value
* See https://stackoverflow.com/a/54393956 for details.
* It might not be 100% accurate but good enough for my usecases :)
*
* @param mixed $hexCode
* @param mixed $adjustPercent
* @return string
*/
private function adjustBrightness($hexCode, $adjustPercent)
{
$hexCode = ltrim($hexCode, '#');
if (strlen($hexCode) == 3) {
$hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
}

$hexCode = array_map('hexdec', str_split($hexCode, 2));
foreach ($hexCode as &$color) {
$adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
$adjustAmount = ceil($adjustableLimit * $adjustPercent);
$color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
}

return '#' . implode($hexCode);
}

/**
* ALFRED - A Lovely FRontend EDitor
*
Expand Down Expand Up @@ -711,6 +737,11 @@ private function createPermission($name, $title)
$p->setAndSave('title', $title);
}

public function darken($hex, $percent): string
{
return $this->adjustBrightness($hex, -1 * ($percent / 100));
}

/**
* Load HtmlPageDom
*
Expand Down Expand Up @@ -1376,6 +1407,11 @@ private function lessFilePath(): string
return $this->wire->config->paths->templates . "less/rf-custom.less";
}

public function lighten($hex, $percent): string
{
return $this->adjustBrightness($hex, $percent / 100);
}

/**
* Setup live reloading
*/
Expand Down

0 comments on commit 852ea50

Please sign in to comment.