gitea源码

color.go 1.9KB

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