itor/gui/create.go
2022-10-09 01:21:00 -04:00

87 lines
1.6 KiB
Go

package gui
import (
"fmt"
"gitea.tyrel.dev/tyrel/itor/models"
tea "github.com/charmbracelet/bubbletea"
)
type errMsg error
const InputCount = 2
func (m *model) nextTabIndex() {
m.createdInputIndex++
m.createdInputIndex = m.createdInputIndex % InputCount
}
func (m *model) createCurrent() {
// Get the value of the front and back of the card
front := m.createInputs[0].Value()
back := m.createInputs[1].Value()
if front == "" || back == "" {
return
}
// Create a new card
card := models.Card{
Front: front,
Back: back,
}
// Add it to the deck
m.deck = append(m.deck, card)
m.selectList.InsertItem(len(m.selectList.Items())+1, card)
// Clear the inputs
for i, _ := range m.createInputs {
m.createInputs[i].Reset()
}
// Back to Select
m.switchMode(Select)
}
func (m *model) updateCreate(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC:
return m, tea.Quit
case tea.KeyEsc:
m.switchMode(Select)
return m, cmd
case tea.KeyEnter:
m.createCurrent()
case tea.KeyTab:
m.createInputs[m.createdInputIndex].Blur()
m.nextTabIndex()
m.createInputs[m.createdInputIndex].Focus()
}
// We handle errors just like any other message
case errMsg:
m.err = msg
return m, nil
}
for i, _ := range m.createInputs {
m.createInputs[i], cmd = m.createInputs[i].Update(msg)
}
return m, cmd
}
func (m *model) viewCreate() string {
s := fmt.Sprintf(
"Create a card:\n\nFront: %s\nBack: %s\n\n[Tab] switch field.\n[Enter] creates new card.\n[Escape] for back.",
m.createInputs[0].View(),
m.createInputs[1].View(),
)
return s
}