gitstack

grindlemire/go-tui code browser

1014 B Go 39 lines 2026-03-01 · 8afcd19 raw
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
package tui

// ClickBinding represents a ref-to-function binding for mouse clicks.
type ClickBinding struct {
	Ref *Ref
	Fn  func()
}

// Click creates a click binding for use with HandleClicks.
func Click(ref *Ref, fn func()) ClickBinding {
	return ClickBinding{Ref: ref, Fn: fn}
}

// HandleClicks checks a mouse event against click bindings and calls
// the first matching handler. Returns true if a click was handled.
// Use this in HandleMouse to simplify ref-based hit testing.
//
// Example:
//
//	func (c *counter) HandleMouse(me tui.MouseEvent) bool {
//	    return tui.HandleClicks(me,
//	        tui.Click(c.incrementBtn, c.increment),
//	        tui.Click(c.decrementBtn, c.decrement),
//	    )
//	}
func HandleClicks(me MouseEvent, bindings ...ClickBinding) bool {
	if me.Button != MouseLeft || me.Action != MousePress {
		return false
	}

	for _, b := range bindings {
		if b.Ref != nil && b.Ref.El() != nil && b.Ref.El().ContainsPoint(me.X, me.Y) {
			b.Fn()
			return true
		}
	}

	return false
}