2018-03-19 20:25:30 +00:00
|
|
|
// Demo code which illustrates how to implement your own primitive.
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2021-04-03 15:11:20 +00:00
|
|
|
"code.rocketnine.space/tslocum/cview"
|
2020-08-30 15:36:03 +00:00
|
|
|
"github.com/gdamore/tcell/v2"
|
2018-03-19 20:25:30 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// RadioButtons implements a simple primitive for radio button selections.
|
|
|
|
type RadioButtons struct {
|
2019-12-30 23:12:17 +00:00
|
|
|
*cview.Box
|
2018-03-19 20:25:30 +00:00
|
|
|
options []string
|
|
|
|
currentOption int
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewRadioButtons returns a new radio button primitive.
|
|
|
|
func NewRadioButtons(options []string) *RadioButtons {
|
|
|
|
return &RadioButtons{
|
2019-12-30 23:12:17 +00:00
|
|
|
Box: cview.NewBox(),
|
2018-03-19 20:25:30 +00:00
|
|
|
options: options,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Draw draws this primitive onto the screen.
|
|
|
|
func (r *RadioButtons) Draw(screen tcell.Screen) {
|
|
|
|
r.Box.Draw(screen)
|
|
|
|
x, y, width, height := r.GetInnerRect()
|
|
|
|
|
|
|
|
for index, option := range r.options {
|
|
|
|
if index >= height {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
radioButton := "\u25ef" // Unchecked.
|
|
|
|
if index == r.currentOption {
|
|
|
|
radioButton = "\u25c9" // Checked.
|
|
|
|
}
|
|
|
|
line := fmt.Sprintf(`%s[white] %s`, radioButton, option)
|
2020-10-06 20:11:45 +00:00
|
|
|
cview.Print(screen, []byte(line), x, y+index, width, cview.AlignLeft, tcell.ColorYellow.TrueColor())
|
2018-03-19 20:25:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// InputHandler returns the handler for this primitive.
|
2019-12-30 23:12:17 +00:00
|
|
|
func (r *RadioButtons) InputHandler() func(event *tcell.EventKey, setFocus func(p cview.Primitive)) {
|
|
|
|
return r.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p cview.Primitive)) {
|
2018-03-19 20:25:30 +00:00
|
|
|
switch event.Key() {
|
|
|
|
case tcell.KeyUp:
|
|
|
|
r.currentOption--
|
|
|
|
if r.currentOption < 0 {
|
|
|
|
r.currentOption = 0
|
|
|
|
}
|
|
|
|
case tcell.KeyDown:
|
|
|
|
r.currentOption++
|
|
|
|
if r.currentOption >= len(r.options) {
|
|
|
|
r.currentOption = len(r.options) - 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2020-10-07 23:34:21 +00:00
|
|
|
app := cview.NewApplication()
|
|
|
|
|
2018-03-19 20:25:30 +00:00
|
|
|
radioButtons := NewRadioButtons([]string{"Lions", "Elephants", "Giraffes"})
|
2020-10-07 23:34:21 +00:00
|
|
|
radioButtons.SetBorder(true)
|
|
|
|
radioButtons.SetTitle("Radio Button Demo")
|
|
|
|
radioButtons.SetRect(0, 0, 30, 5)
|
|
|
|
|
|
|
|
app.SetRoot(radioButtons, false)
|
|
|
|
if err := app.Run(); err != nil {
|
2018-03-19 20:25:30 +00:00
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|