-
Notifications
You must be signed in to change notification settings - Fork 3
/
ui.go
107 lines (87 loc) · 1.96 KB
/
ui.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
package clio
import (
"fmt"
"sync"
"github.com/wagoodman/go-partybus"
)
type UIConstructor func(Config) (*UICollection, error)
type UI interface {
Setup(subscription partybus.Unsubscribable) error
partybus.Handler
Teardown(force bool) error
}
var _ UIConstructor = newUI
func newUI(Config) (*UICollection, error) {
// gracefully degrade to no UI if no constructor is configured
return NewUICollection(), nil
}
var _ UI = (*UICollection)(nil)
type UICollection struct {
uis []UI
active UI
subscription partybus.Unsubscribable
lock *sync.Mutex
}
func NewUICollection(uis ...UI) *UICollection {
return &UICollection{
uis: uis,
lock: &sync.Mutex{},
}
}
func (u *UICollection) Setup(subscription partybus.Unsubscribable) error {
u.lock.Lock()
defer u.lock.Unlock()
return u.setup(subscription)
}
func (u *UICollection) setup(subscription partybus.Unsubscribable) error {
u.subscription = subscription
var setupErr error
for _, ui := range u.uis {
if err := ui.Setup(subscription); err != nil {
setupErr = err
continue
}
setupErr = nil
u.active = ui
break
}
return setupErr
}
func (u UICollection) Handle(event partybus.Event) error {
u.lock.Lock()
defer u.lock.Unlock()
if u.active == nil {
return nil
}
return u.active.Handle(event)
}
func (u *UICollection) Teardown(force bool) error {
u.lock.Lock()
defer u.lock.Unlock()
return u.teardown(force)
}
func (u *UICollection) teardown(force bool) error {
if u.active == nil {
return nil
}
err := u.active.Teardown(force)
u.active = nil
return err
}
func (u *UICollection) Replace(uis ...UI) error {
u.lock.Lock()
defer u.lock.Unlock()
if u.subscription != nil {
if err := u.teardown(false); err != nil {
return fmt.Errorf("unable to teardown existing UI: %w", err)
}
}
u.uis = uis
if u.subscription != nil {
err := u.setup(u.subscription)
if err != nil {
return fmt.Errorf("unable to setup UI replacement: %w", err)
}
}
return nil
}