forked from gomatcha/matcha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slider.go
118 lines (104 loc) · 2.37 KB
/
slider.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package view
import (
"fmt"
"github.com/gogo/protobuf/proto"
"gomatcha.io/matcha/comm"
"gomatcha.io/matcha/internal"
"gomatcha.io/matcha/layout"
"gomatcha.io/matcha/paint"
pbview "gomatcha.io/matcha/proto/view"
)
type sliderLayouter struct {
}
func (l *sliderLayouter) Layout(ctx layout.Context) (layout.Guide, []layout.Guide) {
g := layout.Guide{Frame: layout.Rt(0, 0, ctx.MinSize().X, 31)}
return g, nil
}
func (l *sliderLayouter) Notify(f func()) comm.Id {
return 0 // no-op
}
func (l *sliderLayouter) Unnotify(id comm.Id) {
// no-op
}
type Slider struct {
Embed
PaintStyle *paint.Style
Value float64
ValueNotifier comm.Float64Notifier
valueNotifier comm.Float64Notifier
MaxValue float64
MinValue float64
OnChange func(value float64)
OnSubmit func(value float64)
Enabled bool
}
// New returns a new view.
func NewSlider() *Slider {
return &Slider{
MaxValue: 1,
MinValue: 0,
Enabled: true,
}
}
func (v *Slider) Lifecycle(from, to Stage) {
if ExitsStage(from, to, StageMounted) {
if v.valueNotifier != nil {
v.Unsubscribe(v.valueNotifier)
}
}
}
// Build implements view.View.
func (v *Slider) Build(ctx Context) Model {
val := v.Value
if v.ValueNotifier != nil {
val = v.ValueNotifier.Value()
}
if v.ValueNotifier != v.valueNotifier {
if v.valueNotifier != nil {
v.Unsubscribe(v.valueNotifier)
}
if v.ValueNotifier != nil {
v.Subscribe(v.ValueNotifier)
}
v.valueNotifier = v.ValueNotifier
}
painter := paint.Painter(nil)
if v.PaintStyle != nil {
painter = v.PaintStyle
}
return Model{
Painter: painter,
Layouter: &sliderLayouter{},
NativeViewName: "gomatcha.io/matcha/view/slider",
NativeViewState: internal.MarshalProtobuf(&pbview.Slider{
Value: val,
MaxValue: v.MaxValue,
MinValue: v.MinValue,
Enabled: v.Enabled,
}),
NativeFuncs: map[string]interface{}{
"OnValueChange": func(data []byte) {
event := &pbview.SliderEvent{}
err := proto.Unmarshal(data, event)
if err != nil {
fmt.Println("error", err)
return
}
if v.OnChange != nil {
v.OnChange(event.Value)
}
},
"OnSubmit": func(data []byte) {
event := &pbview.SliderEvent{}
err := proto.Unmarshal(data, event)
if err != nil {
fmt.Println("error", err)
return
}
if v.OnSubmit != nil {
v.OnSubmit(event.Value)
}
},
},
}
}