~eliasnaur/gio

ref: f08568a6dfc3890dcc8ea76c11f1a4cd436a57c1 gio/widget/enum.go -rw-r--r-- 926 bytes
f08568a6Elias Naur widget: report whether Value changed after Enum.Update and Bool.Update 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package widget

import (
	"gioui.org/gesture"
	"gioui.org/layout"
)

type Enum struct {
	Value string

	clicks []gesture.Click
	values []string
}

func index(vs []string, t string) int {
	for i, v := range vs {
		if v == t {
			return i
		}
	}
	return -1
}

// Update the Value according to incoming events, and
// reports whether Value changed.
func (e *Enum) Update(gtx *layout.Context) bool {
	was := e.Value
	for i := range e.clicks {
		for _, ev := range e.clicks[i].Events(gtx) {
			switch ev.Type {
			case gesture.TypeClick:
				e.Value = e.values[i]
			}
		}
	}
	return e.Value != was
}

// Layout adds the event handler for key.
func (e *Enum) Layout(gtx *layout.Context, key string) {
	if index(e.values, key) == -1 {
		e.values = append(e.values, key)
		e.clicks = append(e.clicks, gesture.Click{})
		e.clicks[len(e.clicks)-1].Add(gtx.Ops)
	} else {
		idx := index(e.values, key)
		e.clicks[idx].Add(gtx.Ops)
	}
}