summaryrefslogtreecommitdiffstats
path: root/pkg/utils/color.go
blob: a4ad578e0552ac682de68d8a8c4d3488068717a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package utils

import (
	"regexp"
	"sync"

	"github.com/gookit/color"
	"github.com/jesseduffield/lazygit/pkg/gui/style"
	"github.com/samber/lo"
)

var (
	decoloriseCache = make(map[string]string)
	decoloriseMutex sync.RWMutex
)

// Decolorise strips a string of color
func Decolorise(str string) string {
	decoloriseMutex.RLock()
	val := decoloriseCache[str]
	decoloriseMutex.RUnlock()

	if val != "" {
		return val
	}

	re := regexp.MustCompile(`\x1B\[([0-9]{1,3}(;[0-9]{1,3})*)?[mGK]`)
	ret := re.ReplaceAllString(str, "")

	decoloriseMutex.Lock()
	decoloriseCache[str] = ret
	decoloriseMutex.Unlock()

	return ret
}

func IsValidHexValue(v string) bool {
	if len(v) != 4 && len(v) != 7 {
		return false
	}

	if v[0] != '#' {
		return false
	}

	for _, char := range v[1:] {
		switch char {
		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F':
			continue
		default:
			return false
		}
	}

	return true
}

func SetCustomColors(customColors map[string]string) map[string]style.TextStyle {
	return lo.MapValues(customColors, func(c string, key string) style.TextStyle {
		if s, ok := style.ColorMap[c]; ok {
			return s.Foreground
		}
		return style.New().SetFg(style.NewRGBColor(color.HEX(c, false)))
	})
}