itor/gui/create.go

87 lines
1.6 KiB
Go
Raw Normal View History

2022-10-09 03:18:46 +00:00
package gui
2022-10-09 03:46:15 +00:00
import (
"fmt"
2022-10-09 05:21:00 +00:00
"gitea.tyrel.dev/tyrel/itor/models"
2022-10-09 03:46:15 +00:00
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() {
2022-10-09 03:47:29 +00:00
// Get the value of the front and back of the card
2022-10-09 03:46:15 +00:00
front := m.createInputs[0].Value()
back := m.createInputs[1].Value()
2022-10-09 05:21:00 +00:00
if front == "" || back == "" {
return
}
2022-10-09 03:47:29 +00:00
// Create a new card
2022-10-09 05:21:00 +00:00
card := models.Card{
2022-10-09 03:46:15 +00:00
Front: front,
Back: back,
}
2022-10-09 03:47:29 +00:00
// Add it to the deck
m.deck = append(m.deck, card)
2022-10-09 05:21:00 +00:00
m.selectList.InsertItem(len(m.selectList.Items())+1, card)
2022-10-09 03:46:15 +00:00
2022-10-09 03:47:29 +00:00
// Clear the inputs
2022-10-09 03:46:15 +00:00
for i, _ := range m.createInputs {
m.createInputs[i].Reset()
}
// Back to Select
m.switchMode(Select)
}
2022-10-09 03:18:46 +00:00
func (m *model) updateCreate(msg tea.Msg) (tea.Model, tea.Cmd) {
2022-10-09 03:46:15 +00:00
var cmd tea.Cmd
2022-10-09 03:18:46 +00:00
2022-10-09 03:46:15 +00:00
switch msg := msg.(type) {
2022-10-09 03:18:46 +00:00
case tea.KeyMsg:
2022-10-09 03:46:15 +00:00
switch msg.Type {
case tea.KeyCtrlC:
2022-10-09 03:18:46 +00:00
return m, tea.Quit
2022-10-09 03:46:15 +00:00
case tea.KeyEsc:
2022-10-09 03:18:46 +00:00
m.switchMode(Select)
2022-10-09 03:46:15 +00:00
return m, cmd
case tea.KeyEnter:
m.createCurrent()
case tea.KeyTab:
m.createInputs[m.createdInputIndex].Blur()
m.nextTabIndex()
m.createInputs[m.createdInputIndex].Focus()
2022-10-09 03:18:46 +00:00
}
2022-10-09 03:46:15 +00:00
// 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)
2022-10-09 03:18:46 +00:00
}
2022-10-09 03:46:15 +00:00
return m, cmd
2022-10-09 03:18:46 +00:00
}
func (m *model) viewCreate() string {
2022-10-09 03:46:15 +00:00
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(),
)
2022-10-09 03:18:46 +00:00
return s
}