summaryrefslogtreecommitdiff
path: root/internal/ui/handlers.go
blob: 78320702438178cd8a5204d0adde69d9a9a45931 (plain)
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package ui

import (
	"fmt"
	"strings"

	"charm.land/bubbles/v2/textinput"
	tea "charm.land/bubbletea/v2"
)

// handleTextInput provides generic text input handling for all input modes
func (m *Model) handleTextInput(msg tea.KeyPressMsg, input *textinput.Model, onEnter func(string) error, onExit func()) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "enter":
		value := input.Value()
		if err := onEnter(value); err != nil {
			return m, m.showErrorTimed(err)
		}
		input.Blur()
		onExit()
		m.updateTableHeight()
		return m, nil
	case "esc":
		input.Blur()
		onExit()
		m.updateTableHeight()
		return m, nil
	}
	var cmd tea.Cmd
	*input, cmd = input.Update(msg)
	return m, cmd
}

// handleAnnotationMode handles keyboard input when in annotation mode
func (m *Model) handleAnnotationMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	onEnter := func(value string) error {
		// Annotation can be empty when replacing (to remove all)
		if !m.replaceAnnotations && strings.TrimSpace(value) == "" {
			return fmt.Errorf("annotation cannot be empty")
		}

		if m.replaceAnnotations {
			ctx, cancel := m.taskOperationContext()
			defer cancel()
			if err := m.taskwarriorClient().ReplaceAnnotations(ctx, m.annotateID, value); err != nil {
				return err
			}
			m.replaceAnnotations = false
		} else {
			ctx, cancel := m.taskOperationContext()
			defer cancel()
			if err := m.taskwarriorClient().AnnotateContext(ctx, m.annotateID, value); err != nil {
				return err
			}
		}
		if err := m.reload(); err != nil {
			return fmt.Errorf("reloading tasks: %w", err)
		}
		return nil
	}

	onExit := func() {
		m.annotating = false
		m.replaceAnnotations = false
	}

	model, cmd := m.handleTextInput(msg, &m.annotateInput, onEnter, onExit)
	if msg.String() == "enter" && m.annotateInput.Value() != "" {
		// Start blink after successful annotation
		return model, m.startBlink(m.annotateID, false)
	}
	return model, cmd
}

// handleDescriptionMode handles keyboard input when editing description
func (m *Model) handleDescriptionMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	onEnter := func(value string) error {
		if err := validateDescription(value); err != nil {
			return err
		}
		ctx, cancel := m.taskOperationContext()
		defer cancel()
		if err := m.taskwarriorClient().SetDescriptionContext(ctx, m.descID, value); err != nil {
			return err
		}
		if err := m.reload(); err != nil {
			return fmt.Errorf("reloading tasks: %w", err)
		}
		return nil
	}

	onExit := func() {
		m.descEditing = false
	}

	model, cmd := m.handleTextInput(msg, &m.descInput, onEnter, onExit)
	if msg.String() == "enter" {
		return model, m.startBlink(m.descID, false)
	}
	return model, cmd
}

// handleTagsMode handles keyboard input when editing tags
func (m *Model) handleTagsMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	onEnter := func(value string) error {
		words := strings.Fields(value)
		var adds, removes []string
		for _, w := range words {
			if strings.HasPrefix(w, "-") {
				if len(w) > 1 {
					tagName := w[1:]
					if err := validateTagName(tagName); err != nil {
						return fmt.Errorf("remove tag '%s': %w", tagName, err)
					}
					removes = append(removes, tagName)
				}
			} else {
				w = strings.TrimPrefix(w, "+")
				if w != "" {
					if err := validateTagName(w); err != nil {
						return fmt.Errorf("add tag '%s': %w", w, err)
					}
					adds = append(adds, w)
				}
			}
		}
		if len(adds) > 0 || len(removes) > 0 {
			ctx, cancel := m.taskOperationContext()
			defer cancel()
			if len(adds) > 0 {
				if err := m.taskwarriorClient().AddTagsContext(ctx, m.tagsID, adds); err != nil {
					return err
				}
			}
			if len(removes) > 0 {
				if err := m.taskwarriorClient().RemoveTagsContext(ctx, m.tagsID, removes); err != nil {
					return err
				}
			}
		}
		if err := m.reload(); err != nil {
			return fmt.Errorf("reloading tasks: %w", err)
		}
		return nil
	}

	onExit := func() {
		m.tagsEditing = false
	}

	model, cmd := m.handleTextInput(msg, &m.tagsInput, onEnter, onExit)
	if msg.String() == "enter" {
		if m.showTaskDetail {
			// In detail view, blink the tags field
			return model, m.startDetailBlink(4) // Tags is field index 4
		}
		return model, m.startBlink(m.tagsID, false)
	}
	return model, cmd
}

