...
1 package termenv
2
3 import (
4 "image/color"
5 "strconv"
6 "strings"
7
8 "github.com/lucasb-eyer/go-colorful"
9 )
10
11
12 type Profile int
13
14 const (
15
16 TrueColor = Profile(iota)
17
18 ANSI256
19
20 ANSI
21
22 Ascii
23 )
24
25
26 func (p Profile) String(s ...string) Style {
27 return Style{
28 profile: p,
29 string: strings.Join(s, " "),
30 }
31 }
32
33
34 func (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
68
69 func (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
94 func (p Profile) FromColor(c color.Color) Color {
95 col, _ := colorful.MakeColor(c)
96 return p.Color(col.Hex())
97 }
98
View as plain text