code.gitea.io/gitea@v1.22.3/modules/util/color.go (about)

     1  // Copyright 2023 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package util
     5  
     6  import (
     7  	"fmt"
     8  	"strconv"
     9  	"strings"
    10  )
    11  
    12  // HexToRBGColor parses color as RGB values in 0..255 range from the hex color string (with or without #)
    13  func HexToRBGColor(colorString string) (float64, float64, float64) {
    14  	hexString := colorString
    15  	if strings.HasPrefix(colorString, "#") {
    16  		hexString = colorString[1:]
    17  	}
    18  	// only support transfer of rgb, rgba, rrggbb and rrggbbaa
    19  	// if not in these formats, use default values 0, 0, 0
    20  	if len(hexString) != 3 && len(hexString) != 4 && len(hexString) != 6 && len(hexString) != 8 {
    21  		return 0, 0, 0
    22  	}
    23  	if len(hexString) == 3 || len(hexString) == 4 {
    24  		hexString = fmt.Sprintf("%c%c%c%c%c%c", hexString[0], hexString[0], hexString[1], hexString[1], hexString[2], hexString[2])
    25  	}
    26  	if len(hexString) == 8 {
    27  		hexString = hexString[0:6]
    28  	}
    29  	color, err := strconv.ParseUint(hexString, 16, 64)
    30  	if err != nil {
    31  		return 0, 0, 0
    32  	}
    33  	r := float64(uint8(0xFF & (uint32(color) >> 16)))
    34  	g := float64(uint8(0xFF & (uint32(color) >> 8)))
    35  	b := float64(uint8(0xFF & uint32(color)))
    36  	return r, g, b
    37  }
    38  
    39  // GetRelativeLuminance returns relative luminance for a SRGB color - https://en.wikipedia.org/wiki/Relative_luminance
    40  // Keep this in sync with web_src/js/utils/color.js
    41  func GetRelativeLuminance(color string) float64 {
    42  	r, g, b := HexToRBGColor(color)
    43  	return (0.2126729*r + 0.7151522*g + 0.0721750*b) / 255
    44  }
    45  
    46  func UseLightText(backgroundColor string) bool {
    47  	return GetRelativeLuminance(backgroundColor) < 0.453
    48  }
    49  
    50  // ContrastColor returns a black or white foreground color that the highest contrast ratio.
    51  // In the future, the APCA contrast function, or CSS `contrast-color` will be better.
    52  // https://github.com/color-js/color.js/blob/eb7b53f7a13bb716ec8b28c7a56f052cd599acd9/src/contrast/APCA.js#L42
    53  func ContrastColor(backgroundColor string) string {
    54  	if UseLightText(backgroundColor) {
    55  		return "#fff"
    56  	}
    57  	return "#000"
    58  }