@@ -4,22 +4,10 @@ package util
44
55import (
66 "fmt"
7- "math"
87 "strconv"
98 "strings"
109)
1110
12- // Check similar implementation in web_src/js/utils/color.js and keep synchronization
13-
14- // Return R, G, B values defined in reletive luminance
15- func getLuminanceRGB (channel float64 ) float64 {
16- sRGB := channel / 255
17- if sRGB <= 0.03928 {
18- return sRGB / 12.92
19- }
20- return math .Pow ((sRGB + 0.055 )/ 1.055 , 2.4 )
21- }
22-
2311// Get color as RGB values in 0..255 range from the hex color string (with or without #)
2412func HexToRBGColor (colorString string ) (float64 , float64 , float64 ) {
2513 hexString := colorString
@@ -47,19 +35,23 @@ func HexToRBGColor(colorString string) (float64, float64, float64) {
4735 return r , g , b
4836}
4937
50- // return luminance given RGB channels
51- // Reference from: https://www.w3.org/WAI/GL/wiki/Relative_luminance
52- func GetLuminance (r , g , b float64 ) float64 {
53- R := getLuminanceRGB (r )
54- G := getLuminanceRGB (g )
55- B := getLuminanceRGB (b )
56- luminance := 0.2126 * R + 0.7152 * G + 0.0722 * B
57- return luminance
38+ // Returns relative luminance for a SRGB color - https://en.wikipedia.org/wiki/Relative_luminance
39+ // Keep this in sync with web_src/js/utils/color.js
40+ func GetRelativeLuminance (color string ) float64 {
41+ r , g , b := HexToRBGColor (color )
42+ return (0.2126729 * r + 0.7151522 * g + 0.0721750 * b ) / 255
5843}
5944
60- // Reference from: https://firsching.ch/github_labels.html
61- // In the future WCAG 3 APCA may be a better solution.
62- // Check if text should use light color based on RGB of background
63- func UseLightTextOnBackground (r , g , b float64 ) bool {
64- return GetLuminance (r , g , b ) < 0.453
45+ func UseLightText (backgroundColor string ) bool {
46+ return GetRelativeLuminance (backgroundColor ) < 0.453
47+ }
48+
49+ // Given a background color, returns a black or white foreground color that the highest
50+ // contrast ratio. In the future, the APCA contrast function, or CSS `contrast-color` will be better.
51+ // https://github.com/color-js/color.js/blob/eb7b53f7a13bb716ec8b28c7a56f052cd599acd9/src/contrast/APCA.js#L42
52+ func ContrastColor (backgroundColor string ) string {
53+ if UseLightText (backgroundColor ) {
54+ return "#fff"
55+ }
56+ return "#000"
6557}
0 commit comments