summaryrefslogtreecommitdiff
path: root/internal/picker/picker.go
blob: 290e9f9651af8289d29785413e8bc6cc715aa81f (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package picker

import (
	"github.com/ChausseBenjamin/golorpicker/internal/slider"
	"github.com/charmbracelet/bubbles/list"
	tea "github.com/charmbracelet/bubbletea"
)

const (
	rgbTitle string = "RGB"
)

// A picker is a list of sliders allowing the user to select a color
// It must therefore be capable of exporting a HEX value for previewing
// as well as a

type RGBPicker struct {
	sliders list.Model
	r, g, b slider.Slider
	loaded  bool
}

func NewRGB() *RGBPicker {
	r := slider.New("R", 0, 255)
	g := slider.New("G", 0, 255)
	b := slider.New("B", 0, 255)

	sliders := list.New(
		[]list.Item{*r, *g, *b},
		list.NewDefaultDelegate(),
		80, 6,
	)
	sliders.Title = rgbTitle
	sliders.SetShowHelp(false)
	sliders.SetShowFilter(false)
	sliders.DisableQuitKeybindings()

	return &RGBPicker{
		sliders: sliders,
		r:       *r,
		g:       *g,
		b:       *b,
		loaded:  false,
	}
}

func (p RGBPicker) toHex() string {
	const txt = "0123456789ABCDEF"
	rgb := string([]byte{
		'#',
		txt[(p.r.Val()>>4)&0x0F],
		txt[p.r.Val()&0x0F],
		txt[(p.g.Val()>>4)&0x0F],
		txt[p.g.Val()&0x0F],
		txt[(p.b.Val()>>4)&0x0F],
		txt[p.b.Val()&0x0F],
	})
	return rgb
}

func (p RGBPicker) Init() tea.Cmd {
	return nil
}

func (p RGBPicker) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		if p.sliders.Width() != msg.Width && !p.loaded {
			p.sliders.SetWidth(msg.Width - 6)
			p.loaded = true
		}
	case tea.KeyMsg:
		key := msg.String()
		for _, k := range slider.Keystrokes() {
			if key == k {
				m := p.sliders.Items()[p.sliders.Index()].(slider.Slider)
				return m.Update(msg)
			}
		}
	}

	var cmd tea.Cmd
	p.sliders, cmd = p.sliders.Update(msg)
	return p, cmd
}

func (p RGBPicker) View() string {
	return p.sliders.View()
}