vendor/github.com/muesli/termenv/profile.go
97 lines · 1668 bytes
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// String returns a new Style.
26func (p Profile) String(s ...string) Style {
27 return Style{
28 profile: p,
29 string: strings.Join(s, " "),
30 }
31}
32
33// Convert transforms a given Color to a Color supported within the Profile.
34func (p Profile) Convert(c Color) Color {
35 if p == Ascii {
36 return NoColor{}
37 }
38
39 switch v := c.(type) {
40 case ANSIColor:
41 return v
42
43 case ANSI256Color:
44 if p == ANSI {
45 return ansi256ToANSIColor(v)
46 }
47 return v
48
49 case RGBColor:
50 h, err := colorful.Hex(string(v))
51 if err != nil {
52 return nil
53 }
54 if p != TrueColor {
55 ac := hexToANSI256Color(h)
56 if p == ANSI {
57 return ansi256ToANSIColor(ac)
58 }
59 return ac
60 }
61 return v
62 }
63
64 return c
65}
66
67// Color creates a Color from a string. Valid inputs are hex colors, as well as
68// ANSI color codes (0-15, 16-255).
69func (p Profile) Color(s string) Color {
70 if len(s) == 0 {
71 return nil
72 }
73
74 var c Color
75 if strings.HasPrefix(s, "#") {
76 c = RGBColor(s)
77 } else {
78 i, err := strconv.Atoi(s)
79 if err != nil {
80 return nil
81 }
82
83 if i < 16 {
84 c = ANSIColor(i)
85 } else {
86 c = ANSI256Color(i)
87 }
88 }
89
90 return p.Convert(c)
91}
92
93// FromColor creates a Color from a color.Color.
94func (p Profile) FromColor(c color.Color) Color {
95 col, _ := colorful.MakeColor(c)
96 return p.Color(col.Hex())
97}