Skip to content

Commit 3f80a77

Browse files
Use new APCA standard for colors
1 parent ca47442 commit 3f80a77

File tree

1 file changed

+37
-10
lines changed

1 file changed

+37
-10
lines changed

webapp/src/Twig/TwigExtension.php

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,6 +1148,35 @@ public function fileTypeIcon(string $type): string
11481148
return 'fas fa-file-' . $iconName;
11491149
}
11501150

1151+
private function relativeLuminance(string $rgb): float
1152+
{
1153+
// See https://en.wikipedia.org/wiki/Relative_luminance
1154+
1155+
[$r, $g, $b] = Utils::parseHexColor($rgb);
1156+
1157+
[$lr, $lg, $lb] = [
1158+
pow($r / 255, 2.4),
1159+
pow($g / 255, 2.4),
1160+
pow($b / 255, 2.4),
1161+
];
1162+
1163+
return 0.2126 * $lr + 0.7152 * $lg + 0.0722 * $lb;
1164+
}
1165+
1166+
private function apcaContrast(string $fgColor, string $bgColor): float
1167+
{
1168+
// Based on WCAG 3.x (https://www.w3.org/TR/wcag-3.0/)
1169+
1170+
$luminanceForeground = $this->relativeLuminance($fgColor);
1171+
$luminanceBackground = $this->relativeLuminance($bgColor);
1172+
1173+
$contrast = ($luminanceBackground > $luminanceForeground)
1174+
? (pow($luminanceBackground, 0.56) - pow($luminanceForeground, 0.57)) * 1.14
1175+
: (pow($luminanceBackground, 0.65) - pow($luminanceForeground, 0.62)) * 1.14;
1176+
1177+
return round($contrast * 100, 2);
1178+
}
1179+
11511180
/**
11521181
* @return array{string, string}
11531182
*/
@@ -1162,17 +1191,15 @@ private function hexToForegroundAndBorder(string $rgb): array
11621191
$darker[2] = max($darker[2] - 64, 0);
11631192
$border = Utils::rgbToHex($darker);
11641193

1165-
[$r, $g, $b] = $background;
1194+
// Pick the text color with the biggest absolute contrast.
1195+
$contrastWithWhite = $this->apcaContrast('#ffffff', $rgb);
1196+
$contrastWithBlack = $this->apcaContrast('#000000', $rgb);
11661197

1167-
// Calculate relative luminance
1168-
// Source: https://www.w3.org/WAI/GL/wiki/Relative_luminance
1169-
$r = ($r / 255 <= 0.03928) ? ($r / 255) / 12.92 : pow(($r / 255 + 0.055) / 1.055, 2.4);
1170-
$g = ($g / 255 <= 0.03928) ? ($g / 255) / 12.92 : pow(($g / 255 + 0.055) / 1.055, 2.4);
1171-
$b = ($b / 255 <= 0.03928) ? ($b / 255) / 12.92 : pow(($b / 255 + 0.055) / 1.055, 2.4);
1172-
1173-
$luminance = 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
1174-
1175-
$foreground = ($luminance > 0.179) ? '#000000' : '#FFFFFF';
1198+
if (abs($contrastWithBlack) > abs($contrastWithWhite)) {
1199+
$foreground = '#000000';
1200+
} else {
1201+
$foreground = '#ffffff';
1202+
}
11761203

11771204
return [$foreground, $border];
11781205
}

0 commit comments

Comments
 (0)