// handleDueEditMode handles due date editing
func (m *Model) handleDueEditMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "enter":
		ctx, cancel := m.taskOperationContext()
		err := m.taskwarriorClient().SetDueDateContext(ctx, m.dueID, m.dueDate.Format("2006-01-02"))
		cancel()
		if err != nil {
			return m, m.showErrorTimed(err)
		}
		m.dueEditing = false
		if !m.reloadAndReport() {
			return m, nil
		}
		var cmd tea.Cmd
		if m.showTaskDetail {
			// In detail view, blink the due field
			cmd = m.startDetailBlink(5) // Due is field index 5
		} else {
			cmd = m.startBlink(m.dueID, false)
		}
		m.updateTableHeight()
		return m, cmd
	case "esc":
		m.dueEditing = false
		m.updateTableHeight()
		return m, nil
	}

	switch msg.String() {
	case "h", "left":
		m.dueDate = m.dueDate.AddDate(0, 0, -1)
	case "l", "right":
		m.dueDate = m.dueDate.AddDate(0, 0, 1)
	case "k", "up":
		m.dueDate = m.dueDate.AddDate(0, 0, -7)
	case "j", "down":
		m.dueDate = m.dueDate.AddDate(0, 0, 7)
	}
	return m, nil
}

// handleRecurrenceMode handles recurrence editing
func (m *Model) handleRecurrenceMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	onEnter := func(value string) error {
		if err := validateRecurrence(value); err != nil {
			return err
		}
		ctx, cancel := m.taskOperationContext()
		defer cancel()
		if err := m.taskwarriorClient().SetRecurrenceContext(ctx, m.recurID, value); err != nil {
			return err
		}
		if err := m.reload(); err != nil {
			return fmt.Errorf("reloading tasks: %w", err)
		}
		return nil
	}

	onExit := func() {
		m.recurEditing = false
	}

	model, cmd := m.handleTextInput(msg, &m.recurInput, onEnter, onExit)
	if msg.String() == "enter" {
		if m.showTaskDetail {
			if t := m.currentDetailTask(); t != nil && t.Recur != "" {
				return model, m.startDetailBlink(fieldRecur)
			}
		}
		return model, m.startBlink(m.recurID, false)
	}
	return model, cmd
}

// handleProjectMode handles project editing
func (m *Model) handleProjectMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	onEnter := func(value string) error {
		ctx, cancel := m.taskOperationContext()
		defer cancel()
		return m.taskwarriorClient().SetProjectContext(ctx, m.projID, value)
	}

	onExit := func() {
		m.projEditing = false
		m.reloadAndReport()
	}

	model, cmd := m.handleTextInput(msg, &m.projInput, onEnter, onExit)
	if msg.String() == "enter" {
		if m.showTaskDetail {
			// In detail view, blink the project field
			return model, m.startDetailBlink(fieldProject) // Project field index in detail view
		}
		return model, m.startBlink(m.projID, false)
	}
	return model, cmd
}

// handlePriorityMode handles priority selection
func (m *Model) handlePriorityMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "enter":
		priority := priorityOptions[m.priorityIndex]
		if err := validatePriority(priority); err != nil {
			return m, m.showErrorTimed(err)
		}
		ctx, cancel := m.taskOperationContext()
		err := m.taskwarriorClient().SetPriorityContext(ctx, m.priorityID, priority)
		cancel()
		if err != nil {
			return m, m.showErrorTimed(err)
		}
		m.prioritySelecting = false
		if !m.reloadAndReport() {
			return m, nil
		}
		var cmd tea.Cmd
		if m.showTaskDetail {
			// In detail view, blink the priority field
			cmd = m.startDetailBlink(3) // Priority is field index 3
		} else {
			cmd = m.startBlink(m.priorityID, false)
		}
		m.updateTableHeight()
		return m, cmd
	case "esc":
		m.prioritySelecting = false
		m.updateTableHeight()
		return m, nil
	}

	switch msg.String() {
	case "h", "left":
		m.priorityIndex = (m.priorityIndex + len(priorityOptions) - 1) % len(priorityOptions)
	case "l", "right":
		m.priorityIndex = (m.priorityIndex + 1) % len(priorityOptions)
	}
	return m, nil
}

// handleFilterMode handles filter editing for both traditional and ultra mode.
// The filter value is split using shell-quoting rules (via parseFilterInput)
// so that expressions with quoted values (e.g. description:"my task") are
// passed to taskwarrior as a single argument. Any taskwarrior filter expression
// that is valid on the command line (proj:xxx, +tag, description:"...", etc.)
// is therefore accepted here too. Taskwarrior errors are propagated back to
// the user via the status bar rather than being silently discarded.
func (m *Model) handleFilterMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	onEnter := func(value string) error {
		fields, err := parseFilterInput(value)
		if err != nil {
			return err
		}
		m.filters = fields
		// Propagate taskwarrior errors so the user sees feedback when a
		// filter expression is rejected by taskwarrior.
		if err := m.reload(); err != nil {
			// Roll back the filters to avoid leaving the UI in a broken state
			// where an empty task list is shown without any explanation.
			m.filters = nil
			return fmt.Errorf("filter error: %w", err)
		}
		return nil
	}

	onExit := func() {
		m.filterEditing = false
	}

	return m.handleTextInput(msg, &m.filterInput, onEnter, onExit)
}

