clui/radiogroup.go

74 lines
1.5 KiB
Go
Raw Permalink Normal View History

2015-10-17 01:27:43 +08:00
package clui
2015-10-30 02:48:01 +08:00
// RadioGroup is non-interactive invisible object. It manages
// set of Radio buttons: at a time no more than one radio
// button from a group can be selected
2015-10-17 01:27:43 +08:00
type RadioGroup struct {
items []*Radio
}
2015-10-30 02:48:01 +08:00
// NewRadioGroup creates a new RadioGroup
2015-10-17 01:27:43 +08:00
func NewRadioGroup() *RadioGroup {
c := new(RadioGroup)
c.items = make([]*Radio, 0)
return c
}
2015-10-30 02:48:01 +08:00
// Selected returns the number of currently selected radio
// button inside the group or -1 if no button is selected
2015-10-17 01:27:43 +08:00
func (c *RadioGroup) Selected() int {
selected := -1
for id, item := range c.items {
if item.Selected() {
selected = id
break
}
}
return selected
}
2015-10-30 02:48:01 +08:00
// SelectItem makes the radio selected. The function returns false
// if it failed to find the radio in the radio group
2015-10-17 01:27:43 +08:00
func (c *RadioGroup) SelectItem(r *Radio) bool {
found := false
for _, item := range c.items {
if item == r {
found = true
item.SetSelected(true)
} else {
item.SetSelected(false)
}
}
return found
}
2015-10-30 02:48:01 +08:00
// SetSelected selects the radio by its number. The function
// returns false if the number is invalid for the radio group
2015-10-17 01:27:43 +08:00
func (c *RadioGroup) SetSelected(id int) bool {
found := false
if id < 0 || id >= len(c.items) {
return false
}
for idx, item := range c.items {
if idx == id {
found = true
item.SetSelected(true)
} else {
item.SetSelected(false)
}
}
return found
}
2015-10-30 02:48:01 +08:00
// AddItem add a new radio button to group
2015-10-17 01:27:43 +08:00
func (c *RadioGroup) AddItem(r *Radio) {
c.items = append(c.items, r)
r.SetGroup(c)
}