mast/main.go
Anish Lakhwara 5ca28cfb19 init
;10u
2024-08-03 18:06:43 -07:00

99 lines
1.8 KiB
Go

package main
import (
"database/sql"
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
_ "github.com/mattn/go-sqlite3"
"git.sealight.xyz/aynish/mast/db"
)
type model struct {
db *sql.DB
todos []string
cursor int
}
func initialModel() model {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
err = RunMigrations(db)
if err != nil {
panic(err)
}
m := model{
db: db,
todos: []string{},
cursor: 0,
}
m.loadTodos()
return m
}
func (m *model) addTodo(todo string) {
_, err := m.db.Exec("INSERT INTO todos (content) VALUES (?)", todo)
if err != nil {
panic(err)
}
m.loadTodos()
}
func (m *model) loadTodos() {
rows, err := m.db.Query("SELECT content FROM todos")
if err != nil {
panic(err)
}
defer rows.Close()
m.todos = []string{}
for rows.Next() {
var content string
if err := rows.Scan(&content); err != nil {
panic(err)
}
m.todos = append(m.todos, content)
}
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
}
}
return m, nil
}
func (m model) View() string {
s := "Todo List:\n\n"
for i, todo := range m.todos {
cursor := " "
if m.cursor == i {
cursor = ">"
}
s += fmt.Sprintf("%s %s\n", cursor, todo)
}
s += "\nPress q to quit.\n"
return s
}
func main() {
p := tea.NewProgram(initialModel())
if _, err := p.Run(); err != nil {
fmt.Printf("Alas, there's been an error: %v", err)
os.Exit(1)
}
}