spacetea/place.go

80 lines
2.0 KiB
Go
Raw Normal View History

2022-05-18 22:47:48 -04:00
package main
import (
2022-05-19 17:09:46 -04:00
sim "git.saintnet.tech/stryan/spacetea/simulator"
2022-05-18 22:47:48 -04:00
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
2022-05-19 17:09:46 -04:00
"github.com/charmbracelet/lipgloss"
2022-05-18 22:47:48 -04:00
)
2022-05-19 17:09:46 -04:00
var docStyle = lipgloss.NewStyle().Margin(1, 2)
2022-05-18 22:47:48 -04:00
type item struct {
2022-05-19 17:09:46 -04:00
title, desc, id string
2022-05-18 22:47:48 -04:00
}
func (i item) Title() string { return i.title }
func (i item) Description() string { return i.desc }
2022-05-19 17:09:46 -04:00
func (i item) ID() string { return i.id }
2022-05-18 22:47:48 -04:00
func (i item) FilterValue() string { return i.title }
type placeModel struct {
list list.Model
}
2022-05-19 12:58:37 -04:00
type placeMsg string
func (p placeModel) buildPlaceMsg() tea.Msg {
i := p.list.SelectedItem().(item)
2022-05-19 17:09:46 -04:00
return placeMsg(i.ID())
2022-05-19 12:58:37 -04:00
}
2022-05-19 17:09:46 -04:00
func newPlaceModel(entries []sim.ItemEntry, m tea.Model) placeModel {
2022-05-18 22:47:48 -04:00
var p placeModel
items := []list.Item{}
for _, v := range entries {
2022-05-19 17:09:46 -04:00
items = append(items, item{v.Name(), "no description", v.ID()})
2022-05-18 22:47:48 -04:00
}
//w,h
2022-05-19 17:09:46 -04:00
p.list = list.New(items, list.NewDefaultDelegate(), 32, 32)
2022-05-18 22:47:48 -04:00
p.list.Title = "What do you want to place?"
p.list.DisableQuitKeybindings()
return p
}
// Init is the first function that will be called. It returns an optional
// initial command. To not perform an initial command return nil.
func (p placeModel) Init() tea.Cmd {
return tea.EnterAltScreen
}
// Update is called when a message is received. Use it to inspect messages
// and, in response, update the model and/or send a command.
func (p placeModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
2022-05-19 17:09:46 -04:00
h, v := docStyle.GetFrameSize()
p.list.SetSize(msg.Width-h, msg.Height-v)
2022-05-18 22:47:48 -04:00
return p, nil
case tea.KeyMsg:
switch keypress := msg.String(); keypress {
case "ctrl-c":
return p, tea.Quit
case "esc":
2022-05-19 17:09:46 -04:00
return initMainscreen(), heartbeat()
2022-05-18 22:47:48 -04:00
case "enter":
2022-05-19 17:09:46 -04:00
return initMainscreen(), tea.Batch(p.buildPlaceMsg, heartbeat())
2022-05-18 22:47:48 -04:00
}
}
var cmd tea.Cmd
p.list, cmd = p.list.Update(msg)
return p, cmd
}
// View renders the program's UI, which is just a string. The view is
// rendered after every Update.
func (p placeModel) View() string {
return p.list.View()
}