Compare commits
No commits in common. "master" and "v0.3.0" have entirely different histories.
24
README.md
24
README.md
@ -87,30 +87,6 @@ Set custom colors for the progress bar:
|
||||
./gomodoro --color-left="#ff0000" --color-right="#00ff00"
|
||||
```
|
||||
|
||||
## Some Pro Tips!
|
||||
|
||||
- Use the `--on-focus-start` and `--on-focus-end` options to run commands that help you get into the zone and wind down after a focus period or to control your environment (e.g., turning off notifications).
|
||||
|
||||
### My example usage
|
||||
|
||||
I used Shortcuts on my mac to control macOS Focus mode. I named them "Turn On Focus" and "Turn Off Focus". This allows my focus start and end commands to control my notifications for my computer and phone (since I have them synced).
|
||||
|
||||
I also use [Slack Status CLI](https://git.iamthefij.com/iamthefij/slack-status-cli) to set my Slack status to a snooze mode with a tomato emoji when I'm in focus mode and turn it off after.
|
||||
|
||||
```sh
|
||||
gomodoro \
|
||||
--fullscreen \
|
||||
--color-left '#ecdfb1' \
|
||||
--color-right '#c6e889 ' \
|
||||
--on-focus-start "shortcuts run 'Turn On Focus'" \
|
||||
--on-focus-start "say 'Time to focus'" \
|
||||
--on-focus-start "slack-status -snooze -duration 1h -emoji :tomato: Focus" \
|
||||
--on-focus-end "shortcuts run 'Turn Off Focus'" \
|
||||
--on-focus-end "say 'Break time you slacker'" \
|
||||
--on-focus-end "slack-status" \
|
||||
--on-interval-end "say 'Interval done! Phew!'"
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
||||
|
4
go.mod
4
go.mod
@ -3,11 +3,10 @@ module git.iamthefij.com/iamthefij/gomodoro
|
||||
go 1.21.4
|
||||
|
||||
require (
|
||||
git.iamthefij.com/iamthefij/go-shell-runner v0.1.0
|
||||
git.iamthefij.com/iamthefij/slog v1.3.0
|
||||
git.iamthefij.com/iamthefij/tortoise v1.0.1
|
||||
github.com/charmbracelet/bubbles v0.20.0
|
||||
github.com/charmbracelet/bubbletea v1.1.1
|
||||
github.com/charmbracelet/huh v0.6.0
|
||||
github.com/charmbracelet/lipgloss v0.13.0
|
||||
github.com/urfave/cli/v2 v2.27.5
|
||||
)
|
||||
@ -17,6 +16,7 @@ require (
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/catppuccin/go v0.2.0 // indirect
|
||||
github.com/charmbracelet/harmonica v0.2.0 // indirect
|
||||
github.com/charmbracelet/huh v0.6.0 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.2.3 // indirect
|
||||
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.0 // indirect
|
||||
|
12
go.sum
12
go.sum
@ -1,9 +1,7 @@
|
||||
git.iamthefij.com/iamthefij/go-shell-runner v0.1.0 h1:dqiBCMwyD+sTYqDXu5OshDy4NrO3WfVa2jKSQZKFqO4=
|
||||
git.iamthefij.com/iamthefij/go-shell-runner v0.1.0/go.mod h1:Wcke8kBfFj9QDlnRwY/aGSvTRirBc3hC7fKhCsDPbQg=
|
||||
git.iamthefij.com/iamthefij/slog v1.3.0 h1:4Hu5PQvDrW5e3FrTS3q2iIXW0iPvhNY/9qJsqDR3K3I=
|
||||
git.iamthefij.com/iamthefij/slog v1.3.0/go.mod h1:1RUj4hcCompZkAxXCRfUX786tb3cM/Zpkn97dGfUfbg=
|
||||
git.iamthefij.com/iamthefij/tortoise v1.0.1 h1:dtUJuBhMZb9PlBR7bdcxLHLZDxhP2IPtT+YCR7tXdDk=
|
||||
git.iamthefij.com/iamthefij/tortoise v1.0.1/go.mod h1:Y8Sn7jZaMbJw1AWoklp784o3pscfNiy1DkRy60Ne1KQ=
|
||||
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
|
||||
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
||||
@ -46,6 +44,8 @@ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
|
||||
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
|
||||
github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a h1:2MaM6YC3mGu54x+RKAA6JiFFHlHDY1UbkxqppT7wYOg=
|
||||
github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a/go.mod h1:hxSnBBYLK21Vtq/PHd0S2FYCxBXzBua8ov5s1RobyRQ=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
@ -61,7 +61,11 @@ golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
|
||||
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
|
||||
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
|
||||
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
|
238
main.go
238
main.go
@ -9,14 +9,15 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
shellrunner "git.iamthefij.com/iamthefij/go-shell-runner"
|
||||
"git.iamthefij.com/iamthefij/slog"
|
||||
"git.iamthefij.com/iamthefij/tortoise"
|
||||
"github.com/charmbracelet/bubbles/progress"
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/huh"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/charmbracelet/huh"
|
||||
)
|
||||
|
||||
type screen int
|
||||
@ -33,19 +34,12 @@ const (
|
||||
)
|
||||
|
||||
type model struct {
|
||||
// View state
|
||||
form *huh.Form
|
||||
progressBar progress.Model
|
||||
state string
|
||||
intervalNum int
|
||||
currentScreen screen
|
||||
isFocus bool
|
||||
fullscreen bool
|
||||
width int
|
||||
height int
|
||||
|
||||
// Timer state
|
||||
remaining time.Duration
|
||||
currentScreen screen
|
||||
intervals int
|
||||
breakTime time.Duration
|
||||
focusTime time.Duration
|
||||
@ -53,28 +47,15 @@ type model struct {
|
||||
onFocusStart []string
|
||||
onFocusEnd []string
|
||||
onIntervalEnd []string
|
||||
isFocus bool
|
||||
fullscreen bool
|
||||
width int
|
||||
height int
|
||||
err error
|
||||
shellrunner *tortoise.ShellRunner
|
||||
shellrunner *shellrunner.ShellRunner
|
||||
}
|
||||
|
||||
// Message that signals to start the timer
|
||||
type startTimerMsg struct{}
|
||||
|
||||
// Command that triggers start message
|
||||
func startTimer() tea.Msg {
|
||||
return startTimerMsg{}
|
||||
}
|
||||
|
||||
// Message that signals to get values from the form
|
||||
type formSubmitMsg struct{}
|
||||
|
||||
// Command that triggers form submit message
|
||||
func formSubmit() tea.Msg {
|
||||
return formSubmitMsg{}
|
||||
}
|
||||
|
||||
// Create input form with default values if provided
|
||||
func createInputForm(defaultFocusTime, defaultBreakTime, defaultIntervals *string) *huh.Form {
|
||||
func initialModel(fullscreen bool, colorLeft string, colorRight string, defaultFocusTime, defaultBreakTime, defaultIntervals *string) model {
|
||||
// Ceate validation functions for input
|
||||
validateDuration := func(text string) error {
|
||||
_, err := parseDuration(text)
|
||||
@ -89,6 +70,10 @@ func createInputForm(defaultFocusTime, defaultBreakTime, defaultIntervals *strin
|
||||
return nil
|
||||
}
|
||||
|
||||
if colorLeft == "" || colorRight == "" {
|
||||
slog.Panicf("Color flags can't be empty")
|
||||
}
|
||||
|
||||
// Create form fields
|
||||
focusTime := huh.NewInput().
|
||||
Key(FORM_FOCUS).
|
||||
@ -123,19 +108,8 @@ func createInputForm(defaultFocusTime, defaultBreakTime, defaultIntervals *strin
|
||||
intervals = intervals.Value(defaultIntervals)
|
||||
}
|
||||
|
||||
f := huh.NewForm(huh.NewGroup(focusTime, breakTime, intervals)).WithShowErrors(true)
|
||||
f.SubmitCmd = formSubmit
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
func newModelBasic(fullscreen bool, colorLeft, colorRight string) model {
|
||||
if colorLeft == "" || colorRight == "" {
|
||||
slog.Panicf("Color flags can't be empty")
|
||||
}
|
||||
|
||||
return model{
|
||||
form: nil,
|
||||
form: huh.NewForm(huh.NewGroup(focusTime, breakTime, intervals)).WithShowErrors(true),
|
||||
progressBar: progress.New(progress.WithScaledGradient(colorLeft, colorRight)),
|
||||
state: "stopped",
|
||||
intervalNum: 1,
|
||||
@ -143,55 +117,15 @@ func newModelBasic(fullscreen bool, colorLeft, colorRight string) model {
|
||||
currentScreen: INPUT_SCREEN, // Start on input screen
|
||||
isFocus: true,
|
||||
fullscreen: fullscreen,
|
||||
shellrunner: tortoise.NewShellRunner(),
|
||||
shellrunner: shellrunner.NewShellRunner(),
|
||||
}
|
||||
}
|
||||
|
||||
func newModel(fullscreen bool, colorLeft, colorRight string, focusTime, breakTime time.Duration, intervals int, onFocusStart, onFocusEnd, onIntervalEnd []string) model {
|
||||
m := newModelBasic(fullscreen, colorLeft, colorRight)
|
||||
|
||||
if focusTime != 0 && breakTime != 0 && intervals != 0 {
|
||||
// All values provided, initialize timer
|
||||
m.focusTime = focusTime
|
||||
m.breakTime = breakTime
|
||||
m.intervals = intervals
|
||||
m.currentScreen = TIMER_SCREEN
|
||||
} else {
|
||||
// Prompt for input
|
||||
var defaultFocusTime, defaultBreakTime, defaultIntervals *string
|
||||
|
||||
if value := focusTime.String(); value != "0s" {
|
||||
defaultFocusTime = &value
|
||||
}
|
||||
|
||||
if value := breakTime.String(); value != "0s" {
|
||||
defaultBreakTime = &value
|
||||
}
|
||||
|
||||
if intervals != 0 {
|
||||
intervalsString := strconv.Itoa(intervals)
|
||||
defaultIntervals = &intervalsString
|
||||
}
|
||||
|
||||
m.form = createInputForm(defaultFocusTime, defaultBreakTime, defaultIntervals)
|
||||
m.currentScreen = INPUT_SCREEN
|
||||
}
|
||||
|
||||
// Collect command flags
|
||||
m.onFocusStart = onFocusStart
|
||||
m.onFocusEnd = onFocusEnd
|
||||
m.onIntervalEnd = onIntervalEnd
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func (m model) Init() tea.Cmd {
|
||||
// Handle Ctrl+C for graceful exit
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt)
|
||||
|
||||
cmds := []tea.Cmd{tea.WindowSize(), textinput.Blink}
|
||||
|
||||
go func() {
|
||||
<-c
|
||||
|
||||
@ -201,20 +135,10 @@ func (m model) Init() tea.Cmd {
|
||||
os.Exit(0)
|
||||
}()
|
||||
|
||||
if m.form != nil {
|
||||
// Start input form if it exists
|
||||
cmds = append(cmds, m.form.Init())
|
||||
} else {
|
||||
// Start timer if no form
|
||||
cmds = append(cmds, startTimer)
|
||||
}
|
||||
m.form.Init()
|
||||
m.shellrunner.Start()
|
||||
|
||||
// Start shell runner if there are any commands to run
|
||||
if len(m.onFocusStart) > 0 || len(m.onFocusEnd) > 0 || len(m.onIntervalEnd) > 0 {
|
||||
m.shellrunner.Start()
|
||||
}
|
||||
|
||||
return tea.Batch(cmds...)
|
||||
return tea.Batch(tea.WindowSize(), textinput.Blink)
|
||||
}
|
||||
|
||||
// totalTime returns the total time for the current period (focus or break)
|
||||
@ -230,13 +154,52 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
cmds := []tea.Cmd{}
|
||||
|
||||
// Handle input screen
|
||||
if m.currentScreen == INPUT_SCREEN && m.form != nil {
|
||||
if m.currentScreen == INPUT_SCREEN {
|
||||
form, cmd := m.form.Update(msg)
|
||||
if f, ok := form.(*huh.Form); ok {
|
||||
m.form = f
|
||||
}
|
||||
|
||||
cmds = append(cmds, cmd)
|
||||
|
||||
if m.form.State == huh.StateCompleted {
|
||||
// Kick off the timer
|
||||
focusTime, err := parseDuration(m.form.GetString(FORM_FOCUS))
|
||||
if err != nil {
|
||||
m.err = fmt.Errorf("error parsing focus time duration: %w", err)
|
||||
slog.Fatalf("Error parsing focus time: %v", err)
|
||||
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
breakTime, err := parseDuration(m.form.GetString(FORM_BREAK))
|
||||
if err != nil {
|
||||
m.err = fmt.Errorf("error parsing break time duration: %w", err)
|
||||
slog.Fatalf("Error parsing break time: %v", err)
|
||||
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
m.intervals, err = strconv.Atoi(m.form.GetString(FORM_INTERVALS))
|
||||
if err != nil {
|
||||
m.err = fmt.Errorf("error parsing interval: %w", err)
|
||||
slog.Fatalf("Error parsing interval: %v", err)
|
||||
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
m.focusTime = focusTime
|
||||
m.breakTime = breakTime
|
||||
m.remaining = focusTime
|
||||
m.state = "Focus"
|
||||
m.currentScreen = TIMER_SCREEN
|
||||
m.startTime = time.Now()
|
||||
|
||||
// Run onFocusStart commands
|
||||
m.startCommands(m.onFocusStart)
|
||||
|
||||
return m, tick()
|
||||
}
|
||||
}
|
||||
|
||||
// Handle any uncaptured input screen updates
|
||||
@ -254,52 +217,9 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
}
|
||||
}
|
||||
|
||||
case formSubmitMsg:
|
||||
// Get values from the form and send start timer command
|
||||
var err error
|
||||
|
||||
m.focusTime, err = parseDuration(m.form.GetString(FORM_FOCUS))
|
||||
if err != nil {
|
||||
m.err = fmt.Errorf("error parsing focus time duration: %w", err)
|
||||
slog.Fatalf("Error parsing focus time: %v", err)
|
||||
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
m.breakTime, err = parseDuration(m.form.GetString(FORM_BREAK))
|
||||
if err != nil {
|
||||
m.err = fmt.Errorf("error parsing break time duration: %w", err)
|
||||
slog.Fatalf("Error parsing break time: %v", err)
|
||||
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
m.intervals, err = strconv.Atoi(m.form.GetString(FORM_INTERVALS))
|
||||
if err != nil {
|
||||
m.err = fmt.Errorf("error parsing interval: %w", err)
|
||||
slog.Fatalf("Error parsing interval: %v", err)
|
||||
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
return m, startTimer
|
||||
|
||||
case startTimerMsg:
|
||||
// Start the timer
|
||||
m.currentScreen = TIMER_SCREEN
|
||||
// TODO: Could maybe set startTime to 0 and then send a tick command to start the timer
|
||||
// since much of this is duplicate of below
|
||||
m.startTime = time.Now()
|
||||
m.remaining = m.focusTime
|
||||
m.state = "Focus"
|
||||
m.startCommands(m.onFocusStart)
|
||||
|
||||
cmds = append(cmds, tea.SetWindowTitle(fmt.Sprintf("Gomodoro - %s", m.state)), tick())
|
||||
|
||||
case timeMsg:
|
||||
// Handle timer update for each second
|
||||
m.remaining = m.totalTime() - time.Since(m.startTime)
|
||||
// Check if we've reached a new period
|
||||
if m.remaining < 0 {
|
||||
if m.isFocus {
|
||||
// Focus period ends, switch to break
|
||||
@ -327,17 +247,16 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.startCommands(m.onFocusStart)
|
||||
}
|
||||
|
||||
cmds = append(cmds, tea.SetWindowTitle(fmt.Sprintf("Gomodoro - %s", m.state)))
|
||||
return m, tick()
|
||||
}
|
||||
|
||||
cmds = append(cmds, tick())
|
||||
return m, tick()
|
||||
|
||||
case tea.WindowSizeMsg:
|
||||
m.width = msg.Width
|
||||
m.height = msg.Height
|
||||
}
|
||||
|
||||
// Get errors from shellrunner
|
||||
for {
|
||||
result := m.shellrunner.GetResults()
|
||||
if result == nil {
|
||||
@ -385,10 +304,6 @@ func (m model) View() string {
|
||||
|
||||
// View for input screen
|
||||
func (m model) inputScreenView() string {
|
||||
if m.form == nil {
|
||||
return "Loading..."
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
|
||||
builder.WriteString("Enter your Pomodoro settings:\n\n")
|
||||
@ -500,17 +415,34 @@ func main() {
|
||||
return nil
|
||||
}
|
||||
|
||||
m := newModel(
|
||||
// Set focus, break, and interval values if provided
|
||||
var defaultFocusTime, defaultBreakTime, defaultIntervals *string
|
||||
|
||||
if focusTime := c.Duration("focus").String(); focusTime != "0s" {
|
||||
defaultFocusTime = &focusTime
|
||||
}
|
||||
if breakTime := c.Duration("break").String(); breakTime != "0s" {
|
||||
defaultBreakTime = &breakTime
|
||||
}
|
||||
if intervals := c.Int("intervals"); intervals != 0 {
|
||||
intervalsString := strconv.Itoa(intervals)
|
||||
defaultIntervals = &intervalsString
|
||||
}
|
||||
|
||||
m := initialModel(
|
||||
c.Bool("fullscreen"),
|
||||
c.String("color-left"),
|
||||
c.String("color-right"),
|
||||
c.Duration("focus"),
|
||||
c.Duration("break"),
|
||||
c.Int("intervals"),
|
||||
c.StringSlice("on-focus-start"),
|
||||
c.StringSlice("on-focus-end"),
|
||||
c.StringSlice("on-interval-end"),
|
||||
defaultFocusTime,
|
||||
defaultBreakTime,
|
||||
defaultIntervals,
|
||||
)
|
||||
|
||||
// Collect command flags
|
||||
m.onFocusStart = c.StringSlice("on-focus-start")
|
||||
m.onFocusEnd = c.StringSlice("on-focus-end")
|
||||
m.onIntervalEnd = c.StringSlice("on-interval-end")
|
||||
|
||||
// Start tea program
|
||||
|
||||
options := []tea.ProgramOption{}
|
||||
|
266
main_test.go
266
main_test.go
@ -1,20 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
func notThis[T comparable](f compareFunc[T]) compareFunc[T] {
|
||||
return func(a, b T) bool {
|
||||
return !f(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
type compareFunc[T comparable] func(T, T) bool
|
||||
|
||||
func assertFunc[T comparable](t *testing.T, compare compareFunc[T], actual, expected T, msg string) {
|
||||
@ -43,171 +35,6 @@ func assertNotEqual(t *testing.T, actual, expected interface{}, msg string) {
|
||||
}
|
||||
}
|
||||
|
||||
// keyMsgs converts a series of strings or KeyTypes into a slice of KeyMsgs
|
||||
func keyMsgs(keys ...interface{}) []tea.KeyMsg {
|
||||
keyMessages := []tea.KeyMsg{}
|
||||
|
||||
for _, key := range keys {
|
||||
switch keyType := key.(type) {
|
||||
case tea.KeyType:
|
||||
keyMessages = append(keyMessages, tea.KeyMsg{Type: keyType})
|
||||
case string:
|
||||
for _, r := range key.(string) {
|
||||
keyMessages = append(keyMessages, tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
|
||||
}
|
||||
default:
|
||||
panic(fmt.Sprintf("Unknown key type: %v", key))
|
||||
}
|
||||
}
|
||||
|
||||
return keyMessages
|
||||
}
|
||||
|
||||
func sendKeys[T tea.Model](m T, keys ...interface{}) (T, []tea.Cmd) {
|
||||
var updatedModel tea.Model
|
||||
|
||||
var cmd tea.Cmd
|
||||
|
||||
var cmds []tea.Cmd
|
||||
|
||||
for _, key := range keyMsgs(keys...) {
|
||||
updatedModel, cmd = m.Update(key)
|
||||
m = updatedModel.(T)
|
||||
|
||||
if cmd != nil {
|
||||
m, cmds, _ = batchCmdUpdate(m, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
return m, cmds
|
||||
}
|
||||
|
||||
func batchCmdUpdate[T tea.Model](m T, cmd tea.Cmd) (T, []tea.Cmd, error) {
|
||||
var updatedModel tea.Model
|
||||
|
||||
var resultCmd tea.Cmd
|
||||
|
||||
var cmds []tea.Cmd
|
||||
|
||||
resultMsg := cmd()
|
||||
|
||||
batchMsg, ok := resultMsg.(tea.BatchMsg)
|
||||
if !ok {
|
||||
updatedModel, resultCmd = m.Update(resultMsg)
|
||||
m = updatedModel.(T)
|
||||
|
||||
cmds = append(cmds, resultCmd)
|
||||
|
||||
return m, cmds, fmt.Errorf("Expected a batch message, got %v", resultMsg)
|
||||
}
|
||||
|
||||
// Apply batch messages
|
||||
for _, cmd := range batchMsg {
|
||||
updatedModel, resultCmd = m.Update(cmd())
|
||||
m = updatedModel.(T)
|
||||
|
||||
cmds = append(cmds, resultCmd)
|
||||
}
|
||||
|
||||
return m, cmds, nil
|
||||
}
|
||||
|
||||
type mockModel struct {
|
||||
messages []tea.Msg
|
||||
}
|
||||
|
||||
func (m mockModel) Init() tea.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m mockModel) View() string {
|
||||
s := ""
|
||||
|
||||
for _, msg := range m.messages {
|
||||
if keyMsg, ok := msg.(tea.KeyMsg); ok {
|
||||
if keyMsg.Type == tea.KeyRunes {
|
||||
s += string(keyMsg.Runes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (m mockModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
var cmds []tea.Cmd
|
||||
|
||||
m.messages = append(m.messages, msg)
|
||||
|
||||
if msg, ok := msg.(tea.KeyMsg); ok {
|
||||
if msg.Type == tea.KeyEnter {
|
||||
cmds = append(cmds, func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'\n'}} })
|
||||
}
|
||||
}
|
||||
|
||||
return m, tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
func TestBatchCmdUpdate(t *testing.T) {
|
||||
m := mockModel{}
|
||||
|
||||
cmds := []tea.Cmd{
|
||||
func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'a'}} },
|
||||
func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'b'}} },
|
||||
}
|
||||
|
||||
m, _, err := batchCmdUpdate(m, tea.Batch(cmds...))
|
||||
if err != nil {
|
||||
t.Fatalf("Expected no error, got %v", err)
|
||||
}
|
||||
|
||||
if len(m.messages) != 2 {
|
||||
t.Fatalf("Expected 2 messages, got %v", len(m.messages))
|
||||
}
|
||||
|
||||
if m.View() != "ab" {
|
||||
t.Fatalf("Expected 'ab', got %s, %+v", m.View(), m)
|
||||
}
|
||||
|
||||
m, _, err = batchCmdUpdate(m, func() tea.Msg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'c'}} })
|
||||
if err == nil {
|
||||
t.Fatalf("Expected error, got nil")
|
||||
}
|
||||
|
||||
if len(m.messages) != 3 {
|
||||
t.Fatalf("Expected 3 messages, got %v", len(m.messages))
|
||||
}
|
||||
|
||||
if m.View() != "abc" {
|
||||
t.Fatalf("Expected 'abc', got %v", m.View())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendKeys(t *testing.T) {
|
||||
m := mockModel{}
|
||||
|
||||
m, _ = sendKeys(m, "ab")
|
||||
|
||||
if len(m.messages) != 2 {
|
||||
t.Fatalf("Expected 2 messages, got %v", len(m.messages))
|
||||
}
|
||||
|
||||
if m.View() != "ab" {
|
||||
t.Fatalf("Expected 'ab', got %s", m.View())
|
||||
}
|
||||
|
||||
m, _ = sendKeys(m, "c", tea.KeyEnter)
|
||||
|
||||
// We expect 5 because enter key should create a new message for the newline
|
||||
if len(m.messages) != 5 {
|
||||
t.Fatalf("Expected 5 messages, got %v", len(m.messages))
|
||||
}
|
||||
|
||||
if m.View() != "abc\n" {
|
||||
t.Fatalf("Expected 'abc\n', got %s", m.View())
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseDuration tests the parseDuration function
|
||||
func TestParseDuration(t *testing.T) {
|
||||
tests := []struct {
|
||||
@ -233,76 +60,83 @@ func TestParseDuration(t *testing.T) {
|
||||
|
||||
// TestRunCommands tests the runCommands function
|
||||
func TestRunCommands(t *testing.T) {
|
||||
m := newModelBasic(false, "#ffdd57", "#57ddff")
|
||||
m.onFocusStart = []string{"echo Focus Start"}
|
||||
|
||||
m := initialModel(false, "#ffdd57", "#57ddff", nil, nil, nil)
|
||||
m.Init()
|
||||
m.startCommands(m.onFocusStart)
|
||||
|
||||
m.startCommands([]string{"echo Hello, World!"})
|
||||
|
||||
m.shellrunner.Stop()
|
||||
}
|
||||
|
||||
func sendKeys(m model, keys ...tea.KeyType) (model, tea.Cmd) {
|
||||
var updatedModel tea.Model
|
||||
|
||||
var cmd tea.Cmd
|
||||
|
||||
for _, key := range keys {
|
||||
updatedModel, cmd = m.Update(tea.KeyMsg{Type: key})
|
||||
m = updatedModel.(model)
|
||||
m.form.UpdateFieldPositions()
|
||||
}
|
||||
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// TestInputView tests the Update method of the model for the input view
|
||||
func TestInputView(t *testing.T) {
|
||||
m := newModel(false, "#ffdd57", "#57ddff", 0, 0, 0, []string{}, []string{}, []string{})
|
||||
focusInput := "10m"
|
||||
breakInput := "5m"
|
||||
intervalInput := "1"
|
||||
|
||||
var err error
|
||||
m := initialModel(false, "#ffdd57", "#57ddff", &focusInput, &breakInput, &intervalInput)
|
||||
m.View()
|
||||
|
||||
m, _, err = batchCmdUpdate(m, m.Init())
|
||||
if err != nil {
|
||||
t.Fatalf("Expected batch command after init: %v", err)
|
||||
}
|
||||
assertEqual(t, m.currentScreen, INPUT_SCREEN, "Expected currentScreen to be inputScreen")
|
||||
|
||||
// Verify we're on the input screen
|
||||
assertEqual(t, m.currentScreen, INPUT_SCREEN, "Expected currentScreen to be INPUT_SCREEN")
|
||||
assertFunc(t, strings.Contains, m.View(), "Break time", "Expected view to contain 'Break time'")
|
||||
var resultCmd tea.Cmd
|
||||
m, resultCmd = sendKeys(m, tea.KeyTab, tea.KeyTab, tea.KeyTab, tea.KeyEnter)
|
||||
assertNotEqual(t, resultCmd, nil, "Expected resultCmd to be not nil")
|
||||
|
||||
// Fill the form
|
||||
m, _ = sendKeys(m, "10m", tea.KeyEnter, "10m", tea.KeyEnter, "2", tea.KeyEnter)
|
||||
/*
|
||||
* assertEqual(t, m.form.State, huh.StateCompleted, fmt.Sprintf("Expected form state to be completed: %s", m.form.View()))
|
||||
* assertEqual(t, m.currentScreen, TIMER_SCREEN, "Expected currentScreen to be timerScreen")
|
||||
* assertEqual(t, m.remaining.Round(time.Second), 10*time.Minute, "Expected remaining to be 10 minutes")
|
||||
*/
|
||||
|
||||
// Pass on submit command, doesn't happen because we have multiple layers of batching at the end
|
||||
m, _, _ = batchCmdUpdate(m, formSubmit)
|
||||
|
||||
assertEqual(t, m.focusTime, 10*time.Minute, "Expected focus time to be 10 minutes")
|
||||
assertEqual(t, m.breakTime, 10*time.Minute, "Expected break time to be 10 minutes")
|
||||
assertEqual(t, m.intervals, 2, "Expected rounds to be 2")
|
||||
|
||||
// Pass on start command, doesn't happen because we have multiple layers of batching at the end
|
||||
m, _, _ = batchCmdUpdate(m, startTimer)
|
||||
|
||||
assertFunc(t, notThis(strings.Contains), m.View(), "Break time", "Expected view to NOT contain 'Break time'")
|
||||
assertEqual(t, m.currentScreen, TIMER_SCREEN, "Expected currentScreen to be TIMER_SCREEN")
|
||||
assertEqual(t, m.err, nil, "Expected no error")
|
||||
}
|
||||
|
||||
func TestTimerView(t *testing.T) {
|
||||
m := newModel(false, "#ffdd57", "#57ddff", 10*time.Minute, 10*time.Minute, 2, []string{}, []string{}, []string{})
|
||||
m := initialModel(false, "#ffdd57", "#57ddff", nil, nil, nil)
|
||||
m.View()
|
||||
|
||||
// Init model with timer values
|
||||
m, _, err := batchCmdUpdate(m, m.Init())
|
||||
if err != nil {
|
||||
t.Fatalf("Expected batch command after init: %v", err)
|
||||
}
|
||||
|
||||
// Start timer (batch result from above doesn't apply here)
|
||||
m, _, _ = batchCmdUpdate(m, startTimer)
|
||||
m.focusTime = 10 * time.Minute
|
||||
m.breakTime = 10 * time.Minute
|
||||
m.intervals = 2
|
||||
m.state = "Focus"
|
||||
m.currentScreen = TIMER_SCREEN
|
||||
m.startTime = time.Now()
|
||||
|
||||
// Test timer view
|
||||
assertEqual(t, m.currentScreen, TIMER_SCREEN, "Expected currentScreen to be timerScreen")
|
||||
assertFunc(t, strings.Contains, m.View(), "Focus", "Expected view to contain 'Focus'")
|
||||
assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'")
|
||||
m.View()
|
||||
|
||||
oneSecCmd := func() tea.Msg { return timeMsg(time.Now().Add(1 * time.Second)) }
|
||||
m, _, _ = batchCmdUpdate(m, oneSecCmd)
|
||||
oneSec := timeMsg(time.Now().Add(1 * time.Second))
|
||||
updatedModel, _ := m.Update(oneSec)
|
||||
m = updatedModel.(model)
|
||||
|
||||
assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'")
|
||||
|
||||
// Test switch to break time
|
||||
m.startTime = m.startTime.Add(-10 * time.Minute)
|
||||
m, _, _ = batchCmdUpdate(m, oneSecCmd)
|
||||
updatedModel, _ = m.Update(oneSec)
|
||||
m = updatedModel.(model)
|
||||
|
||||
assertEqual(t, m.state, "Break", "Expected state to be 'Break'")
|
||||
|
||||
// Switch back to focus time
|
||||
m.startTime = m.startTime.Add(-10 * time.Minute)
|
||||
m, _, _ = batchCmdUpdate(m, oneSecCmd)
|
||||
updatedModel, _ = m.Update(oneSec)
|
||||
m = updatedModel.(model)
|
||||
|
||||
assertEqual(t, m.state, "Focus", "Expected state to be 'Focus'")
|
||||
t.Logf("Incorrect state %+v", m)
|
||||
|
Loading…
Reference in New Issue
Block a user