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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
|
package tui
import (
"fmt"
"strings"
"time"
timesamurai "codeberg.org/snonux/timesamurai/internal"
"codeberg.org/snonux/timesamurai/internal/config"
"codeberg.org/snonux/timesamurai/internal/worktime"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
type tab int
const (
tabEntries tab = iota
tabReport
tabTimer
tabCount
)
var tabLabels = []string{"Entries", "Report", "Timer"}
type rootTimerTickMsg struct{}
func rootTimerTick() tea.Cmd {
return tea.Tick(time.Second, func(time.Time) tea.Msg {
return rootTimerTickMsg{}
})
}
// Model is the root TUI scaffold model.
type Model struct {
activeTab tab
width int
height int
showHelp bool
confirmQuit bool
pendingG bool
pendingZ bool
styles Styles
theme Theme
disco bool
entries EntriesModel
report ReportModel
timer TimerModel
entriesErr string
reportErr string
timerTickScheduled bool
}
// NewModel creates a new root TUI model.
func NewModel() *Model {
model, _ := NewModelWithConfig(config.Default())
return model
}
// NewModelWithConfig creates a data-backed root model from config.
func NewModelWithConfig(cfg config.Config) (*Model, error) {
return NewModelWithConfigAndDisco(cfg, false)
}
// NewModelWithConfigAndDisco creates a data-backed root model and optionally enables disco mode.
func NewModelWithConfigAndDisco(cfg config.Config, disco bool) (*Model, error) {
theme := DefaultTheme()
model := &Model{
activeTab: tabEntries,
styles: StylesFromTheme(theme),
theme: theme,
disco: disco,
entries: NewEntriesModel(nil),
report: NewReportModel(nil),
}
entries, err := worktime.LoadAll(cfg.WorktimeDBDir)
if err != nil {
model.entriesErr = err.Error()
} else {
host, hostErr := cfg.EffectiveHostname()
if hostErr != nil {
host = strings.TrimSpace(cfg.Hostname)
}
model.entries.SetEntries(entries)
model.entries.SetPersistence(cfg.WorktimeDBDir, host)
weeks, reportErr := worktime.BuildReport(entries, cfg)
if reportErr != nil {
model.reportErr = reportErr.Error()
} else {
model.report.SetWeeks(weeks)
}
if warning := reportOpenSessionWarning(entries); warning != "" {
model.report.SetWarning(warning)
}
}
timerModel, timerErr := NewTimerModel("doom", cfg)
if timerErr != nil {
model.timer = newFallbackTimerModel("timer init error: " + timerErr.Error())
} else {
model.timer = timerModel
}
if model.disco {
model.randomizeTheme()
}
return model, nil
}
// Init implements tea.Model.
func (m *Model) Init() tea.Cmd {
return m.startRootTimerTicker()
}
// Update implements tea.Model.
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case rootTimerTickMsg:
m.timerTickScheduled = false
return m, m.startRootTimerTicker()
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
bodyWidth, bodyHeight := m.bodySize()
m.entries.SetSize(bodyWidth, bodyHeight)
m.report.SetSize(bodyWidth, bodyHeight)
m.timer.SetSize(bodyWidth, bodyHeight)
return m, nil
case tea.KeyMsg:
key := msg.String()
if m.confirmQuit {
switch key {
case "s":
if err := m.entries.savePendingChanges(); err != nil {
m.entries.setStatusError("Save failed: " + err.Error())
m.confirmQuit = false
return m, nil
}
m.confirmQuit = false
return m, tea.Quit
case "d", "n":
m.confirmQuit = false
return m, tea.Quit
case "esc":
m.confirmQuit = false
return m, nil
default:
return m, nil
}
}
if m.pendingZ {
m.pendingZ = false
if key == "Q" {
return m.requestQuit()
}
}
if m.pendingG {
m.pendingG = false
switch key {
case "t":
return m, m.nextTab()
case "T":
return m, m.prevTab()
}
}
switch key {
case "tab":
return m, m.nextTab()
case "1":
return m, m.switchTab(tabEntries)
case "2":
return m, m.switchTab(tabReport)
case "3":
return m, m.switchTab(tabTimer)
case "?", "H":
m.showHelp = !m.showHelp
return m, nil
case "esc":
if m.showHelp {
m.showHelp = false
return m, nil
}
case "c":
m.randomizeTheme()
return m, nil
case "C":
m.resetTheme()
return m, nil
case "x":
m.disco = !m.disco
if m.disco {
m.randomizeTheme()
}
return m, nil
case "g":
m.pendingG = true
return m, nil
case "Z":
m.pendingZ = true
return m, nil
case "q", "ctrl+c":
return m.requestQuit()
}
}
return m.updateActiveTab(msg)
}
// View implements tea.Model.
func (m *Model) View() string {
header := m.renderTabs()
body := m.renderBody()
status := m.renderStatusLine()
if m.confirmQuit {
body = m.styles.Help.Render(strings.Join([]string{
"Unsaved entry changes detected.",
"",
"Save before quitting?",
"",
"s : save and quit",
"d : discard changes and quit",
"Esc : cancel",
}, "\n"))
}
if !m.confirmQuit && m.showHelp {
body = m.styles.Help.Render(strings.Join([]string{
"Global keys",
"",
"Tab / gt / gT / 1 / 2 / 3 : switch tabs",
"? / H : toggle help",
"c / C : random/reset theme",
"x : toggle disco mode",
"q / ZQ : quit",
"",
"Entries",
"",
"j/k rows, h/l columns, Enter edit selected cell",
"/ search, f category filter, e/v quick edit, s save, dd delete entry",
"D day-off datepicker (8h off entry)",
}, "\n"))
}
content := lipgloss.JoinVertical(lipgloss.Left, header, body, status)
rendered := m.styles.App.Render(content)
if m.width > 0 && m.height > 0 {
return lipgloss.Place(m.width, m.height, lipgloss.Left, lipgloss.Top, rendered)
}
return rendered
}
func (m *Model) nextTab() tea.Cmd {
return m.switchTab((m.activeTab + 1) % tabCount)
}
func (m *Model) prevTab() tea.Cmd {
next := m.activeTab - 1
if next < 0 {
next = tabCount - 1
}
return m.switchTab(next)
}
func (m *Model) renderTabs() string {
parts := make([]string, 0, len(tabLabels))
parts = append(parts, lipgloss.NewStyle().Bold(true).Render("timesamurai "+timesamurai.Version))
for idx, label := range tabLabels {
if tab(idx) == m.activeTab {
parts = append(parts, m.styles.ActiveTab.Render(label))
continue
}
parts = append(parts, m.styles.Tab.Render(label))
}
if m.disco {
parts = append(parts, m.styles.ActiveTab.Render("DISCO"))
}
if m.entries.hasUnsavedChanges() {
parts = append(parts, m.styles.ActiveTab.Render("UNSAVED"))
}
line := strings.Join(parts, " ")
return m.styles.Header.Width(m.statusWidth()).Render(line)
}
func (m *Model) renderBody() string {
switch m.activeTab {
case tabEntries:
if m.entriesErr != "" {
return m.styles.Body.Render("Entries\n\nFailed to load entries: " + m.entriesErr)
}
return m.entries.View(m.styles)
case tabReport:
if m.entriesErr != "" {
return m.styles.Body.Render("Report\n\nUnavailable because entries failed to load: " + m.entriesErr)
}
if m.reportErr != "" {
return m.styles.Body.Render("Report\n\nFailed to build report: " + m.reportErr)
}
return m.report.View(m.styles)
case tabTimer:
return m.timer.View()
default:
return ""
}
}
func newFallbackTimerModel(status string) TimerModel {
return TimerModel{
helpStyle: lipgloss.NewStyle().Faint(true),
timerStyle: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#00BFFF")),
statusStyle: lipgloss.NewStyle().Italic(true),
font: "doom",
work: workIntegration{
status: status,
},
}
}
func (m *Model) switchTab(next tab) tea.Cmd {
m.activeTab = next
return m.startRootTimerTicker()
}
func (m *Model) bodySize() (width int, height int) {
width = m.width - 4
height = m.height - 6
if width < 20 {
width = m.width
}
if height < 6 {
height = m.height
}
if width < 1 {
width = 1
}
if height < 1 {
height = 1
}
return width, height
}
func (m *Model) updateActiveTab(msg tea.Msg) (tea.Model, tea.Cmd) {
switch m.activeTab {
case tabEntries:
beforeMutations := m.entries.mutationCount
updated, cmd := m.entries.Update(msg)
m.entries = updated
if m.disco && m.entries.mutationCount != beforeMutations {
m.randomizeTheme()
}
return m, cmd
case tabReport:
updated, cmd := m.report.Update(msg)
m.report = updated
return m, cmd
case tabTimer:
updatedModel, _ := m.timer.Update(msg)
if updated, ok := updatedModel.(TimerModel); ok {
m.timer = updated
}
return m, m.startRootTimerTicker()
default:
return m, nil
}
}
func (m *Model) startRootTimerTicker() tea.Cmd {
if m.activeTab != tabTimer || !m.timer.state.Running {
return nil
}
if m.timerTickScheduled {
return nil
}
m.timerTickScheduled = true
return rootTimerTick()
}
func (m *Model) randomizeTheme() {
m.theme = RandomTheme()
m.styles = StylesFromTheme(m.theme)
}
func (m *Model) resetTheme() {
m.theme = DefaultTheme()
m.styles = StylesFromTheme(m.theme)
}
func (m *Model) renderStatusLine() string {
status := fmt.Sprintf(
"Entries timeline table | unsaved:%t | disco:%t | H help | c/C theme | x disco | q quit",
m.entries.hasUnsavedChanges(),
m.disco,
)
if m.showHelp {
status = "Help mode active (press H or ? to close)"
}
if m.confirmQuit {
status = "Unsaved changes: s save+quit, d discard+quit, Esc cancel"
}
return m.styles.Status.Width(m.statusWidth()).Render(status)
}
func (m *Model) statusWidth() int {
if m.width <= 0 {
return 80
}
if m.width <= 2 {
return m.width
}
return m.width - 2
}
func (m *Model) requestQuit() (tea.Model, tea.Cmd) {
if m.entries.hasUnsavedChanges() {
m.confirmQuit = true
return m, nil
}
return m, tea.Quit
}
func reportOpenSessionWarning(entries []worktime.Entry) string {
openSessions := worktime.OpenSessions(entries)
if len(openSessions) == 0 {
return ""
}
items := make([]string, 0, len(openSessions))
for _, session := range openSessions {
items = append(items, fmt.Sprintf(
"%s (since %s)",
session.Category,
time.Unix(session.Login.Epoch, 0).Format("2006-01-02 15:04"),
))
}
return "currently logged in: " + strings.Join(items, ", ")
}
|