objects/checkbox.go

79 lines
2.0 KiB
Go
Raw Normal View History

2024-05-07 11:45:06 -06:00
package objects
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/event"
// Checkbox is a control that can be toggled.
type Checkbox struct {
tomo.Box
value bool
on struct {
valueChange event.FuncBroadcaster
}
}
// NewCheckbox creates a new checkbox with the specified value.
func NewCheckbox (value bool) *Checkbox {
box := &Checkbox {
Box: tomo.NewBox(),
}
2024-07-21 09:48:28 -06:00
box.SetRole(tomo.R("objects", "Checkbox"))
box.SetValue(value)
2024-05-07 11:45:06 -06:00
2024-07-21 09:48:28 -06:00
box.OnButtonDown(box.handleButtonDown)
box.OnButtonUp(box.handleButtonUp)
2024-07-25 10:58:38 -06:00
box.OnKeyDown(box.handleKeyDown)
2024-05-07 11:45:06 -06:00
box.OnKeyUp(box.handleKeyUp)
box.SetFocusable(true)
return box
}
// Value returns the value of the checkbox.
func (this *Checkbox) Value () bool {
return this.value
}
2024-05-07 11:45:06 -06:00
// SetValue sets the value of the checkbox.
func (this *Checkbox) SetValue (value bool) {
this.value = value
2024-07-21 09:48:28 -06:00
// the theme shall decide what checked and unchecked states look like
this.SetTag("checked", value)
this.SetTag("unchecked", !value)
2024-05-07 11:45:06 -06:00
}
// Toggle toggles the value of the checkbox between true and false.
func (this *Checkbox) Toggle () {
this.SetValue(!this.Value())
}
// OnValueChange specifies a function to be called when the user checks or
// unchecks the checkbox.
2024-05-07 11:45:06 -06:00
func (this *Checkbox) OnValueChange (callback func ()) event.Cookie {
return this.on.valueChange.Connect(callback)
}
2024-07-25 10:58:38 -06:00
func (this *Checkbox) handleKeyDown (key input.Key, numberPad bool) bool {
if key != input.KeyEnter && key != input.Key(' ') { return false }
2024-05-07 11:45:06 -06:00
this.Toggle()
2024-07-25 10:58:38 -06:00
return true
2024-05-07 11:45:06 -06:00
}
2024-07-25 10:58:38 -06:00
func (this *Checkbox) handleKeyUp (key input.Key, numberPad bool) bool {
if key != input.KeyEnter && key != input.Key(' ') { return false}
return true
2024-07-21 09:48:28 -06:00
}
2024-07-25 10:58:38 -06:00
func (this *Checkbox) handleButtonDown (button input.Button) bool {
if button != input.ButtonLeft { return false }
return true
}
func (this *Checkbox) handleButtonUp (button input.Button) bool {
if button != input.ButtonLeft { return false }
2024-07-21 09:48:28 -06:00
if this.Window().MousePosition().In(this.Bounds()) {
2024-05-07 11:45:06 -06:00
this.Toggle()
}
2024-07-25 10:58:38 -06:00
return true
2024-05-07 11:45:06 -06:00
}