aboutsummaryrefslogtreecommitdiff
path: root/confirm.go
blob: a7d4748119655e6010e83bbe9d1dd116d93af3cd (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
package main

import (
	"fmt"

	"github.com/charmbracelet/bubbles/viewport"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

type confirmModel struct {
	ready    bool
	doRun    bool
	selected item
	viewport viewport.Model
	returnTo selectingModel
}

func switchToConfirm(m selectingModel) (confirmModel, tea.Cmd) {
	model := confirmModel{
		selected: m.list.SelectedItem().(item),
		returnTo: m,
	}
	return model, model.Init()
}

func (m confirmModel) View() string {
	if !m.ready {
		return "Initialising..."
	}

	return appStyle.Render(fmt.Sprintf("%s\n%s\n%s", m.headerView(), m.viewport.View(), m.footerView()))
}

func (m confirmModel) Init() tea.Cmd {
	return func() tea.Msg {
		// FIXME: Hacky way to get a WindowSizeMsg event sent
		frame_h, frame_v := appStyle.GetFrameSize()
		return tea.WindowSizeMsg{
			Height: m.returnTo.list.Height() + frame_v,
			Width:  m.returnTo.list.Width() + frame_h,
		}
	}
}

func (m confirmModel) headerView() string {
	return confirmTitleStyle.Render(m.selected.title)
}
func (m confirmModel) footerView() string {
	out := areYouSureTextStyle.Render("Are you sure?")
	out += subtleTextStyle.Render("  RET to continue, q to go back, ctrl+c to quit")
	return out
}

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

	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {

		case "enter":
			m.doRun = true
			return m, tea.Quit
		case "ctrl-c":
			return m, tea.Quit
		case "q":
			return m.returnTo, nil
		}
	case tea.WindowSizeMsg:
		padding_h, padding_v := appStyle.GetFrameSize()
		headerHeight := lipgloss.Height(m.headerView())
		footerHeight := lipgloss.Height(m.footerView())
		verticalMarginHeight := headerHeight + footerHeight + padding_v

		if !m.ready {
			m.viewport = viewport.New(msg.Width-padding_h, msg.Height-verticalMarginHeight)
			m.viewport.YPosition = headerHeight + padding_v + 1
			m.viewport.SetContent(m.selected.contents)
			m.ready = true
		} else {
			m.viewport.Width = msg.Width - padding_h
			m.viewport.Height = msg.Height - verticalMarginHeight - padding_v
		}
	}

	// Handle keyboard and mouse events in the viewport
	var cmd tea.Cmd
	m.viewport, cmd = m.viewport.Update(msg)
	cmds = append(cmds, cmd)
	return m, tea.Batch(cmds...)
}