summaryrefslogtreecommitdiff
path: root/menu/input.go
blob: e2e35b30585e9612d7e78c855de29b8a3273304f (plain)
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
package menu

import tea "github.com/charmbracelet/bubbletea"

func (m *Model) HandleInput(msg tea.KeyMsg) (tea.Cmd, error) {

	if m.Search.Focused() {
		var cmd tea.Cmd
		switch msg.String() {
		case "ctrl+c":
			m.Search.SetValue("")
			m.Search.Blur()
		case "ctrl+d":
			m.Search.Blur()
		case "enter":
			m.Search.Blur()
		default:
			result, c := m.Search.Update(msg)
			cmd = c
			m.Search = result
		}
		return cmd, nil
	}

	var cmd tea.Cmd
	switch msg.String() {
	case "/":
		m.Search.SetValue("")
		fallthrough
	case "?":
		return m.Search.Focus(), nil
	case "i", "I":
		if m.Alt {
			m.Alt = false
			m.AutoAlt = false
			return tea.ExitAltScreen, nil
		} else {
			m.Alt = true
			m.AutoAlt = false
			return tea.EnterAltScreen, nil
		}
	case "h", "left":
		m.Leap(-1)
	case "l", "right":
		m.Leap(1)
	case "up", "k":
		m.Index--
	case "down", "j":
		m.Index++
	case "n":
		m.LeapFilter(1)
	case "N":
		m.LeapFilter(-1)
	case "q", "esc", "ctrl+c":
		m.Cancel = true
		return tea.Quit, nil
	case "space", " ", "enter", "ctrl+d":
		m.Done = true
		return tea.Quit, nil
	}

	_ = m.Validate()

	return cmd, nil
}

func (m *Model) LeapFilter(direction int) {
	startIndex := m.Index
	for {
		m.Index += direction
		clamped := m.Validate()
		if clamped {
			m.Index = startIndex
			return
		}

		source, target := m.Result()
		if m.Highlights(source, target) {
			return
		}
	}
}

func (m *Model) Leap(direction int) {
	for {
		source, target := m.Result()
		m.Index += direction
		m.Validate()
		newSource, newTarget := m.Result()
		if target == newTarget {
			return
		}

		if source != newSource {
			return
		}
	}
}