profile.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package termenv
  2. import (
  3. "image/color"
  4. "strconv"
  5. "strings"
  6. "github.com/lucasb-eyer/go-colorful"
  7. )
  8. // Profile is a color profile: Ascii, ANSI, ANSI256, or TrueColor.
  9. type Profile int
  10. const (
  11. // TrueColor, 24-bit color profile
  12. TrueColor = Profile(iota)
  13. // ANSI256, 8-bit color profile
  14. ANSI256
  15. // ANSI, 4-bit color profile
  16. ANSI
  17. // Ascii, uncolored profile
  18. Ascii //nolint:revive
  19. )
  20. // String returns a new Style.
  21. func (p Profile) String(s ...string) Style {
  22. return Style{
  23. profile: p,
  24. string: strings.Join(s, " "),
  25. }
  26. }
  27. // Convert transforms a given Color to a Color supported within the Profile.
  28. func (p Profile) Convert(c Color) Color {
  29. if p == Ascii {
  30. return NoColor{}
  31. }
  32. switch v := c.(type) {
  33. case ANSIColor:
  34. return v
  35. case ANSI256Color:
  36. if p == ANSI {
  37. return ansi256ToANSIColor(v)
  38. }
  39. return v
  40. case RGBColor:
  41. h, err := colorful.Hex(string(v))
  42. if err != nil {
  43. return nil
  44. }
  45. if p != TrueColor {
  46. ac := hexToANSI256Color(h)
  47. if p == ANSI {
  48. return ansi256ToANSIColor(ac)
  49. }
  50. return ac
  51. }
  52. return v
  53. }
  54. return c
  55. }
  56. // Color creates a Color from a string. Valid inputs are hex colors, as well as
  57. // ANSI color codes (0-15, 16-255).
  58. func (p Profile) Color(s string) Color {
  59. if len(s) == 0 {
  60. return nil
  61. }
  62. var c Color
  63. if strings.HasPrefix(s, "#") {
  64. c = RGBColor(s)
  65. } else {
  66. i, err := strconv.Atoi(s)
  67. if err != nil {
  68. return nil
  69. }
  70. if i < 16 {
  71. c = ANSIColor(i)
  72. } else {
  73. c = ANSI256Color(i)
  74. }
  75. }
  76. return p.Convert(c)
  77. }
  78. // FromColor creates a Color from a color.Color.
  79. func (p Profile) FromColor(c color.Color) Color {
  80. col, _ := colorful.MakeColor(c)
  81. return p.Color(col.Hex())
  82. }