-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
messages.go
70 lines (55 loc) · 1.91 KB
/
messages.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
// Copyright (c) Liam Stanley <[email protected]>. All rights reserved. Use of
// this source code is governed by the MIT license that can be found in
// the LICENSE file.
package zone
import (
"sort"
tea "github.com/charmbracelet/bubbletea"
)
// MsgZoneInBounds is a message sent when the manager detects that a zone is within
// bounds of a mouse event.
type MsgZoneInBounds struct {
Zone *ZoneInfo // The zone that is in bounds.
Event tea.MouseMsg // The mouse event that caused the zone to be in bounds.
}
func (m *Manager) findInBounds(mouse tea.MouseMsg) []*ZoneInfo {
var zones []*ZoneInfo
m.zoneMu.RLock()
defer m.zoneMu.RUnlock()
keys := make([]string, 0, len(m.zones))
for k := range m.zones {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
zone := m.zones[k]
if zone.InBounds(mouse) {
zones = append(zones, zone)
}
}
return zones
}
// AnyInBoundsAndUpdate is the same as AnyInBounds; except the results of the calls
// to Update() are carried through and returned.
//
// The tea.Cmd's that comd off the calls to Update() are wrapped in tea.Batch().
func (m *Manager) AnyInBoundsAndUpdate(model tea.Model, mouse tea.MouseMsg) (tea.Model, tea.Cmd) {
zones := m.findInBounds(mouse)
cmds := make([]tea.Cmd, len(zones))
for i, zone := range zones {
model, cmds[i] = model.Update(MsgZoneInBounds{Zone: zone, Event: mouse})
}
return model, tea.Batch(cmds...)
}
// AnyInBounds sends a MsgZoneInBounds message to the provided model for each zone
// that is in the bounds of the provided mouse event. The results of the call to
// Update() are discarded.
//
// Note that if multiple zones are within bounds, each one will be sent as an event
// in alphabetical sorted order of the ID.
func (m *Manager) AnyInBounds(model tea.Model, mouse tea.MouseMsg) {
zones := m.findInBounds(mouse)
for _, zone := range zones {
_, _ = model.Update(MsgZoneInBounds{Zone: zone, Event: mouse})
}
}