...
1
2 package main
3
4 import (
5 "fmt"
6
7 "github.com/gdamore/tcell/v2"
8 "github.com/rivo/tview"
9 )
10
11
12 type RadioButtons struct {
13 *tview.Box
14 options []string
15 currentOption int
16 }
17
18
19 func NewRadioButtons(options []string) *RadioButtons {
20 return &RadioButtons{
21 Box: tview.NewBox(),
22 options: options,
23 }
24 }
25
26
27 func (r *RadioButtons) Draw(screen tcell.Screen) {
28 r.Box.DrawForSubclass(screen, r)
29 x, y, width, height := r.GetInnerRect()
30
31 for index, option := range r.options {
32 if index >= height {
33 break
34 }
35 radioButton := "\u25ef"
36 if index == r.currentOption {
37 radioButton = "\u25c9"
38 }
39 line := fmt.Sprintf(`%s[white] %s`, radioButton, option)
40 tview.Print(screen, line, x, y+index, width, tview.AlignLeft, tcell.ColorYellow)
41 }
42 }
43
44
45 func (r *RadioButtons) InputHandler() func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
46 return r.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
47 switch event.Key() {
48 case tcell.KeyUp:
49 r.currentOption--
50 if r.currentOption < 0 {
51 r.currentOption = 0
52 }
53 case tcell.KeyDown:
54 r.currentOption++
55 if r.currentOption >= len(r.options) {
56 r.currentOption = len(r.options) - 1
57 }
58 }
59 })
60 }
61
62
63 func (r *RadioButtons) MouseHandler() func(action tview.MouseAction, event *tcell.EventMouse, setFocus func(p tview.Primitive)) (consumed bool, capture tview.Primitive) {
64 return r.WrapMouseHandler(func(action tview.MouseAction, event *tcell.EventMouse, setFocus func(p tview.Primitive)) (consumed bool, capture tview.Primitive) {
65 x, y := event.Position()
66 _, rectY, _, _ := r.GetInnerRect()
67 if !r.InRect(x, y) {
68 return false, nil
69 }
70
71 if action == tview.MouseLeftClick {
72 setFocus(r)
73 index := y - rectY
74 if index >= 0 && index < len(r.options) {
75 r.currentOption = index
76 consumed = true
77 }
78 }
79
80 return
81 })
82 }
83
84 func main() {
85 radioButtons := NewRadioButtons([]string{"Lions", "Elephants", "Giraffes"})
86 radioButtons.SetBorder(true).
87 SetTitle("Radio Button Demo").
88 SetRect(0, 0, 30, 5)
89 if err := tview.NewApplication().SetRoot(radioButtons, false).EnableMouse(true).Run(); err != nil {
90 panic(err)
91 }
92 }
93
View as plain text