Skip to content

Commit

Permalink
Fix contrast color calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
nickygerritsen committed Feb 28, 2025
1 parent a689d60 commit a331bc2
Showing 1 changed file with 28 additions and 16 deletions.
44 changes: 28 additions & 16 deletions webapp/src/Twig/TwigExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -1144,12 +1144,11 @@ public function fileTypeIcon(string $type): string
return 'fas fa-file-' . $iconName;
}

public function problemBadge(ContestProblem $problem, bool $grayedOut = false): string
/**
* @return array{string, string}
*/
private function hexToForegroundAndBorder(string $rgb): array
{
$rgb = Utils::convertToHex($problem->getColor() ?? '#ffffff');
if ($grayedOut || empty($rgb)) {
$rgb = Utils::convertToHex('whitesmoke');
}
$background = Utils::parseHexColor($rgb);

// Pick a border that's a bit darker.
Expand All @@ -1159,8 +1158,29 @@ public function problemBadge(ContestProblem $problem, bool $grayedOut = false):
$darker[2] = max($darker[2] - 64, 0);
$border = Utils::rgbToHex($darker);

// Pick the foreground text color based on the background color.
$foreground = ($background[0] + $background[1] + $background[2] > 450) ? '#000000' : '#ffffff';
[$r, $g, $b] = $background;

// Calculate relative luminance
$r = ($r / 255 <= 0.03928) ? ($r / 255) / 12.92 : pow(($r / 255 + 0.055) / 1.055, 2.4);
$g = ($g / 255 <= 0.03928) ? ($g / 255) / 12.92 : pow(($g / 255 + 0.055) / 1.055, 2.4);
$b = ($b / 255 <= 0.03928) ? ($b / 255) / 12.92 : pow(($b / 255 + 0.055) / 1.055, 2.4);

$luminance = 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;

$foreground = ($luminance > 0.179) ? '#000000' : '#FFFFFF';

return [$foreground, $border];
}

public function problemBadge(ContestProblem $problem, bool $grayedOut = false): string
{
$rgb = Utils::convertToHex($problem->getColor() ?? '#ffffff');
if ($grayedOut || empty($rgb)) {
$rgb = Utils::convertToHex('whitesmoke');
}

[$foreground, $border] = $this->hexToForegroundAndBorder($rgb);

if ($grayedOut) {
$foreground = 'silver';
$border = 'linen';
Expand All @@ -1180,17 +1200,9 @@ public function problemBadgeMaybe(ContestProblem $problem, ScoreboardMatrixItem
if (!$matrixItem->isCorrect || empty($rgb)) {
$rgb = Utils::convertToHex('whitesmoke');
}
$background = Utils::parseHexColor($rgb);

// Pick a border that's a bit darker.
$darker = $background;
$darker[0] = max($darker[0] - 64, 0);
$darker[1] = max($darker[1] - 64, 0);
$darker[2] = max($darker[2] - 64, 0);
$border = Utils::rgbToHex($darker);
[$foreground, $border] = $this->hexToForegroundAndBorder($rgb);

// Pick the foreground text color based on the background color.
$foreground = ($background[0] + $background[1] + $background[2] > 450) ? '#000000' : '#ffffff';
if (!$matrixItem->isCorrect) {
$foreground = 'silver';
$border = 'linen';
Expand Down

0 comments on commit a331bc2

Please sign in to comment.