Skip to content

Commit c4a9039

Browse files
committed
Reapply "Properly implement alpha channels"
This reverts commit 0ccbaec.
1 parent b5fcf94 commit c4a9039

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

webapp/src/Twig/TwigExtension.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1158,7 +1158,7 @@ public function fileTypeIcon(string $type): string
11581158
private function relativeLuminance(string $rgb): float
11591159
{
11601160
// See https://en.wikipedia.org/wiki/Relative_luminance
1161-
[$r, $g, $b] = Utils::parseHexColor($rgb);
1161+
[$r, $g, $b, $a] = Utils::parseHexColor($rgb);
11621162

11631163
[$lr, $lg, $lb] = [
11641164
pow($r / 255, 2.4),
@@ -1194,6 +1194,7 @@ private function hexToForegroundAndBorder(string $rgb): array
11941194
$darker[0] = max($darker[0] - 64, 0);
11951195
$darker[1] = max($darker[1] - 64, 0);
11961196
$darker[2] = max($darker[2] - 64, 0);
1197+
$darker[3] = max($darker[3] - 64, 0);
11971198
$border = Utils::rgbToHex($darker);
11981199

11991200
// Pick the text color with the biggest absolute contrast.

webapp/src/Utils/Utils.php

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -346,25 +346,34 @@ public static function convertToColor(string $hex): ?string
346346
}
347347

348348
/**
349-
* Parse a hex color into it's three RGB values.
349+
* Parse a hex color into it's four RGBA values.
350350
*
351-
* @return array{int, int, int}
351+
* @return array{int, int, int, int}
352352
*/
353353
public static function parseHexColor(string $hex): array
354354
{
355-
// Ignore alpha in hexstrings
356-
if (strlen($hex) === 5) {
357-
$hex = substr($hex, 0, 4);
358-
} else if (strlen($hex) === 9) {
359-
$hex = substr($hex, 0, 7);
355+
// Insert alpha in hexstrings
356+
switch(strlen($hex)) {
357+
case 4:
358+
$hex += 'f';
359+
break;
360+
case 7:
361+
$hex += 'ff';
362+
break;
363+
case: 5:
364+
case: 8:
365+
break;
366+
default:
367+
throw new Exception("Color length of " . strlen($hex) . " not supported.");
360368
}
361369
// Source: https://stackoverflow.com/a/21966100
362-
$length = (strlen($hex) - 1) / 3;
363-
$fact = [17, 1, 0.062272][$length - 1];
370+
$length = (strlen($hex) - 1) / 4;
371+
$fact = [17, 1, 0.062272, 1][$length - 1];
364372
return [
365-
(int)round(hexdec(substr($hex, 1, $length)) * $fact),
366-
(int)round(hexdec(substr($hex, 1 + $length, $length)) * $fact),
373+
(int)round(hexdec(substr($hex, 1, $length)) * $fact),
374+
(int)round(hexdec(substr($hex, 1 + 1 * $length, $length)) * $fact),
367375
(int)round(hexdec(substr($hex, 1 + 2 * $length, $length)) * $fact)
376+
(int)round(hexdec(substr($hex, 1 + 3 * $length, $length)) * $fact)
368377
];
369378
}
370379

0 commit comments

Comments
 (0)