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