-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
326 lines (296 loc) · 8.72 KB
/
handlers.go
File metadata and controls
326 lines (296 loc) · 8.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package main
import (
"fmt"
"log"
"strconv"
"time"
"charm.land/bubbles/v2/progress"
tea "charm.land/bubbletea/v2"
"tiny-timer/status"
)
// Top level event handler that is called each time the screen is updated
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyPressMsg:
return updateKey(m, msg)
case tea.WindowSizeMsg:
return updateWindowSize(m, msg)
case tickMsg:
return updatePercent(m)
case promptMsg:
return handlePromptInput(m, msg)
// FrameMsg is sent when the progress bar wants to animate itself
case progress.FrameMsg:
progressModel, cmd := m.progress.Update(msg)
m.progress = progressModel
return m, cmd
case status.InfoMsg, status.ClearStatusMsg:
// Handle status component updates
statusModel, cmd := m.status.Update(msg)
m.status = statusModel
return m, cmd
default:
return m, nil
}
}
func updatePercent(m model) (tea.Model, tea.Cmd) {
elapsed := time.Now().Unix() - m.startTime
if m.countUpMode {
// In count-up mode, just update the progress bar to show elapsed time
percentCompleted := float64(elapsed) / float64(m.targetDuration)
if percentCompleted > 1.0 {
percentCompleted = 1.0
}
cmd := m.progress.SetPercent(percentCompleted)
return m, tea.Batch(tickCmd(), cmd)
}
// Calculate completion for further evaluation
//
// For count down mode (default), fill progress bar
// and work backwards as time elapses
percentCompleted := float64(m.targetDuration-elapsed) / float64(m.targetDuration)
// Check for completion based on actual elapsed time
if percentCompleted <= 0.0 {
// Ensure progress is set to 0% for final display
m.progress.SetPercent(0.0)
if err := sendNotification("tiny-timer", "Timer has finished"); err != nil {
fmt.Println("Error sending notification:", err)
}
// Activate prompt for title instead of quitting immediately
m.promptActive = true
m.promptType = promptLogAndReset
m.inputBuffer = m.title
return m, nil
}
// Activate normal progress bar update
cmd := m.progress.SetPercent(percentCompleted)
return m, tea.Batch(tickCmd(), cmd)
}
func updateWindowSize(m model, msg tea.WindowSizeMsg) (tea.Model, tea.Cmd) {
width := msg.Width - padding*2 - 4
if width > maxWidth {
width = maxWidth
}
m.progress.SetWidth(width)
m.help.SetWidth(msg.Width)
// Update status component with window size
s, cmd := m.status.Update(msg)
m.status = s
return m, cmd
}
func handlePromptInput(m model, msg promptMsg) (tea.Model, tea.Cmd) {
m.promptActive = false
var cmds []tea.Cmd
switch m.promptType {
case promptLogAndReset:
// Log session to DB and start new session
elapsed := time.Now().Unix() - m.startTime
log.Printf("handlePromptInput: Saving session, elapsed=%d, title=%q", elapsed, msg.title)
if err := saveSessionToDB(elapsed, true, msg.title); err != nil {
log.Printf("handlePromptInput: Error saving session: %v", err)
// Show error status
cmds = append(cmds, func() tea.Msg {
return status.InfoMsg{
Type: status.InfoTypeError,
Msg: fmt.Sprintf("Failed to save session: %v", err),
}
})
} else {
// Show success status
cmds = append(cmds, func() tea.Msg {
return status.InfoMsg{
Type: status.InfoTypeSuccess,
Msg: fmt.Sprintf("Saved: %s (%d:%02d)", msg.title, elapsed/60, elapsed%60),
}
})
}
// Refresh history table if we are logging
log.Printf("handlePromptInput: Building table view after save")
if t, err := buildTableView(10); err == nil {
m.table = t
log.Printf("handlePromptInput: Table view built with %d rows", len(t.Rows()))
} else {
log.Printf("handlePromptInput: Error building table view: %v", err)
}
// Reset timer for new session
m.startTime = time.Now().Unix()
cmd := m.progress.SetPercent(0)
m.title = ""
cmds = append(cmds, tickCmd(), cmd)
return m, tea.Batch(cmds...)
case promptEditTitle:
// Just update title without logging
m.title = msg.title
return m, tickCmd()
case promptSetDuration:
// Set duration in minutes
var minutes int64
if n, err := strconv.ParseInt(msg.title, 10, 64); err == nil && n > 0 {
minutes = n
} else {
// Invalid input, keep current duration
return m, tickCmd()
}
m.targetDuration = minutes * 60
// Reset timer with new duration
m.startTime = time.Now().Unix()
cmd := m.progress.SetPercent(0)
return m, tea.Batch(tickCmd(), cmd)
}
return m, tickCmd()
}
// handlePromptKeyInput handles key input when prompt is active
func handlePromptKeyInput(m model, msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "enter":
return handlePromptInput(m, promptMsg{title: m.inputBuffer, logDB: m.promptType == promptLogAndReset})
case "esc":
m.promptActive = false
return m, nil
case "backspace":
if len(m.inputBuffer) > 0 {
m.inputBuffer = m.inputBuffer[:len(m.inputBuffer)-1]
}
return m, nil
case "space":
// Only allow space for title prompts, not duration
if m.promptType != promptSetDuration {
m.inputBuffer += " "
}
return m, nil
default:
if len(msg.Text) > 0 {
for _, r := range msg.Text {
// For duration prompts, only allow numeric characters
if m.promptType == promptSetDuration {
if r >= '0' && r <= '9' {
m.inputBuffer += string(r)
}
} else {
m.inputBuffer += string(r)
}
}
}
return m, nil
}
}
// handleTableViewKey handles key input when in table view mode
func handleTableViewKey(m model, _ tea.KeyPressMsg) (tea.Model, tea.Cmd) {
// Any key exits table view
m.mode = timerView
return m, nil
}
// handleCountUpModeKey handles key input in count-up mode
func handleCountUpModeKey(m model, msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
key := msg.String()
switch key {
case "d":
// Mark task as done: prompt for title, log to DB, and start new session
m.promptActive = true
m.promptType = promptLogAndReset
m.inputBuffer = m.title
return m, nil
case "h":
// Show history (table view)
log.Printf("handleCountUpModeKey: 'h' pressed, fetching history")
t, err := buildTableView(10)
if err != nil {
log.Printf("handleCountUpModeKey: Error fetching sessions: %v", err)
fmt.Println("Error fetching sessions:", err)
return m, nil
}
log.Printf("handleCountUpModeKey: History fetched, %d rows", len(t.Rows()))
m.table = t
m.mode = tableView
return m, nil
case "t":
// Edit current task title
m.promptActive = true
m.promptType = promptEditTitle
m.inputBuffer = m.title
return m, nil
case "m":
// Set target duration in minutes
m.promptActive = true
m.promptType = promptSetDuration
// Pre-fill with current duration in minutes
currentMinutes := m.targetDuration / 60
m.inputBuffer = strconv.FormatInt(currentMinutes, 10)
return m, nil
case "r":
// Reset timer in count-up mode
m.startTime = time.Now().Unix()
cmd := m.progress.SetPercent(0)
return m, tea.Batch(tickCmd(), cmd)
default:
// Quit on other keys
return m, tea.Quit
}
}
// handleTimerModeKey handles key input in timer mode (non count-up)
func handleTimerModeKey(m model, msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
key := msg.String()
switch key {
case "d":
// Mark task as done: prompt for title, log to DB, and reset timer
m.promptActive = true
m.promptType = promptLogAndReset
m.inputBuffer = m.title
return m, nil
case "h":
// Show history (table view)
log.Printf("handleCountUpModeKey: 'h' pressed, fetching history")
t, err := buildTableView(10)
if err != nil {
log.Printf("handleCountUpModeKey: Error fetching sessions: %v", err)
fmt.Println("Error fetching sessions:", err)
return m, nil
}
log.Printf("handleCountUpModeKey: History fetched, %d rows", len(t.Rows()))
m.table = t
m.mode = tableView
return m, nil
case "t":
// Edit current task title
m.promptActive = true
m.promptType = promptEditTitle
m.inputBuffer = m.title
return m, nil
case "m":
// Set target duration in minutes
m.promptActive = true
m.promptType = promptSetDuration
// Pre-fill with current duration in minutes
currentMinutes := m.targetDuration / 60
m.inputBuffer = strconv.FormatInt(currentMinutes, 10)
return m, nil
case "r":
// Reset timer
m.startTime = time.Now().Unix()
cmd := m.progress.SetPercent(0)
return m, tea.Batch(tickCmd(), cmd)
default:
// Quit if any other key is pressed
return m, tea.Quit
}
}
func updateKey(m model, msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
// Handle Ctrl-Z to suspend in all modes
if msg.String() == "ctrl+z" {
return m, tea.Suspend
}
// Handle prompt input mode
if m.promptActive {
return handlePromptKeyInput(m, msg)
}
// Handle table view mode
if m.mode == tableView {
return handleTableViewKey(m, msg)
}
// Handle count-up mode keys
if m.countUpMode {
return handleCountUpModeKey(m, msg)
}
// Handle timer view mode (non count-up)
return handleTimerModeKey(m, msg)
}