widget: export Button.Update method for accessing raw gesture events

Document Button while we're here.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
This commit is contained in:
Elias Naur
2020-05-11 12:56:56 +02:00
parent 43c2b90716
commit 47ce4b8cb8
+14 -4
View File
@@ -13,6 +13,7 @@ import (
"gioui.org/op" "gioui.org/op"
) )
// Button represents a clickable area.
type Button struct { type Button struct {
click gesture.Click click gesture.Click
// clicks tracks the number of unreported clicks. // clicks tracks the number of unreported clicks.
@@ -26,8 +27,11 @@ type Click struct {
Time time.Time Time time.Time
} }
// Clicked calls Update and reports whether the button was
// clicked since the last call. Multiple clicks result in Clicked
// returning true once per click.
func (b *Button) Clicked(gtx *layout.Context) bool { func (b *Button) Clicked(gtx *layout.Context) bool {
b.processEvents(gtx) b.Update(gtx)
if b.clicks > 0 { if b.clicks > 0 {
b.clicks-- b.clicks--
if b.clicks > 0 { if b.clicks > 0 {
@@ -39,13 +43,15 @@ func (b *Button) Clicked(gtx *layout.Context) bool {
return false return false
} }
// History is the past clicks useful for drawing click markers.
// Clicks are retained for a short duration (about a second).
func (b *Button) History() []Click { func (b *Button) History() []Click {
return b.history return b.history
} }
func (b *Button) Layout(gtx *layout.Context) { func (b *Button) Layout(gtx *layout.Context) {
// Flush clicks from before the previous frame. // Flush clicks from before the previous frame.
b.processEvents(gtx) b.Update(gtx)
var st op.StackOp var st op.StackOp
st.Push(gtx.Ops) st.Push(gtx.Ops)
pointer.Rect(image.Rectangle{Max: gtx.Constraints.Min()}).Add(gtx.Ops) pointer.Rect(image.Rectangle{Max: gtx.Constraints.Min()}).Add(gtx.Ops)
@@ -61,8 +67,11 @@ func (b *Button) Layout(gtx *layout.Context) {
} }
} }
func (b *Button) processEvents(gtx *layout.Context) { // Update the button state by processing events. The underlying
for _, e := range b.click.Events(gtx) { // gesture events are returned for use beyond what Clicked offers.
func (b *Button) Update(gtx *layout.Context) []gesture.ClickEvent {
evts := b.click.Events(gtx)
for _, e := range evts {
switch e.Type { switch e.Type {
case gesture.TypeClick: case gesture.TypeClick:
b.clicks++ b.clicks++
@@ -73,4 +82,5 @@ func (b *Button) processEvents(gtx *layout.Context) {
}) })
} }
} }
return evts
} }