aboutsummaryrefslogtreecommitdiff
path: root/selecting.go
blob: 0817d3dbb3766e4961a11eeb9cd6b9b10dcbe04c (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
99
100
101
102
103
104
105
106
package main

import (
	"fmt"

	"github.com/charmbracelet/bubbles/list"
	tea "github.com/charmbracelet/bubbletea"
)

type selectingModel struct {
	list list.Model
}

func StartSelecting() selectingModel {
	items, err := getItems()
	if err != nil {
		panic(err)
	}

	list := list.New(items, list.NewDefaultDelegate(), 0, 0)
	list.Title = "Commands"

	m := selectingModel{
		list: list,
	}

	return m
}

func (m selectingModel) Init() tea.Cmd {
	return tea.EnterAltScreen
}

func (m selectingModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmds []tea.Cmd

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		h, v := appStyle.GetFrameSize()
		m.list.SetSize(msg.Width-h, msg.Height-v)

	case tea.KeyMsg:
		// Don't match any of the keys below if we're actively filtering.
		if m.list.FilterState() == list.Filtering {
			break
		}

		switch msg.String() {

		case "+", "n":
			cmds = append(cmds, newItemCmd())
		case "enter", " ":
			if m.list.SelectedItem() != nil {
				return switchToConfirm(m)
			}
		case "e":
			if m.list.SelectedItem() != nil {
				cmds = append(cmds, editItemCmd(m.list.SelectedItem().(item)))
			}
		case "d":
			if m.list.SelectedItem() != nil {
				cmds = append(cmds, deleteItemCmd(m.list.SelectedItem().(item)))
			}
		}

	case vimFinishedMsg:
		if msg.err != nil {
			fmt.Println(msg.err)
			return m, tea.Quit
		}

		return switchToDetails(m, msg.snippet)

	case setListItemsMsg:
		cmds = append(cmds, m.list.SetItems(msg.newItems))

	case updateListMsg:
		cmds = append(cmds, func() tea.Msg {
			items, err := getItems()
			if err != nil {
				return fatalErrorMsg(err)
			}

			return setListItemsMsg{items}
		})

	case fatalErrorMsg:
		fmt.Printf("encountered fatal error: %s\n", msg.Error())
		return m, tea.Quit
	}

	// This will also call our delegate's update function.
	newListModel, cmd := m.list.Update(msg)
	m.list = newListModel
	cmds = append(cmds, cmd)

	return m, tea.Batch(cmds...)
}

func (m selectingModel) View() string {
	return appStyle.Render(m.list.View())
}

type setListItemsMsg struct {
	newItems []list.Item
}