whispervis/widgets/switch.go

75 lines
1.5 KiB
Go
Raw Normal View History

2018-10-24 20:43:31 +02:00
package widgets
import (
"fmt"
"math"
"math/rand"
"github.com/gopherjs/vecty"
"github.com/gopherjs/vecty/elem"
"github.com/gopherjs/vecty/event"
"github.com/gopherjs/vecty/prop"
)
// Switch is a wrapper around checkbox-like switch.
type Switch struct {
vecty.Core
2018-10-24 21:08:29 +02:00
title string
2018-10-24 20:43:31 +02:00
isChecked bool
handler func()
2018-10-24 20:43:31 +02:00
domID string
}
// NewSwitch creates and inits a new switch.
2018-10-24 21:08:29 +02:00
func NewSwitch(title string, checked bool, handler func()) *Switch {
2018-10-24 20:43:31 +02:00
rnd := rand.Int63n(math.MaxInt64)
domID := fmt.Sprintf("idSwitch%d", rnd)
return &Switch{
2018-10-24 21:08:29 +02:00
title: title,
2018-10-24 20:43:31 +02:00
isChecked: checked,
handler: handler,
2018-10-24 20:43:31 +02:00
domID: domID,
}
}
// Render implements vecty's Component interface for Switch.
func (s *Switch) Render() vecty.ComponentOrHTML {
return elem.Div(
elem.Input(
vecty.Markup(
vecty.Class("switch", "is-rounded", "is-small"),
prop.ID(s.domID),
prop.Type(prop.TypeCheckbox),
event.Change(s.onToggle),
vecty.MarkupIf(s.isChecked,
vecty.Attribute("checked", "checked"),
),
),
),
elem.Label(
vecty.Markup(
// this is needed to properly handle click
// see https://wikiki.github.io/form/switch/
vecty.Attribute("for", s.domID),
),
2018-10-24 21:08:29 +02:00
vecty.Text(s.title),
2018-10-24 20:43:31 +02:00
),
)
}
// Checked returns the checked state of the switch.
func (s *Switch) Checked() bool {
return s.isChecked
}
// onToggle changes the checked state of the switch.
func (s *Switch) onToggle(*vecty.Event) {
s.isChecked = !s.isChecked
vecty.Rerender(s)
if s.handler != nil {
go s.handler()
}
2018-10-24 20:43:31 +02:00
}