// handleAddTaskMode handles adding a new task
func (m *Model) handleAddTaskMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "enter":
		oldIDs := make(map[int]struct{}, len(m.tasks))
		for _, tsk := range m.tasks {
			oldIDs[tsk.ID] = struct{}{}
		}

		ctx, cancel := m.taskOperationContext()
		err := m.taskwarriorClient().AddLineContext(ctx, m.addInput.Value())
		cancel()
		if err != nil {
			return m, m.showErrorTimed(err)
		}

		m.addingTask = false
		m.addInput.Blur()
		if !m.reloadAndReport() {
			return m, nil
		}

		// Find the newly added task
		var newID int
		row := -1
		for i, tsk := range m.tasks {
			if _, ok := oldIDs[tsk.ID]; !ok {
				newID = tsk.ID
				row = i
				break
			}
		}

		m.updateTableHeight()
		if row >= 0 {
			prevRow := m.tbl.Cursor()
			prevCol := m.tbl.ColumnCursor()
			m.tbl.SetCursor(row)
			m.tbl.SetColumnCursor(7) // Description column
			m.updateSelectionHighlight(prevRow, m.tbl.Cursor(), prevCol, m.tbl.ColumnCursor())
			if m.showUltra {
				m.ultraFocusedID = newID
				m.selectTaskByID(newID)
				m.ultraFocusedID = 0
			}
			return m, m.startBlink(newID, false)
		}
		return m, nil

	case "esc":
		m.addingTask = false
		m.addInput.Blur()
		m.updateTableHeight()
		return m, nil
	}

	var cmd tea.Cmd
	m.addInput, cmd = m.addInput.Update(msg)
	return m, cmd
}

// handleSearchMode handles search input
func (m *Model) handleSearchMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "enter":
		pattern := m.searchInput.Value()
		if pattern != "" {
			// Check cache first
			if cached, ok := cachedSearchRegex(pattern); ok {
				m.searchRegex = cached
			} else {
				// Compile and cache if not found
				re, err := compileAndCacheRegex(pattern)
				if err == nil {
					m.searchRegex = re
				} else {
					m.searchRegex = nil
					m.statusMsg = fmt.Sprintf("Invalid regex: %v", err)
				}
			}
		} else {
			m.searchRegex = nil
		}
		m.searching = false
		m.searchInput.Blur()
		if !m.reloadAndReport() {
			return m, nil
		}
		m.updateTableHeight()

		if len(m.searchMatches) > 0 {
			match := m.searchMatches[m.searchIndex]
			prevRow := m.tbl.Cursor()
			prevCol := m.tbl.ColumnCursor()
			m.tbl.SetCursor(match.row)
			m.tbl.SetColumnCursor(match.col)
			m.updateSelectionHighlight(prevRow, m.tbl.Cursor(), prevCol, m.tbl.ColumnCursor())
		}
		return m, nil

	case "esc":
		m.searching = false
		m.searchInput.Blur()
		m.updateTableHeight()
		return m, nil
	}

	var cmd tea.Cmd
	m.searchInput, cmd = m.searchInput.Update(msg)
	return m, cmd
}

// handleHelpSearchMode handles search input in help mode
func (m *Model) handleHelpSearchMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "enter":
		pattern := m.helpSearchInput.Value()
		if pattern != "" {
			// Check cache first
			if cached, ok := cachedSearchRegex(pattern); ok {
				m.helpSearchRegex = cached
			} else {
				// Compile and cache if not found
				re, err := compileAndCacheRegex(pattern)
				if err == nil {
					m.helpSearchRegex = re
				} else {
					m.helpSearchRegex = nil
					m.statusMsg = fmt.Sprintf("Invalid regex: %v", err)
				}
			}
		} else {
			m.helpSearchRegex = nil
		}
		m.helpSearching = false
		m.helpSearchInput.Blur()

		// Find matching help lines
		m.helpSearchMatches = nil
		if m.helpSearchRegex != nil {
			helpLines := m.getHelpLines()
			for i, line := range helpLines {
				if m.helpSearchRegex.MatchString(line) {
					m.helpSearchMatches = append(m.helpSearchMatches, i)
				}
			}
			// Set to first match
			if len(m.helpSearchMatches) > 0 {
				m.helpSearchIndex = 0
			}
		}
		return m, nil

	case "esc":
		m.helpSearching = false
		m.helpSearchInput.Blur()
		return m, nil
	}

	var cmd tea.Cmd
	m.helpSearchInput, cmd = m.helpSearchInput.Update(msg)
	return m, cmd
}