diff --git a/README.md b/README.md index 13f02c8..7a4b350 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,7 @@ bg = #0D171F bg_alt = #252E35 border = #5F6468 highlight = #AFCFFF +backdrop = #3E464C ``` diff --git a/design/build/main.go b/design/build/main.go index d23fda9..ecb9071 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -78,7 +78,7 @@ var paletteFields = []struct{ token, field string }{ {"primary", "Primary"}, {"accent", "Accent"}, {"success", "Success"}, {"warning", "Warning"}, {"danger", "Danger"}, {"text", "Text"}, {"dim", "Dim"}, {"subtle", "Subtle"}, {"bg", "Bg"}, {"bg_alt", "BgAlt"}, - {"border", "Border"}, {"highlight", "Highlight"}, + {"border", "Border"}, {"highlight", "Highlight"}, {"backdrop", "Backdrop"}, } // tailwindNames renames tokens whose name clashes with a Tailwind utility @@ -334,6 +334,19 @@ func renderPalette(t *Tokens) ([]byte, error) { {"tui-col-earned", "ColEarned"}, {"tui-hero-rows", "HeroRows"}, {"tui-hero-rows-compact", "HeroRowsCompact"}, + {"tui-modal-width", "ModalWidth"}, + {"tui-modal-indent", "ModalIndent"}, + {"tui-modal-label", "ModalLabel"}, + {"tui-suggest-width", "SuggestWidth"}, + {"tui-suggest-rows", "SuggestRows"}, + {"tui-confirm-width", "ConfirmWidth"}, + {"tui-keys-col", "KeysCol"}, + {"tui-keys-cap", "KeysCap"}, + {"tui-keys-gap", "KeysGap"}, + {"tui-keys-cols", "KeysCols"}, + {"tui-modal-min-width", "ModalMinWidth"}, + {"tui-strip-min", "StripMin"}, + {"tui-field-width", "FieldWidth"}, } { v, err := integer(t.Spacing, c.token) if err != nil { diff --git a/design/tokens.json b/design/tokens.json index 1a3f07f..e553170 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -22,6 +22,7 @@ { "name": "bg_alt", "value": "#252E35", "usage": "Selected row, modal fields, panels and cards. Aether's lighter_bg. Tailwind name: bgalt." }, { "name": "border", "value": "#5F6468", "usage": "Rules and box borders on bg (3:1). Not for text. Aether's muted. Tailwind name: line." }, { "name": "highlight", "value": "#AFCFFF", "usage": "Wordmark, the elapsed-time digits, emphasis in headings. Aether's bright_blue." }, + { "name": "backdrop", "value": "#3E464C", "usage": "TUI: the screen behind a modal, redrawn as plain text in this colour on bg. It's inactive, so WCAG 1.4.3 exempts it (1.88:1). An aliasOS theme, or a theme.conf that sets bg or border without a backdrop, gets border mixed 60% over bg." }, { "name": "surface", "value": "#111D26", "usage": "Landing page only: raised cards and the screenshot body, one step above bg." }, { "name": "code_bg", "value": "#0A1319", "usage": "Landing page only: code blocks, one step below bg." }, { "name": "kbd_fill", "value": "rgba(255,255,255,0.03)", "usage": "Landing page only: the faint fill inside key caps." } @@ -75,6 +76,19 @@ { "name": "tui-detail-note-rows", "value": 3, "usage": "TUI: the most rows an entry's notes take in the detail pane; longer notes end in an ellipsis." }, { "name": "tui-hero-rows", "value": 6, "usage": "TUI: rows the wide Timers hero takes, borders included: four rows for the label, task, place and meta line beside three rows of block digits." }, { "name": "tui-hero-rows-compact", "value": 4, "usage": "TUI: rows the compact Timers hero takes, borders included: the task and elapsed time, then the place and today's total." }, + { "name": "tui-modal-width", "value": 70, "usage": "TUI: a form modal's width, borders included (New timer, Edit entry, the client and project forms). A narrower body gets a modal as wide as the body." }, + { "name": "tui-modal-indent", "value": 3, "usage": "TUI: blank columns inside a modal's border before its labels and buttons, and after its fields." }, + { "name": "tui-modal-label", "value": 11, "usage": "TUI: a form modal's label column (Task, Client, Rate ($/h)). The focus mark (glyph-cursor) follows it, then the field." }, + { "name": "tui-suggest-width", "value": 30, "usage": "TUI: the suggestions box under a Client or Project field, borders included; never wider than the field." }, + { "name": "tui-suggest-rows", "value": 5, "usage": "TUI: the most suggestions the box shows at once; the arrow keys scroll through the rest." }, + { "name": "tui-confirm-width", "value": 56, "usage": "TUI: the delete confirm's width, borders included." }, + { "name": "tui-keys-col", "value": 28, "usage": "TUI: one column of the ? keys sheet: the key cap, a space and its label." }, + { "name": "tui-keys-cap", "value": 11, "usage": "TUI: the key-cap column in the ? keys sheet, room for the shift+tab cap." }, + { "name": "tui-keys-gap", "value": 2, "usage": "TUI: blank columns between the ? keys sheet's columns." }, + { "name": "tui-keys-cols", "value": 3, "usage": "TUI: the most columns the ? keys sheet uses; it drops to fewer when the body is too narrow for them." }, + { "name": "tui-modal-min-width", "value": 20, "usage": "TUI: the narrowest a modal gets, border included, however narrow the body is." }, + { "name": "tui-strip-min", "value": 8, "usage": "TUI: the narrowest a form field's bg_alt strip gets in a modal." }, + { "name": "tui-field-width", "value": 44, "usage": "TUI: a form field's width when the form opens; the modal sets it to its strip's width each time it draws." }, { "name": "tui-min-width", "value": 64, "usage": "TUI: the narrowest terminal notch draws, in cells, measured from the views: the widest fixed line is the Projects tab's at 57 cells, 61 with the two margins; the compact Timers range chips need 48. Narrower terminals get a centred \"Terminal too small\" message." }, { "name": "tui-min-height", "value": 22, "usage": "TUI: the shortest terminal notch draws, in rows: the chrome (4), the body's top and bottom padding (2), the compact Timers screen's fixed rows (14) and two list rows (a day header and the selected entry). A wide terminal this short gets the compact layout, since the wide one needs 23 rows (see tui-wide). Shorter terminals get a centred \"Terminal too small\" message." }, { "name": "tui-chrome-rows", "value": 4, "usage": "TUI: rows taken by the chrome: the tab bar and its rule at the top, and a rule and the hotkey and status line at the bottom (measured from their real output). Content gets the rest." }, @@ -113,7 +127,7 @@ "glyph": { "tokens": [ { "name": "glyph-wordmark", "value": "◷", "usage": "The mark before the notch wordmark." }, - { "name": "glyph-cursor", "value": "▌", "usage": "The selected row's cursor in the TUI gutter, in primary." }, + { "name": "glyph-cursor", "value": "▌", "usage": "The selected row's cursor in the TUI gutter, in primary; also the focus mark before a form field or button, and the mark on the selected suggestion (in bg on primary)." }, { "name": "glyph-live", "value": "●", "usage": "The dot in the footer: in the running pill, and in subtle when idle." }, { "name": "glyph-unbilled", "value": "○", "usage": "Status: not invoiced yet, in subtle." }, { "name": "glyph-invoiced", "value": "◐", "usage": "Status: invoiced, not paid, in accent." }, @@ -124,17 +138,19 @@ "contrast": { "pairs": [ { "fg": "text", "bg": "bg", "min": 4.5, "usage": "Body text." }, - { "fg": "text", "bg": "bg_alt", "min": 4.5, "usage": "Text on the selected row, fields and panels." }, + { "fg": "text", "bg": "bg_alt", "min": 4.5, "usage": "Text on the selected row, in modal fields, on secondary buttons and on key caps." }, { "fg": "dim", "bg": "bg", "min": 4.5, "usage": "Secondary text." }, { "fg": "dim", "bg": "bg_alt", "min": 4.5, "usage": "Secondary text on the selected row." }, { "fg": "subtle", "bg": "bg", "min": 4.5, "usage": "Hints and key labels." }, - { "fg": "subtle", "bg": "bg_alt", "min": 4.5, "usage": "Hints in fields and on the selected row." }, + { "fg": "subtle", "bg": "bg_alt", "min": 4.5, "usage": "Placeholders in modal fields (\"now\", \"optional\") and hints on the selected row." }, { "fg": "primary", "bg": "bg", "min": 4.5, "usage": "Day headers in the Timers list and the active tab's underline." }, { "fg": "accent", "bg": "bg", "min": 4.5, "usage": "Field labels, links, and invoiced status (◐) in the Timers list." }, { "fg": "success", "bg": "bg", "min": 4.5, "usage": "Paid and running status, the hero's elapsed time and status messages." }, { "fg": "warning", "bg": "bg", "min": 4.5, "usage": "Section titles and invoiced status in Reports, and the Timers hero's unbilled total." }, { "fg": "danger", "bg": "bg", "min": 4.5, "usage": "Errors and delete actions." }, - { "fg": "danger", "bg": "bg_alt", "min": 4.5, "usage": "Field errors inside modals." }, + { "fg": "danger", "bg": "bg_alt", "min": 4.5, "usage": "The Delete entry button in the edit modal." }, + { "fg": "bg", "bg": "danger", "min": 4.5, "usage": "The Delete button in a delete confirm." }, + { "fg": "backdrop", "bg": "bg", "min": 1, "usage": "The dimmed screen behind a modal. Inactive, so exempt from 1.4.3; listed so the table shows every pair." }, { "fg": "highlight", "bg": "bg", "min": 4.5, "usage": "Wordmark and elapsed time." }, { "fg": "bg", "bg": "primary", "min": 4.5, "usage": "Primary button label and the active range chip." }, { "fg": "bg", "bg": "success", "min": 4.5, "usage": "Running pill label." }, diff --git a/internal/db/db.go b/internal/db/db.go index 4db88d0..ffe5618 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -408,6 +408,29 @@ func (d *DB) GetRunningEntry() (*model.Entry, error) { return entries[0], nil } +// GetEntry returns the entry id with its project and client, or nil when +// there's no such entry. +func (d *DB) GetEntry(id int64) (*model.Entry, error) { + rows, err := d.sql.Query( + `SELECT e.id, e.project_id, e.task, e.start_time, e.end_time, + e.invoiced, e.paid, e.notes, e.created_at, + p.id, p.client_id, p.name, p.created_at, + c.id, c.name, c.hourly_rate, c.created_at + FROM entries e + JOIN projects p ON p.id = e.project_id + JOIN clients c ON c.id = p.client_id + WHERE e.id = ?`, id) + if err != nil { + return nil, err + } + defer rows.Close() + entries, err := scanEntries(rows) + if err != nil || len(entries) == 0 { + return nil, err + } + return entries[0], nil +} + // ListEntries lists entries with optional filters. Pass zero values to skip a filter. // dateFrom/dateTo format: "2006-01-02" func (d *DB) ListEntries(projectID int64, dateFrom, dateTo string, includeRunning bool) ([]*model.Entry, error) { diff --git a/internal/db/db_test.go b/internal/db/db_test.go index ab70062..15dbe5e 100644 --- a/internal/db/db_test.go +++ b/internal/db/db_test.go @@ -1398,3 +1398,29 @@ func TestUpdate_DeletedRowIsNotFound(t *testing.T) { t.Errorf("UpdateProject after delete: err = %v, want ErrNotFound", err) } } + +func TestGetEntry(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 95) + p, _ := d.CreateProject(c.ID, "Web") + start := time.Now().Add(-time.Hour).Truncate(time.Second) + e, err := d.AddEntry(p.ID, "Logo", "notes", start, nil) + if err != nil { + t.Fatal(err) + } + got, err := d.GetEntry(e.ID) + if err != nil || got == nil { + t.Fatalf("GetEntry = %v, %v", got, err) + } + if got.Task != "Logo" || got.Notes != "notes" || !got.StartTime.Equal(start) || got.EndTime != nil || + got.Project == nil || got.Project.Name != "Web" || got.Project.Client == nil || got.Project.Client.Name != "Acme" { + t.Errorf("GetEntry = %+v, want the entry with its project and client", got) + } + if got, err := d.GetEntry(e.ID + 100); got != nil || err != nil { + t.Errorf("GetEntry(missing) = %v, %v; want nil, nil", got, err) + } + d.Close() + if _, err := d.GetEntry(e.ID); err == nil { + t.Error("GetEntry on a closed database should fail") + } +} diff --git a/internal/theme/theme.go b/internal/theme/theme.go index fca9103..5c72c80 100644 --- a/internal/theme/theme.go +++ b/internal/theme/theme.go @@ -40,6 +40,9 @@ type Palette struct { BgAlt lipgloss.Color Border lipgloss.Color Highlight lipgloss.Color + // Backdrop is the text colour of the screen behind a modal: inactive, + // so it's meant to sit back, not to pass 4.5:1. + Backdrop lipgloss.Color } // Default, the built-in palette, is generated from design/tokens.json into @@ -175,6 +178,7 @@ func applyOverridesTo(base Palette, path string) Palette { } defer f.Close() + set := map[string]bool{} scanner := bufio.NewScanner(f) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) @@ -192,8 +196,15 @@ func applyOverridesTo(base Palette, path string) Palette { } if ptr := p.fieldPtr(key); ptr != nil { *ptr = lipgloss.Color(val) + set[key] = true } } + // The backdrop follows the theme: a theme.conf that changes bg or + // border without its own backdrop gets one mixed from them, as every + // other theme's is, rather than keeping the base's. + if !set["backdrop"] && (set["bg"] || set["border"]) { + p.Backdrop = blend(string(p.Bg), string(p.Border), 0.6) + } return p } @@ -226,6 +237,8 @@ func (p *Palette) fieldPtr(key string) *lipgloss.Color { return &p.Border case "highlight": return &p.Highlight + case "backdrop": + return &p.Backdrop } return nil } @@ -387,6 +400,13 @@ func paletteFromOSTheme(kv map[string]string) (Palette, bool) { *c = legible(*c, fg, 4.5, bg, string(p.BgAlt)) } p.Border = legible(p.Border, fg, 3, bg) + // The screen behind a modal: the border mixed most of the way over bg, + // as Default's backdrop is. It's inactive text, so it isn't lifted. + if v, ok := pickHex(kv, "backdrop"); ok { + p.Backdrop = lipgloss.Color(v) + } else { + p.Backdrop = blend(bg, string(p.Border), 0.6) + } return p, true } diff --git a/internal/theme/theme_test.go b/internal/theme/theme_test.go index 452e0a4..9eb16f8 100644 --- a/internal/theme/theme_test.go +++ b/internal/theme/theme_test.go @@ -95,7 +95,8 @@ func TestLoadFrom_AllKnownKeys(t *testing.T) { "bg=#999999\n"+ "bg_alt=#aaaaaa\n"+ "border=#bbbbbb\n"+ - "highlight=#cccccc\n") + "highlight=#cccccc\n"+ + "backdrop=#dddddd\n") p := LoadFrom(path) want := Palette{ @@ -103,6 +104,7 @@ func TestLoadFrom_AllKnownKeys(t *testing.T) { Warning: "#444444", Danger: "#555555", Text: "#666666", Dim: "#777777", Subtle: "#888888", Bg: "#999999", BgAlt: "#aaaaaa", Border: "#bbbbbb", Highlight: "#cccccc", + Backdrop: "#dddddd", } if p != want { t.Errorf("LoadFrom = %+v, want %+v", p, want) @@ -235,6 +237,9 @@ func TestPaletteFromOSTheme_RichFormatUsesNamedShades(t *testing.T) { Subtle: "#8a9aa6", Border: "#5f6468", BgAlt: "#252e35", Success: "#99c2ed", Warning: "#a4cbf7", Danger: "#c79ea9", Accent: "#9dc6e9", Highlight: "#afcfff", + // No backdrop key: border mixed 60% over bg, about Default's + // #3E464C. + Backdrop: "#3e454a", } if p != want { t.Errorf("paletteFromOSTheme = %+v, want %+v", p, want) @@ -627,3 +632,22 @@ func TestCheckReload_ReturnsToStateDirAfterSwapWindow(t *testing.T) { t.Errorf("Colors.Primary = %v, want #60a0e0 from the state theme", Colors.Primary) } } + +// A theme.conf that changes bg (or border) without a backdrop gets one +// mixed from them, like every other theme, not the default's: a light bg +// mustn't keep a backdrop meant for a dark one. It's the rule aliasOS +// themes use. +func TestLoadFrom_BackdropFollowsBg(t *testing.T) { + dir := t.TempDir() + p := LoadFrom(writeConfig(t, dir, "bg=#ffffff\n")) + if want := blend("#ffffff", string(Default.Border), 0.6); p.Backdrop != want { + t.Errorf("backdrop = %v, want %v mixed from the new bg", p.Backdrop, want) + } + if r := contrastRatio(string(p.Backdrop), string(p.Bg)); r < 1.5 || r > 4.5 { + t.Errorf("backdrop on bg = %.2f:1, want it dim but visible (inactive text is exempt)", r) + } + p = LoadFrom(writeConfig(t, dir, "bg=#ffffff\nbackdrop=#aaaaaa\n")) + if p.Backdrop != "#aaaaaa" { + t.Errorf("an explicit backdrop = %v, want #aaaaaa kept", p.Backdrop) + } +} diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index df7b217..7ab5770 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -38,13 +38,20 @@ var Default = Palette{ // Wordmark, the elapsed-time digits, emphasis in headings. Aether's // bright_blue. Highlight: "#AFCFFF", + // TUI: the screen behind a modal, redrawn as plain text in this colour on + // bg. It's inactive, so WCAG 1.4.3 exempts it (1.88:1). An aliasOS theme, or + // a theme.conf that sets bg or border without a backdrop, gets border mixed + // 60% over bg. + Backdrop: "#3E464C", } // Status and brand glyphs. const ( // The mark before the notch wordmark. GlyphWordmark = "◷" - // The selected row's cursor in the TUI gutter, in primary. + // The selected row's cursor in the TUI gutter, in primary; also the focus + // mark before a form field or button, and the mark on the selected + // suggestion (in bg on primary). GlyphCursor = "▌" // The dot in the footer: in the running pill, and in subtle when idle. GlyphLive = "●" @@ -132,3 +139,57 @@ const HeroRows = 6 // takes, borders included: the task and elapsed time, then the place and // today's total. const HeroRowsCompact = 4 + +// ModalWidth (tui-modal-width). TUI: a form modal's width, borders included +// (New timer, Edit entry, the client and project forms). A narrower body gets +// a modal as wide as the body. +const ModalWidth = 70 + +// ModalIndent (tui-modal-indent). TUI: blank columns inside a modal's border +// before its labels and buttons, and after its fields. +const ModalIndent = 3 + +// ModalLabel (tui-modal-label). TUI: a form modal's label column (Task, +// Client, Rate ($/h)). The focus mark (glyph-cursor) follows it, then the +// field. +const ModalLabel = 11 + +// SuggestWidth (tui-suggest-width). TUI: the suggestions box under a Client +// or Project field, borders included; never wider than the field. +const SuggestWidth = 30 + +// SuggestRows (tui-suggest-rows). TUI: the most suggestions the box shows at +// once; the arrow keys scroll through the rest. +const SuggestRows = 5 + +// ConfirmWidth (tui-confirm-width). TUI: the delete confirm's width, borders +// included. +const ConfirmWidth = 56 + +// KeysCol (tui-keys-col). TUI: one column of the ? keys sheet: the key cap, a +// space and its label. +const KeysCol = 28 + +// KeysCap (tui-keys-cap). TUI: the key-cap column in the ? keys sheet, room +// for the shift+tab cap. +const KeysCap = 11 + +// KeysGap (tui-keys-gap). TUI: blank columns between the ? keys sheet's +// columns. +const KeysGap = 2 + +// KeysCols (tui-keys-cols). TUI: the most columns the ? keys sheet uses; it +// drops to fewer when the body is too narrow for them. +const KeysCols = 3 + +// ModalMinWidth (tui-modal-min-width). TUI: the narrowest a modal gets, +// border included, however narrow the body is. +const ModalMinWidth = 20 + +// StripMin (tui-strip-min). TUI: the narrowest a form field's bg_alt strip +// gets in a modal. +const StripMin = 8 + +// FieldWidth (tui-field-width). TUI: a form field's width when the form +// opens; the modal sets it to its strip's width each time it draws. +const FieldWidth = 44 diff --git a/internal/ui/app.go b/internal/ui/app.go index 16ed5aa..fd55e9c 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -134,6 +134,11 @@ type AppModel struct { // just guards against a watch that failed to start or missed an event. tickCount int + // showKeys is the ? keys sheet, open over the active tab; keysOffset + // scrolls it on a terminal too short for all of it. + showKeys bool + keysOffset int + timers views.TimersModel projects views.ProjectsModel clients views.ClientsModel @@ -254,6 +259,13 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } case tea.KeyMsg: + if m.showKeys { + return m.updateKeySheet(msg) + } + if !m.activeViewBusy() && msg.String() == "?" { + m.showKeys, m.keysOffset = true, 0 + return m, nil + } if !m.activeViewBusy() { switch { case key.Matches(msg, appKeys.Quit): @@ -276,7 +288,8 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, m.reports.Init() } } - if key.Matches(msg, appKeys.Quit) { + // In a form or modal q is typing: only ctrl+c quits there. + if msg.Type == tea.KeyCtrlC { return m, tea.Quit } @@ -335,6 +348,23 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, tea.Batch(cmds...) } +// updateKeySheet handles a key while the keys sheet is open: esc or ? +// closes it, the arrows scroll it, q quits, and the rest do nothing. +func (m AppModel) updateKeySheet(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "esc", "?": + m.showKeys = false + case "up", "k": + m.keysOffset = max(0, m.keysOffset-1) + case "down", "j": + cw, ch := m.contentDims() + m.keysOffset = min(m.keysOffset+1, max(0, views.KeySheetRows(cw-2*theme.Margin)-(ch-5))) + case "q", "ctrl+c": + return m, tea.Quit + } + return m, nil +} + // ── View ────────────────────────────────────────────────────────────────────── func (m AppModel) View() string { @@ -486,6 +516,9 @@ func (m AppModel) renderBottomBar() string { var msg string switch { + case m.activeViewFieldErrors() > 0: + // An open form's errors sit under their fields; this counts them. + msg = paint(truncateStr("✕ "+views.FixingText(m.activeViewFieldErrors()), inner), appColorDanger, bg, true) case m.err != "": msg = paint(truncateStr("✕ "+m.err, inner), appColorDanger, bg, true) case m.statusMsg != "": @@ -499,7 +532,11 @@ func (m AppModel) renderBottomBar() string { // q quit comes last, so it's the first key dropped when the line is // short. keys, w := "", 0 - for i, h := range append(m.activeViewHelp(), views.Hotkey{Key: "q", Label: "quit"}) { + quit := views.Hotkey{Key: "q", Label: "quit"} + if m.activeViewBusy() && !m.showKeys { + quit.Key = "ctrl+c" + } + for i, h := range append(m.activeViewHelp(), quit) { cw := hotkeyChipWidth(h) if i > 0 { cw += len(hotkeySep) @@ -514,6 +551,13 @@ func (m AppModel) renderBottomBar() string { w += cw } + // With no message, the right end says where every key is, when the + // keys leave room for it (not in a form, where ? types). + if msg == "" && !m.showKeys && !m.activeViewBusy() { + if hint := "? all keys"; inner-w >= len(hint)+theme.KeyGap { + msg = paint(hint, appColorSubtle, bg, false) + } + } margin := paint(strings.Repeat(" ", theme.Margin), appColorText, bg, false) gap := max(0, inner-w-lipgloss.Width(msg)) line := margin + keys + paint(strings.Repeat(" ", gap), appColorText, bg, false) + msg + margin @@ -553,6 +597,9 @@ func (m AppModel) renderBody() string { case TabReports: view = m.reports.View() } + if m.showKeys { + view = views.WithKeySheet(view, cw-2*theme.Margin, ch-2, m.keysOffset) + } // Content column. Height is a minimum (pads short views to fill the // space); MaxHeight is the hard ceiling: on a very short terminal a @@ -616,6 +663,9 @@ func (m AppModel) activeViewBusy() bool { // activeViewHelp returns the active view's contextual hotkeys for its // current mode, mirroring the activeViewBusy() dispatch pattern. func (m AppModel) activeViewHelp() []views.Hotkey { + if m.showKeys { + return []views.Hotkey{{Key: "esc", Label: "close"}, {Key: "?", Label: "close"}} + } switch m.activeTab { case TabTimers: return m.timers.Help() @@ -629,6 +679,22 @@ func (m AppModel) activeViewHelp() []views.Hotkey { return nil } +// activeViewFieldErrors is how many fields of the active tab's open form +// need fixing. +func (m AppModel) activeViewFieldErrors() int { + switch m.activeTab { + case TabTimers: + return m.timers.FieldErrors() + case TabProjects: + return m.projects.FieldErrors() + case TabClients: + return m.clients.FieldErrors() + case TabReports: + return m.reports.FieldErrors() + } + return 0 +} + // contentDims returns the width and height of the centered content column. // The chrome (top bar + banner + footer) height is set in styles.go. func (m AppModel) contentDims() (width, height int) { diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index a4458b4..e2b4e53 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -55,7 +55,7 @@ func runeKey(r rune) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}} } -func TestQuit_AlwaysEscapesBusyMode(t *testing.T) { +func TestQuit_CtrlCEscapesBusyModeAndQDoesNot(t *testing.T) { // Enter timers filter mode via the exported Update path (pure, no DB touch) // so the model is genuinely "busy" without reaching into unexported views fields. busyTimers, _ := views.NewTimers(nil).Update(runeKey('f')) @@ -74,17 +74,12 @@ func TestQuit_AlwaysEscapesBusyMode(t *testing.T) { t.Errorf("ctrl+c while busy: want tea.QuitMsg, got %T", msg) } - // "q" must behave the same way. - next, cmd2 := m.Update(runeKey('q')) - m2 := next.(AppModel) - if cmd2 == nil { - t.Fatal("'q' while busy: want a quit cmd, got nil") - } - if _, ok := cmd2().(tea.QuitMsg); !ok { - t.Errorf("'q' while busy: want tea.QuitMsg, got %T", cmd2()) - } - if m2.activeTab != TabTimers { - t.Errorf("quit should not otherwise mutate model state, activeTab = %d", m2.activeTab) + // "q" is typing while busy: it reaches the view, and doesn't quit. + _, cmd2 := m.Update(runeKey('q')) + if cmd2 != nil { + if _, ok := cmd2().(tea.QuitMsg); ok { + t.Error("'q' while busy quit the app; only ctrl+c should") + } } } @@ -439,13 +434,7 @@ func TestRenderTopBar_IdleWhenNoRunningEntry(t *testing.T) { // The bottom line carries the view's keys on the left and the latest status // on the right; keys that don't fit are dropped whole. func TestRenderBottomBar_KeysAndStatus(t *testing.T) { - d := newTestDB(t) - m, err := New(d) - if err != nil { - t.Fatalf("New: %v", err) - } - m.width, m.height = 140, 40 - m.timers.SetSize(ContentWidth(140), 36) + m := sampleApp(t, 140, 40) m.statusMsg = `Started "Pricing page layout"` line := strings.Split(plainText(m.renderBottomBar()), "\n")[1] for _, want := range []string{" n new", " space start/stop", " d delete", `✓ Started "Pricing page layout"`} { diff --git a/internal/ui/modal_test.go b/internal/ui/modal_test.go new file mode 100644 index 0000000..eae7ece --- /dev/null +++ b/internal/ui/modal_test.go @@ -0,0 +1,137 @@ +package ui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// Tests for the app's side of ALI-2616: the ? keys sheet and the status +// line's count of a form's field errors. + +func (m AppModel) press(msgs ...tea.Msg) AppModel { + for _, msg := range msgs { + u, _ := m.Update(msg) + m = u.(AppModel) + } + return m +} + +func TestKeySheet_OpensGroupedByTabAndCloses(t *testing.T) { + for _, size := range [][2]int{{140, 40}, {90, 32}} { + m := sampleApp(t, size[0], size[1]).press(runeKey('?')) + if !m.showKeys { + t.Fatalf("%v: ? should open the keys sheet", size) + } + view := plainText(m.View()) + for _, want := range []string{"╭─ Keys ─", "EVERYWHERE", "TIMERS", "RANGES", "PROJECTS", "CLIENTS", "REPORTS", "FORMS", "shift+tab", "toggle invoiced", "esc close"} { + if !strings.Contains(view, want) { + t.Errorf("%v: the keys sheet is missing %q:\n%s", size, want, view) + } + } + if strings.Contains(view, "↑↓ scroll") { + t.Errorf("%v: the whole sheet should fit without scrolling:\n%s", size, view) + } + if lines := strings.Split(m.View(), "\n"); len(lines) != size[1] { + t.Errorf("%v: frame is %d rows, want %d", size, len(lines), size[1]) + } + // Keys under the sheet don't reach the tab. + m = m.press(runeKey('n'), runeKey('2')) + if m.activeTab != TabTimers || m.timers.IsBusy() { + t.Errorf("%v: keys behind the sheet acted on the tab", size) + } + if m = m.press(tea.KeyMsg{Type: tea.KeyEsc}); m.showKeys { + t.Errorf("%v: esc should close the sheet", size) + } + if m = m.press(runeKey('?'), runeKey('?')); m.showKeys { + t.Errorf("%v: ? should close the sheet too", size) + } + } +} + +func TestKeySheet_ScrollsOnTheSmallestTerminal(t *testing.T) { + m := sampleApp(t, MinWidth, MinHeight).press(runeKey('?')) + view := plainText(m.View()) + if !strings.Contains(view, "↑↓ scroll") || !strings.Contains(view, "EVERYWHERE") { + t.Fatalf("at %d×%d the sheet should start at the top and say it scrolls:\n%s", MinWidth, MinHeight, view) + } + for range 40 { + m = m.press(tea.KeyMsg{Type: tea.KeyDown}) + } + if view = plainText(m.View()); !strings.Contains(view, "cancel") || strings.Contains(view, "EVERYWHERE") { + t.Errorf("scrolled to the end, the sheet should show its last key:\n%s", view) + } + for i, l := range strings.Split(m.View(), "\n") { + if w := lipgloss.Width(l); w != MinWidth { + t.Errorf("line %d is %d cells, want %d", i, w, MinWidth) + } + } +} + +func TestKeySheet_QuestionMarkTypesInAForm(t *testing.T) { + m := sampleApp(t, 140, 40) + _, cmd := m.Update(runeKey('n')) + m = m.press(runeKey('n'), cmd()) + if !m.timers.IsBusy() { + t.Fatal("setup: n should open New timer") + } + if m = m.press(runeKey('?')); m.showKeys { + t.Error("? in a form should type, not open the sheet") + } +} + +func TestBottomBar_CountsFieldErrors(t *testing.T) { + m := sampleApp(t, 140, 40) + _, cmd := m.Update(runeKey('n')) + m = m.press(cmd(), tea.KeyMsg{Type: tea.KeyEnter}) // save with no task + line := strings.Split(plainText(m.renderBottomBar()), "\n")[1] + if !strings.HasSuffix(strings.TrimRight(line, " "), "✕ 1 field needs fixing") { + t.Errorf("bottom line %q should end with the error count", line) + } + if strings.Contains(line, "? all keys") { + t.Errorf("a form's key line shouldn't offer ?: %q", line) + } +} + +func TestBottomBar_OffersTheKeysSheet(t *testing.T) { + m := sampleApp(t, 140, 40) + line := strings.Split(plainText(m.renderBottomBar()), "\n")[1] + if !strings.HasSuffix(strings.TrimRight(line, " "), "? all keys") { + t.Errorf("bottom line %q should end with ? all keys", line) + } +} + +// In a form, q is typing: "quote" in Task mustn't quit and lose the form. +// ctrl+c still quits. +func TestQuit_QTypesInAFormAndCtrlCQuits(t *testing.T) { + m := sampleApp(t, 140, 40) + _, cmd := m.Update(runeKey('n')) + m = m.press(cmd()) + if !m.timers.IsBusy() { + t.Fatal("setup: n should open New timer") + } + for _, r := range "quote" { + u, cmd := m.Update(runeKey(r)) + m = u.(AppModel) + if cmd != nil { + if _, quit := cmd().(tea.QuitMsg); quit { + t.Fatalf("typing %q in Task quit the app", r) + } + } + } + if !strings.Contains(plainText(m.View()), "quote") { + t.Errorf("Task should hold what was typed:\n%s", plainText(m.View())) + } + if line := strings.Split(plainText(m.renderBottomBar()), "\n")[1]; !strings.Contains(line, "ctrl+c quit") { + t.Errorf("a form's key line should say ctrl+c quits: %q", line) + } + _, cmd = m.Update(tea.KeyMsg{Type: tea.KeyCtrlC}) + if cmd == nil { + t.Fatal("ctrl+c should quit") + } + if _, quit := cmd().(tea.QuitMsg); !quit { + t.Error("ctrl+c should quit") + } +} diff --git a/internal/ui/views/clients.go b/internal/ui/views/clients.go index 42b00b1..03e289e 100644 --- a/internal/ui/views/clients.go +++ b/internal/ui/views/clients.go @@ -1,6 +1,7 @@ package views import ( + "errors" "fmt" "strings" @@ -24,9 +25,15 @@ type ClientsModel struct { // form fields inputs []textinput.Model - focusIdx int + focusIdx int // an input, clientFieldSave or clientFieldCancel editingID int64 // 0 = new - formErr string + errs fieldErrors + + // deleteFocused: Delete has the focus in the delete confirm (Keep it + // has it at first). deleteID is the client it's for, kept from when it + // opened, so a reload under it can't change what's deleted. + deleteFocused bool + deleteID int64 } type clientMode int @@ -40,7 +47,21 @@ const ( const ( clientFieldName = iota clientFieldRate - clientFieldCount + clientFieldCount // the inputs +) + +// The form's buttons, after its inputs in tab order. +const ( + clientFieldSave = clientFieldCount + iota + clientFieldCancel + clientFocusCount +) + +// The client form's messages, shared with the tests. +const ( + errNameRequired = "Enter a name." + errRate = "Enter a number, like 95 or 95.50." + errClientTaken = "A client with that name already exists." ) func NewClients(database *db.DB) ClientsModel { @@ -65,9 +86,9 @@ func (m ClientsModel) IsBusy() bool { func (m ClientsModel) Help() []Hotkey { switch m.mode { case clientModeForm: - return []Hotkey{{"tab / shift+tab", "move"}, {"enter", "save"}, {"esc", "cancel"}} + return []Hotkey{{"tab", "next field"}, {"enter", "save"}, {"esc", "cancel"}} case clientModeConfirmDelete: - return []Hotkey{{"y", "confirm"}, {"esc", "cancel"}} + return []Hotkey{{"y", "delete"}, {"esc", "keep"}} default: return []Hotkey{{"n", "new"}, {"e", "edit"}, {"d", "delete"}, {"↑ / ↓", "navigate"}} } @@ -88,6 +109,10 @@ func (m ClientsModel) Update(msg tea.Msg) (ClientsModel, tea.Cmd) { if m.cursor >= len(m.clients) && m.cursor > 0 { m.cursor = len(m.clients) - 1 } + if m.mode == clientModeConfirmDelete && m.clientByID(m.deleteID) == nil { + m.mode = clientModeList + return m, ErrCmd(errClientGone) + } return m, nil case tea.KeyMsg: @@ -122,6 +147,8 @@ func (m ClientsModel) updateList(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { case key.Matches(msg, listKeys.Delete): if len(m.clients) > 0 { m.mode = clientModeConfirmDelete + m.deleteFocused = false + m.deleteID = m.clients[m.cursor].ID } } return m, nil @@ -131,53 +158,100 @@ func (m ClientsModel) updateForm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { switch { case key.Matches(msg, formKeys.Cancel): m.mode = clientModeList - m.formErr = "" + m.errs = nil return m, nil - case key.Matches(msg, formKeys.Submit): - return m.submitForm() - case key.Matches(msg, formKeys.NextField): - m.inputs[m.focusIdx].Blur() - m.focusIdx = (m.focusIdx + 1) % clientFieldCount - m.inputs[m.focusIdx].Focus() - return m, textinput.Blink + return m.focus((m.focusIdx + 1) % clientFocusCount), textinput.Blink case key.Matches(msg, formKeys.PrevField): - m.inputs[m.focusIdx].Blur() - m.focusIdx = (m.focusIdx - 1 + clientFieldCount) % clientFieldCount - m.inputs[m.focusIdx].Focus() - return m, textinput.Blink + return m.focus((m.focusIdx - 1 + clientFocusCount) % clientFocusCount), textinput.Blink + + case key.Matches(msg, formKeys.Submit), msg.String() == " " && m.focusIdx >= clientFieldCount: + if m.focusIdx == clientFieldCancel { + m.mode = clientModeList + m.errs = nil + return m, nil + } + return m.submitForm() + } + if m.focusIdx >= clientFieldCount { + return m, nil } - // forward keystrokes to the focused input + // Typing goes to the focused input, and changing it clears its error. var cmd tea.Cmd + before := m.inputs[m.focusIdx].Value() m.inputs[m.focusIdx], cmd = m.inputs[m.focusIdx].Update(msg) + if m.inputs[m.focusIdx].Value() != before { + delete(m.errs, m.focusIdx) + } return m, cmd } +// focus moves the form's focus to idx: an input or a button. +func (m ClientsModel) focus(idx int) ClientsModel { + for i := range m.inputs { + m.inputs[i].Blur() + } + m.focusIdx = idx + if idx < clientFieldCount { + m.inputs[idx].Focus() + } + return m +} + +// updateConfirm handles the delete confirm: y deletes and esc keeps; tab +// and the arrows move the focus between Delete and Keep it, and enter or +// space presses the focused one. func (m ClientsModel) updateConfirm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { - switch msg.String() { - case "y", "Y": - if len(m.clients) == 0 { - m.mode = clientModeList - return m, nil - } - id := m.clients[m.cursor].ID - if err := m.db.DeleteClient(id); err != nil { - m.mode = clientModeList - return m, ErrCmd(fmt.Sprintf("delete client: %v", err)) - } - m.mode = clientModeList - return m, tea.Batch( - loadClientsCmd(m.db), - loadProjectsData(m.db), - StatusCmd("Client deleted."), - ) + del := false + switch { + case msg.String() == "y", msg.String() == "Y": + del = true + case msg.Type == tea.KeyTab, msg.Type == tea.KeyShiftTab, msg.Type == tea.KeyLeft, msg.Type == tea.KeyRight: + m.deleteFocused = !m.deleteFocused + return m, nil + case msg.Type == tea.KeyEnter, msg.String() == " ": + del = m.deleteFocused + case key.Matches(msg, formKeys.Cancel), msg.String() == "n", msg.String() == "N": + // esc and n keep it, in every tab's confirm. default: - m.mode = clientModeList + return m, nil } - return m, nil + m.mode = clientModeList + if !del { + return m, nil + } + // Checked in the database, not the loaded list: it may be gone + // already, and deleting nothing would still say "deleted". + if _, err := m.db.GetClient(m.deleteID); errors.Is(err, db.ErrNotFound) { + return m, tea.Batch(loadClientsCmd(m.db), ErrCmd(errClientGone)) + } else if err != nil { + return m, ErrCmd(fmt.Sprintf("delete client: %v", err)) + } + if err := m.db.DeleteClient(m.deleteID); err != nil { + return m, ErrCmd(fmt.Sprintf("delete client: %v", err)) + } + return m, tea.Batch( + loadClientsCmd(m.db), + loadProjectsData(m.db), + StatusCmd("Client deleted."), + ) +} + +// errClientGone is the status when the client a delete confirm is for was +// deleted elsewhere while it was open. +const errClientGone = "That client no longer exists" + +// clientByID is the loaded client id, or nil. +func (m ClientsModel) clientByID(id int64) *model.Client { + for _, c := range m.clients { + if c.ID == id { + return c + } + } + return nil } // -- Form helpers ------------------------------------------------------------ @@ -185,8 +259,8 @@ func (m ClientsModel) updateConfirm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { func (m ClientsModel) openForm(c *model.Client) ClientsModel { inputs := make([]textinput.Model, clientFieldCount) - name := makeTextInput("Client name", 120, 36) - rate := makeTextInput("0.00", 12, 36) + name := makeTextInput("Harbor & Pine", 120, theme.FieldWidth) + rate := makeTextInput("0, or a rate like 95", 12, theme.FieldWidth) if c != nil { name.SetValue(c.Name) @@ -200,13 +274,12 @@ func (m ClientsModel) openForm(c *model.Client) ClientsModel { inputs[clientFieldRate] = rate m.inputs = inputs - m.focusIdx = 0 - m.inputs[0].Focus() m.mode = clientModeForm - m.formErr = "" - return m + m.errs = nil + return m.focus(clientFieldName) } +// submitForm saves the client, or puts what needs fixing under its field. func (m ClientsModel) submitForm() (ClientsModel, tea.Cmd) { name := strings.TrimSpace(m.inputs[clientFieldName].Value()) rateStr := strings.TrimSpace(m.inputs[clientFieldRate].Value()) @@ -214,27 +287,40 @@ func (m ClientsModel) submitForm() (ClientsModel, tea.Cmd) { rateStr = "0" } + m.errs = fieldErrors{} if name == "" { - m.formErr = "Client name is required." - return m, nil + m.errs[clientFieldName] = errNameRequired } rate, err := model.ParseRate(rateStr) if err != nil { - m.formErr = "Hourly rate must be a number from 0 to 1,000,000." + m.errs[clientFieldRate] = errRate + } + if len(m.errs) > 0 { return m, nil } if m.editingID == 0 { _, err = m.db.CreateClient(name, rate) } else { + // Saved to the client the form opened for; deleted elsewhere + // meanwhile, the form closes rather than write to nothing. + if _, gerr := m.db.GetClient(m.editingID); errors.Is(gerr, db.ErrNotFound) { + m.mode = clientModeList + m.errs = nil + return m, tea.Batch(loadClientsCmd(m.db), ErrCmd(errClientGone)) + } err = m.db.UpdateClient(&model.Client{ID: m.editingID, Name: name, HourlyRate: rate}) } - if err != nil { - m.formErr = fmt.Sprintf("Save failed: %v", err) + if errors.Is(err, db.ErrClientNameTaken) { + m.errs[clientFieldName] = errClientTaken return m, nil } + if err != nil { + return m, ErrCmd(fmt.Sprintf("Save failed: %v", err)) + } m.mode = clientModeList + m.errs = nil action := "created" if m.editingID != 0 { action = "updated" @@ -246,17 +332,28 @@ func (m ClientsModel) submitForm() (ClientsModel, tea.Cmd) { ) } +// FieldErrors is how many fields of the open form need fixing, for the +// app's status line. +func (m ClientsModel) FieldErrors() int { + if m.mode == clientModeForm { + return len(m.errs) + } + return 0 +} + // -- View -------------------------------------------------------------------- func (m ClientsModel) View() string { + w, h := usableWidth(m.width), max(1, m.height-2) switch m.mode { case clientModeForm: - return m.viewForm() + return modalOver(m.viewList(), w, h, m.viewForm(w, h)) case clientModeConfirmDelete: - return m.viewConfirm() - default: - return m.viewList() + if box := m.viewConfirm(w, h); box != nil { + return modalOver(m.viewList(), w, h, box) + } } + return m.viewList() } // listColWidths returns the NAME and HOURLY RATE column widths so the list @@ -311,50 +408,47 @@ func (m ClientsModel) viewList() string { return sb.String() } -func (m ClientsModel) viewForm() string { - var sb strings.Builder - - title := "New Client" - if m.editingID != 0 { - title = "Edit Client" - } - sb.WriteString(StyleTitle.Render(title) + "\n\n") - - labels := []string{"Name", "Hourly Rate ($)"} - for i, inp := range m.inputs { - refreshInputStyle(&inp) - focused := i == m.focusIdx - var label lipgloss.Style - var inputStyle lipgloss.Style - if focused { - label = StyleFormLabelFocused - inputStyle = StyleFormInputFocused - } else { - label = StyleFormLabel - inputStyle = StyleFormInput +// viewForm is the New client or Edit client modal. +func (m ClientsModel) viewForm(w, h int) []string { + sw := stripWidth(modalInner(theme.ModalWidth, w)) + field := func(label string, idx int) modalField { + return modalField{ + label: label, + focused: m.focusIdx == idx, + mark: m.focusIdx == idx, + strip: true, + value: stripInput(m.inputs[idx], sw), + err: m.errs[idx], } - sb.WriteString(lipgloss.JoinHorizontal(lipgloss.Top, padCellToTwoLines(label.Render(labels[i])), inputStyle.Render(inp.View())) + "\n\n") } - - if m.formErr != "" { - sb.WriteString(StyleDanger.Render("✖ "+m.formErr) + "\n\n") + title := "New client" + if m.editingID != 0 { + title = "Edit client" } - - sb.WriteString(StyleButtonPrimary.Render("Save")) - sb.WriteString(" " + StyleButton.Render("Cancel")) - - return sb.String() + return formModal{ + title: title, + fields: []modalField{field("Name", clientFieldName), field("Rate ($/h)", clientFieldRate)}, + left: []modalButton{ + {label: "Save", kind: buttonPrimary, focused: m.focusIdx == clientFieldSave}, + {label: "Cancel", kind: buttonSecondary, focused: m.focusIdx == clientFieldCancel}, + }, + hint: "tab next · esc close", + }.render(w, h) } -func (m ClientsModel) viewConfirm() string { - if len(m.clients) == 0 { - return "" +// viewConfirm is the delete confirm for the selected client. +func (m ClientsModel) viewConfirm(w, h int) []string { + c := m.clientByID(m.deleteID) + if c == nil { + return nil } - c := m.clients[m.cursor] - // Plain "\n" join, not lipgloss.JoinVertical — see renderConfirmDelete in common.go. - return StyleDanger.Bold(true).Render("Delete \""+c.Name+"\"?") + "\n\n" + - StyleMuted.Render("All projects and time entries for this client will also be deleted.") + "\n\n" + - StyleHelp.Render("y confirm esc cancel") + return confirmModal{ + title: "Delete client?", + name: c.Name, + detail: formatRate(c.HourlyRate), + warning: "Its projects and time entries go too. This can’t be undone.", + deleteFocused: m.deleteFocused, + }.render(w, h) } // padRight pads s with spaces to the given width (rune-aware). diff --git a/internal/ui/views/clients_test.go b/internal/ui/views/clients_test.go index 234ae04..5af04a5 100644 --- a/internal/ui/views/clients_test.go +++ b/internal/ui/views/clients_test.go @@ -8,6 +8,7 @@ import ( "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" ) func newTestDB(t *testing.T) *db.DB { @@ -97,8 +98,11 @@ func TestClientsSubmitForm_BlankNameRejected(t *testing.T) { m.inputs[clientFieldRate].SetValue("50") got, cmd := m.submitForm() - if got.formErr == "" { - t.Error("want a validation error for a blank name") + if got.errs[clientFieldName] != errNameRequired { + t.Errorf("Name error = %q, want %q", got.errs[clientFieldName], errNameRequired) + } + if got.FieldErrors() != 1 { + t.Errorf("FieldErrors() = %d, want 1", got.FieldErrors()) } if got.mode != clientModeForm { t.Errorf("mode after failed validation = %v, want to stay clientModeForm", got.mode) @@ -116,8 +120,11 @@ func TestClientsSubmitForm_InvalidRateRejected(t *testing.T) { m.inputs[clientFieldRate].SetValue(rate) got, cmd := m.submitForm() - if got.formErr == "" { - t.Errorf("rate %q: want a validation error", rate) + if got.errs[clientFieldRate] != errRate { + t.Errorf("rate %q: Rate error = %q, want %q", rate, got.errs[clientFieldRate], errRate) + } + if _, ok := got.errs[clientFieldName]; ok { + t.Errorf("rate %q: the name is fine, but it has an error too", rate) } if cmd != nil { t.Errorf("rate %q: want nil cmd on validation failure", rate) @@ -132,8 +139,8 @@ func TestClientsSubmitForm_BlankRateDefaultsToZero(t *testing.T) { m.inputs[clientFieldRate].SetValue("") got, cmd := m.submitForm() - if got.formErr != "" { - t.Errorf("unexpected validation error: %q", got.formErr) + if len(got.errs) != 0 { + t.Errorf("unexpected validation errors: %v", got.errs) } if cmd == nil { t.Fatal("want a non-nil save cmd on success") @@ -160,8 +167,8 @@ func TestClientsSubmitForm_EditExistingClientUpdatesAndReportsAction(t *testing. m.inputs[clientFieldRate].SetValue("99.00") got, cmd := m.submitForm() - if got.formErr != "" { - t.Fatalf("unexpected validation error: %q", got.formErr) + if len(got.errs) != 0 { + t.Fatalf("unexpected validation errors: %v", got.errs) } if got.mode != clientModeList { t.Errorf("mode after successful edit = %v, want clientModeList", got.mode) @@ -180,7 +187,7 @@ func TestClientsSubmitForm_EditExistingClientUpdatesAndReportsAction(t *testing. } } -func TestClientsSubmitForm_DBErrorSetsFormErr(t *testing.T) { +func TestClientsSubmitForm_DBErrorReportsErrCmd(t *testing.T) { d := newTestDB(t) d.Close() // force CreateClient to fail @@ -189,14 +196,44 @@ func TestClientsSubmitForm_DBErrorSetsFormErr(t *testing.T) { m.inputs[clientFieldRate].SetValue("10") got, cmd := m.submitForm() - if got.formErr == "" { - t.Error("want formErr to be set when the DB save fails") + if got.mode != clientModeForm { + t.Errorf("mode = %v, want the form kept open", got.mode) } - if !strings.Contains(got.formErr, "Save failed:") { - t.Errorf("formErr = %q, want it to start with %q", got.formErr, "Save failed:") + if cmd == nil { + t.Fatal("want an ErrCmd when the DB save fails") } - if cmd != nil { - t.Error("want nil cmd when the DB save fails") + if msg, ok := cmd().(ErrMsg); !ok || !strings.Contains(string(msg), "Save failed:") { + t.Errorf("cmd() = %#v, want an ErrMsg starting %q", cmd(), "Save failed:") + } +} + +func TestClientsSubmitForm_TakenNameIsANameError(t *testing.T) { + d := newTestDB(t) + if _, err := d.CreateClient("Acme", 50); err != nil { + t.Fatal(err) + } + m := ClientsModel{db: d}.openForm(nil) + m.inputs[clientFieldName].SetValue("Acme") + + got, cmd := m.submitForm() + if got.errs[clientFieldName] != errClientTaken || cmd != nil { + t.Errorf("errs = %v, cmd = %v; want %q under Name and no cmd", got.errs, cmd, errClientTaken) + } +} + +func TestClientsUpdateForm_TypingClearsThatFieldsError(t *testing.T) { + m := ClientsModel{}.openForm(nil) + m.inputs[clientFieldRate].SetValue("x") + m, _ = m.submitForm() + if len(m.errs) != 2 { + t.Fatalf("errs = %v, want Name and Rate", m.errs) + } + m, _ = m.updateForm(runeKey('A')) + if _, ok := m.errs[clientFieldName]; ok { + t.Error("typing in Name should clear its error") + } + if m.errs[clientFieldRate] != errRate { + t.Error("typing in Name shouldn't clear Rate's error") } } @@ -209,7 +246,7 @@ func TestClientsUpdateConfirm_YDeletes(t *testing.T) { t.Fatal(err) } - m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, cursor: 0} + m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, cursor: 0, deleteID: c.ID} got, cmd := m.updateConfirm(runeKey('y')) if got.mode != clientModeConfirmDelete && got.mode != clientModeList { t.Fatalf("unexpected mode after 'y': %v", got.mode) @@ -233,7 +270,7 @@ func TestClientsUpdateConfirm_OtherKeyCancels(t *testing.T) { if err != nil { t.Fatal(err) } - m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, cursor: 0} + m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, cursor: 0, deleteID: c.ID} got, cmd := m.updateConfirm(tea.KeyMsg{Type: tea.KeyEsc}) if got.mode != clientModeList { @@ -248,14 +285,27 @@ func TestClientsUpdateConfirm_OtherKeyCancels(t *testing.T) { } } -func TestClientsUpdateConfirm_YWithNoClientsReturnsToList(t *testing.T) { - m := ClientsModel{mode: clientModeConfirmDelete, clients: nil} +func TestClientsUpdateConfirm_YWithTheClientGoneSaysSo(t *testing.T) { + // The loaded list still has the client; the database doesn't. + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 0) + m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, deleteID: c.ID} + if err := d.DeleteClient(c.ID); err != nil { + t.Fatal(err) + } got, cmd := m.updateConfirm(runeKey('y')) if got.mode != clientModeList { t.Errorf("mode = %v, want clientModeList", got.mode) } - if cmd != nil { - t.Error("want nil cmd when confirming delete with no clients loaded") + found := false + for _, msg := range runCmd(t, cmd) { + found = found || msg == ErrMsg(errClientGone) + if s, ok := msg.(StatusMsg); ok { + t.Errorf("status %q for a client already gone", s) + } + } + if !found { + t.Errorf("want %q when the client is gone", errClientGone) } } @@ -267,7 +317,7 @@ func TestClientsUpdateConfirm_YWithDBErrorReportsErrCmd(t *testing.T) { } d.Close() // force DeleteClient to fail - m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, cursor: 0} + m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, cursor: 0, deleteID: c.ID} got, cmd := m.updateConfirm(runeKey('y')) if got.mode != clientModeList { t.Errorf("mode after DB error = %v, want clientModeList", got.mode) @@ -376,8 +426,8 @@ func TestClientsHelp(t *testing.T) { wantKey string wantLabel string }{ - {clientModeForm, "tab / shift+tab", "move"}, - {clientModeConfirmDelete, "y", "confirm"}, + {clientModeForm, "tab", "next field"}, + {clientModeConfirmDelete, "y", "delete"}, {clientModeList, "n", "new"}, } for _, c := range cases { @@ -472,13 +522,13 @@ func TestClientsUpdate_UnrecognizedMsgTypeIsNoop(t *testing.T) { func TestClientsUpdateForm_CancelKey(t *testing.T) { m := ClientsModel{}.openForm(nil) - m.formErr = "some error" + m.errs = fieldErrors{clientFieldName: "some error"} got, cmd := m.updateForm(tea.KeyMsg{Type: tea.KeyEsc}) if got.mode != clientModeList { t.Errorf("mode after cancel = %v, want clientModeList", got.mode) } - if got.formErr != "" { - t.Errorf("formErr after cancel = %q, want empty", got.formErr) + if len(got.errs) != 0 { + t.Errorf("errs after cancel = %v, want none", got.errs) } if cmd != nil { t.Error("want nil cmd on cancel") @@ -490,7 +540,7 @@ func TestClientsUpdateForm_SubmitKeyDispatchesToSubmitForm(t *testing.T) { // leave the name blank so submitForm takes its validation-error path, // which is enough to prove the Submit branch dispatches correctly. got, cmd := m.updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.formErr == "" { + if len(got.errs) == 0 { t.Error("want a validation error to confirm updateForm dispatched to submitForm") } if cmd != nil { @@ -520,25 +570,27 @@ func TestClientsUpdateForm_NextPrevFieldWraps(t *testing.T) { t.Error("want a non-nil blink cmd after tab") } - // tab again: 1 -> 0 (wraps around clientFieldCount) - m, _ = m.updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if m.focusIdx != clientFieldName { - t.Errorf("focusIdx after second tab = %d, want %d (wrapped)", m.focusIdx, clientFieldName) + // tab on through Save and Cancel, then back to Name. + for _, want := range []int{clientFieldSave, clientFieldCancel, clientFieldName} { + m, _ = m.updateForm(tea.KeyMsg{Type: tea.KeyTab}) + if m.focusIdx != want { + t.Errorf("focusIdx after tab = %d, want %d", m.focusIdx, want) + } } - // shift+tab from 0: wraps backward to the last field + // shift+tab from Name wraps back to Cancel. m, cmd2 := m.updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if m.focusIdx != clientFieldRate { - t.Errorf("focusIdx after shift+tab from 0 = %d, want %d (wrapped backward)", m.focusIdx, clientFieldRate) + if m.focusIdx != clientFieldCancel { + t.Errorf("focusIdx after shift+tab from Name = %d, want %d (wrapped backward)", m.focusIdx, clientFieldCancel) } if cmd2 == nil { t.Error("want a non-nil blink cmd after shift+tab") } - // shift+tab again: 1 -> 0 - m, _ = m.updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if m.focusIdx != clientFieldName { - t.Errorf("focusIdx after second shift+tab = %d, want %d", m.focusIdx, clientFieldName) + // enter on Cancel closes the form without saving. + m, _ = m.updateForm(tea.KeyMsg{Type: tea.KeyEnter}) + if m.mode != clientModeList { + t.Errorf("enter on Cancel: mode = %v, want clientModeList", m.mode) } } @@ -583,53 +635,159 @@ func TestClientsView_ListModePopulated(t *testing.T) { func TestClientsView_FormModeNew(t *testing.T) { m := ClientsModel{}.openForm(nil) - m.width = 100 - out := m.View() - for _, want := range []string{"New Client", "Name", "Hourly Rate ($)", "Save", "Cancel"} { + m.width, m.height = 100, 30 + out := ansi.Strip(m.View()) + for _, want := range []string{"New client", "Name", "Rate ($/h)", "Save", "Cancel", "tab next · esc close"} { if !strings.Contains(out, want) { t.Errorf("View() for new-client form missing %q; got %q", want, out) } } } -func TestClientsView_FormModeEditWithErrorAndLastFieldFocused(t *testing.T) { +func TestClientsView_FormModeEditShowsErrorUnderItsField(t *testing.T) { c := &model.Client{ID: 9, Name: "Acme", HourlyRate: 50} m := ClientsModel{}.openForm(c) - m.width = 100 - m.formErr = "Save failed: boom" - // Move focus to the last field — a regression check for the bug where - // Save incorrectly rendered in StyleButtonActive (green) whenever the - // last *field* was focused, confusing it with the Save *button* being - // focused (which this form has no separate state for at all: Enter - // always submits regardless of which field is focused). Save should - // always render as StyleButtonPrimary here. - m.focusIdx = clientFieldCount - 1 - - out := m.View() - for _, want := range []string{"Edit Client", "Save failed: boom", "Save", "Cancel"} { - if !strings.Contains(out, want) { - t.Errorf("View() for edit form missing %q; got %q", want, out) + m.width, m.height = 100, 30 + m.inputs[clientFieldRate].SetValue("lots") + m, _ = m.submitForm() + + lines := strings.Split(ansi.Strip(m.View()), "\n") + rate := -1 + for i, l := range lines { + if strings.Contains(l, "Rate ($/h)") { + rate = i } } + if rate < 0 || rate+1 >= len(lines) || !strings.Contains(lines[rate+1], "✕ "+errRate) { + t.Errorf("want %q on the line under Rate; got %q", "✕ "+errRate, lines) + } + if !strings.Contains(ansi.Strip(m.View()), "Edit client") { + t.Error("want the Edit client title") + } } func TestClientsView_ConfirmModeEmpty(t *testing.T) { - m := ClientsModel{mode: clientModeConfirmDelete} - if out := m.View(); out != "" { - t.Errorf("View() in confirm mode with no clients = %q, want empty string", out) + m := ClientsModel{mode: clientModeConfirmDelete, width: 100, height: 30} + if out := ansi.Strip(m.View()); !strings.Contains(out, "No clients yet.") || strings.Contains(out, "Delete") { + t.Errorf("View() in confirm mode with no clients = %q, want just the list", out) } } func TestClientsView_ConfirmModePopulated(t *testing.T) { m := ClientsModel{ - mode: clientModeConfirmDelete, - cursor: 0, - clients: []*model.Client{{ID: 1, Name: "Acme"}}, - } - out := m.View() - for _, want := range []string{`Delete "Acme"?`, "y confirm esc cancel"} { + mode: clientModeConfirmDelete, + deleteID: 1, + width: 100, + height: 30, + cursor: 0, + clients: []*model.Client{{ID: 1, Name: "Acme", HourlyRate: 95}}, + } + out := ansi.Strip(m.View()) + for _, want := range []string{"Delete client?", "“Acme”", "$95/h", "Its projects and time entries go too.", "Delete", "Keep it", "y / esc"} { if !strings.Contains(out, want) { t.Errorf("View() in confirm mode missing %q; got %q", want, out) } } } + +func TestClientsUpdateConfirm_EnterKeepsUntilDeleteHasFocus(t *testing.T) { + d := newTestDB(t) + c, err := d.CreateClient("Acme", 100) + if err != nil { + t.Fatal(err) + } + m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, deleteID: c.ID} + if got, cmd := m.updateConfirm(tea.KeyMsg{Type: tea.KeyEnter}); got.mode != clientModeList || cmd != nil { + t.Fatalf("enter with Keep it focused: mode %v, cmd %v; want the list and no delete", got.mode, cmd) + } + m, _ = m.updateConfirm(tea.KeyMsg{Type: tea.KeyTab}) + if !m.deleteFocused { + t.Fatal("tab should move the focus to Delete") + } + _, cmd := m.updateConfirm(tea.KeyMsg{Type: tea.KeyEnter}) + if cmd == nil { + t.Fatal("enter with Delete focused should delete") + } + cmd() + if clients, _ := d.ListClients(); len(clients) != 0 { + t.Errorf("clients = %v, want none", clients) + } +} + +// The confirm deletes the client it opened for, even when a reload under +// it moves the cursor onto another; when that client is deleted elsewhere, +// the confirm closes and says so. +func TestClientsConfirm_DeletesTheClientItOpenedFor(t *testing.T) { + d := newTestDB(t) + bravo, _ := d.CreateClient("Bravo", 0) + charlie, _ := d.CreateClient("Charlie", 0) + m := ClientsModel{db: d, clients: []*model.Client{bravo, charlie}, width: 100, height: 30} + m, _ = m.updateList(runeKey('d')) // on Bravo + alpha, _ := d.CreateClient("Alpha", 0) + m, _ = m.Update(clientsLoadedMsg{clients: []*model.Client{alpha, bravo, charlie}}) + if !strings.Contains(ansi.Strip(m.View()), "“Bravo”") { + t.Errorf("the confirm should still name Bravo:\n%s", ansi.Strip(m.View())) + } + _, cmd := m.updateConfirm(runeKey('y')) + if cmd == nil { + t.Fatal("want the delete to run") + } + cmd() + clients, _ := d.ListClients() + for _, c := range clients { + if c.ID == bravo.ID { + t.Error("Bravo is still there") + } + } + if len(clients) != 2 { + t.Errorf("clients = %d, want Alpha and Charlie left", len(clients)) + } + + m = ClientsModel{db: d, clients: []*model.Client{charlie}, width: 100, height: 30} + m, _ = m.updateList(runeKey('d')) // on Charlie, then deleted elsewhere + got, cmd := m.Update(clientsLoadedMsg{clients: []*model.Client{alpha}}) + if got.mode != clientModeList || cmd == nil || cmd() != ErrMsg(errClientGone) { + t.Errorf("mode %v; want the confirm closed with %q when its client is gone", got.mode, errClientGone) + } +} + +// Edit client saves to the client it opened for; when that client is +// deleted elsewhere meanwhile, the form closes and says so, rather than +// reporting a save that wrote nothing. +func TestClientsEditForm_GoneClientClosesTheForm(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 95) + other, _ := d.CreateClient("Beta", 0) + m := ClientsModel{db: d, clients: []*model.Client{c, other}, width: 100, height: 30} + m, _ = m.updateList(listKeyMsg("e")) // on Acme + m, _ = m.Update(clientsLoadedMsg{clients: []*model.Client{other, c}}) + m.inputs[clientFieldName].SetValue("Acme Co") + got, _ := m.submitForm() + if got.mode != clientModeList { + t.Fatalf("mode = %v, errs %v; want it saved", got.mode, got.errs) + } + if a, _ := d.GetClient(c.ID); a.Name != "Acme Co" { + t.Errorf("Acme is now %q, want Acme Co", a.Name) + } + if b, _ := d.GetClient(other.ID); b.Name != "Beta" { + t.Errorf("Beta is now %q, want it untouched", b.Name) + } + + m, _ = m.updateList(listKeyMsg("e")) + if err := d.DeleteClient(m.editingID); err != nil { + t.Fatal(err) + } + got, cmd := m.submitForm() + if got.mode != clientModeList || cmd == nil { + t.Fatalf("mode %v; want the form closed when its client is gone", got.mode) + } + found := false + for _, msg := range runCmd(t, cmd) { + found = found || msg == ErrMsg(errClientGone) + } + if !found { + t.Errorf("want %q", errClientGone) + } +} + +func listKeyMsg(k string) tea.KeyMsg { return runeKey([]rune(k)[0]) } diff --git a/internal/ui/views/common.go b/internal/ui/views/common.go index 197603a..a338e46 100644 --- a/internal/ui/views/common.go +++ b/internal/ui/views/common.go @@ -33,6 +33,7 @@ var ( cBgAlt lipgloss.Color cBorder lipgloss.Color cHighlight lipgloss.Color + cBackdrop lipgloss.Color ) // ── Shared message types ────────────────────────────────────────────────────── @@ -163,16 +164,9 @@ var ( // Forms StyleFormLabel lipgloss.Style - StyleFormLabelFocused lipgloss.Style StyleFormInput lipgloss.Style StyleFormInputFocused lipgloss.Style - // Buttons - StyleButton lipgloss.Style - StyleButtonPrimary lipgloss.Style - StyleButtonActive lipgloss.Style - StyleButtonDanger lipgloss.Style - // Panels — subtle border, no filled background StylePanel lipgloss.Style StylePanelFocused lipgloss.Style @@ -199,6 +193,7 @@ func RefreshTheme() { cBgAlt = theme.Colors.BgAlt cBorder = theme.Colors.Border cHighlight = theme.Colors.Highlight + cBackdrop = theme.Colors.Backdrop // Every style below carries an explicit Background(cBg): each .Render() call // ends with its own SGR reset, so a fragment without a background would show @@ -233,15 +228,13 @@ func RefreshTheme() { // Forms StyleFormLabel = lipgloss.NewStyle().Foreground(cDim).Background(cBg).Width(16).PaddingRight(1) - StyleFormLabelFocused = lipgloss.NewStyle().Foreground(cAccent).Background(cBg).Bold(true).Width(16).PaddingRight(1) StyleFormInput = lipgloss.NewStyle(). Foreground(cText). Background(cBg). Border(lipgloss.NormalBorder(), false, false, true, false). BorderForeground(cBorder). // BorderBackground is a separate property from Background — the - // border glyph itself doesn't inherit it (see renderConfirmModal's - // comment for the same rule), so without this the underline shows + // border glyph itself doesn't inherit it, so without this the underline shows // the terminal's default color instead of cBg. BorderBackground(cBg). Width(40) @@ -253,41 +246,6 @@ func RefreshTheme() { BorderBackground(cBg). Width(40) - // Buttons - StyleButton = lipgloss.NewStyle(). - Foreground(cText). - Background(cSubtle). - Padding(0, 3). - Bold(true) - // Foreground is cBg, not cText: cPrimary/cGreen/cRed are theme accent - // colors, which in a pastel-on-dark theme can be close in brightness to - // cText (light-on-light — poor contrast, and the original bug report - // here). cBg is by construction the theme's darkest color, so it stays - // legible against an accent fill regardless of how light or dark that - // particular theme's accent happens to be — the same reasoning - // StyleButtonActive already relied on before either of these did. - // (A cBgAlt/cSubtle *background* was tried instead at one point, to - // keep cText as the button's foreground — reverted because a theme - // whose "elevated surface" shade sits close to cBg made the button - // visually blend into the page instead of reading as a button. An - // accent-colored fill can't have that problem: cPrimary/cGreen/cRed are - // never close to cBg, unlike cBgAlt in a low-elevation theme.) - StyleButtonPrimary = lipgloss.NewStyle(). - Foreground(cBg). - Background(cPrimary). - Padding(0, 3). - Bold(true) - StyleButtonActive = lipgloss.NewStyle(). - Foreground(cBg). - Background(cGreen). - Padding(0, 3). - Bold(true) - StyleButtonDanger = lipgloss.NewStyle(). - Foreground(cBg). - Background(cRed). - Padding(0, 3). - Bold(true) - // Panels — subtle border, no filled background StylePanel = lipgloss.NewStyle(). Border(lipgloss.RoundedBorder()). @@ -383,16 +341,6 @@ func formatNoteDetail(notes string, width int) string { return StyleTableRow.Render(truncate(notes, max)) } -func renderConfirmDelete(target string, _ int) string { - // Plain "\n" join, not lipgloss.JoinVertical: JoinVertical pads shorter - // lines to the width of the widest one using *unstyled* spaces, which - // would punch a hole in the background between these lines of differing - // width. The outer content column (see app.go) fills the rest correctly. - return StyleDanger.Bold(true).Render("Delete "+target+"?") + "\n\n" + - StyleMuted.Render("This cannot be undone.") + "\n\n" + - StyleHelp.Render("y confirm esc cancel") -} - // ── Modal overlay ───────────────────────────────────────────────────────────── // // Neither bubbletea nor lipgloss ships a modal/dialog widget — this is the @@ -402,27 +350,6 @@ func renderConfirmDelete(target string, _ int) string { // so cutting a styled background line mid-run doesn't corrupt its color // codes on either side of the pasted box. -// renderConfirmModal renders a small bordered "are you sure?" dialog meant to -// be composited over a view with centerOverlay, rather than replacing that -// view's content outright — the table (or form) stays visible around it. -func renderConfirmModal(title string) string { - content := StyleDanger.Bold(true).Render(title) + "\n\n" + - StyleMuted.Render("This cannot be undone.") + "\n\n" + - StyleHelp.Render("y confirm esc cancel") - return lipgloss.NewStyle(). - Background(cBg). - Border(lipgloss.RoundedBorder()). - BorderForeground(cRed). - // BorderBackground is a separate property from Background — the - // border glyphs don't inherit it, so without this the box's own - // border cells show the terminal's default color (see the footer - // border comment in app.go for the same rule). - BorderBackground(cBg). - Width(44). - Padding(2, 4). - Render(content) -} - // overlay composites fg on top of bg at the given (col, row) cell offset. // bg lines shorter than col are padded with plain spaces first; fg rows past // the end of bg are dropped rather than growing the background. diff --git a/internal/ui/views/common_test.go b/internal/ui/views/common_test.go index 2e16317..5a37386 100644 --- a/internal/ui/views/common_test.go +++ b/internal/ui/views/common_test.go @@ -44,8 +44,7 @@ func forceTrueColor(t *testing.T) { // repeatedly: lipgloss.JoinHorizontal/JoinVertical auto-pad a block that's // shorter than its neighbors with genuinely unstyled blank runs, which show // the terminal's own default color instead of the app's background once -// concatenated with properly-styled fragments (see padCellToTwoLines and -// renderConfirmModal's BorderBackground comment for the two variants of it). +// concatenated with properly-styled fragments (see padCellToTwoLines). // // It takes a render callback rather than an already-rendered string: // SetColorProfile only affects .Render() calls made after it, so the target @@ -301,70 +300,6 @@ func withTestPalette(t *testing.T, p theme.Palette) { RefreshTheme() } -// TestButtonStyles_TextStaysLegibleAgainstAccentFill guards against two bugs -// found in the same session: StyleButtonPrimary originally paired a light -// accent fill with light (cText) button text — legible only when the theme's -// accent happened to be darker than its text color, which pastel-on-dark -// themes routinely aren't. The fix mirrors StyleButtonActive's already- -// working pattern (accent background + cBg foreground) rather than -// swapping in a different *background* (e.g. cBgAlt): cBg is the one color a -// theme is guaranteed to keep far from every accent color (an accent that -// didn't contrast with the base background would make the whole desktop -// theme illegible, not just this button), where a "slightly elevated -// surface" shade like cBgAlt is not guaranteed to be far from cBg itself. -func TestButtonStyles_TextStaysLegibleAgainstAccentFill(t *testing.T) { - // A pastel-on-dark palette where every accent sits close in brightness - // to Text — exactly the case that broke the original StyleButtonPrimary. - withTestPalette(t, theme.Palette{ - Primary: "#91b0de", Accent: "#9dc6e9", Success: "#99c2ed", - Warning: "#a4cbf7", Danger: "#c79ea9", Text: "#c2d9e9", - Dim: "#b7d2e5", Subtle: "#899eac", Bg: "#0d171f", - BgAlt: "#0f1720", Border: "#5f6468", Highlight: "#afcfff", - }) - - for _, tt := range []struct { - name string - style lipgloss.Style - fill lipgloss.Color - }{ - {"StyleButtonPrimary", StyleButtonPrimary, cPrimary}, - {"StyleButtonActive", StyleButtonActive, cGreen}, - {"StyleButtonDanger", StyleButtonDanger, cRed}, - } { - if got := tt.style.GetForeground(); got != lipgloss.TerminalColor(cBg) { - t.Errorf("%s.GetForeground() = %v, want cBg (%v)", tt.name, got, cBg) - } - if got := tt.style.GetBackground(); got != lipgloss.TerminalColor(tt.fill) { - t.Errorf("%s.GetBackground() = %v, want its accent fill (%v)", tt.name, got, tt.fill) - } - } -} - -// TestButtonStyles_BackgroundNeverMatchesPageBackground guards against a -// button silently blending into the page: with the fix above in place, this -// mostly re-confirms Primary/Active/Danger are never filled with cBg itself, -// across a theme where the "elevated surface" shade (cBgAlt) sits close -// enough to cBg that using it for a button (an earlier, reverted fix) would -// have made the button hard to spot against the page. -func TestButtonStyles_BackgroundNeverMatchesPageBackground(t *testing.T) { - withTestPalette(t, theme.Palette{ - Primary: "#668691", Accent: "#afe6ea", Success: "#a3cdc8", - Warning: "#cdfef3", Danger: "#849d8e", Text: "#e5e4e8", - Dim: "#acabae", Subtle: "#5d6466", Bg: "#020d10", - BgAlt: "#0a0f11", Border: "#5d6466", Highlight: "#749daa", - }) - - for name, sty := range map[string]lipgloss.Style{ - "StyleButtonPrimary": StyleButtonPrimary, - "StyleButtonActive": StyleButtonActive, - "StyleButtonDanger": StyleButtonDanger, - } { - if got := sty.GetBackground(); got == lipgloss.TerminalColor(cBg) { - t.Errorf("%s.GetBackground() = %v, matches cBg — button would be invisible against the page", name, got) - } - } -} - // The report columns reserve theme.Gutter columns for the row cursor, so // RowPrefix must render exactly that wide in both states. func TestRowPrefix_WidthMatchesGutterToken(t *testing.T) { diff --git a/internal/ui/views/keys.go b/internal/ui/views/keys.go new file mode 100644 index 0000000..200c7ce --- /dev/null +++ b/internal/ui/views/keys.go @@ -0,0 +1,139 @@ +package views + +// The ? keys sheet (ALI-2616), drawn from the design canvas's Keys board: +// every key, grouped by tab, in a modal over the dimmed screen. The hotkey +// line then only needs the keys used most. + +import ( + "strings" + + "github.com/aliasproject/notch/internal/theme" +) + +type keyGroup struct { + title string + keys []Hotkey +} + +// keyGroups lists every key by where it works. +func keyGroups() []keyGroup { + return []keyGroup{ + {"Everywhere", []Hotkey{{"1 2 3 4", "switch tab"}, {"?", "this help"}, {"q", "quit"}}}, + {"Timers", []Hotkey{ + {"n", "new timer"}, {"space", "start / stop"}, {"r", "resume entry"}, + {"e", "edit"}, {"i", "toggle invoiced"}, {"p", "toggle paid"}, + {"d", "delete"}, {"enter", "details"}, + }}, + {"Ranges", []Hotkey{ + {"t", "today"}, {"y", "yesterday"}, {"w", "this week"}, + {"m", "this month"}, {"a", "all time"}, {"f", "custom range"}, + }}, + {"Projects", []Hotkey{{"n", "new project"}, {"e", "edit"}, {"d", "delete"}}}, + {"Clients", []Hotkey{{"n", "new client"}, {"e", "edit"}, {"d", "delete"}}}, + {"Reports", []Hotkey{ + {"enter", "show entries"}, {"e", "edit entry"}, {"f", "custom range"}, + {"t w m", "day, week, month"}, {"y a", "year, all time"}, + }}, + {"Forms", []Hotkey{ + {"tab", "next field"}, {"shift+tab", "previous field"}, {"↑ ↓", "suggestions"}, + {"space", "toggle"}, {"enter", "save"}, {"esc", "cancel"}, + }}, + } +} + +// keySheetColumns lays the groups out in cols columns, in order, each +// column as close to an even share of the rows as whole groups allow. +func keySheetColumns(cols int) [][]string { + groups := keyGroups() + rendered := make([][]string, len(groups)) + total := 0 + for i, g := range groups { + lines := []string{renderSegs(cBg, seg{s: fit(strings.ToUpper(g.title), theme.KeysCol), fg: cAccent, bold: true})} + for _, k := range g.keys { + cap := " " + k.Key + " " + lines = append(lines, renderSegs(cBg, + seg{s: cap, bg: cBgAlt, bold: true}, + seg{s: strings.Repeat(" ", max(1, theme.KeysCap+1-len([]rune(cap))))}, + seg{s: fit(k.Label, max(0, theme.KeysCol-theme.KeysCap-1)), fg: cDim}, + )) + } + rendered[i] = lines + total += len(lines) + 1 + } + target := (total + cols - 1) / cols + out := make([][]string, 1, cols) + for _, lines := range rendered { + cur := &out[len(out)-1] + if len(*cur) > 0 && len(*cur)+1+len(lines) > target && len(out) < cols { + out = append(out, nil) + cur = &out[len(out)-1] + } + if len(*cur) > 0 { + *cur = append(*cur, blankLine(theme.KeysCol)) + } + *cur = append(*cur, lines...) + } + return out +} + +// keySheetRows is the sheet's content for a body w wide: rows inner cells +// wide, as many columns as fit (up to tui-keys-cols). +func keySheetRows(w int) (rows []string, inner int) { + cols := theme.KeysCols + width := func(c int) int { return 2*theme.ModalIndent + c*theme.KeysCol + (c-1)*theme.KeysGap } + for cols > 1 && width(cols)+2 > w { + cols-- + } + inner = min(width(cols), w-2) + columns := keySheetColumns(cols) + n := 0 + for _, c := range columns { + n = max(n, len(c)) + } + for i := 0; i < n; i++ { + line := blankLine(theme.ModalIndent) + for j, c := range columns { + if j > 0 { + line += blankLine(theme.KeysGap) + } + if i < len(c) { + line += padTo(c[i], theme.KeysCol) + } else { + line += blankLine(theme.KeysCol) + } + } + rows = append(rows, padTo(line, inner)) + } + return rows, inner +} + +// KeySheetRows is how many rows the sheet's keys take in a body w wide, +// so the app can tell how far it scrolls. +func KeySheetRows(w int) int { + rows, _ := keySheetRows(w) + return len(rows) +} + +// WithKeySheet draws the keys sheet over body, dimmed to w×h. When the +// sheet is taller than the body it starts offset rows down, and its last +// row says there's more. +func WithKeySheet(body string, w, h, offset int) string { + rows, inner := keySheetRows(w) + room := max(1, h-2) + var box []boxRow + if len(rows) <= room { + box = append(box, boxRow{blankLine(inner), dropMargin}) + for _, r := range rows { + box = append(box, boxRow{r, dropKeep}) + } + box = append(box, boxRow{blankLine(inner), dropMargin}) + } else { + offset = max(0, min(offset, len(rows)-(room-1))) + for _, r := range rows[offset:min(len(rows), offset+room-1)] { + box = append(box, boxRow{r, dropKeep}) + } + more := "↑↓ scroll" + box = append(box, boxRow{padTo(blankLine(theme.ModalIndent)+renderSegs(cBg, seg{s: more, fg: cSubtle}), inner), dropKeep}) + } + return modalOver(body, w, h, modalFrame("Keys", cText, cPrimary, inner, fitRows(box, room))) +} diff --git a/internal/ui/views/modal.go b/internal/ui/views/modal.go new file mode 100644 index 0000000..a0ad4fa --- /dev/null +++ b/internal/ui/views/modal.go @@ -0,0 +1,439 @@ +package views + +// Modals (ALI-2616), drawn from the design canvas's "Redesign · TUI" +// boards (New timer, Edit entry, Delete, Keys): a box centred over the +// screen it came from, with that screen redrawn behind it as plain text in +// backdrop, so it reads as inactive. +// +// A form modal puts each field on a bg_alt strip after its label. The +// focused field's label turns primary and a primary ▌ (theme.GlyphCursor) +// sits before its strip; a field with an error has a danger label and +// "✕ message" under it, and the app's status line counts them. Buttons are +// primary (bg on primary) or secondary (text on bg_alt), and the focused +// one has the same ▌ before it, so focus never rests on colour alone. + +import ( + "fmt" + "strings" + + "github.com/aliasproject/notch/internal/theme" + "github.com/charmbracelet/bubbles/textinput" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" +) + +// fieldErrors maps a form's field (its index) to what's wrong with it. +type fieldErrors map[int]string + +// FixingText is the status line's count of a form's field errors. +func FixingText(n int) string { + if n == 1 { + return "1 field needs fixing" + } + return fmt.Sprintf("%d fields need fixing", n) +} + +// ── Backdrop ────────────────────────────────────────────────────────────────── + +// dimBackdrop redraws body as plain text in backdrop on bg, exactly w×h +// cells: lines past h are dropped, short ones padded. +func dimBackdrop(body string, w, h int) string { + lines := strings.Split(body, "\n") + st := lipgloss.NewStyle().Foreground(cBackdrop).Background(cBg) + out := make([]string, max(0, h)) + for i := range out { + var plain string + if i < len(lines) { + plain = ansi.Truncate(ansi.Strip(lines[i]), w, "") + } + out[i] = st.Render(plain + strings.Repeat(" ", max(0, w-ansi.StringWidth(plain)))) + } + return strings.Join(out, "\n") +} + +// modalOver draws box centred over body, dimmed to w×h. +func modalOver(body string, w, h int, box []string) string { + return centerOverlay(dimBackdrop(body, w, h), strings.Join(box, "\n")) +} + +// padTo pads a styled line with bg to w cells. It doesn't cut. +func padTo(s string, w int) string { + return s + blankLine(w-ansi.StringWidth(s)) +} + +// ── Frame ───────────────────────────────────────────────────────────────────── + +// modalFrame wraps rows, each inner cells wide, in a rounded border in edge +// with title (bold, in titleFg) set into its top edge. +func modalFrame(title string, titleFg, edge lipgloss.Color, inner int, rows []string) []string { + title = truncate(title, max(1, inner-4)) + out := []string{renderSegs(cBg, + seg{s: "╭─", fg: edge}, + seg{s: " " + title + " ", fg: titleFg, bold: true}, + seg{s: strings.Repeat("─", max(0, inner-ansi.StringWidth(title)-3)) + "╮", fg: edge}, + )} + side := renderSegs(cBg, seg{s: "│", fg: edge}) + for _, r := range rows { + out = append(out, side+r+side) + } + return append(out, renderSegs(cBg, seg{s: "╰" + strings.Repeat("─", inner) + "╯", fg: edge})) +} + +// fitRows drops rows, highest rank first and the last of a rank first, +// until no more than n are left or only rank-0 rows remain. +func fitRows(rows []boxRow, n int) []string { + keep := fitIndexes(rows, n) + out := make([]string, len(keep)) + for i, k := range keep { + out[i] = rows[k].s + } + return out +} + +// fitIndexes is fitRows's choice: the indexes of the rows it keeps. +func fitIndexes(rows []boxRow, n int) []int { + keep := make([]int, len(rows)) + for i := range keep { + keep[i] = i + } + for len(keep) > n { + at := -1 + for i, k := range keep { + if d := rows[k].drop; d > 0 && (at < 0 || d >= rows[keep[at]].drop) { + at = i + } + } + if at < 0 { + break + } + keep = append(keep[:at], keep[at+1:]...) + } + return keep +} + +// Drop ranks for modal rows, highest first: the blank rows at the top and +// bottom, then field hints, then the blank rows between fields. +const ( + dropKeep = 0 + dropGap = 1 + dropHint = 2 + dropMargin = 3 +) + +// ── Buttons ─────────────────────────────────────────────────────────────────── + +type buttonKind int + +const ( + buttonPrimary buttonKind = iota // bg on primary + buttonSecondary // text on bg_alt + buttonDanger // danger on bg_alt + buttonDangerFilled // bg on danger +) + +type modalButton struct { + label string + kind buttonKind + focused bool +} + +// focusMark is the cell before a focused field or button: the cursor glyph +// in primary, or a blank. +func focusMark(on bool) seg { + if on { + return seg{s: theme.GlyphCursor, fg: cPrimary} + } + return seg{s: " "} +} + +// segs is the button with its focus mark before it. +func (b modalButton) segs() []seg { + fg, bg := cBg, cPrimary + switch b.kind { + case buttonSecondary: + fg, bg = cText, cBgAlt + case buttonDanger: + fg, bg = cRed, cBgAlt + case buttonDangerFilled: + fg, bg = cBg, cRed + } + return []seg{focusMark(b.focused), {s: " " + b.label + " ", fg: fg, bg: bg, bold: true}} +} + +// buttonRow lays out left from the modal's indent, each button after a +// one-cell gap and its focus mark, and right (buttons, or a hint in subtle) +// against the right indent. +func buttonRow(inner int, left, right []modalButton, hint string) string { + var l []seg + l = append(l, seg{s: strings.Repeat(" ", theme.ModalIndent-2)}) + for _, b := range left { + l = append(l, seg{s: " "}) + l = append(l, b.segs()...) + } + var r []seg + for _, b := range right { + r = append(r, b.segs()...) + } + if hint != "" && segsWidth(l)+segsWidth(r)+len(hint)+2 <= inner-theme.ModalIndent { + r = append(r, seg{s: hint, fg: cSubtle}) + } + r = append(r, seg{s: strings.Repeat(" ", theme.ModalIndent)}) + return spread(inner, cBg, l, r) +} + +// ── Form modal ──────────────────────────────────────────────────────────────── + +// modalField is one row of a form modal. +type modalField struct { + label string + focused bool // the label turns primary + mark bool // a ▌ before the field (focused, and not a row of toggles) + value string // styled; sits on a bg_alt strip when strip is set + strip bool + err string // "✕ err" under the field, in danger + hint string // a hint under the field, in subtle + // suggests marks a field that can open suggestions: the modal keeps + // room under it for them, open or not. suggest, when set, draws the + // open box in at most n rows. + suggests bool + suggest func(n int) []string +} + +type formModal struct { + title string + fields []modalField + left []modalButton + right []modalButton + hint string // subtle, at the right end of the button row + err string // a problem with the whole form, above the buttons +} + +// modalInner is a modal's width inside its border, for a body w wide. +func modalInner(want, w int) int { + return max(theme.ModalMinWidth, min(want, w)) - 2 +} + +// fieldCol is where a form modal's fields start: after the indent, the +// label column and the focus mark. +func fieldCol() int { return theme.ModalIndent + theme.ModalLabel + 1 } + +// stripWidth is the width of a field's bg_alt strip in a modal inner wide. +func stripWidth(inner int) int { + return max(theme.StripMin, inner-fieldCol()-theme.ModalIndent) +} + +// render draws the modal for a body w×h: as wide as tui-modal-width allows, +// with spacing dropped until it fits in h rows where it can. +// +// Suggestions float over the rows under their field, down to the button +// row, rather than pushing them down: the box keeps its size and place +// while they open and close, and the buttons and border always show. +func (fm formModal) render(w, h int) []string { + inner := modalInner(theme.ModalWidth, w) + sw := stripWidth(inner) + indent := blankLine(theme.ModalIndent) + textCol := blankLine(fieldCol() + 1) + + rows := []boxRow{{blankLine(inner), dropMargin}} + suggestAt, buttonsAt, roomFrom := -1, -1, -1 + var suggest func(int) []string + for i, f := range fm.fields { + if i > 0 { + rows = append(rows, boxRow{blankLine(inner), dropGap}) + } + labelFg := cAccent + switch { + case f.err != "": + labelFg = cRed + case f.focused: + labelFg = cPrimary + } + label := renderSegs(cBg, seg{s: fit(f.label, theme.ModalLabel), fg: labelFg, bold: true}, focusMark(f.mark)) + value := f.value + if f.strip { + value = padStrip(value, sw) + } + if f.suggest != nil { + suggestAt, suggest = len(rows), f.suggest + } + if f.suggests { + roomFrom = len(rows) + 1 + } + rows = append(rows, boxRow{padTo(indent+label+value, inner), dropKeep}) + if f.err != "" { + // An error wraps rather than cuts: it's the one thing on the + // row that has to be read whole. + for i, l := range wrapWords(f.err, inner-fieldCol()-3-theme.ModalIndent) { + mark := "✕ " + if i > 0 { + mark = " " + } + rows = append(rows, boxRow{padTo(textCol+renderSegs(cBg, seg{s: mark + l, fg: cRed}), inner), dropKeep}) + } + } + if f.hint != "" { + hint := truncate(f.hint, inner-fieldCol()-1-theme.ModalIndent) + rows = append(rows, boxRow{padTo(textCol+renderSegs(cBg, seg{s: hint, fg: cSubtle}), inner), dropHint}) + } + } + // Room for a full suggestions box under the last field that has one, + // so it never needs to cover the buttons. + if roomFrom >= 0 { + for n := len(rows) + 1 - roomFrom; n < theme.SuggestRows+3; n++ { + rows = append(rows, boxRow{blankLine(inner), dropGap}) + } + } + rows = append(rows, boxRow{blankLine(inner), dropGap}) + if fm.err != "" { + for i, l := range wrapWords(fm.err, inner-2*theme.ModalIndent-2) { + mark := "✕ " + if i > 0 { + mark = " " + } + rows = append(rows, boxRow{padTo(indent+renderSegs(cBg, seg{s: mark + l, fg: cRed}), inner), dropKeep}) + } + } + buttonsAt = len(rows) + rows = append(rows, + boxRow{buttonRow(inner, fm.left, fm.right, fm.hint), dropKeep}, + boxRow{blankLine(inner), dropMargin}, + ) + keep := fitIndexes(rows, h-2) + out := make([]string, len(keep)) + from, to := -1, -1 + for i, k := range keep { + out[i] = rows[k].s + switch k { + case suggestAt: + from = i + 1 + case buttonsAt: + to = i + } + } + if suggest != nil && from > 0 && to > from { + box := suggest(to - from) + body := overlay(strings.Join(out, "\n"), strings.Join(box, "\n"), fieldCol(), from) + out = strings.Split(body, "\n") + } + return modalFrame(fm.title, cText, cPrimary, inner, out) +} + +// padStrip sets a field's styled value on a bg_alt strip w cells wide, +// one cell in. +func padStrip(value string, w int) string { + pad := lipgloss.NewStyle().Background(cBgAlt) + return pad.Render(" ") + value + pad.Render(strings.Repeat(" ", max(0, w-1-ansi.StringWidth(value)))) +} + +// stripInput renders a text input for a strip w cells wide: on bg_alt, its +// placeholder in subtle, scrolled so the cursor stays inside the strip. +func stripInput(ti textinput.Model, w int) string { + ti.PromptStyle = lipgloss.NewStyle().Background(cBgAlt) + ti.TextStyle = lipgloss.NewStyle().Foreground(cText).Background(cBgAlt) + ti.PlaceholderStyle = lipgloss.NewStyle().Foreground(cSubtle).Background(cBgAlt) + ti.Cursor.Style = lipgloss.NewStyle().Foreground(cText).Background(cBgAlt) + ti.Cursor.TextStyle = lipgloss.NewStyle().Foreground(cText).Background(cBgAlt) + // textinput draws Width cells plus one for a cursor at the end, and the + // strip keeps a cell of padding on its left. + // + // The width is only known here, but the input scrolled by the width it + // had when typed into, so its window may not hold the cursor at this + // one. Recompute it, on this copy: a window ending at the text's end, + // or, when the cursor is left of that, one starting a quarter of the + // strip before the cursor, so there's text to read on both sides. + pos := ti.Position() + ti.Width = 0 + ti.CursorEnd() + ti.Width = max(1, w-3) + ti.CursorEnd() + ti.SetCursor(max(0, pos-ti.Width/4)) + ti.SetCursor(pos) + v := trimTrailingUnstyledPad(ti.View()) + if ansi.StringWidth(v) > w-1 { + v = ansi.Truncate(v, w-1, "") + } + return v +} + +// toggle renders a checkbox, its focus mark before it. +func toggle(label string, on, focused bool) string { + box := "[ ] " + if on { + box = "[x] " + } + return renderSegs(cBg, focusMark(focused), seg{s: box + label}) +} + +// suggestions draws the box under a Client or Project field in at most +// maxRows rows: the items (the selected one in bg on primary), and how to +// choose. It shows at most tui-suggest-rows items, fewer when maxRows is +// short (the hint goes first), scrolled to keep the selection in view. +func suggestions(items []dropdownItem, sel, fieldW, maxRows int) []string { + if maxRows < 3 || len(items) == 0 { + return nil + } + w := min(theme.SuggestWidth, fieldW) + inner := w - 2 + n := min(theme.SuggestRows, len(items)) + hint := maxRows-3 >= 1 + if hint { + n = min(n, maxRows-3) + } else { + n = min(n, maxRows-2) + } + start := max(0, min(sel-n/2, len(items)-n)) + end := min(len(items), start+n) + edge := seg{s: "│", fg: cBorder} + out := []string{renderSegs(cBg, seg{s: "╭" + strings.Repeat("─", inner) + "╮", fg: cBorder})} + for i := start; i < end; i++ { + item := seg{s: fit(" "+items[i].label, inner), fg: cDim} + if i == sel { + // The glyph marks it too, so the selection isn't colour alone. + item = seg{s: fit(theme.GlyphCursor+" "+items[i].label, inner), fg: cBg, bg: cPrimary, bold: true} + } + out = append(out, renderSegs(cBg, edge, item, edge)) + } + if hint { + out = append(out, renderSegs(cBg, edge, seg{s: fit(" ↑↓ choose · enter pick", inner), fg: cSubtle}, edge)) + } + return append(out, renderSegs(cBg, seg{s: "╰" + strings.Repeat("─", inner) + "╯", fg: cBorder})) +} + +// ── Delete confirm ──────────────────────────────────────────────────────────── + +// confirmModal is a delete confirm: a danger border and title, what goes +// (name in bold, detail in dim), what else goes with it, and Delete and +// Keep it. y deletes and esc keeps, whichever button has focus. +type confirmModal struct { + title, name, detail, warning string + deleteFocused bool +} + +func (c confirmModal) render(w, h int) []string { + inner := modalInner(theme.ConfirmWidth, w) + text := func(s string, fg lipgloss.Color, bold bool) string { + return padTo(blankLine(theme.ModalIndent)+renderSegs(cBg, seg{s: truncate(s, inner-2*theme.ModalIndent), fg: fg, bold: bold}), inner) + } + rows := []boxRow{ + {blankLine(inner), dropMargin}, + {text("“"+c.name+"”", cText, true), dropKeep}, + } + if c.detail != "" { + rows = append(rows, boxRow{text(c.detail, cDim, false), dropKeep}) + } + rows = append(rows, + boxRow{blankLine(inner), dropGap}, + ) + for _, l := range wrapWords(c.warning, inner-2*theme.ModalIndent) { + rows = append(rows, boxRow{text(l, cSubtle, false), dropKeep}) + } + rows = append(rows, + boxRow{blankLine(inner), dropGap}, + boxRow{buttonRow(inner, []modalButton{ + {label: "Delete", kind: buttonDangerFilled, focused: c.deleteFocused}, + {label: "Keep it", kind: buttonSecondary, focused: !c.deleteFocused}, + }, nil, "y / esc"), dropKeep}, + boxRow{blankLine(inner), dropMargin}, + ) + return modalFrame(c.title, cRed, cRed, inner, fitRows(rows, h-2)) +} diff --git a/internal/ui/views/projects.go b/internal/ui/views/projects.go index bcb1c2f..fbd5bbf 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -1,7 +1,7 @@ package views import ( - "fmt" + "errors" "strings" "github.com/aliasproject/notch/internal/db" @@ -10,7 +10,6 @@ import ( "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" ) type projectsMode int @@ -26,7 +25,21 @@ const ( const ( projFieldClient = iota projFieldName - projFieldCount + projFieldCount // the inputs +) + +// The form's buttons, after its inputs in tab order. +const ( + projFieldSave = projFieldCount + iota + projFieldCancel + projFocusCount +) + +// The project form's messages, shared with the tests. +const ( + errPickClient = "Pick a client." + errPickListClient = "Pick a client from the list." + errProjectTaken = "That client already has a project with that name." ) // listColWidths returns the PROJECT and CLIENT column widths so the list @@ -66,8 +79,19 @@ type ProjectsModel struct { clientSel int showClientDrop bool - deleteTarget string - err string + // errs holds the form's field errors; err, a message for the list. + errs fieldErrors + err string + + // deleteFocused: Delete has the focus in the delete confirm (Keep it + // has it at first). deleteID is the project it's for, kept from when + // it opened, so a reload under it can't change what's deleted. + deleteFocused bool + deleteID int64 + + // editingID is the project Edit project opened for: it saves to that + // one, never to the row under the cursor at save time. + editingID int64 } func NewProjects(database *db.DB) ProjectsModel { @@ -88,14 +112,13 @@ func (m ProjectsModel) IsBusy() bool { func (m ProjectsModel) Help() []Hotkey { switch m.mode { case projectsModeNewProject, projectsModeEditProject: - return []Hotkey{ - {"tab / shift+tab", "move"}, - {"↑ / ↓", "dropdown"}, - {"enter", "save"}, - {"esc", "cancel"}, + keys := []Hotkey{{"tab", "next field"}} + if m.focusedInput == projFieldClient { + keys = append(keys, Hotkey{"↑↓", "suggestions"}) } + return append(keys, Hotkey{"enter", "save"}, Hotkey{"esc", "cancel"}) case projectsModeConfirmDelete: - return []Hotkey{{"y", "confirm"}, {"esc", "cancel"}} + return []Hotkey{{"y", "delete"}, {"esc", "keep"}} default: return []Hotkey{{"n", "new"}, {"e", "edit"}, {"d", "delete"}} } @@ -143,6 +166,10 @@ func (m ProjectsModel) Update(msg tea.Msg) (ProjectsModel, tea.Cmd) { m.cursor = len(m.projects) - 1 } m.err = "" + if m.mode == projectsModeConfirmDelete && m.projectByID(m.deleteID) == nil { + m.mode = projectsModeList + return m, ErrCmd(errProjectGone) + } return m, nil case tea.KeyMsg: @@ -174,10 +201,9 @@ func (m ProjectsModel) updateList(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { m.mode = projectsModeNewProject m.inputs = makeProjectInputs(nil, "") m.clientID = 0 - m.focusedInput = projFieldClient - m.inputs[projFieldClient].Focus() + m.errs = nil + m = m.focus(projFieldClient) m.rebuildClientMatches() - m.showClientDrop = len(m.clientMatches) > 0 m.err = "" case key.Matches(msg, projectsKeys.Edit): @@ -188,18 +214,19 @@ func (m ProjectsModel) updateList(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { m.clientID = p.Client.ID } m.mode = projectsModeEditProject + m.editingID = p.ID m.inputs = makeProjectInputs(p, clientName) - m.focusedInput = projFieldClient - m.inputs[projFieldClient].Focus() + m.errs = nil + m = m.focus(projFieldClient) m.rebuildClientMatches() - m.showClientDrop = false m.err = "" } case key.Matches(msg, projectsKeys.Delete): if p := m.selectedProject(); p != nil { m.mode = projectsModeConfirmDelete - m.deleteTarget = fmt.Sprintf("project \"%s\"", p.Name) + m.deleteFocused = false + m.deleteID = p.ID } } return m, nil @@ -207,137 +234,201 @@ func (m ProjectsModel) updateList(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { func (m ProjectsModel) updateForm(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { if m.mode == projectsModeConfirmDelete { - switch msg.String() { - case "y", "Y": - return m.doDelete() - case "n", "N", "esc": - m.mode = projectsModeList - } - return m, nil - } - - // Client dropdown navigation while the client field is focused - if m.focusedInput == projFieldClient { - switch { - case msg.Type == tea.KeyUp: - if m.clientSel > 0 { - m.clientSel-- - } - m.showClientDrop = true - return m, nil - case msg.Type == tea.KeyDown: - if m.clientSel < len(m.clientMatches)-1 { - m.clientSel++ - } - m.showClientDrop = true - return m, nil - } + return m.updateConfirm(msg) } switch { + case key.Matches(msg, projectsKeys.Cancel): + m.mode = projectsModeList + m.errs = nil + return m, nil + + case m.focusedInput == projFieldClient && (msg.Type == tea.KeyUp || msg.Type == tea.KeyDown): + m.clientSel = moveSel(m.clientSel, len(m.clientMatches), msg.Type == tea.KeyUp, m.showClientDrop) + m.showClientDrop = len(m.clientMatches) > 0 + return m, nil + case key.Matches(msg, projectsKeys.Confirm): - if m.focusedInput == projFieldClient { + switch { + case m.focusedInput == projFieldClient && m.showClientDrop: + // enter picks the suggestion and moves on to Name. m.applyClientSelection() - m.inputs[projFieldClient].Blur() - m.focusedInput = projFieldName - m.inputs[projFieldName].Focus() - m.showClientDrop = false + return m.focus(projFieldName), nil + case m.focusedInput == projFieldCancel: + m.mode = projectsModeList + m.errs = nil return m, nil } + m = m.leave() return m.saveForm() - case key.Matches(msg, projectsKeys.Cancel): - m.mode = projectsModeList - m.err = "" - return m, nil + case msg.String() == " " && m.focusedInput >= projFieldCount: + if m.focusedInput == projFieldCancel { + m.mode = projectsModeList + m.errs = nil + return m, nil + } + return m.saveForm() case key.Matches(msg, projectsKeys.NextField): - m.inputs[m.focusedInput].Blur() - if m.focusedInput == projFieldClient { - m.focusedInput = projFieldName - } else { - m.focusedInput = projFieldClient - } - m.inputs[m.focusedInput].Focus() - m.rebuildClientMatches() - m.showClientDrop = m.focusedInput == projFieldClient && len(m.clientMatches) > 0 - return m, nil + return m.leave().focus((m.focusedInput + 1) % projFocusCount), nil case key.Matches(msg, projectsKeys.PrevField): - m.inputs[m.focusedInput].Blur() - if m.focusedInput == projFieldName { - m.focusedInput = projFieldClient - } else { - m.focusedInput = projFieldName - } - m.inputs[m.focusedInput].Focus() - m.rebuildClientMatches() - m.showClientDrop = m.focusedInput == projFieldClient && len(m.clientMatches) > 0 + return m.leave().focus((m.focusedInput - 1 + projFocusCount) % projFocusCount), nil + } + if m.focusedInput >= projFieldCount { return m, nil + } - default: - var cmd tea.Cmd - m.inputs[m.focusedInput], cmd = m.inputs[m.focusedInput].Update(msg) - if m.focusedInput == projFieldClient { - m.clientID = 0 - m.rebuildClientMatches() - m.showClientDrop = len(m.clientMatches) > 0 - } + var cmd tea.Cmd + before := m.inputs[m.focusedInput].Value() + m.inputs[m.focusedInput], cmd = m.inputs[m.focusedInput].Update(msg) + if m.inputs[m.focusedInput].Value() == before { return m, cmd } + delete(m.errs, m.focusedInput) + if m.focusedInput == projFieldClient { + m.clientID, m.clientSel = 0, 0 + m.rebuildClientMatches() + m.showClientDrop = strings.TrimSpace(m.inputs[projFieldClient].Value()) != "" && len(m.clientMatches) > 0 + } + return m, cmd +} + +// leave finishes the focused field before the focus moves or the form is +// saved: open suggestions in Client pick the highlighted client. +func (m ProjectsModel) leave() ProjectsModel { + if m.focusedInput == projFieldClient && m.showClientDrop { + m.applyClientSelection() + } + m.showClientDrop = false + return m +} + +// focus moves the form's focus to idx: an input or a button. +func (m ProjectsModel) focus(idx int) ProjectsModel { + for i := range m.inputs { + m.inputs[i].Blur() + } + m.focusedInput = idx + if idx < projFieldCount { + m.inputs[idx].Focus() + } + m.showClientDrop = false + return m } +// updateConfirm handles the delete confirm: y deletes and esc keeps; tab +// and the arrows move the focus between Delete and Keep it, and enter or +// space presses the focused one. +func (m ProjectsModel) updateConfirm(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { + switch { + case msg.String() == "y", msg.String() == "Y": + return m.doDelete() + case msg.Type == tea.KeyTab, msg.Type == tea.KeyShiftTab, msg.Type == tea.KeyLeft, msg.Type == tea.KeyRight: + m.deleteFocused = !m.deleteFocused + case msg.Type == tea.KeyEnter, msg.String() == " ": + if m.deleteFocused { + return m.doDelete() + } + m.mode = projectsModeList + case key.Matches(msg, projectsKeys.Cancel), msg.String() == "n", msg.String() == "N": + m.mode = projectsModeList + } + return m, nil +} + +// saveForm saves the project, or puts what needs fixing under its field. func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { + m.errs = fieldErrors{} name := strings.TrimSpace(m.inputs[projFieldName].Value()) if name == "" { - m.err = "Name is required" - return m, nil + m.errs[projFieldName] = errNameRequired } if err := m.resolveClientID(); err != nil { - m.err = err.Error() + m.errs[projFieldClient] = err.Error() + } + if len(m.errs) > 0 { return m, nil } + var err error + status := "Project created" switch m.mode { case projectsModeNewProject: - _, err := m.db.CreateProject(m.clientID, name) - if err != nil { - m.err = err.Error() - return m, nil - } - m.mode = projectsModeList - return m, tea.Batch(loadProjectsData(m.db), StatusCmd("Project created")) - + _, err = m.db.CreateProject(m.clientID, name) case projectsModeEditProject: - p := m.selectedProject() - if p == nil { + // Saved to the project the form opened for. A fresh copy, so a + // refused rename doesn't show in the list; deleted elsewhere + // meanwhile, the form closes. + p, gerr := m.db.GetProject(m.editingID) + if errors.Is(gerr, db.ErrNotFound) { m.mode = projectsModeList - return m, nil + m.errs = nil + return m, tea.Batch(loadProjectsData(m.db), ErrCmd(errProjectGone)) } - p.ClientID = m.clientID - p.Name = name - if err := m.db.UpdateProject(p); err != nil { - m.err = err.Error() - return m, nil + if gerr != nil { + return m, ErrCmd(gerr.Error()) } - m.mode = projectsModeList - return m, tea.Batch(loadProjectsData(m.db), StatusCmd("Project updated")) + edited := *p + edited.ClientID = m.clientID + edited.Name = name + err = m.db.UpdateProject(&edited) + status = "Project updated" + default: + return m, nil } - return m, nil + if errors.Is(err, db.ErrProjectNameTaken) { + m.errs[projFieldName] = errProjectTaken + return m, nil + } + if err != nil { + return m, ErrCmd(err.Error()) + } + m.mode = projectsModeList + m.errs = nil + return m, tea.Batch(loadProjectsData(m.db), StatusCmd(status)) +} + +// FieldErrors is how many fields of the open form need fixing, for the +// app's status line. +func (m ProjectsModel) FieldErrors() int { + if m.mode == projectsModeNewProject || m.mode == projectsModeEditProject { + return len(m.errs) + } + return 0 } func (m ProjectsModel) doDelete() (ProjectsModel, tea.Cmd) { m.mode = projectsModeList - if p := m.selectedProject(); p != nil { - if err := m.db.DeleteProject(p.ID); err != nil { - return m, ErrCmd(err.Error()) - } - if m.cursor > 0 { - m.cursor-- + // Checked in the database, not the loaded list: it may be gone + // already, and deleting nothing would still say "deleted". + if _, err := m.db.GetProject(m.deleteID); errors.Is(err, db.ErrNotFound) { + return m, tea.Batch(loadProjectsData(m.db), ErrCmd(errProjectGone)) + } else if err != nil { + return m, ErrCmd(err.Error()) + } + if err := m.db.DeleteProject(m.deleteID); err != nil { + return m, ErrCmd(err.Error()) + } + if m.cursor > 0 { + m.cursor-- + } + return m, tea.Batch(loadProjectsData(m.db), StatusCmd("Project deleted")) +} + +// errProjectGone is the status when the project a delete confirm is for +// was deleted elsewhere while it was open. +const errProjectGone = "That project no longer exists" + +// projectByID is the loaded project id, or nil. +func (m ProjectsModel) projectByID(id int64) *model.Project { + for _, p := range m.projects { + if p.ID == id { + return p } - return m, tea.Batch(loadProjectsData(m.db), StatusCmd("Project deleted")) } - return m, nil + return nil } // resolveClientID resolves the client from the dropdown selection or the typed text. @@ -348,7 +439,7 @@ func (m *ProjectsModel) resolveClientID() error { } text := strings.TrimSpace(m.inputs[projFieldClient].Value()) if text == "" { - return fmt.Errorf("Select a client") + return errors.New(errPickClient) } for _, c := range m.clients { if strings.EqualFold(c.Name, text) { @@ -356,18 +447,26 @@ func (m *ProjectsModel) resolveClientID() error { return nil } } - return fmt.Errorf("Select an existing client from the dropdown") + return errors.New(errPickListClient) } // rebuildClientMatches filters clients by the current client input text. func (m *ProjectsModel) rebuildClientMatches() { - query := strings.ToLower(strings.TrimSpace(m.inputs[projFieldClient].Value())) - m.clientMatches = nil + typed := strings.TrimSpace(m.inputs[projFieldClient].Value()) + query := strings.ToLower(typed) + // An exact name goes first, so it's what tab and enter take: "Acme" + // stays Acme, not "ACME Corp", which sorts before it, nor "acme". + var exacts, rest []dropdownItem + var names []string for _, c := range m.clients { - if query == "" || strings.Contains(strings.ToLower(c.Name), query) { - m.clientMatches = append(m.clientMatches, dropdownItem{id: c.ID, label: c.Name}) + switch { + case typed != "" && strings.EqualFold(c.Name, typed): + exacts, names = append(exacts, dropdownItem{id: c.ID, label: c.Name}), append(names, c.Name) + case query == "" || strings.Contains(strings.ToLower(c.Name), query): + rest = append(rest, dropdownItem{id: c.ID, label: c.Name}) } } + m.clientMatches = exactFirst(exacts, names, typed, rest) if m.clientSel >= len(m.clientMatches) { m.clientSel = 0 } @@ -392,9 +491,20 @@ func (m *ProjectsModel) applyClientSelection() { // -- View --------------------------------------------------------------------- func (m ProjectsModel) View() string { - if m.mode != projectsModeList { - return m.viewForm() + if m.mode == projectsModeList { + return m.viewList() } + w, h := usableWidth(m.width), max(1, m.height-2) + if m.mode == projectsModeConfirmDelete { + if box := m.viewConfirm(w, h); box != nil { + return modalOver(m.viewList(), w, h, box) + } + return m.viewList() + } + return modalOver(m.viewList(), w, h, m.viewForm(w, h)) +} + +func (m ProjectsModel) viewList() string { var b strings.Builder @@ -445,58 +555,56 @@ func (m ProjectsModel) View() string { return b.String() } -func (m ProjectsModel) viewForm() string { - if m.mode == projectsModeConfirmDelete { - return renderConfirmDelete(m.deleteTarget, m.width) - } - - title := "New Project" - if m.mode == projectsModeEditProject { - title = "Edit Project" +// viewForm is the New project or Edit project modal. +func (m ProjectsModel) viewForm(w, h int) []string { + sw := stripWidth(modalInner(theme.ModalWidth, w)) + field := func(label string, idx int) modalField { + return modalField{ + label: label, + focused: m.focusedInput == idx, + mark: m.focusedInput == idx, + strip: true, + value: stripInput(m.inputs[idx], sw), + err: m.errs[idx], + } } - - var b strings.Builder - b.WriteString(StyleTitle.Render(title) + "\n\n") - - b.WriteString(m.renderField("Client", projFieldClient) + "\n") + client := field("Client", projFieldClient) + client.suggests = true if m.focusedInput == projFieldClient && m.showClientDrop && len(m.clientMatches) > 0 { - b.WriteString(renderDropdown(m.clientMatches, m.clientSel) + "\n") + client.suggest = func(n int) []string { return suggestions(m.clientMatches, m.clientSel, sw, n) } } - b.WriteString("\n") - b.WriteString(m.renderField("Name", projFieldName) + "\n\n") - - b.WriteString(StyleButtonPrimary.Render("Save")) - b.WriteString(" ") - b.WriteString(StyleButton.Render("Cancel")) - b.WriteString("\n\n") - - if m.err != "" { - b.WriteString(StyleDanger.Render("✖ "+m.err) + "\n\n") - } - - return b.String() + title := "New project" + if m.mode == projectsModeEditProject { + title = "Edit project" + } + return formModal{ + title: title, + fields: []modalField{client, field("Name", projFieldName)}, + left: []modalButton{ + {label: "Save", kind: buttonPrimary, focused: m.focusedInput == projFieldSave}, + {label: "Cancel", kind: buttonSecondary, focused: m.focusedInput == projFieldCancel}, + }, + hint: "tab next · esc close", + }.render(w, h) } -func (m ProjectsModel) renderField(label string, idx int) string { - focused := m.focusedInput == idx - ti := m.inputs[idx] - refreshInputStyle(&ti) - - var labelStr string - if focused { - labelStr = StyleFormLabelFocused.Render(label) - } else { - labelStr = StyleFormLabel.Render(label) - } - - var inputStr string - if focused { - inputStr = StyleFormInputFocused.Render(ti.View()) - } else { - inputStr = StyleFormInput.Render(ti.View()) +// viewConfirm is the delete confirm for the selected project. +func (m ProjectsModel) viewConfirm(w, h int) []string { + p := m.projectByID(m.deleteID) + if p == nil { + return nil } - - return lipgloss.JoinHorizontal(lipgloss.Top, labelStr, inputStr) + detail := "" + if p.Client != nil { + detail = p.Client.Name + } + return confirmModal{ + title: "Delete project?", + name: p.Name, + detail: detail, + warning: "Its time entries go too. This can’t be undone.", + deleteFocused: m.deleteFocused, + }.render(w, h) } // -- helpers ------------------------------------------------------------------ @@ -509,16 +617,12 @@ func (m ProjectsModel) selectedProject() *model.Project { } func makeProjectInputs(p *model.Project, clientName string) []textinput.Model { - client := textinput.New() - client.Placeholder = "Select a client" - client.CharLimit = 64 + client := makeTextInput("type to find a client", 64, theme.FieldWidth) if clientName != "" { client.SetValue(clientName) } - name := textinput.New() - name.Placeholder = "Project name" - name.CharLimit = 64 + name := makeTextInput("Website rebuild", 64, theme.FieldWidth) if p != nil { name.SetValue(p.Name) } diff --git a/internal/ui/views/projects_test.go b/internal/ui/views/projects_test.go index 6dde9bd..f2c288d 100644 --- a/internal/ui/views/projects_test.go +++ b/internal/ui/views/projects_test.go @@ -9,6 +9,7 @@ import ( "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" _ "modernc.org/sqlite" ) @@ -89,8 +90,11 @@ func TestProjectsSaveForm_BlankNameRejected(t *testing.T) { m := ProjectsModel{mode: projectsModeNewProject, clients: []*model.Client{{ID: 1, Name: "Acme"}}, clientID: 1, inputs: inputs} got, cmd := m.saveForm() - if got.err == "" { - t.Error("want a validation error for a blank name") + if got.errs[projFieldName] != errNameRequired { + t.Errorf("Name error = %q, want %q", got.errs[projFieldName], errNameRequired) + } + if _, ok := got.errs[projFieldClient]; ok { + t.Error("the client resolves, so it shouldn't have an error") } if cmd != nil { t.Error("want nil cmd on validation failure (no DB touch)") @@ -104,8 +108,8 @@ func TestProjectsSaveForm_UnresolvedClientRejected(t *testing.T) { m := ProjectsModel{mode: projectsModeNewProject, clients: []*model.Client{{ID: 1, Name: "Acme"}}, inputs: inputs} got, cmd := m.saveForm() - if got.err == "" { - t.Error("want a validation error when the client doesn't resolve") + if got.errs[projFieldClient] != errPickListClient { + t.Errorf("Client error = %q, want %q", got.errs[projFieldClient], errPickListClient) } if cmd != nil { t.Error("want nil cmd on validation failure (no DB touch)") @@ -126,7 +130,7 @@ func TestProjectsUpdateForm_ConfirmDeleteDispatch(t *testing.T) { } t.Run("y deletes", func(t *testing.T) { - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p}, cursor: 0} + m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p}, cursor: 0, deleteID: p.ID} got, cmd := m.updateForm(runeKey('y')) if got.mode != projectsModeList { t.Errorf("mode after 'y' = %v, want projectsModeList", got.mode) @@ -146,7 +150,7 @@ func TestProjectsUpdateForm_ConfirmDeleteDispatch(t *testing.T) { if err != nil { t.Fatal(err) } - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p2}, cursor: 0} + m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p2}, cursor: 0, deleteID: p2.ID} got, cmd := m.updateForm(runeKey('n')) if got.mode != projectsModeList { t.Errorf("mode after 'n' = %v, want projectsModeList", got.mode) @@ -521,8 +525,8 @@ func TestProjectsUpdateList_DeleteWithSelection(t *testing.T) { if got.mode != projectsModeConfirmDelete { t.Errorf("mode = %v, want projectsModeConfirmDelete", got.mode) } - if got.deleteTarget == "" { - t.Error("want a non-empty deleteTarget") + if got.deleteFocused { + t.Error("want Keep it, not Delete, focused when the confirm opens") } } @@ -547,8 +551,13 @@ func TestProjectsUpdateForm_ClientDropdownNavigation(t *testing.T) { } m.rebuildClientMatches() - // Down moves selection forward and shows the dropdown. + // The first down opens the suggestions on the first match; the next + // moves the selection. got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyDown}) + if got.clientSel != 0 || !got.showClientDrop { + t.Errorf("first down: clientSel = %d, open = %v; want 0 and open", got.clientSel, got.showClientDrop) + } + got, _ = got.updateForm(tea.KeyMsg{Type: tea.KeyDown}) if got.clientSel != 1 { t.Errorf("clientSel after down = %d, want 1", got.clientSel) } @@ -586,6 +595,7 @@ func TestProjectsUpdateForm_ConfirmOnClientAppliesSelection(t *testing.T) { } m.inputs[projFieldClient].Focus() m.rebuildClientMatches() + m.showClientDrop = true // as typing or ↓ leaves it got, cmd := m.updateForm(tea.KeyMsg{Type: tea.KeyEnter}) if cmd != nil { @@ -620,19 +630,19 @@ func TestProjectsUpdateForm_ConfirmOnNameDispatchesSave(t *testing.T) { focusedInput: projFieldName, } got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.err == "" { + if got.errs[projFieldName] != errNameRequired { t.Error("want saveForm's blank-name validation error to surface via updateForm dispatch") } } func TestProjectsUpdateForm_Cancel(t *testing.T) { - m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), err: "boom"} + m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), errs: fieldErrors{projFieldName: "boom"}} got, cmd := m.updateForm(tea.KeyMsg{Type: tea.KeyEsc}) if got.mode != projectsModeList { t.Errorf("mode = %v, want projectsModeList", got.mode) } - if got.err != "" { - t.Errorf("err = %q, want cleared", got.err) + if len(got.errs) != 0 { + t.Errorf("errs = %v, want cleared", got.errs) } if cmd != nil { t.Error("want nil cmd on cancel") @@ -656,12 +666,15 @@ func TestProjectsUpdateForm_NextFieldTogglesFocus(t *testing.T) { t.Error("dropdown should be hidden once focus leaves the client field") } - got2, _ := got.updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if got2.focusedInput != projFieldClient { - t.Errorf("focusedInput after tab from name = %d, want projFieldClient", got2.focusedInput) + // Then Save, Cancel, and round to Client again. + for _, want := range []int{projFieldSave, projFieldCancel, projFieldClient} { + got, _ = got.updateForm(tea.KeyMsg{Type: tea.KeyTab}) + if got.focusedInput != want { + t.Errorf("focusedInput after tab = %d, want %d", got.focusedInput, want) + } } - if !got2.showClientDrop { - t.Error("dropdown should reappear once focus returns to the client field with matches available") + if !got.inputs[projFieldClient].Focused() { + t.Error("client input should be focused again") } } @@ -677,8 +690,8 @@ func TestProjectsUpdateForm_PrevFieldTogglesFocus(t *testing.T) { } got2, _ := got.updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got2.focusedInput != projFieldName { - t.Errorf("focusedInput after shift+tab from client = %d, want projFieldName", got2.focusedInput) + if got2.focusedInput != projFieldCancel { + t.Errorf("focusedInput after shift+tab from client = %d, want projFieldCancel (wrapped)", got2.focusedInput) } } @@ -763,8 +776,8 @@ func TestProjectsSaveForm_CreateError(t *testing.T) { m := ProjectsModel{db: d, mode: projectsModeNewProject, clients: []*model.Client{c}, clientID: c.ID, inputs: inputs} got, cmd := m.saveForm() - if got.err == "" { - t.Error("want a DB error surfaced on duplicate project name") + if got.errs[projFieldName] != errProjectTaken { + t.Errorf("Name error = %q, want %q on a duplicate project name", got.errs[projFieldName], errProjectTaken) } if cmd != nil { t.Error("want nil cmd when CreateProject fails") @@ -790,7 +803,7 @@ func TestProjectsSaveForm_EditSuccess(t *testing.T) { m := ProjectsModel{ db: d, mode: projectsModeEditProject, clients: []*model.Client{c}, projects: []*model.Project{p}, cursor: 0, - clientID: c.ID, inputs: inputs, + clientID: c.ID, inputs: inputs, editingID: p.ID, } got, cmd := m.saveForm() @@ -830,39 +843,62 @@ func TestProjectsSaveForm_EditError(t *testing.T) { m := ProjectsModel{ db: d, mode: projectsModeEditProject, clients: []*model.Client{c}, projects: []*model.Project{p2}, cursor: 0, - clientID: c.ID, inputs: inputs, + clientID: c.ID, inputs: inputs, editingID: p2.ID, } got, cmd := m.saveForm() - if got.err == "" { - t.Error("want a DB error surfaced on duplicate project name during update") + if got.errs[projFieldName] != errProjectTaken { + t.Errorf("Name error = %q, want %q on a duplicate name during update", got.errs[projFieldName], errProjectTaken) } if cmd != nil { t.Error("want nil cmd when UpdateProject fails") } + // The refused name mustn't reach the list, which shares the project. + if got.projects[0].Name != "App" { + t.Errorf("list shows %q after a refused rename, want App", got.projects[0].Name) + } _ = p1 } -func TestProjectsSaveForm_EditWithNoSelectedProjectResetsMode(t *testing.T) { +// Edit project saves to the project it opened for, even when a reload +// under it moves the cursor; when that project is gone it closes and +// says so. +func TestProjectsEditForm_SavesToTheProjectItOpenedFor(t *testing.T) { d := newTestDB(t) - c, err := d.CreateClient("Acme", 100) - if err != nil { - t.Fatal(err) + c, _ := d.CreateClient("Acme", 0) + webP, _ := d.CreateProject(c.ID, "Web") + appP, _ := d.CreateProject(c.ID, "App") + web, _ := d.GetProject(webP.ID) // with its client, as the tab loads them + app, _ := d.GetProject(appP.ID) + m := ProjectsModel{db: d, clients: []*model.Client{c}, projects: []*model.Project{web, app}, width: 100, height: 30} + m, _ = m.updateList(runeKey('e')) // on Web + m, _ = m.Update(projectsDataMsg{clients: []*model.Client{c}, projects: []*model.Project{app, web}}) + m.inputs[projFieldName].SetValue("Website") + got, _ := m.saveForm() + if got.mode != projectsModeList { + t.Fatalf("mode = %v, errs %v; want it saved", got.mode, got.errs) } - inputs := makeProjectInputs(nil, "") - inputs[projFieldName].SetValue("Website") - m := ProjectsModel{ - db: d, mode: projectsModeEditProject, - clients: []*model.Client{c}, projects: nil, cursor: 0, - clientID: c.ID, inputs: inputs, + if p, _ := d.GetProject(web.ID); p.Name != "Website" { + t.Errorf("Web is now %q, want Website", p.Name) + } + if p, _ := d.GetProject(app.ID); p.Name != "App" { + t.Errorf("App is now %q, want it untouched", p.Name) } + m, _ = got.updateList(runeKey('e')) + if err := d.DeleteProject(m.editingID); err != nil { + t.Fatal(err) + } got, cmd := m.saveForm() - if got.mode != projectsModeList { - t.Errorf("mode = %v, want projectsModeList", got.mode) + if got.mode != projectsModeList || cmd == nil { + t.Fatalf("mode %v; want the form closed when its project is gone", got.mode) } - if cmd != nil { - t.Error("want nil cmd when there is no selected project to update") + found := false + for _, msg := range runCmd(t, cmd) { + found = found || msg == ErrMsg(errProjectGone) + } + if !found { + t.Errorf("want %q", errProjectGone) } } @@ -901,7 +937,7 @@ func TestProjectsDoDelete_Success(t *testing.T) { t.Fatal(err) } - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p1, p2}, cursor: 1} + m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p1, p2}, cursor: 1, deleteID: p2.ID} got, cmd := m.doDelete() if got.mode != projectsModeList { t.Errorf("mode = %v, want projectsModeList", got.mode) @@ -932,14 +968,28 @@ func TestProjectsDoDelete_CursorStaysAtZero(t *testing.T) { } } -func TestProjectsDoDelete_NoSelectionIsNoop(t *testing.T) { - m := ProjectsModel{mode: projectsModeConfirmDelete} +func TestProjectsDoDelete_GoneProjectSaysSo(t *testing.T) { + // The loaded list still has the project; the database doesn't. + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 0) + p, _ := d.CreateProject(c.ID, "Web") + m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p}, deleteID: p.ID} + if err := d.DeleteProject(p.ID); err != nil { + t.Fatal(err) + } got, cmd := m.doDelete() if got.mode != projectsModeList { t.Errorf("mode = %v, want projectsModeList", got.mode) } - if cmd != nil { - t.Error("want nil cmd when there is nothing to delete") + found := false + for _, msg := range runCmd(t, cmd) { + found = found || msg == ErrMsg(errProjectGone) + if s, ok := msg.(StatusMsg); ok { + t.Errorf("status %q for a project already gone", s) + } + } + if !found { + t.Errorf("want %q when the project is gone", errProjectGone) } } @@ -1048,23 +1098,28 @@ func TestProjectsView_ErrorLine(t *testing.T) { // ── viewForm ────────────────────────────────────────────────────────────────── -func TestProjectsViewForm_ConfirmDeleteDelegates(t *testing.T) { - m := ProjectsModel{mode: projectsModeConfirmDelete, deleteTarget: `project "Website"`, width: 100} - got := m.viewForm() - if !strings.Contains(got, "Website") { - t.Errorf("viewForm() in confirm-delete mode = %q, want it to mention the delete target", got) +func viewText(lines []string) string { return ansi.Strip(strings.Join(lines, "\n")) } + +func TestProjectsView_ConfirmDeleteNamesProjectAndClient(t *testing.T) { + p := &model.Project{ID: 1, Name: "Website", Client: &model.Client{Name: "Acme"}} + m := ProjectsModel{mode: projectsModeConfirmDelete, projects: []*model.Project{p}, deleteID: p.ID, width: 100, height: 30} + got := ansi.Strip(m.View()) + for _, want := range []string{"Delete project?", "“Website”", "Acme", "Its time entries go too.", "Keep it"} { + if !strings.Contains(got, want) { + t.Errorf("View() in confirm-delete mode missing %q; got %q", want, got) + } } } func TestProjectsViewForm_TitlesByMode(t *testing.T) { - newM := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), width: 100} - if got := newM.viewForm(); !strings.Contains(got, "New Project") { - t.Errorf("viewForm() in new mode = %q, want it to contain %q", got, "New Project") + newM := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), width: 100, height: 30} + if got := viewText(newM.viewForm(96, 28)); !strings.Contains(got, "New project") { + t.Errorf("viewForm() in new mode = %q, want it to contain %q", got, "New project") } - editM := ProjectsModel{mode: projectsModeEditProject, inputs: makeProjectInputs(nil, ""), width: 100} - if got := editM.viewForm(); !strings.Contains(got, "Edit Project") { - t.Errorf("viewForm() in edit mode = %q, want it to contain %q", got, "Edit Project") + editM := ProjectsModel{mode: projectsModeEditProject, inputs: makeProjectInputs(nil, ""), width: 100, height: 30} + if got := viewText(editM.viewForm(96, 28)); !strings.Contains(got, "Edit project") { + t.Errorf("viewForm() in edit mode = %q, want it to contain %q", got, "Edit project") } } @@ -1078,30 +1133,125 @@ func TestProjectsViewForm_DropdownRenders(t *testing.T) { } m.rebuildClientMatches() - got := m.viewForm() - if !strings.Contains(got, "Acme") || !strings.Contains(got, "Beta") { - t.Errorf("viewForm() with dropdown open = %q, want both client names listed", got) + got := viewText(m.viewForm(96, 28)) + if !strings.Contains(got, "Acme") || !strings.Contains(got, "Beta") || !strings.Contains(got, "↑↓ choose · enter pick") { + t.Errorf("viewForm() with suggestions open = %q, want both client names listed", got) } } -func TestProjectsViewForm_ErrorLine(t *testing.T) { - m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), width: 100, err: "bad input"} - got := m.viewForm() - if !strings.Contains(got, "bad input") { - t.Errorf("viewForm() = %q, want the error message rendered", got) +func TestProjectsViewForm_ErrorsSitUnderTheirFields(t *testing.T) { + m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), width: 100} + m, _ = m.saveForm() + if m.FieldErrors() != 2 { + t.Fatalf("FieldErrors() = %d, want 2 (Client and Name)", m.FieldErrors()) + } + lines := strings.Split(viewText(m.viewForm(96, 28)), "\n") + for _, c := range []struct{ label, msg string }{{"Client", errPickClient}, {"Name", errNameRequired}} { + found := false + for i, l := range lines[:len(lines)-1] { + if strings.Contains(l, c.label) && strings.Contains(lines[i+1], "✕ "+c.msg) { + found = true + } + } + if !found { + t.Errorf("want %q under %s; got %q", "✕ "+c.msg, c.label, lines) + } } } -// ── renderField (exercised through viewForm for both focus states) ─────────── - func TestProjectsRenderField_FocusedAndUnfocused(t *testing.T) { inputs := makeProjectInputs(nil, "") inputs[projFieldClient].SetValue("Acme") inputs[projFieldName].SetValue("Website") m := ProjectsModel{mode: projectsModeNewProject, inputs: inputs, focusedInput: projFieldClient, width: 100} - got := m.viewForm() + got := viewText(m.viewForm(96, 28)) if !strings.Contains(got, "Acme") || !strings.Contains(got, "Website") { t.Errorf("viewForm() = %q, want both field values rendered regardless of focus", got) } } + +// The confirm deletes the project it opened for, even when a reload under +// it moves the cursor; when that project is gone, it closes and says so. +func TestProjectsConfirm_DeletesTheProjectItOpenedFor(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 0) + web, _ := d.CreateProject(c.ID, "Web") + app, _ := d.CreateProject(c.ID, "App") + m := ProjectsModel{db: d, projects: []*model.Project{web, app}, width: 100, height: 30} + m, _ = m.updateList(runeKey('d')) // on Web + m, _ = m.Update(projectsDataMsg{clients: []*model.Client{c}, projects: []*model.Project{app, web}}) + _, cmd := m.updateConfirm(runeKey('y')) + if cmd == nil { + t.Fatal("want the delete to run") + } + projects, _ := d.ListProjects(0) + if len(projects) != 1 || projects[0].ID != app.ID { + t.Errorf("projects = %v, want only App left", projects) + } + + m = ProjectsModel{db: d, projects: []*model.Project{app}, width: 100, height: 30} + m, _ = m.updateList(runeKey('d')) + got, cmd := m.Update(projectsDataMsg{clients: []*model.Client{c}}) + if got.mode != projectsModeList || cmd == nil || cmd() != ErrMsg(errProjectGone) { + t.Errorf("mode %v; want the confirm closed with %q when its project is gone", got.mode, errProjectGone) + } +} + +// An exact client name wins on tab over a name that sorts before it +// ("ACME Corp" before "Acme" in the database's order). +func TestProjectsForm_ExactClientNameWins(t *testing.T) { + d := newTestDB(t) + corp, _ := d.CreateClient("ACME Corp", 0) + acme, _ := d.CreateClient("Acme", 0) + clients, _ := d.ListClients() + if clients[0].ID != corp.ID { + t.Fatalf("setup: want ACME Corp listed first, got %q", clients[0].Name) + } + m := ProjectsModel{db: d, clients: clients, width: 100, height: 30} + m, _ = m.updateList(runeKey('n')) + for _, r := range "Acme" { + m, _ = m.updateForm(runeKey(r)) + } + m, _ = m.updateForm(tea.KeyMsg{Type: tea.KeyTab}) + if m.clientID != acme.ID || m.inputs[projFieldClient].Value() != "Acme" { + t.Errorf("Client = %q (id %d), want Acme", m.inputs[projFieldClient].Value(), m.clientID) + } +} + +// esc and n keep, in every confirm. +func TestConfirms_NKeeps(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 0) + cm := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}, deleteID: c.ID} + if got, cmd := cm.updateConfirm(runeKey('n')); got.mode != clientModeList || cmd != nil { + t.Errorf("Clients: n gave mode %v, cmd %v; want kept", got.mode, cmd) + } + tm, _, _ := confirmTimers(t) + tm, _ = tm.updateList(runeKey('d')) + if got, cmd := tm.updateConfirm(runeKey('n')); got.mode != timersModeList || cmd != nil { + t.Errorf("Timers: n gave mode %v, cmd %v; want kept", got.mode, cmd) + } + if clients, _ := d.ListClients(); len(clients) != 1 { + t.Error("n deleted the client") + } +} + +// "Acme" picks Acme over acme in the Project form too. +func TestProjectsForm_ExactCaseWinsOverOtherCase(t *testing.T) { + d := newTestDB(t) + upper, _ := d.CreateClient("Acme", 0) + lower, _ := d.CreateClient("acme", 0) + clients, _ := d.ListClients() + for typed, want := range map[string]int64{"Acme": upper.ID, "acme": lower.ID} { + m := ProjectsModel{db: d, clients: clients, width: 100, height: 30} + m, _ = m.updateList(runeKey('n')) + for _, r := range typed { + m, _ = m.updateForm(runeKey(r)) + } + m, _ = m.updateForm(tea.KeyMsg{Type: tea.KeyTab}) + if m.clientID != want { + t.Errorf("typed %q: client %d, want %d", typed, m.clientID, want) + } + } +} diff --git a/internal/ui/views/reports.go b/internal/ui/views/reports.go index fef94d9..b892698 100644 --- a/internal/ui/views/reports.go +++ b/internal/ui/views/reports.go @@ -47,13 +47,11 @@ type ReportsModel struct { entriesCursor int // index into the selected row's entries, in reportsModeEntries; see clampEntriesOffset entriesOffset int // scroll offset within entries; see clampEntriesOffset - // editForm/editFormErr back reportsModeEditEntry — populated from - // reportsOpenEditMsg, driven by updateTimerFormFields/viewTimerForm - // (shared with TimersModel's own form; see updateTimerFormFields' doc - // comment in timers.go for why those are free functions rather than - // TimersModel methods). - editForm timerForm - editFormErr string + // editForm backs reportsModeEditEntry: the Edit entry form, filled + // from reportsOpenEditMsg and shared with the Timers tab (see + // updateTimerFormFields in timer_form.go). Its field errors live in + // editForm.errs. + editForm timerForm fromInput textinput.Model toInput textinput.Model @@ -106,12 +104,7 @@ func (m ReportsModel) Help() []Hotkey { case reportsModeEntries: return []Hotkey{{"↑ / ↓", "navigate"}, {"e", "edit"}, {"esc", "back"}} case reportsModeEditEntry: - return []Hotkey{ - {"tab / shift+tab", "move"}, - {"↑ / ↓", "dropdown"}, - {"enter", "confirm"}, - {"esc", "cancel"}, - } + return m.editForm.help("Save") default: return []Hotkey{ {"↑ / ↓", "navigate"}, @@ -334,12 +327,11 @@ func (m ReportsModel) updateEntries(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { func (m ReportsModel) updateEditEntry(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { action, cmd := updateTimerFormFields(&m.editForm, msg) switch action { - case "cancel": + case formCancel: m.mode = reportsModeEntries - m.editFormErr = "" return m, nil - case "submit": - return m.submitEditEntry() + case formSubmit: + return m.submitEditEntry(time.Now()) } return m, cmd } @@ -347,16 +339,19 @@ func (m ReportsModel) updateEditEntry(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { // submitEditEntry validates the edit form and, if valid, writes the change // and reloads this report's rows so the table/entries list reflects it — // the Reports-side counterpart to TimersModel.submitForm's edit branch, -// sharing the same validateTimerForm/submitEditEntryCmd. -func (m ReportsModel) submitEditEntry() (ReportsModel, tea.Cmd) { - v, errMsg := validateTimerForm(m.editForm) - if errMsg != "" { - m.editFormErr = errMsg +// sharing the same validateTimerForm and submitEdit. +func (m ReportsModel) submitEditEntry(now time.Time) (ReportsModel, tea.Cmd) { + v, errs := validateTimerForm(m.editForm, now) + if len(errs) > 0 { + m.editForm.errs = errs return m, nil } - m.mode = reportsModeEntries - m.editFormErr = "" - return m, submitEditEntryCmd(m.db, m.editForm.entryID, v, m.loadCmd()) + m.editForm.errs = nil + closeForm, cmd := m.editForm.submitEdit(m.db, v, m.loadCmd()) + if closeForm { + m.mode = reportsModeEntries + } + return m, cmd } // reportsOpenEditMsg carries the data needed to populate the edit-entry @@ -401,27 +396,10 @@ func (m ReportsModel) handleOpenEditEntry(msg reportsOpenEditMsg) ReportsModel { } f := newTimerForm(msg.clients, msg.projects) - f.entryID = e.ID - f.inputs[fieldTask].SetValue(e.Task) - f.inputs[fieldNotes].SetValue(e.Notes) - f.inputs[fieldStart].SetValue(e.StartTime.Local().Format("2006-01-02 15:04")) - if e.EndTime != nil { - f.inputs[fieldEnd].SetValue(e.EndTime.Local().Format("2006-01-02 15:04")) - } - if e.Project != nil { - f.projectID = e.Project.ID - f.inputs[fieldProject].SetValue(e.Project.Name) - if e.Project.Client != nil { - f.clientID = e.Project.Client.ID - f.inputs[fieldClient].SetValue(e.Project.Client.Name) - } - } - f.rebuildClientMatches() - f.rebuildProjectMatches() + f.fill(e) m.editForm = f m.mode = reportsModeEditEntry - m.editFormErr = "" return m } @@ -499,7 +477,8 @@ func (m ReportsModel) View() string { // see updateTimerFormFields' doc comment for why the form logic lives // as free functions rather than TimersModel methods. if m.mode == reportsModeEditEntry { - return viewTimerForm(m.editForm, m.editFormErr, "Save") + w, h := usableWidth(m.width), max(1, m.height-2) + return modalOver(m.renderEntriesView(), w, h, m.editForm.view(w, h, "Save")) } var sb strings.Builder @@ -771,7 +750,7 @@ func (m ReportsModel) renderTotals() string { cards := m.renderSummaryCards(totalHours, totalEarnings, totalEntries, totalInvoiced, totalPaid) - // Plain "\n" join, not lipgloss.JoinVertical — see renderConfirmDelete in + // Plain "\n" join, not lipgloss.JoinVertical — see padCellToTwoLines in // common.go for why: JoinVertical would pad the narrower `cards` line(s) to // the divider's width using unstyled spaces, punching a hole to their right. return divider + "\n" + totals + "\n\n" + cards @@ -790,7 +769,7 @@ func (m ReportsModel) renderSummaryCards(hours, earned float64, entries, invoice // The box style itself carries Background(cBg): lipgloss's own Padding // fill (and the fill it adds to left-align the shorter of label/value) // respects the style's background, unlike lipgloss.JoinVertical's raw - // unstyled padding — see renderConfirmDelete in common.go. Margin is a + // unstyled padding — see padCellToTwoLines in common.go. Margin is a // *separate* property in lipgloss (MarginBackground, distinct from // Background) and defaults to no color at all, so MarginRight needs its // own explicit background or the gap between cards shows the terminal's @@ -1026,3 +1005,12 @@ func (m ReportsModel) renderEntriesView() string { return header + "\n\n" + tableStr + "\n\n" + detail } + +// FieldErrors is how many fields of the Edit entry form need fixing, for +// the app's status line. +func (m ReportsModel) FieldErrors() int { + if m.mode == reportsModeEditEntry { + return len(m.editForm.errs) + } + return 0 +} diff --git a/internal/ui/views/timer_form.go b/internal/ui/views/timer_form.go new file mode 100644 index 0000000..9aa673e --- /dev/null +++ b/internal/ui/views/timer_form.go @@ -0,0 +1,926 @@ +package views + +// The timer form (ALI-2616): New timer on the Timers tab, and Edit entry +// on the Timers and Reports tabs, drawn as a modal (see modal.go). +// +// New timer: Task, Client, Project, Notes, Start and End. Start is blank +// for now or takes a past time; with an End too, it records a finished +// entry instead of starting a timer. Task takes quick add: "Logo +// @Fieldnote Studio/Brand refresh" fills Client and Project when the field +// is left (tab, or enter to save), the same text `notch start --task` +// reads (internal/quickadd). +// +// Edit entry adds the Invoiced and Paid toggles and, on the Timers tab, +// Delete entry. +// +// Times follow the CLI's rules: none in the future, and the end not before +// the start. Errors sit under their field. + +import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/aliasproject/notch/internal/db" + "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/quickadd" + "github.com/aliasproject/notch/internal/theme" + "github.com/charmbracelet/bubbles/key" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" +) + +// ── Fields ──────────────────────────────────────────────────────────────────── + +// The form's text inputs, in timerForm.inputs. +const ( + fieldTask = iota + fieldClient + fieldProject + fieldStart + fieldEnd + fieldNotes + fieldInputs +) + +// Its toggles and buttons, after the inputs. +const ( + fieldInvoiced = fieldInputs + iota + fieldPaid + fieldSave + fieldCancel + fieldDelete + fieldCount +) + +// The form's results from updateTimerFormFields. +const ( + formCancel = "cancel" + formSubmit = "submit" + formDelete = "delete" +) + +// Suggestion navigation. Deliberately arrow-only: the list keymaps alias +// j/k to up/down, and those letters have to type into the field. +var ( + dropdownUp = key.NewBinding(key.WithKeys("up"), key.WithHelp("↑", "up")) + dropdownDown = key.NewBinding(key.WithKeys("down"), key.WithHelp("↓", "down")) +) + +// The form's messages, shared with the tests. +const ( + errTaskRequired = "Enter what you're working on." + errTimeFormat = "Use a time like 9:05 AM or 2026-12-03 09:05." + errStartFuture = "The start can't be in the future." + errEndFuture = "The end can't be in the future." + errStartRequired = "Enter a start time." + errEndRequired = "Enter an end time." + errEndNeedsStart = "An End needs a past Start." + errEndBeforeStart = "The end is before the start." + errRunningLater = "The running timer started after this. Stop it or pick a later start." + errPickProjectClient = "Pick the client, or choose the project from the list." + errInvoiceRunning = "Stop the timer before invoicing it." +) + +type dropdownItem struct { + id int64 // 0 = "+ Create" + label string +} + +// timerForm holds the state of a New timer or Edit entry form. Client and +// Project suggest matches as you type and create what doesn't exist yet. +type timerForm struct { + entryID int64 // 0 = new + running bool // editing a running entry: End can stay blank + canDelete bool // offer Delete entry (the Timers tab) + + // orig is the entry as the form found it, and filledStart/filledEnd + // the text Start and End were filled with: a field left as filled + // keeps its stored time, seconds and all, a bare time of day is read + // on the entry's own day, and the save writes only what changed. + orig entrySnapshot + filledStart, filledEnd string + + inputs [fieldInputs]textinput.Model + focusIdx int + + allClients []*model.Client + clientMatches []dropdownItem + clientSel int + clientID int64 // 0 = create from the typed name + + allProjects []*model.Project + projectMatches []dropdownItem + projectSel int + projectID int64 // 0 = create from the typed name + + showClientDrop bool + showProjectDrop bool + + // chose* is set when the arrows moved a suggestion selection, and + // *Exact when a suggestion's name is the typed text (ignoring case): + // only then does tab take a suggestion. Otherwise the typed name + // stands, to be created. + choseClient, choseProject bool + clientExact, projectExact bool + // projectClash counts the projects named exactly as typed when there + // are several (under different clients, Client left blank): tab then + // leaves the name as typed, and Project asks for a pick. + projectClash int + + // formErr is a problem with the whole form, shown above its buttons: + // the entry changed elsewhere since it opened. + formErr string + + invoiced, paid bool + + errs fieldErrors +} + +func newTimerForm(clients []*model.Client, projects []*model.Project) timerForm { + var inputs [fieldInputs]textinput.Model + inputs[fieldTask] = makeTextInput("what you're working on", 200, theme.FieldWidth) + inputs[fieldClient] = makeTextInput("type to find or create", 64, theme.FieldWidth) + inputs[fieldProject] = makeTextInput("type to find or create", 64, theme.FieldWidth) + inputs[fieldStart] = makeTextInput("now", 20, theme.FieldWidth) + inputs[fieldEnd] = makeTextInput("blank keeps it running", 20, theme.FieldWidth) + inputs[fieldNotes] = makeTextInput("optional", 500, theme.FieldWidth) + inputs[fieldTask].Focus() + + f := timerForm{ + inputs: inputs, + focusIdx: fieldTask, + allClients: clients, + allProjects: projects, + } + f.rebuildClientMatches() + f.rebuildProjectMatches() + return f +} + +// fill loads e into an Edit entry form. +func (f *timerForm) fill(e *model.Entry) { + f.entryID = e.ID + f.running = e.IsRunning() + f.invoiced, f.paid = e.Invoiced, e.Paid + f.inputs[fieldTask].SetValue(e.Task) + f.inputs[fieldNotes].SetValue(e.Notes) + f.orig = snapshotOf(e) + f.filledStart = e.StartTime.Local().Format("2006-01-02 15:04") + f.inputs[fieldStart].SetValue(f.filledStart) + f.inputs[fieldStart].Placeholder = "2026-12-03 09:05" + if e.EndTime != nil { + f.filledEnd = e.EndTime.Local().Format("2006-01-02 15:04") + f.inputs[fieldEnd].SetValue(f.filledEnd) + f.inputs[fieldEnd].Placeholder = "2026-12-03 17:30" + } else { + f.inputs[fieldEnd].Placeholder = "running" + } + if e.Project != nil { + f.projectID = e.Project.ID + f.inputs[fieldProject].SetValue(e.Project.Name) + if e.Project.Client != nil { + f.clientID = e.Project.Client.ID + f.inputs[fieldClient].SetValue(e.Project.Client.Name) + } + } + f.projectID = e.ProjectID + f.rebuildClientMatches() + f.rebuildProjectMatches() +} + +// entrySnapshot is every field Edit entry writes, as stored. +type entrySnapshot struct { + task, notes string + projectID int64 + start time.Time + end *time.Time + invoiced, paid bool +} + +func snapshotOf(e *model.Entry) entrySnapshot { + return entrySnapshot{ + task: e.Task, notes: e.Notes, projectID: e.ProjectID, + start: e.StartTime, end: e.EndTime, + invoiced: e.Invoiced, paid: e.Paid, + } +} + +func sameTime(a, b *time.Time) bool { + return (a == nil) == (b == nil) && (a == nil || a.Equal(*b)) +} + +// ── Suggestions ─────────────────────────────────────────────────────────────── + +// rebuildClientMatches lists the clients whose names hold the typed text, +// an exact match first, then "+ Create" when none matches exactly. +func (f *timerForm) rebuildClientMatches() { + typed := strings.TrimSpace(f.inputs[fieldClient].Value()) + query := strings.ToLower(typed) + var exacts, rest []dropdownItem + var names []string + for _, c := range f.allClients { + switch { + case typed != "" && strings.EqualFold(c.Name, typed): + exacts, names = append(exacts, dropdownItem{id: c.ID, label: c.Name}), append(names, c.Name) + case query == "" || strings.Contains(strings.ToLower(c.Name), query): + rest = append(rest, dropdownItem{id: c.ID, label: c.Name}) + } + } + exact := len(exacts) > 0 + f.clientMatches = exactFirst(exacts, names, typed, rest) + if typed != "" && !exact { + f.clientMatches = append(f.clientMatches, dropdownItem{id: 0, label: fmt.Sprintf("+ Create “%s”", typed)}) + } + f.clientExact = exact + if f.clientSel >= len(f.clientMatches) { + f.clientSel = 0 + } +} + +// exactFirst lists the suggestions for typed: exacts (the items whose +// names, in names, equal typed ignoring case) first, the one in typed's +// own case before the rest of them, so "Acme" picks Acme over acme; then +// rest, the other matches. +func exactFirst(exacts []dropdownItem, names []string, typed string, rest []dropdownItem) []dropdownItem { + out := make([]dropdownItem, 0, len(exacts)+len(rest)) + for i, n := range names { + if n == typed { + out = append(out, exacts[i]) + } + } + for i, n := range names { + if n != typed { + out = append(out, exacts[i]) + } + } + return append(out, rest...) +} + +// rebuildProjectMatches lists the projects whose names hold the typed +// text, only the chosen client's when there is one, an exact match first, +// then "+ Create" when none matches exactly. +func (f *timerForm) rebuildProjectMatches() { + typed := strings.TrimSpace(f.inputs[fieldProject].Value()) + query := strings.ToLower(typed) + f.projectMatches = nil + exact, exactN := false, 0 + // The client the projects belong to: the one picked, or the one whose + // name is typed. A typed name that isn't a client yet is a new client, + // with no projects to suggest: the project is created under it. + clientID := f.clientID + clientText := strings.TrimSpace(f.inputs[fieldClient].Value()) + newClient := false + if clientID == 0 && clientText != "" { + for _, c := range f.allClients { + if strings.EqualFold(c.Name, clientText) { + clientID = c.ID + break + } + } + newClient = clientID == 0 + } + var exacts, rest []dropdownItem + var names []string + for _, p := range f.allProjects { + if newClient || (clientID != 0 && p.ClientID != clientID) { + continue + } + label := p.Name + if clientID == 0 && p.Client != nil { + label = p.Client.Name + " › " + p.Name + } + switch { + case typed != "" && strings.EqualFold(p.Name, typed): + exact = true + exactN++ + exacts, names = append(exacts, dropdownItem{id: p.ID, label: label}), append(names, p.Name) + case query == "" || strings.Contains(strings.ToLower(p.Name), query): + rest = append(rest, dropdownItem{id: p.ID, label: label}) + } + } + f.projectMatches = exactFirst(exacts, names, typed, rest) + if typed != "" && !exact { + f.projectMatches = append(f.projectMatches, dropdownItem{id: 0, label: fmt.Sprintf("+ Create “%s”", typed)}) + } + f.projectExact = exactN == 1 + f.projectClash = 0 + if exactN > 1 { + f.projectClash = exactN + } + if f.projectSel >= len(f.projectMatches) { + f.projectSel = 0 + } +} + +// applyClientSelection puts the highlighted suggestion in the Client field. +// A different client clears Project. +func (f *timerForm) applyClientSelection() { + if len(f.clientMatches) == 0 { + return + } + item := f.clientMatches[f.clientSel] + if item.id == 0 { + f.clientID = 0 + f.clearProject() + } else if item.id != f.clientID { + f.clearProject() + f.clientID = item.id + for _, c := range f.allClients { + if c.ID == item.id { + f.inputs[fieldClient].SetValue(c.Name) + break + } + } + } + f.showClientDrop = false + f.rebuildProjectMatches() +} + +// clearProject empties Project, so a project of the old client isn't kept. +func (f *timerForm) clearProject() { + f.inputs[fieldProject].SetValue("") + f.projectID = 0 + f.projectSel = 0 +} + +// applyProjectSelection puts the highlighted suggestion in the Project +// field, and its client in an empty Client field. +func (f *timerForm) applyProjectSelection() { + if len(f.projectMatches) == 0 { + return + } + item := f.projectMatches[f.projectSel] + f.projectID = item.id + for _, p := range f.allProjects { + if p.ID == item.id && item.id != 0 { + f.inputs[fieldProject].SetValue(p.Name) + if f.clientID == 0 && p.Client != nil { + f.clientID = p.Client.ID + f.inputs[fieldClient].SetValue(p.Client.Name) + delete(f.errs, fieldClient) + } + break + } + } + f.showProjectDrop = false +} + +// applyQuickAdd moves an "@client/project" ending from Task into Client and +// Project, when both are empty, matching existing names without regard to +// case. +func (f *timerForm) applyQuickAdd() { + if f.entryID != 0 { + return // Edit entry keeps a task's "@" as typed + } + if strings.TrimSpace(f.inputs[fieldClient].Value()) != "" || strings.TrimSpace(f.inputs[fieldProject].Value()) != "" { + return + } + q := quickadd.Parse(f.inputs[fieldTask].Value()) + if !q.Placed() { + return + } + f.inputs[fieldTask].SetValue(q.Task) + f.clientID, f.projectID = 0, 0 + f.inputs[fieldClient].SetValue(q.Client) + for _, c := range f.allClients { + if strings.EqualFold(c.Name, q.Client) { + f.clientID = c.ID + f.inputs[fieldClient].SetValue(c.Name) + break + } + } + f.inputs[fieldProject].SetValue(q.Project) + for _, p := range f.allProjects { + if f.clientID != 0 && p.ClientID == f.clientID && strings.EqualFold(p.Name, q.Project) { + f.projectID = p.ID + f.inputs[fieldProject].SetValue(p.Name) + break + } + } + f.rebuildClientMatches() + f.rebuildProjectMatches() +} + +// ── Focus ───────────────────────────────────────────────────────────────────── + +// order is the tab order: the boards' order of the fields, then the buttons. +func (f *timerForm) order() []int { + if f.entryID == 0 { + return []int{fieldTask, fieldClient, fieldProject, fieldNotes, fieldStart, fieldEnd, fieldSave, fieldCancel} + } + o := []int{fieldTask, fieldClient, fieldProject, fieldStart, fieldEnd, fieldNotes, fieldInvoiced, fieldPaid, fieldSave, fieldCancel} + if f.canDelete { + o = append(o, fieldDelete) + } + return o +} + +// step returns the field d places from the focused one in tab order. +func (f *timerForm) step(d int) int { + o := f.order() + at := 0 + for i, idx := range o { + if idx == f.focusIdx { + at = i + } + } + return o[((at+d)%len(o)+len(o))%len(o)] +} + +// focusField moves the focus to idx, with the suggestions closed. +func (f *timerForm) focusField(idx int) { + f.choseClient, f.choseProject = false, false + for i := range f.inputs { + f.inputs[i].Blur() + } + f.focusIdx = idx + if idx < fieldInputs { + f.inputs[idx].Focus() + } + f.showClientDrop, f.showProjectDrop = false, false +} + +// leave finishes the focused field before the focus moves or the form is +// saved: Task's quick add, or the suggestion picked in Client or Project. +func (f *timerForm) leave() { + switch f.focusIdx { + case fieldTask: + f.applyQuickAdd() + case fieldClient: + switch { + case f.showClientDrop && f.choseClient: + f.applyClientSelection() + case f.clientExact && f.clientID == 0: + f.clientSel = 0 + f.applyClientSelection() + } + case fieldProject: + switch { + case f.showProjectDrop && f.choseProject: + f.applyProjectSelection() + case f.projectExact && f.projectID == 0: + f.projectSel = 0 + f.applyProjectSelection() + } + } + f.showClientDrop, f.showProjectDrop = false, false +} + +// toggleBilling flips Invoiced or Paid. Paid needs Invoiced: ticking Paid +// ticks Invoiced, and clearing Invoiced clears Paid. +func (f *timerForm) toggleBilling(idx int) { + switch idx { + case fieldInvoiced: + f.invoiced = !f.invoiced + if !f.invoiced { + f.paid = false + } + case fieldPaid: + f.paid = !f.paid + if f.paid { + f.invoiced = true + } + } + delete(f.errs, fieldInvoiced) +} + +// ── Keys ────────────────────────────────────────────────────────────────────── + +// updateTimerFormFields handles a key in a timer form: tab and shift+tab +// move, the arrows choose a suggestion, space toggles and presses buttons, +// and enter picks a suggestion when they're open and otherwise saves (or +// presses Cancel or Delete entry when one has focus). It returns +// formCancel, formSubmit or formDelete for the caller to act on, or "". +// +// It's a function of the form alone, not of TimersModel, because Reports +// edits entries with the same form: the app sends every message but keys +// to all tabs, so form state kept in TimersModel would react to both. +func updateTimerFormFields(f *timerForm, msg tea.KeyMsg) (action string, cmd tea.Cmd) { + switch { + case key.Matches(msg, timersKeys.Cancel): + return formCancel, nil + + case msg.Type == tea.KeyTab: + f.leave() + f.focusField(f.step(1)) + return "", nil + + case msg.Type == tea.KeyShiftTab: + f.leave() + f.focusField(f.step(-1)) + return "", nil + + case msg.Type == tea.KeyEnter: + switch { + case f.focusIdx == fieldClient && f.showClientDrop: + f.applyClientSelection() + f.focusField(f.step(1)) + return "", nil + case f.focusIdx == fieldProject && f.showProjectDrop: + f.applyProjectSelection() + f.focusField(f.step(1)) + return "", nil + case f.focusIdx == fieldCancel: + return formCancel, nil + case f.focusIdx == fieldDelete: + return formDelete, nil + } + f.leave() + return formSubmit, nil + + case key.Matches(msg, dropdownUp), key.Matches(msg, dropdownDown): + up := key.Matches(msg, dropdownUp) + switch f.focusIdx { + case fieldClient: + f.choseClient = f.choseClient || f.showClientDrop + f.clientSel = moveSel(f.clientSel, len(f.clientMatches), up, f.showClientDrop) + f.showClientDrop = len(f.clientMatches) > 0 + case fieldProject: + f.choseProject = f.choseProject || f.showProjectDrop + f.projectSel = moveSel(f.projectSel, len(f.projectMatches), up, f.showProjectDrop) + f.showProjectDrop = len(f.projectMatches) > 0 + } + return "", nil + } + + if msg.String() == " " { + switch f.focusIdx { + case fieldInvoiced, fieldPaid: + f.toggleBilling(f.focusIdx) + return "", nil + case fieldSave: + return formSubmit, nil + case fieldCancel: + return formCancel, nil + case fieldDelete: + return formDelete, nil + } + } + + idx := f.focusIdx + if idx >= fieldInputs { + return "", nil + } + before := f.inputs[idx].Value() + f.inputs[idx], cmd = f.inputs[idx].Update(msg) + if f.inputs[idx].Value() == before { + return "", cmd + } + delete(f.errs, idx) + switch idx { + case fieldClient: + f.clientID = 0 + f.clientSel, f.choseClient = 0, false + f.clearProject() + f.rebuildClientMatches() + f.rebuildProjectMatches() + f.showClientDrop = strings.TrimSpace(f.inputs[fieldClient].Value()) != "" && len(f.clientMatches) > 0 + case fieldProject: + f.projectID = 0 + f.projectSel, f.choseProject = 0, false + f.rebuildProjectMatches() + f.showProjectDrop = strings.TrimSpace(f.inputs[fieldProject].Value()) != "" && len(f.projectMatches) > 0 + } + return "", cmd +} + +// moveSel moves a suggestion selection up or down. The first press only +// opens the suggestions. +func moveSel(sel, n int, up, open bool) int { + switch { + case !open || n == 0: + return min(sel, max(0, n-1)) + case up: + return max(0, sel-1) + default: + return min(n-1, sel+1) + } +} + +// ── Values ──────────────────────────────────────────────────────────────────── + +// timerFormValues is a timer form's fields, read and checked. +type timerFormValues struct { + task, clientName, projectName, notes string + clientID, projectID int64 + // start is when the entry began (now when a new timer's Start is + // blank); end is when it ended, nil while it runs. + start time.Time + end *time.Time + // Billing, for Edit entry. + invoiced, paid bool + // For Edit entry, the entry as the form found it: the save refuses + // if it has changed since. + orig entrySnapshot +} + +// validateTimerForm reads f's fields at now. errs maps each field that +// needs fixing to why; v is only complete when errs is empty. +func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fieldErrors) { + errs = fieldErrors{} + task := f.inputs[fieldTask].Value() + v.clientName = strings.TrimSpace(f.inputs[fieldClient].Value()) + v.projectName = strings.TrimSpace(f.inputs[fieldProject].Value()) + v.clientID, v.projectID = f.clientID, f.projectID + if f.entryID == 0 && v.clientName == "" && v.projectName == "" { + if q := quickadd.Parse(task); q.Placed() { + task, v.clientName, v.projectName = q.Task, q.Client, q.Project + v.clientID, v.projectID = 0, 0 + } + } + v.task = strings.TrimSpace(task) + if v.task == "" { + errs[fieldTask] = errTaskRequired + } + if f.projectClash > 1 && v.projectID == 0 && v.clientName == "" { + errs[fieldProject] = errPickProjectClient + } + v.notes = strings.TrimSpace(f.inputs[fieldNotes].Value()) + v.invoiced, v.paid = f.invoiced, f.paid + v.orig = f.orig + + startText := strings.TrimSpace(f.inputs[fieldStart].Value()) + startNow := startText == "" || strings.EqualFold(startText, "now") + startOK := false + switch { + case startText == "" && f.entryID != 0: + errs[fieldStart] = errStartRequired + case startNow: + v.start, startOK = now, true + default: + day := now + if f.entryID != 0 { + day = f.orig.start + } + t, ok := parseFormTime(startText, now, day) + if f.entryID != 0 && startText == f.filledStart { + t, ok = f.orig.start, true + } + // A new timer's bare Start later than now, logged with an End, is + // last night's: a block across midnight. Alone it would start a + // timer hours ago, so it stays an error. + endGiven := strings.TrimSpace(f.inputs[fieldEnd].Value()) != "" + if _, bare := parseBareTime(startText, day); ok && bare && f.entryID == 0 && endGiven && t.After(now) { + t = t.AddDate(0, 0, -1) + } + switch { + case !ok: + errs[fieldStart] = errTimeFormat + case t.After(now): + errs[fieldStart] = errStartFuture + default: + v.start, startOK = t, true + } + } + + endText := strings.TrimSpace(f.inputs[fieldEnd].Value()) + switch { + case endText == "": + if f.entryID != 0 && !f.running { + errs[fieldEnd] = errEndRequired + } + case f.entryID == 0 && startNow: + errs[fieldEnd] = errEndNeedsStart + default: + day := now + switch { + case f.orig.end != nil: + day = *f.orig.end + case startOK: + day = v.start + } + t, ok := parseFormTime(endText, now, day) + endKept := f.orig.end != nil && endText == f.filledEnd + if endKept { + t, ok = *f.orig.end, true + } + // A new timer's bare End before its Start is past midnight. + if _, bare := parseBareTime(endText, day); ok && bare && f.entryID == 0 && startOK && t.Before(v.start) { + t = t.AddDate(0, 0, 1) + } + // The fields hold minutes while a kept time has seconds: an End + // typed in a kept Start's minute (or a Start typed in a kept End's) + // is the same moment, a zero-length entry. + if ok && startOK && t.Before(v.start) && t.Truncate(time.Minute).Equal(v.start.Truncate(time.Minute)) { + if endKept { + v.start = t + } else { + t = v.start + } + } + switch { + case !ok: + errs[fieldEnd] = errTimeFormat + case t.After(now): + errs[fieldEnd] = errEndFuture + case startOK && t.Before(v.start): + errs[fieldEnd] = errEndBeforeStart + default: + v.end = &t + } + } + + if f.running && v.invoiced && endText == "" { + errs[fieldInvoiced] = errInvoiceRunning + } + return v, errs +} + +// parseFormTime reads a typed time: "now", the CLI's formats (RFC3339 or +// local "2006-01-02 15:04"), a date with a 12-hour time, or a time alone +// ("9:05 AM", "17:30"), which is on day's date: today for a new timer, the +// entry's own day when editing. +func parseFormTime(s string, now, day time.Time) (time.Time, bool) { + s = strings.TrimSpace(s) + if strings.EqualFold(s, "now") { + return now, true + } + if t, err := model.ParseEditTime(s); err == nil { + return t, true + } + up := strings.ToUpper(s) + for _, layout := range []string{"2006-01-02 3:04 PM", "2006-01-02 3:04PM"} { + if t, err := time.ParseInLocation(layout, up, time.Local); err == nil { + return t, true + } + } + return parseBareTime(s, day) +} + +// parseBareTime reads a time of day alone ("9:05 AM", "17:30") on day's +// date. ok is false for anything else, dates included. +func parseBareTime(s string, day time.Time) (time.Time, bool) { + up := strings.ToUpper(strings.TrimSpace(s)) + for _, layout := range []string{"15:04", "3:04 PM", "3:04PM", "3 PM", "3PM"} { + if t, err := time.ParseInLocation(layout, up, time.Local); err == nil { + d := day.Local() + return time.Date(d.Year(), d.Month(), d.Day(), t.Hour(), t.Minute(), 0, 0, time.Local), true + } + } + return time.Time{}, false +} + +var ( + errEditGone = errors.New(errEntryGone) + errEditStale = errors.New(errEntryChanged) +) + +// saveEditEntry writes the fields the user changed in Edit entry to the +// entry entryID, and leaves the rest as they are now, so a change made +// elsewhere while the form was open (the CLI's --invoiced, the bar +// stopping the timer) stands. It refuses with errEditStale when a field +// the user changed was also changed elsewhere, or the two together would +// end before they start; with errEditGone when the entry is deleted. Both +// are checked before any client or project is created. A changed Client +// or Project is found or created; both blank means the uncategorized +// project, as for `notch start` and a new timer. +func saveEditEntry(database *db.DB, entryID int64, v timerFormValues) error { + target, err := database.GetEntry(entryID) + if err != nil { + return err + } + if target == nil { + return errEditGone + } + o, now := v.orig, snapshotOf(target) + // The form trims what it reads, so the stored text is trimmed to + // compare: whitespace alone isn't a change. + taskCh := v.task != strings.TrimSpace(o.task) + notesCh := v.notes != strings.TrimSpace(o.notes) + projectCh := v.projectID != o.projectID + startCh, endCh := !v.start.Equal(o.start), !sameTime(v.end, o.end) + // Invoiced and paid are one unit: paid needs invoiced, so a change to + // either here and either elsewhere could merge into paid but not + // invoiced. + billingCh := v.invoiced != o.invoiced || v.paid != o.paid + billingElsewhere := now.invoiced != o.invoiced || now.paid != o.paid + if (taskCh && now.task != o.task) || (notesCh && now.notes != o.notes) || + (projectCh && now.projectID != o.projectID) || + (startCh && !now.start.Equal(o.start)) || (endCh && !sameTime(now.end, o.end)) || + (billingCh && billingElsewhere) { + return errEditStale + } + if taskCh { + target.Task = v.task + } + if notesCh { + target.Notes = v.notes + } + if startCh { + target.StartTime = v.start + } + if endCh { + target.EndTime = v.end + } + if target.EndTime != nil && target.EndTime.Before(target.StartTime) { + return errEditStale + } + // The merged entry, times first, must keep the billing rules (paid + // needs invoiced; a running timer can't be billed). + if billingCh { + if err := model.ApplyBilling(target, &v.invoiced, &v.paid); err != nil { + return errEditStale + } + } + if projectCh { + projectID, err := database.ResolveOrCreateProject(v.clientID, v.clientName, v.projectID, v.projectName) + if err == nil && projectID <= 0 { + projectID, err = database.EnsureUncategorizedProject() + } + if err != nil { + return err + } + target.ProjectID = projectID + } + return database.UpdateEntry(target) +} + +// submitEdit saves an Edit entry form, for Timers and Reports alike. +// closeForm is false only when the form should stay open: a stale entry +// (its form error is set) or a failed write. reload are the caller's +// reloads, run after a save or when the entry turns out to be gone. +func (f *timerForm) submitEdit(database *db.DB, v timerFormValues, reload ...tea.Cmd) (closeForm bool, cmd tea.Cmd) { + err := saveEditEntry(database, f.entryID, v) + switch { + case errors.Is(err, errEditStale): + f.formErr = errEntryChanged + return false, nil + case errors.Is(err, errEditGone): + return true, tea.Batch(append(reload, ErrCmd(errEntryGone))...) + case err != nil: + return false, ErrCmd(err.Error()) + } + return true, tea.Batch(append(append([]tea.Cmd{RunningChangedCmd()}, reload...), StatusCmd("Entry updated"))...) +} + +// ── View ────────────────────────────────────────────────────────────────────── + +// view draws the form as a modal for a body w×h. saveLabel is "Save & +// start" for a new timer and "Save" for an edit. +func (f timerForm) view(w, h int, saveLabel string) []string { + sw := stripWidth(modalInner(theme.ModalWidth, w)) + field := func(label string, idx int) modalField { + return modalField{ + label: label, + focused: f.focusIdx == idx, + mark: f.focusIdx == idx, + strip: true, + value: stripInput(f.inputs[idx], sw), + err: f.errs[idx], + } + } + task := field("Task", fieldTask) + client := field("Client", fieldClient) + client.suggests = true + if f.focusIdx == fieldClient && f.showClientDrop && len(f.clientMatches) > 0 { + client.suggest = func(n int) []string { return suggestions(f.clientMatches, f.clientSel, sw, n) } + } + project := field("Project", fieldProject) + project.suggests = true + if f.projectClash > 1 && f.projectID == 0 && f.errs[fieldProject] == "" { + project.hint = fmt.Sprintf("%d clients have %s — pick one", f.projectClash, strings.TrimSpace(f.inputs[fieldProject].Value())) + } + if f.focusIdx == fieldProject && f.showProjectDrop && len(f.projectMatches) > 0 { + project.suggest = func(n int) []string { return suggestions(f.projectMatches, f.projectSel, sw, n) } + } + start, end, notes := field("Start", fieldStart), field("End", fieldEnd), field("Notes", fieldNotes) + save := modalButton{label: saveLabel, kind: buttonPrimary, focused: f.focusIdx == fieldSave} + cancel := modalButton{label: "Cancel", kind: buttonSecondary, focused: f.focusIdx == fieldCancel} + + fm := formModal{left: []modalButton{save, cancel}, hint: "tab next · esc close", err: f.formErr} + if f.entryID == 0 { + fm.title = "New timer" + task.hint = "end it with @client/project to fill both" + start.hint = "or a past time like 9:05 AM, with an End" + fm.fields = []modalField{task, client, project, notes, start, end} + return fm.render(w, h) + } + fm.title = "Edit entry" + billing := modalField{ + label: "Billing", + focused: f.focusIdx == fieldInvoiced || f.focusIdx == fieldPaid, + value: toggle("Invoiced", f.invoiced, f.focusIdx == fieldInvoiced) + blankLine(3) + toggle("Paid", f.paid, f.focusIdx == fieldPaid), + err: f.errs[fieldInvoiced], + hint: "space toggles", + } + fm.fields = []modalField{task, client, project, start, end, notes, billing} + if f.canDelete { + fm.right = []modalButton{{label: "Delete entry", kind: buttonDanger, focused: f.focusIdx == fieldDelete}} + fm.hint = "" + } + return fm.render(w, h) +} + +// formHelp is the key line for a timer form. +func (f timerForm) help(saveLabel string) []Hotkey { + keys := []Hotkey{{"tab", "next field"}} + switch f.focusIdx { + case fieldClient, fieldProject: + keys = append(keys, Hotkey{"↑↓", "suggestions"}) + case fieldInvoiced, fieldPaid: + keys = append(keys, Hotkey{"space", "toggle"}) + } + return append(keys, Hotkey{"enter", strings.ToLower(saveLabel)}, Hotkey{"esc", "cancel"}) +} diff --git a/internal/ui/views/timer_form_test.go b/internal/ui/views/timer_form_test.go new file mode 100644 index 0000000..1898bee --- /dev/null +++ b/internal/ui/views/timer_form_test.go @@ -0,0 +1,1501 @@ +package views + +import ( + "errors" + "fmt" + "regexp" + "strconv" + "strings" + "testing" + "time" + + "github.com/aliasproject/notch/internal/db" + "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/theme" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" +) + +// Tests for the modal timer form (ALI-2616): keys, quick add, validation +// messages tied to their fields, saving through AddEntry, the delete +// confirm and the modal views. + +var ( + keyTab = tea.KeyMsg{Type: tea.KeyTab} + keyShiftTab = tea.KeyMsg{Type: tea.KeyShiftTab} + keyEnter = tea.KeyMsg{Type: tea.KeyEnter} + keyEsc = tea.KeyMsg{Type: tea.KeyEsc} + keyDown = tea.KeyMsg{Type: tea.KeyDown} + keyUp = tea.KeyMsg{Type: tea.KeyUp} + keySpace = tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}} +) + +func typeInto(f *timerForm, s string) { + for _, r := range s { + updateTimerFormFields(f, runeKey(r)) + } +} + +// editForm is an Edit entry form filled from e. +func editForm(e *model.Entry, clients []*model.Client, projects []*model.Project) timerForm { + f := newTimerForm(clients, projects) + f.fill(e) + return f +} + +// ── Keys ────────────────────────────────────────────────────────────────────── + +func TestTimerForm_TabOrderFollowsTheBoards(t *testing.T) { + walk := func(f timerForm) []int { + var got []int + for range f.order() { + updateTimerFormFields(&f, keyTab) + got = append(got, f.focusIdx) + } + return got + } + newWant := []int{fieldClient, fieldProject, fieldNotes, fieldStart, fieldEnd, fieldSave, fieldCancel, fieldTask} + if got := walk(newTimerForm(nil, nil)); !equalInts(got, newWant) { + t.Errorf("New timer tab order = %v, want %v", got, newWant) + } + + p := mkProject(1, "Web", mkClient(1, "Acme", 0)) + f := editForm(mkEntry(7, p, "t", time.Now().Add(-2*time.Hour), 30), nil, nil) + f.canDelete = true + editWant := []int{fieldClient, fieldProject, fieldStart, fieldEnd, fieldNotes, fieldInvoiced, fieldPaid, fieldSave, fieldCancel, fieldDelete, fieldTask} + if got := walk(f); !equalInts(got, editWant) { + t.Errorf("Edit entry tab order = %v, want %v", got, editWant) + } + + g := newTimerForm(nil, nil) + updateTimerFormFields(&g, keyShiftTab) + if g.focusIdx != fieldCancel { + t.Errorf("shift+tab from Task = %d, want Cancel (%d)", g.focusIdx, fieldCancel) + } +} + +func equalInts(a, b []int) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestTimerForm_EnterSavesFromAFieldAndPressesButtons(t *testing.T) { + f := newTimerForm(nil, nil) + typeInto(&f, "Pricing page") + if a, _ := updateTimerFormFields(&f, keyEnter); a != formSubmit { + t.Errorf("enter in Task = %q, want %q (the board's \"enter save & start\")", a, formSubmit) + } + f.focusField(fieldCancel) + if a, _ := updateTimerFormFields(&f, keyEnter); a != formCancel { + t.Errorf("enter on Cancel = %q, want %q", a, formCancel) + } + f.focusField(fieldSave) + if a, _ := updateTimerFormFields(&f, keySpace); a != formSubmit { + t.Errorf("space on Save = %q, want %q", a, formSubmit) + } + f.focusField(fieldDelete) + if a, _ := updateTimerFormFields(&f, keyEnter); a != formDelete { + t.Errorf("enter on Delete entry = %q, want %q", a, formDelete) + } + if a, _ := updateTimerFormFields(&f, keyEsc); a != formCancel { + t.Errorf("esc = %q, want %q", a, formCancel) + } +} + +func TestTimerForm_SuggestionsOpenAsYouTypeAndEnterPicks(t *testing.T) { + clients := []*model.Client{mkClient(1, "Harbor & Pine", 0), mkClient(2, "Harbinger", 0)} + f := newTimerForm(clients, nil) + f.focusField(fieldClient) + if f.showClientDrop { + t.Fatal("suggestions shouldn't open before anything is typed") + } + typeInto(&f, "Harb") + if !f.showClientDrop { + t.Fatal("typing should open the suggestions") + } + labels := []string{} + for _, m := range f.clientMatches { + labels = append(labels, m.label) + } + if want := "+ Create “Harb”"; labels[len(labels)-1] != want { + t.Errorf("suggestions = %v, want them to end with %q", labels, want) + } + updateTimerFormFields(&f, keyDown) + if f.clientSel != 1 { + t.Errorf("clientSel after down = %d, want 1", f.clientSel) + } + updateTimerFormFields(&f, keyUp) + updateTimerFormFields(&f, keyDown) + if a, _ := updateTimerFormFields(&f, keyEnter); a != "" { + t.Fatalf("enter with suggestions open = %q, want it to pick, not save", a) + } + if f.clientID != 2 || f.inputs[fieldClient].Value() != "Harbinger" || f.focusIdx != fieldProject { + t.Errorf("after picking: clientID %d, Client %q, focus %d; want 2, Harbinger, Project", f.clientID, f.inputs[fieldClient].Value(), f.focusIdx) + } +} + +func TestTimerForm_ExactMatchIsSuggestedFirst(t *testing.T) { + clients := []*model.Client{mkClient(1, "Harbor & Pine", 0), mkClient(2, "Harbor", 0)} + f := newTimerForm(clients, nil) + f.focusField(fieldClient) + typeInto(&f, "harbor") + updateTimerFormFields(&f, keyTab) + if f.clientID != 2 { + t.Errorf("tab after typing an exact name picked client %d, want 2 (Harbor)", f.clientID) + } +} + +func TestTimerForm_TabWithSuggestionsClosedKeepsTheTypedName(t *testing.T) { + clients := []*model.Client{mkClient(1, "Acme", 0)} + f := newTimerForm(clients, nil) + f.focusField(fieldClient) + // Leaving an untouched Client empty mustn't pick the first client. + updateTimerFormFields(&f, keyTab) + if f.clientID != 0 || f.inputs[fieldClient].Value() != "" { + t.Errorf("tab through an empty Client set it to %q (id %d), want it left empty", f.inputs[fieldClient].Value(), f.clientID) + } +} + +func TestTimerForm_QuickAddFillsClientAndProjectOnLeavingTask(t *testing.T) { + c := mkClient(4, "Fieldnote Studio", 95) + p := mkProject(9, "Brand refresh", c) + p.ClientID = c.ID + f := newTimerForm([]*model.Client{c}, []*model.Project{p}) + typeInto(&f, "Logo explorations @fieldnote studio/brand refresh") + updateTimerFormFields(&f, keyTab) + + if got := f.inputs[fieldTask].Value(); got != "Logo explorations" { + t.Errorf("Task = %q, want %q", got, "Logo explorations") + } + if f.clientID != c.ID || f.inputs[fieldClient].Value() != "Fieldnote Studio" { + t.Errorf("Client = %q (id %d), want the existing Fieldnote Studio", f.inputs[fieldClient].Value(), f.clientID) + } + if f.projectID != p.ID || f.inputs[fieldProject].Value() != "Brand refresh" { + t.Errorf("Project = %q (id %d), want the existing Brand refresh", f.inputs[fieldProject].Value(), f.projectID) + } +} + +func TestTimerForm_QuickAddLeavesAFilledClientAlone(t *testing.T) { + f := newTimerForm(nil, nil) + f.inputs[fieldClient].SetValue("Acme") + typeInto(&f, "Mail bob @home") + updateTimerFormFields(&f, keyTab) + if got := f.inputs[fieldTask].Value(); got != "Mail bob @home" { + t.Errorf("Task = %q, want it kept as typed when Client is already filled", got) + } +} + +func TestTimerForm_BillingToggles(t *testing.T) { + p := mkProject(1, "Web", mkClient(1, "Acme", 0)) + f := editForm(mkEntry(7, p, "t", time.Now().Add(-2*time.Hour), 30), nil, nil) + f.focusField(fieldPaid) + updateTimerFormFields(&f, keySpace) + if !f.paid || !f.invoiced { + t.Errorf("space on Paid: invoiced %v, paid %v; want both ticked (paid needs invoiced)", f.invoiced, f.paid) + } + f.focusField(fieldInvoiced) + updateTimerFormFields(&f, keySpace) + if f.paid || f.invoiced { + t.Errorf("space on Invoiced: invoiced %v, paid %v; want both cleared", f.invoiced, f.paid) + } +} + +func TestTimerForm_TypingClearsOnlyThatFieldsError(t *testing.T) { + f := newTimerForm(nil, nil) + f.errs = fieldErrors{fieldTask: errTaskRequired, fieldEnd: errEndBeforeStart} + typeInto(&f, "x") + if _, ok := f.errs[fieldTask]; ok { + t.Error("typing in Task should clear Task's error") + } + if f.errs[fieldEnd] != errEndBeforeStart { + t.Error("typing in Task shouldn't clear End's error") + } + // An arrow key changes nothing, so it leaves the error. + f.errs[fieldTask] = errTaskRequired + updateTimerFormFields(&f, tea.KeyMsg{Type: tea.KeyLeft}) + if f.errs[fieldTask] != errTaskRequired { + t.Error("a key that doesn't change the value shouldn't clear the error") + } +} + +// ── Validation ──────────────────────────────────────────────────────────────── + +func TestValidateTimerForm_Messages(t *testing.T) { + now := time.Date(2026, 12, 3, 12, 0, 0, 0, time.Local) + p := mkProject(1, "Web", mkClient(1, "Acme", 0)) + stopped := mkEntry(7, p, "Logo", now.Add(-3*time.Hour), 60) + running := mkRunningEntry(8, p, "Logo", now.Add(-time.Hour)) + + cases := []struct { + name string + form func() timerForm + field int + want string + }{ + {"blank task", func() timerForm { return newTimerForm(nil, nil) }, fieldTask, errTaskRequired}, + {"start not a time", func() timerForm { + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("x") + f.inputs[fieldStart].SetValue("yesterdayish") + return f + }, fieldStart, errTimeFormat}, + {"start in the future", func() timerForm { + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("x") + f.inputs[fieldStart].SetValue("2026-12-03 1:00 PM") + return f + }, fieldStart, errStartFuture}, + {"end in the future", func() timerForm { + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("x") + f.inputs[fieldStart].SetValue("9:00") + f.inputs[fieldEnd].SetValue("2026-12-03 13:00") + return f + }, fieldEnd, errEndFuture}, + {"end without a past start", func() timerForm { + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("x") + f.inputs[fieldEnd].SetValue("11:00") + return f + }, fieldEnd, errEndNeedsStart}, + {"end before start", func() timerForm { + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("x") + f.inputs[fieldStart].SetValue("11:00 AM") + f.inputs[fieldEnd].SetValue("2026-12-03 10:30") + return f + }, fieldEnd, errEndBeforeStart}, + {"edit: start cleared", func() timerForm { + f := editForm(stopped, nil, nil) + f.inputs[fieldStart].SetValue("") + return f + }, fieldStart, errStartRequired}, + {"edit: end cleared on a stopped entry", func() timerForm { + f := editForm(stopped, nil, nil) + f.inputs[fieldEnd].SetValue("") + return f + }, fieldEnd, errEndRequired}, + {"edit: invoicing a running entry", func() timerForm { + f := editForm(running, nil, nil) + f.invoiced = true + return f + }, fieldInvoiced, errInvoiceRunning}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, errs := validateTimerForm(c.form(), now) + if errs[c.field] != c.want { + t.Errorf("errs = %v, want %q on field %d", errs, c.want, c.field) + } + if len(errs) != 1 { + t.Errorf("errs = %v, want only that one", errs) + } + }) + } +} + +func TestValidateTimerForm_CountsEveryFieldAtOnce(t *testing.T) { + now := time.Date(2026, 12, 3, 12, 0, 0, 0, time.Local) + f := newTimerForm(nil, nil) + f.inputs[fieldStart].SetValue("soon") + _, errs := validateTimerForm(f, now) + if len(errs) != 2 || errs[fieldTask] != errTaskRequired || errs[fieldStart] != errTimeFormat { + t.Errorf("errs = %v, want Task and Start", errs) + } + if FixingText(len(errs)) != "2 fields need fixing" || FixingText(1) != "1 field needs fixing" { + t.Errorf("FixingText = %q / %q", FixingText(len(errs)), FixingText(1)) + } +} + +func TestValidateTimerForm_ValidValues(t *testing.T) { + now := time.Date(2026, 12, 3, 12, 0, 0, 0, time.Local) + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("Logo @Fieldnote Studio/Brand refresh") + f.inputs[fieldNotes].SetValue(" Three directions ") + f.inputs[fieldStart].SetValue("9:05 am") + v, errs := validateTimerForm(f, now) + if len(errs) != 0 { + t.Fatalf("errs = %v, want none", errs) + } + if want := time.Date(2026, 12, 3, 9, 5, 0, 0, time.Local); !v.start.Equal(want) || v.end != nil { + t.Errorf("start %v, end %v; want %v and running", v.start, v.end, want) + } + if v.task != "Logo" || v.clientName != "Fieldnote Studio" || v.projectName != "Brand refresh" || v.notes != "Three directions" { + t.Errorf("values = %+v, want the quick add read and notes trimmed", v) + } + + blank := newTimerForm(nil, nil) + blank.inputs[fieldTask].SetValue("x") + if v, _ := validateTimerForm(blank, now); !v.start.Equal(now) { + t.Errorf("a blank Start = %v, want now (%v)", v.start, now) + } +} + +func TestParseFormTime(t *testing.T) { + now := time.Date(2026, 12, 3, 12, 0, 0, 0, time.Local) + for in, want := range map[string]time.Time{ + "now": now, + "2026-12-02 17:30": time.Date(2026, 12, 2, 17, 30, 0, 0, time.Local), + "2026-12-02 5:30 PM": time.Date(2026, 12, 2, 17, 30, 0, 0, time.Local), + "9:05 AM": time.Date(2026, 12, 3, 9, 5, 0, 0, time.Local), + "9:05am": time.Date(2026, 12, 3, 9, 5, 0, 0, time.Local), + "17:30": time.Date(2026, 12, 3, 17, 30, 0, 0, time.Local), + "3 pm": time.Date(2026, 12, 3, 15, 0, 0, 0, time.Local), + } { + got, ok := parseFormTime(in, now, now) + if !ok || !got.Equal(want) { + t.Errorf("parseFormTime(%q) = %v, %v; want %v", in, got, ok, want) + } + } + if _, ok := parseFormTime("half nine", now, now); ok { + t.Error("parseFormTime should refuse text that isn't a time") + } +} + +// ── Saving ──────────────────────────────────────────────────────────────────── + +// newTimersOn is a Timers tab on d with a New timer form open. +func newTimersOn(t *testing.T, d *db.DB) TimersModel { + t.Helper() + clients, _ := d.ListClients() + projects, _ := d.ListProjects(0) + m := NewTimers(d) + m.SetSize(100, 30) + return m.handleOpenForm(openFormMsg{clients: clients, projects: projects}) +} + +func runCmd(t *testing.T, cmd tea.Cmd) []tea.Msg { + t.Helper() + if cmd == nil { + t.Fatal("want a cmd") + } + var out []tea.Msg + var walk func(tea.Msg) + walk = func(msg tea.Msg) { + if b, ok := msg.(tea.BatchMsg); ok { + for _, c := range b { + if c != nil { + walk(c()) + } + } + return + } + out = append(out, msg) + } + walk(cmd()) + return out +} + +func TestSubmitForm_NewTimerSavesNotesAndSelectsIt(t *testing.T) { + d := newTestDB(t) + m := newTimersOn(t, d) + m.form.inputs[fieldTask].SetValue("Logo explorations @Fieldnote Studio/Brand refresh") + m.form.inputs[fieldNotes].SetValue("Three directions, one to keep.") + + got, cmd := m.submitForm(time.Now()) + if got.mode != timersModeList || len(got.form.errs) != 0 { + t.Fatalf("mode %v, errs %v; want the list and no errors", got.mode, got.form.errs) + } + var started *timerStartedMsg + status := "" + for _, msg := range runCmd(t, cmd) { + switch msg := msg.(type) { + case timerStartedMsg: + started = &msg + case StatusMsg: + status = string(msg) + } + } + e, _ := d.GetRunningEntry() + if e == nil || e.Task != "Logo explorations" || e.Notes != "Three directions, one to keep." { + t.Fatalf("running entry = %+v, want the task with its notes", e) + } + if e.Project == nil || e.Project.Name != "Brand refresh" || e.Project.Client == nil || e.Project.Client.Name != "Fieldnote Studio" { + t.Errorf("entry placed in %+v, want Fieldnote Studio › Brand refresh", e.Project) + } + if started == nil || started.id != e.ID { + t.Errorf("timerStartedMsg = %+v, want the new entry's ID %d", started, e.ID) + } + if status != "Timer started" { + t.Errorf("status = %q, want %q", status, "Timer started") + } +} + +func TestSubmitForm_PastStartStopsTheRunningTimerThere(t *testing.T) { + d := newTestDB(t) + now := time.Now() + old, err := d.AddEntry(mustUncategorized(t, d), "Earlier", "", now.Add(-2*time.Hour), nil) + if err != nil { + t.Fatal(err) + } + m := newTimersOn(t, d) + start := now.Add(-30 * time.Minute).Truncate(time.Minute) + m.form.inputs[fieldTask].SetValue("Later") + m.form.inputs[fieldStart].SetValue(start.Format("2006-01-02 15:04")) + _, cmd := m.submitForm(now) + runCmd(t, cmd) + + entries, _ := d.ListEntries(0, "", "", true) + for _, e := range entries { + if e.ID == old.ID && (e.EndTime == nil || !e.EndTime.Equal(start)) { + t.Errorf("the running timer ended at %v, want the new start %v", e.EndTime, start) + } + } + if r, _ := d.GetRunningEntry(); r == nil || r.Task != "Later" || !r.StartTime.Equal(start) { + t.Errorf("running = %+v, want Later from %v", r, start) + } +} + +func mustUncategorized(t *testing.T, d *db.DB) int64 { + t.Helper() + id, err := d.EnsureUncategorizedProject() + if err != nil { + t.Fatal(err) + } + return id +} + +func TestSubmitForm_StartBeforeTheRunningTimerIsAStartError(t *testing.T) { + d := newTestDB(t) + now := time.Now() + if _, err := d.AddEntry(mustUncategorized(t, d), "Running", "", now.Add(-time.Hour), nil); err != nil { + t.Fatal(err) + } + m := newTimersOn(t, d) + m.form.inputs[fieldTask].SetValue("Too early @Brand New Co") + m.form.inputs[fieldStart].SetValue(now.Add(-2 * time.Hour).Format("2006-01-02 15:04")) + + got, cmd := m.submitForm(now) + if cmd != nil || got.mode != timersModeNew { + t.Fatalf("mode %v, cmd %v; want the form kept open and nothing run", got.mode, cmd) + } + if got.form.errs[fieldStart] != errRunningLater || got.FieldErrors() != 1 { + t.Errorf("errs = %v, want %q on Start", got.form.errs, errRunningLater) + } + clients, _ := d.ListClients() + for _, c := range clients { + if c.Name == "Brand New Co" { + t.Error("a refused start created its client") + } + } +} + +func TestSubmitForm_StartAndEndAddAFinishedEntry(t *testing.T) { + d := newTestDB(t) + now := time.Now() + running, err := d.AddEntry(mustUncategorized(t, d), "Running", "", now.Add(-time.Hour), nil) + if err != nil { + t.Fatal(err) + } + m := newTimersOn(t, d) + start, end := now.Add(-5*time.Hour).Truncate(time.Minute), now.Add(-4*time.Hour).Truncate(time.Minute) + m.form.inputs[fieldTask].SetValue("Call") + m.form.inputs[fieldStart].SetValue(start.Format("2006-01-02 15:04")) + m.form.inputs[fieldEnd].SetValue(end.Format("2006-01-02 15:04")) + _, cmd := m.submitForm(now) + status := "" + for _, msg := range runCmd(t, cmd) { + if s, ok := msg.(StatusMsg); ok { + status = string(s) + } + } + if status != "Entry added" { + t.Errorf("status = %q, want %q", status, "Entry added") + } + if r, _ := d.GetRunningEntry(); r == nil || r.ID != running.ID { + t.Errorf("running = %+v, want the earlier timer left running", r) + } +} + +func TestSubmitForm_InvalidFormTouchesNothing(t *testing.T) { + d := newTestDB(t) + m := newTimersOn(t, d) + got, cmd := m.submitForm(time.Now()) + if cmd != nil || got.mode != timersModeNew || got.form.errs[fieldTask] != errTaskRequired { + t.Errorf("mode %v, cmd %v, errs %v; want the form open with Task's error", got.mode, cmd, got.form.errs) + } + if entries, _ := d.ListEntries(0, "", "", true); len(entries) != 0 { + t.Errorf("entries = %v, want none", entries) + } +} + +func TestSubmitForm_DBErrorGoesToTheStatusLine(t *testing.T) { + d := newTestDB(t) + m := newTimersOn(t, d) + m.form.inputs[fieldTask].SetValue("Do work") + d.Close() + got, cmd := m.submitForm(time.Now()) + if got.mode != timersModeNew { + t.Errorf("mode = %v, want the form kept open", got.mode) + } + if msgs := runCmd(t, cmd); len(msgs) != 1 { + t.Errorf("msgs = %v, want one ErrMsg", msgs) + } else if _, ok := msgs[0].(ErrMsg); !ok { + t.Errorf("msg = %T, want ErrMsg", msgs[0]) + } +} + +func TestSubmitForm_EditSavesTimesAndBilling(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 0) + p, _ := d.CreateProject(c.ID, "Web") + now := time.Now() + e, err := d.AddEntry(p.ID, "original", "", now.Add(-3*time.Hour), ptrTime(now.Add(-2*time.Hour))) + if err != nil { + t.Fatal(err) + } + m := NewTimers(d) + m.SetSize(100, 30) + m = m.setEntries(mustLoadEntries(d), e.ID) + m = m.handleOpenForm(openFormMsg{entryID: e.ID}) + if m.mode != timersModeEdit || !m.form.canDelete { + t.Fatalf("mode %v, canDelete %v; want Edit entry with Delete entry", m.mode, m.form.canDelete) + } + start := now.Add(-4 * time.Hour).Truncate(time.Minute) + m.form.inputs[fieldTask].SetValue("Updated task") + m.form.inputs[fieldStart].SetValue(start.Format("2006-01-02 15:04")) + m.form.invoiced, m.form.paid = true, true + + got, cmd := m.submitForm(now) + if got.mode != timersModeList { + t.Fatalf("mode = %v, errs = %v", got.mode, got.form.errs) + } + runCmd(t, cmd) + entries, _ := d.ListEntries(0, "", "", true) + if len(entries) != 1 || entries[0].Task != "Updated task" || !entries[0].StartTime.Equal(start) || !entries[0].Invoiced || !entries[0].Paid { + t.Errorf("entry after edit = %+v, want the new task, start and billing", entries[0]) + } +} + +func ptrTime(t time.Time) *time.Time { return &t } + +// storedEntry is entry id as the database has it. +func storedEntry(t *testing.T, d *db.DB, id int64) *model.Entry { + t.Helper() + entries, _ := d.ListEntries(0, "", "", true) + for _, e := range entries { + if e.ID == id { + return e + } + } + return nil +} + +// editValues opens Edit entry on the stored entry id and reads it. +func editValues(t *testing.T, d *db.DB, id int64, change func(*timerForm)) (timerForm, timerFormValues) { + t.Helper() + f := editForm(storedEntry(t, d, id), nil, nil) + if change != nil { + change(&f) + } + v, errs := validateTimerForm(f, time.Now()) + if len(errs) != 0 { + t.Fatalf("errs = %v", errs) + } + return f, v +} + +func TestSaveEditEntry_WriteError(t *testing.T) { + d := newTestDB(t) + e, _ := d.AddEntry(mustUncategorized(t, d), "t", "", time.Now().Add(-time.Hour), nil) + _, v := editValues(t, d, e.ID, nil) + v.projectID = 99999 // the foreign key fails + if err := saveEditEntry(d, e.ID, v); err == nil || errors.Is(err, errEditStale) || errors.Is(err, errEditGone) { + t.Errorf("err = %v, want the write's error", err) + } +} + +func TestSaveEditEntry_GoneEntryCreatesNothing(t *testing.T) { + d := newTestDB(t) + e, _ := d.AddEntry(mustUncategorized(t, d), "t", "", time.Now().Add(-time.Hour), nil) + _, v := editValues(t, d, e.ID, func(f *timerForm) { f.inputs[fieldClient].SetValue("Brand New Co") }) + if err := d.DeleteEntry(e.ID); err != nil { + t.Fatal(err) + } + if err := saveEditEntry(d, e.ID, v); !errors.Is(err, errEditGone) { + t.Errorf("err = %v, want %v", err, errEditGone) + } + clients, _ := d.ListClients() + for _, c := range clients { + if c.Name == "Brand New Co" { + t.Error("a save for a gone entry created its client") + } + } +} + +// editOpen is the Timers tab with Edit entry open on e. +func editOpen(t *testing.T, d *db.DB, e *model.Entry) TimersModel { + t.Helper() + m := NewTimers(d) + m.SetSize(100, 30) + m = m.setEntries(mustLoadEntries(d), e.ID) + return m.handleOpenForm(openFormMsg{entryID: e.ID}) +} + +// Changes made elsewhere while Edit entry is open (the bar stops the +// timer, the CLI marks it invoiced) stand: the save writes only what the +// user changed, so it can't restart the timer or clear the flag. +func TestSubmitForm_EditKeepsChangesMadeElsewhere(t *testing.T) { + d := newTestDB(t) + e, _ := d.AddEntry(mustUncategorized(t, d), "Running", "", time.Now().Add(-time.Hour), nil) + m := editOpen(t, d, e) + if err := d.StopEntry(e.ID); err != nil { + t.Fatal(err) + } + s := storedEntry(t, d, e.ID) + s.Invoiced = true + if err := d.UpdateEntry(s); err != nil { + t.Fatal(err) + } + m.form.inputs[fieldTask].SetValue("Renamed") + got, cmd := m.submitForm(time.Now()) + if got.mode != timersModeList || cmd == nil { + t.Fatalf("mode %v, errs %v, formErr %q; want it saved", got.mode, got.form.errs, got.form.formErr) + } + if s := storedEntry(t, d, e.ID); s.Task != "Renamed" || s.IsRunning() || !s.Invoiced { + t.Errorf("stored = %+v, want renamed, still stopped and still invoiced", s) + } +} + +// When a field the user changed was also changed elsewhere, the save +// refuses and the form says so. +func TestSubmitForm_EditRefusesAConflictingChange(t *testing.T) { + d := newTestDB(t) + start := time.Now().Add(-time.Hour) + e, _ := d.AddEntry(mustUncategorized(t, d), "Running", "", start, nil) + m := editOpen(t, d, e) + if err := d.StopEntry(e.ID); err != nil { + t.Fatal(err) + } + m.form.inputs[fieldEnd].SetValue(start.Add(30 * time.Minute).Format("2006-01-02 15:04")) + got, cmd := m.submitForm(time.Now()) + if got.mode != timersModeEdit || cmd != nil { + t.Fatalf("mode %v, cmd %v; want the form kept open and nothing run", got.mode, cmd) + } + if !strings.Contains(plain(got.View()), "✕ This entry changed elsewhere — reopen it to edit") { + t.Errorf("want the form error above the buttons:\n%s", plain(got.View())) + } + if s := storedEntry(t, d, e.ID); s.EndTime == nil || s.EndTime.Equal(start.Add(30*time.Minute).Truncate(time.Minute)) { + t.Errorf("stored end = %v, want the bar's stop kept", s.EndTime) + } +} + +func TestEditEntry_ClosesWhenItsEntryIsGone(t *testing.T) { + m, _, e := confirmTimers(t) + m = m.handleOpenForm(openFormMsg{entryID: e.ID}) + var rest []*model.Entry + for _, x := range m.entries { + if x.ID != e.ID { + rest = append(rest, x) + } + } + got, cmd := m.Update(timerEntriesMsg(rest)) + if got.mode != timersModeList { + t.Errorf("mode = %v, want Edit entry closed", got.mode) + } + if msgs := runCmd(t, cmd); len(msgs) != 1 || msgs[0] != ErrMsg(errEntryGone) { + t.Errorf("msgs = %v, want %q", msgs, errEntryGone) + } +} + +func TestStartCmd_UsesOneWriteAndSelectsTheNewEntry(t *testing.T) { + d := newTestDB(t) + pid := mustUncategorized(t, d) + old, _ := d.AddEntry(pid, "Old", "", time.Now().Add(-time.Hour), nil) + m := NewTimers(d) + var started *timerStartedMsg + for _, msg := range runCmd(t, m.startCmd(pid, "Resumed")) { + if s, ok := msg.(timerStartedMsg); ok { + started = &s + } + } + r, _ := d.GetRunningEntry() + if r == nil || r.Task != "Resumed" || started == nil || started.id != r.ID { + t.Fatalf("running %+v, started %+v; want Resumed running and selected", r, started) + } + entries, _ := d.ListEntries(0, "", "", true) + for _, e := range entries { + if e.ID == old.ID && (e.EndTime == nil || !e.EndTime.Equal(r.StartTime)) { + t.Errorf("the old timer ended at %v, want the new start %v", e.EndTime, r.StartTime) + } + } +} + +// ── Delete confirm ──────────────────────────────────────────────────────────── + +func confirmTimers(t *testing.T) (TimersModel, *db.DB, *model.Entry) { + t.Helper() + d := newTestDB(t) + pid := mustUncategorized(t, d) + now := time.Now() + e, _ := d.AddEntry(pid, "Logo explorations", "", now.Add(-3*time.Hour), ptrTime(now.Add(-90*time.Minute))) + if _, err := d.AddEntry(pid, "Other", "", now.Add(-5*time.Hour), ptrTime(now.Add(-4*time.Hour))); err != nil { + t.Fatal(err) + } + m := NewTimers(d) + m.SetSize(100, 30) + m = m.setEntries(mustLoadEntries(d), e.ID) + return m, d, e +} + +func TestConfirm_KeepItHasTheFocusFirst(t *testing.T) { + m, d, _ := confirmTimers(t) + m, _ = m.updateList(runeKey('d')) + if m.mode != timersModeConfirmDelete || m.deleteFocused { + t.Fatalf("mode %v, deleteFocused %v; want the confirm with Keep it focused", m.mode, m.deleteFocused) + } + got, cmd := m.updateConfirm(keyEnter) + if got.mode != timersModeList || cmd != nil { + t.Errorf("enter on Keep it: mode %v, cmd %v; want the list and nothing deleted", got.mode, cmd) + } + if entries, _ := d.ListEntries(0, "", "", true); len(entries) != 2 { + t.Errorf("entries = %d, want 2", len(entries)) + } +} + +func TestConfirm_TabThenEnterDeletesTheNamedEntry(t *testing.T) { + m, d, e := confirmTimers(t) + m, _ = m.updateList(runeKey('d')) + m.cursor = 1 // a reload moving the cursor mustn't change what's deleted + m, _ = m.updateConfirm(keyTab) + if !m.deleteFocused { + t.Fatal("tab should focus Delete") + } + _, cmd := m.updateConfirm(keyEnter) + runCmd(t, cmd) + entries, _ := d.ListEntries(0, "", "", true) + if len(entries) != 1 || entries[0].ID == e.ID { + t.Errorf("entries = %+v, want only the other entry left", entries) + } +} + +func TestConfirm_YDeletesAndOtherKeysDoNothing(t *testing.T) { + m, d, _ := confirmTimers(t) + m, _ = m.updateList(runeKey('d')) + if got, cmd := m.updateConfirm(runeKey('x')); got.mode != timersModeConfirmDelete || cmd != nil { + t.Errorf("x: mode %v, cmd %v; want nothing to happen", got.mode, cmd) + } + _, cmd := m.updateConfirm(runeKey('y')) + runCmd(t, cmd) + if entries, _ := d.ListEntries(0, "", "", true); len(entries) != 1 { + t.Errorf("entries = %d, want 1 after y", len(entries)) + } +} + +func TestConfirm_FromTheEditFormKeepGoesBackToIt(t *testing.T) { + m, _, e := confirmTimers(t) + m = m.handleOpenForm(openFormMsg{entryID: e.ID}) + m.form.focusField(fieldDelete) + m, _ = m.updateForm(keyEnter) + if m.mode != timersModeConfirmDelete || m.deleteID != e.ID || !m.deleteFromForm { + t.Fatalf("mode %v, deleteID %d; want the confirm for entry %d", m.mode, m.deleteID, e.ID) + } + m, _ = m.updateConfirm(keyEsc) + if m.mode != timersModeEdit { + t.Errorf("esc from the form's confirm: mode %v, want back to Edit entry", m.mode) + } +} + +// ── Views ───────────────────────────────────────────────────────────────────── + +func TestView_NewTimerModalOverTheDimmedList(t *testing.T) { + m := boardTimers(140, 36) + m = m.handleOpenForm(openFormMsg{}) + forceTrueColor(t) + out := m.viewAt(time.Now()) + text := plain(out) + for _, want := range []string{"╭─ New timer ─", "Task", "Client", "Project", "Notes", "Start", "End", "Save & start", "Cancel", "tab next · esc close", "or a past time like 9:05 AM, with an End"} { + if !strings.Contains(text, want) { + t.Errorf("New timer modal is missing %q:\n%s", want, text) + } + } + // The screen behind is plain text in backdrop. + // (Within a step: the terminal profile rounds the colour.) + if got := activeForegroundAt(out, "NOW TRACKING"); !nearRGB(got, rgb(cBackdrop)) { + t.Errorf("text behind the modal is in %q, want backdrop %q", got, rgb(cBackdrop)) + } + lines := strings.Split(out, "\n") + if len(lines) != m.innerHeight() { + t.Errorf("view is %d rows, want %d", len(lines), m.innerHeight()) + } + for i, l := range lines { + if w := ansi.StringWidth(l); w != m.innerWidth() { + t.Errorf("line %d is %d cells, want %d", i, w, m.innerWidth()) + } + } +} + +func TestView_FocusedFieldHasTheCursorMark(t *testing.T) { + m := boardTimers(140, 36).handleOpenForm(openFormMsg{}) + m.form.focusField(fieldClient) + for _, l := range strings.Split(plain(m.View()), "\n") { + if strings.Contains(l, "Task") && strings.Contains(l, theme.GlyphCursor) { + t.Errorf("unfocused Task has the mark: %q", l) + } + if strings.Contains(l, "Client") && !strings.Contains(l, "Client "+theme.GlyphCursor) { + t.Errorf("focused Client should have the mark after its label: %q", l) + } + } +} + +func TestView_EditEntryErrorSitsUnderItsField(t *testing.T) { + m := boardTimers(140, 36) + e := m.selectedEntry() + m = m.handleOpenForm(openFormMsg{entryID: e.ID}) + m.form.inputs[fieldEnd].SetValue(e.StartTime.Add(-30 * time.Minute).Format("2006-01-02 15:04")) + m, _ = m.submitForm(time.Now()) + if m.FieldErrors() != 1 { + t.Fatalf("FieldErrors() = %d, want 1", m.FieldErrors()) + } + lines := strings.Split(plain(m.View()), "\n") + found := false + for i, l := range lines[:len(lines)-1] { + if strings.Contains(l, "│ End ") && strings.Contains(lines[i+1], "✕ "+errEndBeforeStart) { + found = true + } + } + if !found { + t.Errorf("want %q under End:\n%s", "✕ "+errEndBeforeStart, strings.Join(lines, "\n")) + } + for _, want := range []string{"Edit entry", "Billing", "[ ] Invoiced", "[ ] Paid", "space toggles", "Delete entry"} { + if !strings.Contains(strings.Join(lines, "\n"), want) { + t.Errorf("Edit entry is missing %q", want) + } + } +} + +func TestView_SuggestionsBox(t *testing.T) { + clients := []*model.Client{mkClient(1, "Harbor & Pine", 120)} + m := boardTimers(140, 36).handleOpenForm(openFormMsg{clients: clients}) + updateTimerFormFields(&m.form, keyTab) + typeInto(&m.form, "Harb") + text := plain(m.View()) + // The selected row has the cursor glyph, not only its colour. + for _, want := range []string{"│" + theme.GlyphCursor + " Harbor & Pine", "│ + Create “Harb”", "↑↓ choose · enter pick"} { + if !strings.Contains(text, want) { + t.Errorf("suggestions are missing %q:\n%s", want, text) + } + } +} + +func TestView_DeleteConfirmNamesTheEntryWithItsTime(t *testing.T) { + m := boardTimers(140, 36) + e := m.selectedEntry() + m, _ = m.updateList(runeKey('d')) + text := plain(m.View()) + detail := e.StartTime.Local().Format("Mon Jan 2") + " · " + entryTimes(e, "–") + for _, want := range []string{"╭─ Delete entry? ─", "“" + e.Task + "”", detail, "This can’t be undone.", "Delete", "Keep it", "y / esc"} { + if !strings.Contains(text, want) { + t.Errorf("delete confirm is missing %q:\n%s", want, text) + } + } +} + +// At the smallest terminal (64×22) the modal drops its spacing to fit, and still +// shows every field and the buttons. +func TestView_ModalFitsTheSmallestTerminal(t *testing.T) { + m := boardTimers(64, 18) // a 64×22 terminal + e := m.selectedEntry() + m = m.handleOpenForm(openFormMsg{entryID: e.ID}) + m.form.inputs[fieldEnd].SetValue("not a time") + m, _ = m.submitForm(time.Now()) + text := plain(m.View()) + lines := strings.Split(text, "\n") + if len(lines) != m.innerHeight() { + t.Errorf("view is %d rows, want %d", len(lines), m.innerHeight()) + } + for _, want := range []string{"Edit entry", "Task", "Client", "Project", "Start", "End", "✕ Use a time like 9:05 AM or", " 09:05.", "Notes", "Billing", "Save", "Cancel", "╰"} { + if !strings.Contains(text, want) { + t.Errorf("64×22 modal is missing %q:\n%s", want, text) + } + } + for i, l := range lines { + if w := ansi.StringWidth(l); w != m.innerWidth() { + t.Errorf("line %d is %d cells, want %d", i, w, m.innerWidth()) + } + } +} + +func TestView_ModalHasNoUnstyledCells(t *testing.T) { + m := boardTimers(140, 36) + e := m.selectedEntry() + m = m.handleOpenForm(openFormMsg{entryID: e.ID}) + var got string + if n := unstyledCellCount(t, func() string { got = m.View(); return got }); n > 0 { + t.Errorf("the Edit entry modal has %d unstyled cell(s):\n%s", n, got) + } + m.form.errs = fieldErrors{fieldEnd: errEndBeforeStart} + if n := unstyledCellCount(t, func() string { got = m.View(); return got }); n > 0 { + t.Errorf("the modal with an error has %d unstyled cell(s):\n%s", n, got) + } +} + +// A form opened before a theme switch draws its fields in the new bg_alt: +// the input styles are set at every render, not when the form opened. +func TestStripInput_PicksUpLiveThemeChange(t *testing.T) { + pal := theme.Default + pal.BgAlt = "#010101" + withTestPalette(t, pal) + f := newTimerForm(nil, nil) + f.focusField(fieldClient) // no cursor in Task's placeholder + forceTrueColor(t) + if got := activeBackgroundAt(stripInput(f.inputs[fieldTask], 40), "hat you're working on"); got != "1;1;1" { + t.Fatalf("before: placeholder background = %q, want 1;1;1", got) + } + pal.BgAlt = "#020202" + withTestPalette(t, pal) + if got := activeBackgroundAt(stripInput(f.inputs[fieldTask], 40), "hat you're working on"); got != "2;2;2" { + t.Errorf("after: placeholder background = %q, want 2;2;2", got) + } +} + +func TestView_FirstRunHelpAndModal(t *testing.T) { + m := TimersModel{width: 140, height: 36, loaded: true} + // The copy says clients are created as you type, so the key line + // doesn't send you to the Clients tab first. + if h := m.Help(); len(h) != 1 || h[0] != (Hotkey{"n", "new timer"}) { + t.Errorf("first-run Help() = %v, want only n new timer", h) + } + m = m.handleOpenForm(openFormMsg{}) + if text := plain(m.View()); !strings.Contains(text, "New timer") || !strings.Contains(text, "Press") { + t.Errorf("New timer on the first-run screen should sit over it:\n%s", text) + } +} + +var fgColorRE = regexp.MustCompile(`(?:^|;)38;2;(\d+;\d+;\d+)`) + +// activeForegroundAt is activeBackgroundAt for the foreground. +func activeForegroundAt(s, needle string) string { + fg := "" + for i := 0; i < len(s); { + if s[i] == 0x1b { + if loc := csiRE.FindStringSubmatchIndex(s[i:]); loc != nil && loc[0] == 0 { + params, final := s[i+loc[2]:i+loc[3]], s[i+loc[4]:i+loc[5]] + if final == "m" { + if params == "" || params == "0" { + fg = "" + } else if m := fgColorRE.FindStringSubmatch(params); m != nil { + fg = m[1] + } + } + i += loc[1] + continue + } + } + if strings.HasPrefix(s[i:], needle) { + return fg + } + i++ + } + return "" +} + +// nearRGB reports whether two "r;g;b" values are within one step. +func nearRGB(a, b string) bool { + pa, pb := strings.Split(a, ";"), strings.Split(b, ";") + if len(pa) != 3 || len(pb) != 3 { + return false + } + for i := range pa { + x, _ := strconv.Atoi(pa[i]) + y, _ := strconv.Atoi(pb[i]) + if x-y > 1 || y-x > 1 { + return false + } + } + return true +} + +// rgb is a hex colour as "r;g;b". +func rgb(c lipgloss.Color) string { + v, _ := strconv.ParseUint(strings.TrimPrefix(string(c), "#"), 16, 32) + return fmt.Sprintf("%d;%d;%d", v>>16&0xff, v>>8&0xff, v&0xff) +} + +// ── PR #15 review, round 1 ──────────────────────────────────────────────────── + +func TestOpenForm_GoneEntryLeavesTheListAndSaysSo(t *testing.T) { + m, _, _ := confirmTimers(t) + got, cmd := m.Update(openFormMsg{entryID: 999}) + if got.mode != timersModeList { + t.Errorf("mode = %v, want the list kept", got.mode) + } + if msgs := runCmd(t, cmd); len(msgs) != 1 || msgs[0] != ErrMsg(errEntryGone) { + t.Errorf("msgs = %v, want %q", msgs, errEntryGone) + } +} + +func TestConfirm_EntryGoneClosesIt(t *testing.T) { + m, _, e := confirmTimers(t) + m, _ = m.updateList(runeKey('d')) + var rest []*model.Entry + for _, x := range m.entries { + if x.ID != e.ID { + rest = append(rest, x) + } + } + got, cmd := m.Update(timerEntriesMsg(rest)) + if got.mode != timersModeList { + t.Errorf("mode = %v, want the list once the entry is gone", got.mode) + } + if msgs := runCmd(t, cmd); len(msgs) != 1 || msgs[0] != ErrMsg(errEntryGone) { + t.Errorf("msgs = %v, want %q", msgs, errEntryGone) + } +} + +func manyClients() []*model.Client { + var cs []*model.Client + for i := 1; i <= 6; i++ { + cs = append(cs, mkClient(int64(10+i), fmt.Sprintf("Harbor %d", i), 0)) + } + return cs +} + +// At 64×22, Edit entry with three errors and six client suggestions still +// shows its buttons and bottom border, and its top edge doesn't move as +// the suggestions open. +func TestView_SuggestionsKeepTheModalStillAndWhole(t *testing.T) { + m := boardTimers(64, 18) + e := m.selectedEntry() + m = m.handleOpenForm(openFormMsg{entryID: e.ID, clients: manyClients()}) + m.form.inputs[fieldTask].SetValue("") + m.form.inputs[fieldStart].SetValue("soon") + m.form.inputs[fieldEnd].SetValue("later") + m, _ = m.submitForm(time.Now()) + if m.FieldErrors() != 3 { + t.Fatalf("FieldErrors() = %d, want 3", m.FieldErrors()) + } + m.form.focusField(fieldClient) + m.form.inputs[fieldClient].SetValue("") + top := func(view string) int { + for i, l := range strings.Split(view, "\n") { + if strings.Contains(l, "╭─ Edit entry") { + return i + } + } + return -1 + } + closed := plain(m.View()) + typeInto(&m.form, "Har") + open := plain(m.View()) + if !strings.Contains(open, "Harbor 1") { + t.Fatalf("want the suggestions open:\n%s", open) + } + if top(open) != top(closed) || top(open) < 0 { + t.Errorf("the top edge moved from row %d to %d as suggestions opened:\n%s\n%s", top(closed), top(open), closed, open) + } + if lines := strings.Split(open, "\n"); len(lines) != m.innerHeight() { + t.Errorf("view is %d rows, want %d", len(lines), m.innerHeight()) + } + for _, want := range []string{"Save", "Cancel", "Delete entry", "╰────"} { + if !strings.Contains(open, want) { + t.Errorf("with suggestions open the modal lost %q:\n%s", want, open) + } + } +} + +func TestTimerForm_TabKeepsAPartlyTypedNameAndArrowsChoose(t *testing.T) { + c := mkClient(4, "Fieldnote Studio", 95) + f := newTimerForm([]*model.Client{c, mkClient(5, "Fieldwork", 0)}, nil) + f.focusField(fieldClient) + typeInto(&f, "Fieldnote") + updateTimerFormFields(&f, keyTab) + if got := f.inputs[fieldClient].Value(); got != "Fieldnote" || f.clientID != 0 { + t.Errorf("tab after typing Fieldnote: Client %q (id %d), want the typed name kept for a new client", got, f.clientID) + } + + g := newTimerForm([]*model.Client{c, mkClient(5, "Fieldwork", 0)}, nil) + g.focusField(fieldClient) + typeInto(&g, "Field") + updateTimerFormFields(&g, keyDown) + if g.clientSel != 1 { + t.Fatalf("clientSel after down = %d, want 1", g.clientSel) + } + typeInto(&g, "w") + if g.clientSel != 0 { + t.Errorf("clientSel after typing = %d, want it reset to 0", g.clientSel) + } + updateTimerFormFields(&g, keyDown) + updateTimerFormFields(&g, keyUp) + updateTimerFormFields(&g, keyTab) + if g.clientID != 5 || g.inputs[fieldClient].Value() != "Fieldwork" { + t.Errorf("tab after the arrows chose: Client %q (id %d), want Fieldwork", g.inputs[fieldClient].Value(), g.clientID) + } +} + +func TestSaveEditEntry_BlankClientAndProjectIsUncategorized(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 0) + p, _ := d.CreateProject(c.ID, "Web") + start := time.Now().Add(-2 * time.Hour) + e, _ := d.AddEntry(p.ID, "t", "", start, ptrTime(start.Add(time.Hour))) + _, v := editValues(t, d, e.ID, func(f *timerForm) { + f.inputs[fieldClient].SetValue("") + f.inputs[fieldProject].SetValue("") + f.clientID, f.projectID = 0, 0 + }) + if err := saveEditEntry(d, e.ID, v); err != nil { + t.Fatal(err) + } + if uncategorized := mustUncategorized(t, d); storedEntry(t, d, e.ID).ProjectID != uncategorized { + t.Errorf("project = %d, want the uncategorized project %d", storedEntry(t, d, e.ID).ProjectID, uncategorized) + } +} + +func TestTimerForm_SameProjectNameUnderTwoClients(t *testing.T) { + acme, beta := mkClient(1, "Acme", 0), mkClient(2, "Beta", 0) + web1, web2, app := mkProject(1, "Website", acme), mkProject(2, "Website", beta), mkProject(3, "App", beta) + web1.ClientID, web2.ClientID, app.ClientID = 1, 2, 2 + + f := newTimerForm([]*model.Client{acme, beta}, []*model.Project{web1, web2, app}) + f.focusField(fieldProject) + typeInto(&f, "website") + updateTimerFormFields(&f, keyTab) + if f.projectID != 0 || f.clientID != 0 || f.inputs[fieldProject].Value() != "website" { + t.Errorf("tab with two Websites: project %d, client %d, Project %q; want the text left as typed", f.projectID, f.clientID, f.inputs[fieldProject].Value()) + } + if text := ansi.Strip(strings.Join(f.view(140, 36, "Save & start"), "\n")); !strings.Contains(text, "2 clients have website — pick one") { + t.Errorf("want the pick-one hint under Project:\n%s", text) + } + + g := newTimerForm([]*model.Client{acme, beta}, []*model.Project{web1, web2, app}) + g.focusField(fieldProject) + typeInto(&g, "app") + updateTimerFormFields(&g, keyTab) + if g.projectID != 3 || g.clientID != 2 { + t.Errorf("tab with one App: project %d, client %d; want App under Beta", g.projectID, g.clientID) + } +} + +// A new timer from 23:30 to 00:15, typed as bare times at 00:20. +func TestValidateTimerForm_NewTimerAcrossMidnight(t *testing.T) { + now := time.Date(2026, 12, 4, 0, 20, 0, 0, time.Local) + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("Late fix") + f.inputs[fieldStart].SetValue("23:30") + f.inputs[fieldEnd].SetValue("00:15") + v, errs := validateTimerForm(f, now) + if len(errs) != 0 { + t.Fatalf("errs = %v", errs) + } + if want := time.Date(2026, 12, 3, 23, 30, 0, 0, time.Local); !v.start.Equal(want) { + t.Errorf("start = %v, want %v", v.start, want) + } + if want := time.Date(2026, 12, 4, 0, 15, 0, 0, time.Local); v.end == nil || !v.end.Equal(want) { + t.Errorf("end = %v, want %v", v.end, want) + } + // The checks still apply: an End after now is still in the future. + f.inputs[fieldEnd].SetValue("00:30") + if _, errs := validateTimerForm(f, now); errs[fieldEnd] != errEndFuture { + t.Errorf("End 00:30 at 00:20: errs = %v, want %q", errs, errEndFuture) + } +} + +func TestValidateTimerForm_TypedEndInAKeptStartsMinute(t *testing.T) { + now := time.Date(2026, 12, 3, 12, 0, 0, 0, time.Local) + p := mkProject(1, "Web", mkClient(1, "Acme", 0)) + e := mkEntry(7, p, "Logo", time.Date(2026, 12, 3, 9, 5, 40, 0, time.Local), 60) + f := editForm(e, nil, nil) + f.inputs[fieldEnd].SetValue("09:05") + v, errs := validateTimerForm(f, now) + if len(errs) != 0 { + t.Fatalf("errs = %v, want none for an End in the Start's minute", errs) + } + if v.end == nil || !v.end.Equal(v.start) || !v.start.Equal(e.StartTime) { + t.Errorf("start %v, end %v; want a zero-length entry at %v", v.start, v.end, e.StartTime) + } + f.inputs[fieldEnd].SetValue("09:04") + if _, errs := validateTimerForm(f, now); errs[fieldEnd] != errEndBeforeStart { + t.Errorf("End a minute earlier: errs = %v, want %q", errs, errEndBeforeStart) + } +} + +func TestValidateTimerForm_EditTimes(t *testing.T) { + now := time.Date(2026, 12, 3, 12, 0, 0, 0, time.Local) + p := mkProject(1, "Web", mkClient(1, "Acme", 0)) + old := mkEntry(7, p, "Logo", time.Date(2026, 11, 20, 10, 0, 37, 0, time.Local), 60) + + t.Run("a bare time is on the entry's own day", func(t *testing.T) { + f := editForm(old, nil, nil) + f.inputs[fieldStart].SetValue("9:30") + f.inputs[fieldEnd].SetValue("11:15 AM") + v, errs := validateTimerForm(f, now) + if len(errs) != 0 { + t.Fatalf("errs = %v", errs) + } + if want := time.Date(2026, 11, 20, 9, 30, 0, 0, time.Local); !v.start.Equal(want) { + t.Errorf("start = %v, want %v", v.start, want) + } + if want := time.Date(2026, 11, 20, 11, 15, 0, 0, time.Local); v.end == nil || !v.end.Equal(want) { + t.Errorf("end = %v, want %v", v.end, want) + } + }) + + t.Run("untouched times keep their seconds", func(t *testing.T) { + f := editForm(old, nil, nil) + f.inputs[fieldTask].SetValue("Logo, round two") + v, errs := validateTimerForm(f, now) + if len(errs) != 0 { + t.Fatalf("errs = %v", errs) + } + if !v.start.Equal(old.StartTime) || v.end == nil || !v.end.Equal(*old.EndTime) { + t.Errorf("start %v, end %v; want the stored %v and %v", v.start, v.end, old.StartTime, *old.EndTime) + } + }) + + t.Run("a stopped entry with End cleared is only an End error", func(t *testing.T) { + f := editForm(old, nil, nil) + f.invoiced = true + f.inputs[fieldEnd].SetValue("") + _, errs := validateTimerForm(f, now) + if len(errs) != 1 || errs[fieldEnd] != errEndRequired { + t.Errorf("errs = %v, want only %q on End", errs, errEndRequired) + } + }) +} + +// The welcome screen waits for a load that succeeded with no entries: not +// before the first load, and not after a failed one. +func TestFirstRun_OnlyAfterASuccessfulEmptyLoad(t *testing.T) { + m := TimersModel{width: 140, height: 36} + if strings.Contains(plain(m.View()), "Nothing tracked yet") { + t.Error("the welcome screen showed before the first load") + } + m, _ = m.Update(ErrMsg("load entries: disk on fire")) + if strings.Contains(plain(m.View()), "Nothing tracked yet") { + t.Error("the welcome screen showed after a failed load") + } + m, _ = m.Update(timerEntriesMsg(nil)) + if !strings.Contains(plain(m.View()), "Nothing tracked yet") { + t.Errorf("want the welcome screen after an empty load:\n%s", plain(m.View())) + } +} + +func TestReloads_AFailedLoadIsAnError(t *testing.T) { + d := newTestDB(t) + d.Close() + for name, cmd := range map[string]tea.Cmd{"entries": loadTimerEntriesCmd(d), "started": loadStartedCmd(d, 1)} { + if _, ok := cmd().(ErrMsg); !ok { + t.Errorf("%s: a failed load should be an ErrMsg", name) + } + } +} + +func twoWebsites() ([]*model.Client, []*model.Project) { + acme, beta := mkClient(1, "Acme", 0), mkClient(2, "Beta", 0) + web1, web2 := mkProject(1, "Website", acme), mkProject(2, "Website", beta) + web1.ClientID, web2.ClientID = 1, 2 + return []*model.Client{acme, beta}, []*model.Project{web1, web2} +} + +// With Client blank, a project name two clients have can't be saved: it +// would land under whichever came first. +func TestValidateTimerForm_AmbiguousProjectNeedsAClient(t *testing.T) { + clients, projects := twoWebsites() + f := newTimerForm(clients, projects) + f.inputs[fieldTask].SetValue("Hero") + f.focusField(fieldProject) + typeInto(&f, "Website") + _, errs := validateTimerForm(f, time.Now()) + if errs[fieldProject] != errPickProjectClient { + t.Errorf("errs = %v, want %q on Project", errs, errPickProjectClient) + } + f.errs = errs + if text := ansi.Strip(strings.Join(f.view(140, 36, "Save & start"), "\n")); strings.Contains(text, "pick one") { + t.Errorf("the error replaces the hint:\n%s", text) + } + f.inputs[fieldClient].SetValue("Beta") + f.rebuildProjectMatches() + if _, errs := validateTimerForm(f, time.Now()); len(errs) != 0 { + t.Errorf("with Client typed: errs = %v, want none", errs) + } +} + +// A project typed under a new client belongs to it, even when another +// client has a project with that name. +func TestTimerForm_ProjectUnderANewClientIsNotTakenFromAnother(t *testing.T) { + acme := mkClient(1, "Acme", 0) + web := mkProject(1, "Website", acme) + web.ClientID = 1 + f := newTimerForm([]*model.Client{acme}, []*model.Project{web}) + f.focusField(fieldClient) + typeInto(&f, "Zed") + updateTimerFormFields(&f, keyTab) + typeInto(&f, "website") + updateTimerFormFields(&f, keyTab) + if f.clientID != 0 || f.projectID != 0 || f.inputs[fieldClient].Value() != "Zed" || f.inputs[fieldProject].Value() != "website" { + t.Errorf("Client %q (id %d), Project %q (id %d); want Zed and website, both new", + f.inputs[fieldClient].Value(), f.clientID, f.inputs[fieldProject].Value(), f.projectID) + } + for _, m := range f.projectMatches { + if m.id != 0 { + t.Errorf("suggested %q, another client's project, under a new client", m.label) + } + } +} + +// At 09:30 a bare "9:05 PM" with no End is a typo, not last night: it +// stays in the future. With an End it logs a block across midnight. +func TestValidateTimerForm_BareStartRollsBackOnlyWithAnEnd(t *testing.T) { + now := time.Date(2026, 12, 4, 9, 30, 0, 0, time.Local) + f := newTimerForm(nil, nil) + f.inputs[fieldTask].SetValue("x") + f.inputs[fieldStart].SetValue("9:05 PM") + if _, errs := validateTimerForm(f, now); errs[fieldStart] != errStartFuture { + t.Errorf("errs = %v, want %q", errs, errStartFuture) + } + f.inputs[fieldEnd].SetValue("11:00 PM") + v, errs := validateTimerForm(f, now) + if len(errs) != 0 || !v.start.Equal(time.Date(2026, 12, 3, 21, 5, 0, 0, time.Local)) { + t.Errorf("with an End: start %v, errs %v; want last night at 21:05", v.start, errs) + } +} + +// Quick add is for new timers: Edit entry keeps a task's "@" as typed. +func TestEditEntry_NoQuickAdd(t *testing.T) { + p := mkProject(1, "Web", mkClient(1, "Acme", 0)) + p.ClientID = 1 + f := editForm(mkEntry(7, p, "Logo", time.Now().Add(-3*time.Hour), 30), nil, nil) + f.inputs[fieldTask].SetValue("Reply to @jane about Q4") + f.inputs[fieldClient].SetValue("") + f.inputs[fieldProject].SetValue("") + v, _ := validateTimerForm(f, time.Now()) + updateTimerFormFields(&f, keyTab) + if f.inputs[fieldTask].Value() != "Reply to @jane about Q4" || f.inputs[fieldClient].Value() != "" { + t.Errorf("after tab: Task %q, Client %q; want the task kept and no client", f.inputs[fieldTask].Value(), f.inputs[fieldClient].Value()) + } + if v.task != "Reply to @jane about Q4" || v.clientName != "" { + t.Errorf("task %q, client %q; want the task kept and no client", v.task, v.clientName) + } +} + +// On a narrow terminal the strip is narrower than the input's starting +// width; the text by the cursor must still show as you type and move. +func TestStripInput_CursorStaysVisibleWhenNarrow(t *testing.T) { + f := newTimerForm(nil, nil) + long := "Draft the onboarding emails for the spring launch ENDMARK" + typeInto(&f, long) + view := func() string { return ansi.Strip(strings.Join(f.view(60, 18, "Save & start"), "\n")) } + if v := view(); !strings.Contains(v, "ENDMARK") { + t.Errorf("typing at the end of a long task hides it:\n%s", v) + } + updateTimerFormFields(&f, tea.KeyMsg{Type: tea.KeyHome}) + if v := view(); !strings.Contains(v, "Draft the") { + t.Errorf("home should show the start:\n%s", v) + } + for range 30 { + updateTimerFormFields(&f, tea.KeyMsg{Type: tea.KeyRight}) + } + // The cursor is at "spring"; the window must hold the text by it. + if v := view(); !strings.Contains(v, "for the s") { + t.Errorf("the text by the cursor is hidden:\n%s", v) + } +} + +func billingEntry(t *testing.T, invoiced, paid bool) (*db.DB, *model.Entry) { + t.Helper() + d := newTestDB(t) + start := time.Now().Add(-2 * time.Hour) + e, _ := d.AddEntry(mustUncategorized(t, d), "t", "", start, ptrTime(start.Add(time.Hour))) + s := storedEntry(t, d, e.ID) + s.Invoiced, s.Paid = invoiced, paid + if err := d.UpdateEntry(s); err != nil { + t.Fatal(err) + } + return d, s +} + +// Invoiced and paid are one unit in the merge: a change to either here and +// either elsewhere can't land as paid but not invoiced. +func TestSaveEditEntry_BillingIsOneUnit(t *testing.T) { + t.Run("paid here, un-invoiced elsewhere", func(t *testing.T) { + d, e := billingEntry(t, true, false) + _, v := editValues(t, d, e.ID, func(f *timerForm) { f.paid = true }) + s := storedEntry(t, d, e.ID) + s.Invoiced = false + d.UpdateEntry(s) + if err := saveEditEntry(d, e.ID, v); !errors.Is(err, errEditStale) { + t.Errorf("err = %v, want %v", err, errEditStale) + } + if s := storedEntry(t, d, e.ID); s.Paid { + t.Error("stored paid without invoiced") + } + }) + t.Run("un-invoiced here, paid elsewhere", func(t *testing.T) { + d, e := billingEntry(t, true, false) + _, v := editValues(t, d, e.ID, func(f *timerForm) { f.invoiced = false }) + s := storedEntry(t, d, e.ID) + s.Paid = true + d.UpdateEntry(s) + if err := saveEditEntry(d, e.ID, v); !errors.Is(err, errEditStale) { + t.Errorf("err = %v, want %v", err, errEditStale) + } + if s := storedEntry(t, d, e.ID); s.Paid && !s.Invoiced { + t.Error("stored paid without invoiced") + } + }) + t.Run("the merged entry keeps the billing rules", func(t *testing.T) { + d, e := billingEntry(t, false, false) + _, v := editValues(t, d, e.ID, nil) + v.paid = true // paid without invoiced, which the form never sends + if err := saveEditEntry(d, e.ID, v); !errors.Is(err, errEditStale) { + t.Errorf("err = %v, want %v", err, errEditStale) + } + }) +} + +// The form trims what it reads; stored text with stray spaces isn't a +// change, so a change elsewhere to it doesn't make the save stale. +func TestSaveEditEntry_WhitespaceIsNotAChange(t *testing.T) { + d := newTestDB(t) + start := time.Now().Add(-2 * time.Hour) + e, _ := d.AddEntry(mustUncategorized(t, d), " Logo ", " notes ", start, ptrTime(start.Add(time.Hour))) + _, v := editValues(t, d, e.ID, func(f *timerForm) { f.paid, f.invoiced = true, true }) + s := storedEntry(t, d, e.ID) + s.Task, s.Notes = "Logo, renamed elsewhere", "notes, edited elsewhere" + d.UpdateEntry(s) + if err := saveEditEntry(d, e.ID, v); err != nil { + t.Fatalf("err = %v, want the billing saved", err) + } + if s := storedEntry(t, d, e.ID); s.Task != "Logo, renamed elsewhere" || s.Notes != "notes, edited elsewhere" || !s.Paid { + t.Errorf("stored = %+v, want the other edits kept and paid saved", s) + } +} + +// With the cursor left of the end on a narrow strip, the window starts a +// little before it, so the text being typed into has context on its left. +func TestStripInput_ContextLeftOfTheCursor(t *testing.T) { + f := newTimerForm(nil, nil) + typeInto(&f, "Draft the onboarding emails for the spring launch ENDMARK") + updateTimerFormFields(&f, tea.KeyMsg{Type: tea.KeyHome}) + // Onto "onboarding", left of the window that ends at the text's end. + for range 12 { + updateTimerFormFields(&f, tea.KeyMsg{Type: tea.KeyRight}) + } + v := ansi.Strip(strings.Join(f.view(60, 18, "Save & start"), "\n")) + if !strings.Contains(v, "the onb") || !strings.Contains(v, "emails for the") { + t.Errorf("want text on both sides of the cursor:\n%s", v) + } +} + +// "Acme" picks Acme over acme: the exact case first, then any case. +func TestTimerForm_ExactCaseWinsOverOtherCase(t *testing.T) { + clients := []*model.Client{mkClient(1, "Acme", 0), mkClient(2, "acme", 0)} + for typed, want := range map[string]int64{"Acme": 1, "acme": 2, "ACME": 1} { + f := newTimerForm(clients, nil) + f.focusField(fieldClient) + typeInto(&f, typed) + updateTimerFormFields(&f, keyTab) + if f.clientID != want { + t.Errorf("typed %q: client %d, want %d", typed, f.clientID, want) + } + } +} diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index bc530e4..c3ff83f 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -1,6 +1,7 @@ package views import ( + "errors" "fmt" "strings" "time" @@ -10,7 +11,6 @@ import ( "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" ) // ── Modes ───────────────────────────────────────────────────────────────────── @@ -25,20 +25,6 @@ const ( timersModeFilter ) -// ── Form field indices ──────────────────────────────────────────────────────── - -const ( - fieldTask = 0 - fieldClient = 1 - fieldProject = 2 - fieldStart = 3 // edit mode only — see timerForm.entryID - fieldEnd = 4 // edit mode only — see timerForm.entryID - fieldNotes = 5 - fieldSave = 6 - fieldCancel = 7 - fieldCount = 8 -) - // ── Key bindings ────────────────────────────────────────────────────────────── type timersKeyMap struct { @@ -83,229 +69,6 @@ var timersKeys = timersKeyMap{ Cancel: key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "cancel")), } -// Dropdown navigation inside the timer form. Deliberately arrow-only: the -// list keymap above aliases j/k to Up/Down (vim-style), and reusing those -// bindings while a text input has focus swallows the letters j and k -// instead of typing them. -var ( - dropdownUp = key.NewBinding(key.WithKeys("up"), key.WithHelp("↑", "up")) - dropdownDown = key.NewBinding(key.WithKeys("down"), key.WithHelp("↓", "down")) -) - -// ── Dropdown item ───────────────────────────────────────────────────────────── - -type dropdownItem struct { - id int64 // 0 = "(create new)" - label string -} - -// ── Form ────────────────────────────────────────────────────────────────────── - -// timerForm holds all state for the new/edit timer form. -// Client and project fields support live fuzzy filtering and inline creation. -type timerForm struct { - entryID int64 // 0 = new - - inputs [fieldCount]textinput.Model - focusIdx int - - // client dropdown - allClients []*model.Client - clientMatches []dropdownItem - clientSel int // index into clientMatches - clientID int64 // 0 = will be created from input text - - // project dropdown - allProjects []*model.Project - projectMatches []dropdownItem - projectSel int - projectID int64 // 0 = will be created from input text - - showClientDrop bool - showProjectDrop bool -} - -func newTimerForm(clients []*model.Client, projects []*model.Project) timerForm { - var inputs [fieldCount]textinput.Model - inputs[fieldTask] = makeTextInput("What are you working on?", 200, 44) - inputs[fieldClient] = makeTextInput("Client name (or leave blank)", 64, 44) - inputs[fieldProject] = makeTextInput("Project name (or leave blank)", 64, 44) - // Width 44 (not something tighter around CharLimit's 16) to match every - // other field in this form: ti.Width caps the placeholder-rendering - // budget independently of the outer 48-wide box, so a narrower value - // here doesn't gain anything (CharLimit already caps typed length) and - // was truncating End's 34-character placeholder even though the box - // had plenty of room. - inputs[fieldStart] = makeTextInput("YYYY-MM-DD HH:MM", 16, 44) - inputs[fieldEnd] = makeTextInput("YYYY-MM-DD HH:MM (blank = running)", 16, 44) - inputs[fieldNotes] = makeTextInput("Notes (optional)", 500, 44) - inputs[fieldTask].Focus() - - f := timerForm{ - inputs: inputs, - focusIdx: fieldTask, - allClients: clients, - allProjects: projects, - } - f.rebuildClientMatches() - f.rebuildProjectMatches() - return f -} - -// rebuildClientMatches filters allClients by the current client input text. -func (f *timerForm) rebuildClientMatches() { - query := strings.ToLower(strings.TrimSpace(f.inputs[fieldClient].Value())) - f.clientMatches = nil - - for _, c := range f.allClients { - if query == "" || strings.Contains(strings.ToLower(c.Name), query) { - f.clientMatches = append(f.clientMatches, dropdownItem{id: c.ID, label: c.Name}) - } - } - - // Always offer "create new" if typed text doesn't exactly match an existing name - exactMatch := false - for _, c := range f.allClients { - if strings.EqualFold(c.Name, query) { - exactMatch = true - break - } - } - if query != "" && !exactMatch { - f.clientMatches = append(f.clientMatches, dropdownItem{id: 0, label: fmt.Sprintf(`+ Create "%s"`, f.inputs[fieldClient].Value())}) - } - - // clamp selection - if f.clientSel >= len(f.clientMatches) { - f.clientSel = 0 - } -} - -// rebuildProjectMatches filters allProjects by current text, scoped to selected client. -func (f *timerForm) rebuildProjectMatches() { - query := strings.ToLower(strings.TrimSpace(f.inputs[fieldProject].Value())) - f.projectMatches = nil - - for _, p := range f.allProjects { - // If a client is selected, only show that client's projects - if f.clientID != 0 && p.ClientID != f.clientID { - continue - } - if query == "" || strings.Contains(strings.ToLower(p.Name), query) { - label := p.Name - if f.clientID == 0 && p.Client != nil { - label = fmt.Sprintf("%s › %s", p.Client.Name, p.Name) - } - f.projectMatches = append(f.projectMatches, dropdownItem{id: p.ID, label: label}) - } - } - - // Offer "create new" if typed text doesn't exactly match - exactMatch := false - for _, p := range f.allProjects { - if strings.EqualFold(p.Name, query) { - exactMatch = true - break - } - } - if query != "" && !exactMatch { - f.projectMatches = append(f.projectMatches, dropdownItem{id: 0, label: fmt.Sprintf(`+ Create "%s"`, f.inputs[fieldProject].Value())}) - } - - if f.projectSel >= len(f.projectMatches) { - f.projectSel = 0 - } -} - -// applyClientSelection commits the highlighted dropdown item to the client field. -func (f *timerForm) applyClientSelection() { - if len(f.clientMatches) == 0 { - return - } - item := f.clientMatches[f.clientSel] - if item.id == 0 { - // "create new" — keep the typed text, clear ID - f.clientID = 0 - f.clearProject() - } else if item.id != f.clientID { - f.clearProject() - f.clientID = item.id - // Find the name and set it - for _, c := range f.allClients { - if c.ID == item.id { - f.inputs[fieldClient].SetValue(c.Name) - break - } - } - } - f.showClientDrop = false - f.rebuildProjectMatches() -} - -// clearProject resets the project field so a stale selection isn't kept when the client changes. -func (f *timerForm) clearProject() { - f.inputs[fieldProject].SetValue("") - f.projectID = 0 - f.projectSel = 0 -} - -// applyProjectSelection commits the highlighted dropdown item to the project field. -func (f *timerForm) applyProjectSelection() { - if len(f.projectMatches) == 0 { - return - } - item := f.projectMatches[f.projectSel] - if item.id == 0 { - f.projectID = 0 - } else { - f.projectID = item.id - for _, p := range f.allProjects { - if p.ID == item.id { - f.inputs[fieldProject].SetValue(p.Name) - // also fill client if blank - if f.clientID == 0 && p.Client != nil { - f.clientID = p.Client.ID - f.inputs[fieldClient].SetValue(p.Client.Name) - } - break - } - } - } - f.showProjectDrop = false -} - -// fieldAfterProject returns the field that follows Project in tab order: -// Start (so the start/end time can be corrected) when editing an existing -// entry, or straight to Notes for a brand-new timer, which always starts -// "now" and has no times to edit yet. -func (f *timerForm) fieldAfterProject() int { - if f.entryID != 0 { - return fieldStart - } - return fieldNotes -} - -// fieldBeforeNotes is fieldAfterProject's inverse, for Notes' shift+tab. -func (f *timerForm) fieldBeforeNotes() int { - if f.entryID != 0 { - return fieldEnd - } - return fieldProject -} - -// focusField blurs all inputs then focuses the given one. -func (f *timerForm) focusField(idx int) { - for i := range f.inputs { - f.inputs[i].Blur() - } - f.focusIdx = idx - if idx < fieldSave { - f.inputs[idx].Focus() - } - f.showClientDrop = idx == fieldClient && len(f.clientMatches) > 0 - f.showProjectDrop = idx == fieldProject && len(f.projectMatches) > 0 -} - // ── Model ───────────────────────────────────────────────────────────────────── type TimersModel struct { @@ -314,12 +77,20 @@ type TimersModel struct { height int mode timersMode entries []*model.Entry // all entries, as loaded from the DB + loaded bool // a load has succeeded (see firstRun) filtered []*model.Entry // entries within [dateFrom, dateTo]; see recomputeFiltered cursor int // index into filtered offset int // index into buildLines() output; see clampOffset form timerForm err string + // The delete confirm: the entry it deletes, whether it came from the + // Edit entry form (Keep it goes back there), and whether Delete has + // the focus (Keep it has it at first, so a stray enter keeps). + deleteID int64 + deleteFromForm bool + deleteFocused bool + // Date-range filter. Both are "YYYY-MM-DD" local calendar dates; "" means // unbounded on that side (dateFrom == dateTo == "" is "all time"). dateFrom string @@ -499,17 +270,6 @@ func parseLocalDate(s string) (t time.Time, ok bool) { return t, err == nil } -// parseLocalDateTime parses a "YYYY-MM-DD HH:MM" string in the local zone; -// ok is false for an empty or unparseable string. -func parseLocalDateTime(s string) (t time.Time, ok bool) { - s = strings.TrimSpace(s) - if s == "" { - return time.Time{}, false - } - t, err := time.ParseInLocation("2006-01-02 15:04", s, time.Local) - return t, err == nil -} - // rowsBudget returns how many render lines (day headers + entry rows, // including a synthesized sticky day header when one is needed — see // viewList) fit between the header and the detail pane given the current @@ -594,18 +354,18 @@ func (m TimersModel) IsBusy() bool { // display in the app-level hotkey bar (see app.go renderBottomBar). func (m TimersModel) Help() []Hotkey { switch m.mode { - case timersModeNew, timersModeEdit: - return []Hotkey{ - {"tab / shift+tab", "move"}, - {"↑ / ↓", "dropdown"}, - {"enter", "confirm"}, - {"esc", "cancel"}, - } + case timersModeNew: + return m.form.help(saveAndStart) + case timersModeEdit: + return m.form.help("Save") case timersModeConfirmDelete: - return []Hotkey{{"y", "confirm"}, {"esc", "cancel"}} + return []Hotkey{{"y", "delete"}, {"esc", "keep"}} case timersModeFilter: return []Hotkey{{"tab", "switch"}, {"enter", "apply"}, {"esc", "cancel"}} default: + if m.firstRun() { + return []Hotkey{{"n", "new timer"}} + } if !m.wide() { return []Hotkey{ {"n", "new"}, @@ -641,13 +401,27 @@ func (m TimersModel) Update(msg tea.Msg) (TimersModel, tea.Cmd) { if e := m.selectedEntry(); e != nil { keepID = e.ID } - return m.setEntries(msg, keepID), nil + m = m.setEntries(msg, keepID) + m.loaded = true + // The entry a confirm or Edit entry is about may be gone (another + // process deleted it): close them rather than show nothing. + gone := (m.mode == timersModeConfirmDelete && m.entryByID(m.deleteID) == nil) || + (m.mode == timersModeEdit && m.entryByID(m.form.entryID) == nil) + if gone { + m.mode = timersModeList + return m, ErrCmd(errEntryGone) + } + return m, nil case timerStartedMsg: // After r or space starts a timer, select the new entry. + m.loaded = true return m.setEntries(msg.entries, msg.id), nil case openFormMsg: + if msg.entryID != 0 && m.entryByID(msg.entryID) == nil { + return m, ErrCmd(errEntryGone) + } m = m.handleOpenForm(msg) return m, nil @@ -693,8 +467,9 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { } case key.Matches(msg, timersKeys.Delete): - if len(m.filtered) > 0 { + if e := m.selectedEntry(); e != nil { m.mode = timersModeConfirmDelete + m.deleteID, m.deleteFromForm, m.deleteFocused = e.ID, false, false } case key.Matches(msg, timersKeys.Toggle): @@ -822,204 +597,52 @@ type openFormMsg struct { func (m TimersModel) updateForm(msg tea.KeyMsg) (TimersModel, tea.Cmd) { action, cmd := updateTimerFormFields(&m.form, msg) switch action { - case "cancel": + case formCancel: m.mode = timersModeList m.err = "" return m, nil - case "submit": - return m.submitForm() + case formSubmit: + return m.submitForm(time.Now()) + case formDelete: + m.mode = timersModeConfirmDelete + m.deleteID, m.deleteFromForm, m.deleteFocused = m.form.entryID, true, false + return m, nil } return m, cmd } -// updateTimerFormFields handles field navigation, dropdown selection, and -// text input for a timer/entry form — shared by TimersModel's own New/Edit -// Timer form and ReportsModel's "edit entry" flow (see -// ReportsModel.updateEditEntry), so the two forms behave identically and -// can't drift apart. It's a free function, not a TimersModel method, -// deliberately: app.go broadcasts every non-key tea.Msg to *all* tabs, not -// just the active one, so anything routed through TimersModel-specific -// state or message types here would also fire on the real Timers tab even -// while editing from Reports. Operating purely on a *timerForm sidesteps -// that entirely. -// -// It doesn't perform Cancel/Save itself, since those differ per caller -// (TimersModel returns to its list, ReportsModel to its entries view; only -// TimersModel's Save path can create a brand new entry) — it just signals -// the caller via the returned action: "cancel", "submit", or "" for an -// ordinary keystroke. -func updateTimerFormFields(f *timerForm, msg tea.KeyMsg) (action string, cmd tea.Cmd) { - // Always allow cancel - if key.Matches(msg, timersKeys.Cancel) { - return "cancel", nil - } - - switch f.focusIdx { - - // ── Task field ──────────────────────────────────────────────────────────── - case fieldTask: - switch { - case msg.Type == tea.KeyTab: - f.focusField(fieldClient) - case msg.Type == tea.KeyShiftTab: - f.focusField(fieldSave) - case key.Matches(msg, timersKeys.Confirm): - f.focusField(fieldClient) - default: - f.inputs[fieldTask], cmd = f.inputs[fieldTask].Update(msg) - return "", cmd - } - - // ── Client field ────────────────────────────────────────────────────────── - case fieldClient: - switch { - case msg.Type == tea.KeyTab: - f.applyClientSelection() - f.focusField(fieldProject) - case msg.Type == tea.KeyShiftTab: - f.applyClientSelection() - f.focusField(fieldTask) - case key.Matches(msg, timersKeys.Confirm): - f.applyClientSelection() - f.focusField(fieldProject) - case key.Matches(msg, dropdownUp): - if f.clientSel > 0 { - f.clientSel-- - } - f.showClientDrop = true - case key.Matches(msg, dropdownDown): - if f.clientSel < len(f.clientMatches)-1 { - f.clientSel++ - } - f.showClientDrop = true - default: - f.inputs[fieldClient], cmd = f.inputs[fieldClient].Update(msg) - // Reset resolved ID when user edits the text - f.clientID = 0 - f.clearProject() - f.rebuildClientMatches() - f.showClientDrop = len(f.clientMatches) > 0 - f.rebuildProjectMatches() - return "", cmd - } - - // ── Project field ───────────────────────────────────────────────────────── - case fieldProject: - switch { - case msg.Type == tea.KeyTab: - f.applyProjectSelection() - f.focusField(f.fieldAfterProject()) - case msg.Type == tea.KeyShiftTab: - f.applyProjectSelection() - f.focusField(fieldClient) - case key.Matches(msg, timersKeys.Confirm): - f.applyProjectSelection() - f.focusField(f.fieldAfterProject()) - case key.Matches(msg, dropdownUp): - if f.projectSel > 0 { - f.projectSel-- - } - f.showProjectDrop = true - case key.Matches(msg, dropdownDown): - if f.projectSel < len(f.projectMatches)-1 { - f.projectSel++ - } - f.showProjectDrop = true - default: - f.inputs[fieldProject], cmd = f.inputs[fieldProject].Update(msg) - f.projectID = 0 - f.rebuildProjectMatches() - f.showProjectDrop = len(f.projectMatches) > 0 - return "", cmd - } - - // ── Start field (edit mode only) ───────────────────────────────────────── - case fieldStart: - switch { - case msg.Type == tea.KeyTab: - f.focusField(fieldEnd) - case msg.Type == tea.KeyShiftTab: - f.focusField(fieldProject) - case key.Matches(msg, timersKeys.Confirm): - f.focusField(fieldEnd) - default: - f.inputs[fieldStart], cmd = f.inputs[fieldStart].Update(msg) - return "", cmd - } - - // ── End field (edit mode only) ─────────────────────────────────────────── - case fieldEnd: - switch { - case msg.Type == tea.KeyTab: - f.focusField(fieldNotes) - case msg.Type == tea.KeyShiftTab: - f.focusField(fieldStart) - case key.Matches(msg, timersKeys.Confirm): - f.focusField(fieldNotes) - default: - f.inputs[fieldEnd], cmd = f.inputs[fieldEnd].Update(msg) - return "", cmd - } - - // ── Notes field ─────────────────────────────────────────────────────────── - case fieldNotes: - switch { - case msg.Type == tea.KeyTab: - f.focusField(fieldSave) - case msg.Type == tea.KeyShiftTab: - f.focusField(f.fieldBeforeNotes()) - case key.Matches(msg, timersKeys.Confirm): - f.focusField(fieldSave) - default: - f.inputs[fieldNotes], cmd = f.inputs[fieldNotes].Update(msg) - return "", cmd - } - - // ── Save button ─────────────────────────────────────────────────────────── - case fieldSave: - switch { - case msg.Type == tea.KeyTab: - f.focusField(fieldCancel) - case msg.Type == tea.KeyShiftTab: - f.focusField(fieldNotes) - case key.Matches(msg, timersKeys.Confirm): - return "submit", nil - } - - // ── Cancel button ───────────────────────────────────────────────────────── - case fieldCancel: - switch { - case msg.Type == tea.KeyTab: - f.focusField(fieldTask) - case msg.Type == tea.KeyShiftTab: - f.focusField(fieldSave) - case key.Matches(msg, timersKeys.Confirm): - return "cancel", nil - } - } - - return "", nil -} - // ── Confirm delete ──────────────────────────────────────────────────────────── +// updateConfirm handles the delete confirm: y deletes and esc keeps, +// whichever button has the focus; tab and the arrows move it, and enter or +// space presses it. Keep it has the focus first, so a reflexive enter +// keeps the entry. func (m TimersModel) updateConfirm(msg tea.KeyMsg) (TimersModel, tea.Cmd) { + del := false switch { - // Deliberately "y"/"Y" only, not the shared Confirm (enter) binding — a - // destructive delete shouldn't fire from a reflexive Enter press. Mirrors - // clients.go/projects.go's confirm-delete dispatch. case msg.String() == "y", msg.String() == "Y": + del = true + case key.Matches(msg, timersKeys.Cancel), msg.String() == "n", msg.String() == "N": + // esc and n keep it, in every tab's confirm. + case msg.Type == tea.KeyTab, msg.Type == tea.KeyShiftTab, msg.Type == tea.KeyLeft, msg.Type == tea.KeyRight: + m.deleteFocused = !m.deleteFocused + return m, nil + case msg.Type == tea.KeyEnter, msg.String() == " ": + del = m.deleteFocused + default: + return m, nil + } + if !del { + // Keep it: back to wherever the confirm came from. m.mode = timersModeList - m.detailOpen = false - e := m.selectedEntry() - if e == nil { - return m, nil + if m.deleteFromForm { + m.mode = timersModeEdit } - return m, m.deleteCmd(e.ID) - case key.Matches(msg, timersKeys.Cancel): - m.mode = timersModeList + return m, nil } - return m, nil + m.mode = timersModeList + m.detailOpen = false + return m, m.deleteCmd(m.deleteID) } // ── Filter update ───────────────────────────────────────────────────────────── @@ -1073,7 +696,7 @@ func (m TimersModel) stopCmd(id int64) tea.Cmd { } return tea.BatchMsg{ func() tea.Msg { return RunningChangedMsg{} }, - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, + loadTimerEntriesCmd(m.db), func() tea.Msg { return StatusMsg("Timer stopped") }, } } @@ -1081,16 +704,14 @@ func (m TimersModel) stopCmd(id int64) tea.Cmd { func (m TimersModel) startCmd(projectID int64, task string) tea.Cmd { return func() tea.Msg { - if err := m.db.StopAllRunning(); err != nil { - return ErrMsg(err.Error()) - } - e, err := m.db.StartEntry(projectID, task) + // AddEntry stops the running timer and starts this one in one write. + e, err := m.db.AddEntry(projectID, task, "", time.Now(), nil) if err != nil { return ErrMsg(err.Error()) } return tea.BatchMsg{ func() tea.Msg { return RunningChangedMsg{} }, - func() tea.Msg { return timerStartedMsg{entries: mustLoadEntries(m.db), id: e.ID} }, + loadStartedCmd(m.db, e.ID), func() tea.Msg { return StatusMsg("Timer started") }, } } @@ -1103,7 +724,7 @@ func (m TimersModel) deleteCmd(id int64) tea.Cmd { } return tea.BatchMsg{ func() tea.Msg { return RunningChangedMsg{} }, - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, + loadTimerEntriesCmd(m.db), func() tea.Msg { return StatusMsg("Entry deleted") }, } } @@ -1127,7 +748,7 @@ func (m TimersModel) toggleInvoiceCmd(e *model.Entry) tea.Cmd { return ErrMsg(err.Error()) } return tea.BatchMsg{ - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, + loadTimerEntriesCmd(m.db), func() tea.Msg { return StatusMsg("Invoice status updated") }, } } @@ -1139,175 +760,119 @@ func (m TimersModel) togglePaidCmd(e *model.Entry) tea.Cmd { return ErrMsg(err.Error()) } return tea.BatchMsg{ - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, + loadTimerEntriesCmd(m.db), func() tea.Msg { return StatusMsg("Payment status updated") }, } } } -// timerFormValues is a timerForm's fields, parsed and validated — -// everything resolveProject/db writes need, decoupled from the form/input -// widgets themselves. Shared between TimersModel.submitForm and -// ReportsModel.submitEditEntry (see validateTimerForm). -type timerFormValues struct { - task, clientName, projectName, notes string - clientID, projectID int64 - // Edit mode also lets the start/end time be corrected. New timers - // always start "now" via startCmd, so these only apply once - // f.entryID != 0. A blank field means "leave that time as it already - // is" — the fields come pre-filled when opening an edit, so blank only - // happens if the user clears one deliberately, and forcing a value in - // both would make it impossible to touch just one. newStart/newEnd nil - // means no override; haveEndOverride distinguishes "no override" from - // "override to nil" (clear End back to running) for End specifically. - newStart, newEnd *time.Time - haveEndOverride bool -} - -// validateTimerForm parses and validates a timerForm's fields, returning a -// non-empty errMsg (and a zero/partial timerFormValues) if invalid. Shared -// by TimersModel.submitForm and ReportsModel.submitEditEntry — see -// updateTimerFormFields' doc comment for why this is a free function rather -// than a TimersModel method. -func validateTimerForm(f timerForm) (v timerFormValues, errMsg string) { - v.task = strings.TrimSpace(f.inputs[fieldTask].Value()) - if v.task == "" { - return v, "Task description is required" +// saveAndStart is the New timer form's save button. +const saveAndStart = "Save & start" + +// submitForm saves the form at now. A new timer is written here, not in a +// command, so a start the running timer comes after can go back to the +// form as an error on Start: AddEntry stops the running timer and starts +// this one in one write, and with an End it records a finished entry and +// leaves the running timer alone, as `notch start --start --end` does. +func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { + v, errs := validateTimerForm(m.form, now) + if len(errs) > 0 { + m.form.errs = errs + return m, nil } - v.clientName = strings.TrimSpace(f.inputs[fieldClient].Value()) - v.projectName = strings.TrimSpace(f.inputs[fieldProject].Value()) - v.notes = strings.TrimSpace(f.inputs[fieldNotes].Value()) - v.clientID = f.clientID - v.projectID = f.projectID - - if f.entryID != 0 { - if startStr := strings.TrimSpace(f.inputs[fieldStart].Value()); startStr != "" { - st, ok := parseLocalDateTime(startStr) - if !ok { - return v, "Start time must be in YYYY-MM-DD HH:MM format" - } - v.newStart = &st - } - if endStr := strings.TrimSpace(f.inputs[fieldEnd].Value()); endStr != "" { - et, ok := parseLocalDateTime(endStr) - if !ok { - return v, "End time must be in YYYY-MM-DD HH:MM format" - } - v.newEnd = &et - v.haveEndOverride = true + m.form.errs = nil + + if m.form.entryID != 0 { + closeForm, cmd := m.form.submitEdit(m.db, v, + loadTimerEntriesCmd(m.db), + loadProjectsData(m.db), + loadClientsCmd(m.db), + ) + if closeForm { + m.mode = timersModeList + m.err = "" + } + return m, cmd + } + + // Checked before the client or project is created, as the CLI does; + // AddEntry checks again in its own write. + if v.end == nil { + running, err := m.db.GetRunningEntry() + if err != nil { + return m, ErrCmd(err.Error()) } - if v.newStart != nil && v.newEnd != nil && v.newEnd.Before(*v.newStart) { - return v, "End time must not be before the start time" + if running != nil && running.StartTime.After(v.start) { + m.form.errs = fieldErrors{fieldStart: errRunningLater} + return m, nil } } - return v, "" + projectID, err := m.db.ResolveOrCreateProject(v.clientID, v.clientName, v.projectID, v.projectName) + if err == nil && projectID <= 0 { + projectID, err = m.db.EnsureUncategorizedProject() + } + if err != nil { + return m, ErrCmd(err.Error()) + } + e, err := m.db.AddEntry(projectID, v.task, v.notes, v.start, v.end) + if errors.Is(err, db.ErrRunningStartedLater) { + m.form.errs = fieldErrors{fieldStart: errRunningLater} + return m, nil + } + if err != nil { + return m, ErrCmd(err.Error()) + } + + m.mode = timersModeList + m.err = "" + status := "Timer started" + if v.end != nil { + status = "Entry added" + } + return m, tea.Batch( + RunningChangedCmd(), + loadStartedCmd(m.db, e.ID), + loadProjectsData(m.db), + loadClientsCmd(m.db), + StatusCmd(status), + ) } -// submitEditEntryCmd returns a tea.Cmd that resolves/creates the -// client+project then applies a validated form's values to the existing -// entry with the given ID. Shared by TimersModel.submitForm's edit branch -// and ReportsModel.submitEditEntry — editing an entry is otherwise -// identical regardless of which view it's driven from. extra are additional -// commands the caller wants batched in alongside the "Entry updated" status -// (e.g. reloading whichever list/report the caller displays). -func submitEditEntryCmd(database *db.DB, entryID int64, v timerFormValues, extra ...tea.Cmd) tea.Cmd { +// loadStartedCmd reloads the entries after a start, to select entry id; +// a failed load is an error, not an empty list. +func loadStartedCmd(database *db.DB, id int64) tea.Cmd { return func() tea.Msg { - resolvedProjectID, err := database.ResolveOrCreateProject(v.clientID, v.clientName, v.projectID, v.projectName) - if err != nil { - return ErrMsg(err.Error()) - } - entries, err := database.ListEntries(0, "", "", true) if err != nil { - return ErrMsg(err.Error()) + return ErrMsg(fmt.Sprintf("load entries: %v", err)) } - var target *model.Entry - for _, e := range entries { - if e.ID == entryID { - target = e - break - } - } - if target == nil { - return ErrMsg("Entry not found") - } - target.Task = v.task - target.Notes = v.notes - if v.newStart != nil { - target.StartTime = *v.newStart - } - if v.haveEndOverride { - target.EndTime = v.newEnd - } - if target.EndTime != nil && target.EndTime.Before(target.StartTime) { - return ErrMsg("End time must not be before the start time") - } - if resolvedProjectID > 0 { - target.ProjectID = resolvedProjectID - } - if err := database.UpdateEntry(target); err != nil { - return ErrMsg(err.Error()) - } - - batch := make(tea.BatchMsg, 0, len(extra)+1) - for _, c := range extra { - batch = append(batch, c) - } - batch = append(batch, func() tea.Msg { return StatusMsg("Entry updated") }) - return batch + return timerStartedMsg{entries: entries, id: id} } } -// submitForm resolves/creates the client+project then starts or updates the entry. -func (m TimersModel) submitForm() (TimersModel, tea.Cmd) { - f := m.form - v, errMsg := validateTimerForm(f) - if errMsg != "" { - m.err = errMsg - return m, nil - } +// firstRun is whether to show the welcome screen: a load succeeded and +// there are no entries at all. Not before the first load, nor after a +// failed one. +func (m TimersModel) firstRun() bool { + return m.loaded && len(m.entries) == 0 && m.mode != timersModeFilter +} - m.mode = timersModeList - m.err = "" +// errEntryGone is the status when an entry is deleted (by another process) +// before or while its Edit entry or delete confirm is open. +const errEntryGone = "That entry no longer exists" - if f.entryID == 0 { - // New timer - return m, func() tea.Msg { - resolvedProjectID, err := m.db.ResolveOrCreateProject(v.clientID, v.clientName, v.projectID, v.projectName) - if err != nil { - return ErrMsg(err.Error()) - } - if err := m.db.StopAllRunning(); err != nil { - return ErrMsg(err.Error()) - } - if resolvedProjectID <= 0 { - // No project — start with a placeholder project - pid, err := m.db.EnsureUncategorizedProject() - if err != nil { - return ErrMsg(err.Error()) - } - resolvedProjectID = pid - } - started, err := m.db.StartEntry(resolvedProjectID, v.task) - if err != nil { - return ErrMsg(err.Error()) - } - return tea.BatchMsg{ - func() tea.Msg { return RunningChangedMsg{} }, - func() tea.Msg { return timerStartedMsg{entries: mustLoadEntries(m.db), id: started.ID} }, - func() tea.Msg { return loadProjectsData(m.db)() }, - func() tea.Msg { return loadClientsCmd(m.db)() }, - func() tea.Msg { return StatusMsg("Timer started") }, - } +// errEntryChanged is Edit entry's form error when the entry's times or +// running state changed elsewhere after the form opened. +const errEntryChanged = "This entry changed elsewhere — reopen it to edit" + +// entryByID is the loaded entry id, or nil. +func (m TimersModel) entryByID(id int64) *model.Entry { + for _, e := range m.entries { + if e.ID == id { + return e } } - - // Edit existing entry - return m, submitEditEntryCmd(m.db, f.entryID, v, - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, - loadProjectsCmd(m.db, 0), - loadClientsCmd(m.db), - ) + return nil } func mustLoadEntries(database *db.DB) []*model.Entry { @@ -1315,47 +880,24 @@ func mustLoadEntries(database *db.DB) []*model.Entry { return entries } -// ── Update: handle openFormMsg ──────────────────────────────────────────────── - -// We need to handle openFormMsg in the main Update switch. -// Re-open Update to inject it cleanly by adding a case in the top-level switch. -// This is handled below by extending Update via a patch in the Init section. +// ── Open the form ───────────────────────────────────────────────────────────── +// handleOpenForm opens New timer (entry 0) or Edit entry for msg.entryID. +// When that entry is gone it leaves the tab as it was; Update says so. func (m TimersModel) handleOpenForm(msg openFormMsg) TimersModel { f := newTimerForm(msg.clients, msg.projects) - f.entryID = msg.entryID - - // Pre-populate for edit + mode := timersModeNew if msg.entryID != 0 { - for _, e := range m.entries { - if e.ID == msg.entryID { - f.inputs[fieldTask].SetValue(e.Task) - f.inputs[fieldNotes].SetValue(e.Notes) - f.inputs[fieldStart].SetValue(e.StartTime.Local().Format("2006-01-02 15:04")) - if e.EndTime != nil { - f.inputs[fieldEnd].SetValue(e.EndTime.Local().Format("2006-01-02 15:04")) - } - if e.Project != nil { - f.projectID = e.Project.ID - f.inputs[fieldProject].SetValue(e.Project.Name) - if e.Project.Client != nil { - f.clientID = e.Project.Client.ID - f.inputs[fieldClient].SetValue(e.Project.Client.Name) - } - } - break - } + e := m.entryByID(msg.entryID) + if e == nil { + return m } - f.rebuildClientMatches() - f.rebuildProjectMatches() + f.fill(e) + f.canDelete = true + mode = timersModeEdit } - + m.mode = mode m.form = f - if msg.entryID == 0 { - m.mode = timersModeNew - } else { - m.mode = timersModeEdit - } m.err = "" return m } @@ -1363,15 +905,50 @@ func (m TimersModel) handleOpenForm(msg openFormMsg) TimersModel { // ── View ────────────────────────────────────────────────────────────────────── func (m TimersModel) View() string { + return m.viewAt(time.Now()) +} + +// viewAt draws the tab at now: the list, or a modal over it dimmed. +func (m TimersModel) viewAt(now time.Time) string { + under := m + under.mode = timersModeList switch m.mode { - case timersModeNew, timersModeEdit: - return m.viewForm() - default: - // timersModeConfirmDelete renders inline within viewList (the selected - // row becomes a "Delete ...?" prompt) rather than replacing the whole - // screen — deleting one row shouldn't hide the table it belongs to. - return m.viewList() + case timersModeNew: + return modalOver(under.viewListAt(now), m.innerWidth(), m.innerHeight(), m.form.view(m.innerWidth(), m.innerHeight(), saveAndStart)) + case timersModeEdit: + return modalOver(under.viewListAt(now), m.innerWidth(), m.innerHeight(), m.form.view(m.innerWidth(), m.innerHeight(), "Save")) + case timersModeConfirmDelete: + if box := m.deleteModal(now); box != nil { + return modalOver(under.viewListAt(now), m.innerWidth(), m.innerHeight(), box) + } + } + return m.viewListAt(now) +} + +// deleteModal is the delete confirm for m.deleteID: the entry named with +// its day, times and length. It's nil when the entry has gone. +func (m TimersModel) deleteModal(now time.Time) []string { + for _, e := range m.entries { + if e.ID == m.deleteID { + return confirmModal{ + title: "Delete entry?", + name: e.Task, + detail: e.StartTime.Local().Format("Mon Jan 2") + " · " + entryTimes(e, "–") + " · " + model.FormatDuration(durationAt(e, now)), + warning: "This can’t be undone.", + deleteFocused: m.deleteFocused, + }.render(m.innerWidth(), m.innerHeight()) + } } + return nil +} + +// FieldErrors is how many fields of the open form need fixing, for the +// app's status line. +func (m TimersModel) FieldErrors() int { + if m.mode == timersModeNew || m.mode == timersModeEdit { + return len(m.form.errs) + } + return 0 } // ── List view ───────────────────────────────────────────────────────────────── @@ -1441,148 +1018,6 @@ func (m TimersModel) renderFilterBar() string { return renderDateFilterBar(m.fromInput, m.toInput, m.filterIdx) } -// ── Form view ───────────────────────────────────────────────────────────────── - -func (m TimersModel) viewForm() string { - saveLabel := "Save & Start" - if m.form.entryID != 0 { - saveLabel = "Save" - } - return viewTimerForm(m.form, m.err, saveLabel) -} - -// viewTimerForm renders a timer/entry form — shared by TimersModel's own -// New/Edit Timer form and ReportsModel's edit-entry view (see -// updateTimerFormFields' doc comment for why the form logic lives as free -// functions rather than TimersModel methods). saveLabel is parametrized -// because "Save & Start" only makes sense for Timers' own new-timer flow; -// editing a past entry from Reports doesn't start anything running. -func viewTimerForm(f timerForm, errMsg string, saveLabel string) string { - title := "New Timer" - if f.entryID != 0 { - title = "Edit Entry" - } - - var b strings.Builder - b.WriteString(StyleTitle.Render(title) + "\n\n") - - b.WriteString(f.renderFormField("Task", fieldTask) + "\n\n") - - b.WriteString(f.renderFormField("Client", fieldClient) + "\n") - if f.focusIdx == fieldClient && f.showClientDrop && len(f.clientMatches) > 0 { - b.WriteString(renderDropdown(f.clientMatches, f.clientSel) + "\n") - } - b.WriteString("\n") - - b.WriteString(f.renderFormField("Project", fieldProject) + "\n") - if f.focusIdx == fieldProject && f.showProjectDrop && len(f.projectMatches) > 0 { - b.WriteString(renderDropdown(f.projectMatches, f.projectSel) + "\n") - } - b.WriteString("\n") - - if f.entryID != 0 { - b.WriteString(f.renderFormField("Start", fieldStart) + "\n\n") - b.WriteString(f.renderFormField("End", fieldEnd) + "\n\n") - } - - b.WriteString(f.renderFormField("Notes", fieldNotes) + "\n\n") - - saveBtn := StyleButtonPrimary - if f.focusIdx == fieldSave { - saveBtn = StyleButtonActive - } - cancelBtn := StyleButton - if f.focusIdx == fieldCancel { - cancelBtn = StyleButtonActive - } - b.WriteString(saveBtn.Render(saveLabel)) - b.WriteString(lipgloss.NewStyle().Background(cBg).Render(" ")) - b.WriteString(cancelBtn.Render("Cancel")) - - if errMsg != "" { - b.WriteString("\n\n" + StyleDanger.Render("✖ "+errMsg)) - } - - b.WriteString("\n\n") - if f.entryID != 0 { - b.WriteString(StyleHelp.Render("Times use YYYY-MM-DD HH:MM (24h). Leave End blank to keep the timer running.") + "\n") - } - b.WriteString(StyleHelp.Render("Client and project are created automatically if they don't exist.")) - - return b.String() -} - -// renderFormField is a timerForm method (not a TimersModel one) so -// ReportsModel's edit-entry form can render fields identically — see -// updateTimerFormFields' doc comment for why these stay decoupled from -// TimersModel specifically. -func (f timerForm) renderFormField(label string, idx int) string { - focused := f.focusIdx == idx - ti := f.inputs[idx] - refreshInputStyle(&ti) - - var labelStr string - if focused { - labelStr = StyleFormLabelFocused.Render(label) - } else { - labelStr = StyleFormLabel.Render(label) - } - - view := trimTrailingUnstyledPad(ti.View()) - var inputStr string - if focused { - inputStr = StyleFormInputFocused.Width(48).Render(view) - } else { - inputStr = StyleFormInput.Width(48).Render(view) - } - - // The input box is 2 lines (text + its bottom-border underline), but - // labelStr is only 1 — padCellToTwoLines pads it to match with an - // explicit cBg-styled blank line rather than letting JoinHorizontal - // auto-pad the gap, which produces a genuinely unstyled row (see its - // doc comment; same bug this fixed on the date-range filter bar). - return lipgloss.JoinHorizontal(lipgloss.Top, padCellToTwoLines(labelStr), inputStr) -} - -func renderDropdown(items []dropdownItem, sel int) string { - start := sel - 4 - if start < 0 { - start = 0 - } - end := start + 7 - if end > len(items) { - end = len(items) - } - - var lines []string - for i := start; i < end; i++ { - item := items[i] - prefix := cursorOff - var s lipgloss.Style - if i == sel { - prefix = cursorOn - s = StyleTableRowSel.Width(50) - } else if item.id == 0 { - s = StylePrimary.Width(50) - } else { - s = StyleMuted.Width(50) - } - lines = append(lines, s.Render(prefix+item.label)) - } - - return lipgloss.NewStyle(). - Background(cBg). - Border(lipgloss.NormalBorder(), false, false, false, true). - BorderForeground(cPrimary). - // BorderBackground is a separate property from Background — see - // renderConfirmModal's comment for the same rule — so without this - // the left border bar shows the terminal's default color instead - // of cBg. - BorderBackground(cBg). - PaddingLeft(StyleFormLabel.GetWidth()). - Render(strings.Join(lines, "\n")) -} - // ── Helpers ─────────────────────────────────────────────────────────────────── // invoiceLabel renders an entry's billing status for the Reports tab's diff --git a/internal/ui/views/timers_start_test.go b/internal/ui/views/timers_start_test.go index 2083200..e8ea1e1 100644 --- a/internal/ui/views/timers_start_test.go +++ b/internal/ui/views/timers_start_test.go @@ -93,7 +93,7 @@ func TestStart_FormSelectsNewEntry(t *testing.T) { m.form.inputs[fieldTask].SetValue("from the form") m.form.inputs[fieldClient].SetValue("Acme") m.form.inputs[fieldProject].SetValue("Web") - m, cmd := m.submitForm() + m, cmd := m.submitForm(time.Now()) m = feed(m, cmd) if e := m.selectedEntry(); e == nil || !e.IsRunning() || e.Task != "from the form" { t.Errorf("after starting from the form, the cursor is on %+v, want the new running entry", e) diff --git a/internal/ui/views/timers_test.go b/internal/ui/views/timers_test.go index 554d22d..8dc02a2 100644 --- a/internal/ui/views/timers_test.go +++ b/internal/ui/views/timers_test.go @@ -10,7 +10,6 @@ import ( "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" - "github.com/aliasproject/notch/internal/theme" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) @@ -276,70 +275,6 @@ func TestUpdateList_DeleteRequiresNonEmptyList(t *testing.T) { } } -// ── Delete-confirm flow (regression coverage for the y/enter/close-after-delete fix) ── - -func TestUpdateConfirm_YKeyDeletes(t *testing.T) { - c := mkClient(1, "Acme", 100) - p := mkProject(1, "Website", c) - e := mkEntry(1, p, "a", time.Now(), 30) - m := TimersModel{mode: timersModeConfirmDelete, entries: []*model.Entry{e}} - m.recomputeFiltered() - - got, cmd := m.updateConfirm(runeKey('y')) - if got.mode != timersModeList { - t.Errorf("mode after 'y' = %v, want timersModeList (confirmation should close immediately)", got.mode) - } - if cmd == nil { - t.Error("want a non-nil delete cmd after pressing 'y'") - } -} - -// Enter deliberately does NOT confirm a delete — only "y"/"Y" does, since a -// destructive action shouldn't fire from a reflexive Enter press (see -// updateConfirm in timers.go). This matches clients.go/projects.go. -func TestUpdateConfirm_EnterKeyDoesNotDelete(t *testing.T) { - c := mkClient(1, "Acme", 100) - p := mkProject(1, "Website", c) - e := mkEntry(1, p, "a", time.Now(), 30) - m := TimersModel{mode: timersModeConfirmDelete, entries: []*model.Entry{e}} - m.recomputeFiltered() - - got, cmd := m.updateConfirm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.mode != timersModeConfirmDelete { - t.Errorf("mode after enter = %v, want to stay timersModeConfirmDelete", got.mode) - } - if cmd != nil { - t.Error("want nil cmd after pressing enter — enter must not confirm a delete") - } -} - -func TestUpdateConfirm_EscCancels(t *testing.T) { - c := mkClient(1, "Acme", 100) - p := mkProject(1, "Website", c) - e := mkEntry(1, p, "a", time.Now(), 30) - m := TimersModel{mode: timersModeConfirmDelete, entries: []*model.Entry{e}} - m.recomputeFiltered() - - got, cmd := m.updateConfirm(tea.KeyMsg{Type: tea.KeyEsc}) - if got.mode != timersModeList { - t.Errorf("mode after esc = %v, want timersModeList", got.mode) - } - if cmd != nil { - t.Error("want nil cmd after cancelling delete") - } -} - -func TestUpdateConfirm_OtherKeysAreNoOps(t *testing.T) { - m := TimersModel{mode: timersModeConfirmDelete} - got, cmd := m.updateConfirm(runeKey('x')) - if got.mode != timersModeConfirmDelete { - t.Errorf("mode after unrelated key = %v, want to stay timersModeConfirmDelete", got.mode) - } - if cmd != nil { - t.Error("want nil cmd for an unrelated keypress") - } -} - // ── Dropdown / autocomplete ────────────────────────────────────────────────── func TestRebuildClientMatches(t *testing.T) { @@ -482,25 +417,6 @@ func TestApplyProjectSelection_BackfillsClient(t *testing.T) { } } -// ── Form validation ────────────────────────────────────────────────────────── - -func TestSubmitForm_EmptyTaskRejected(t *testing.T) { - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue(" ") - m := TimersModel{mode: timersModeNew, form: f} - - got, cmd := m.submitForm() - if got.err == "" { - t.Error("want a validation error for an empty task") - } - if got.mode != timersModeNew { - t.Errorf("mode after failed validation = %v, want to stay timersModeNew", got.mode) - } - if cmd != nil { - t.Error("want nil cmd on validation failure (no DB touch)") - } -} - // ── handleOpenForm ─────────────────────────────────────────────────────────── func TestHandleOpenForm_New(t *testing.T) { @@ -716,333 +632,6 @@ func TestUpdateForm_CancelAlwaysWins(t *testing.T) { } } -// ── updateForm: fieldTask ──────────────────────────────────────────────────── - -func TestUpdateForm_TaskField(t *testing.T) { - newM := func() TimersModel { - f := newTimerForm(nil, nil) - f.focusField(fieldTask) - return TimersModel{mode: timersModeNew, form: f} - } - - t.Run("tab moves to client", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if got.form.focusIdx != fieldClient { - t.Errorf("focusIdx = %d, want fieldClient", got.form.focusIdx) - } - }) - t.Run("shift+tab moves to save", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got.form.focusIdx != fieldSave { - t.Errorf("focusIdx = %d, want fieldSave", got.form.focusIdx) - } - }) - t.Run("enter confirms to client", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.form.focusIdx != fieldClient { - t.Errorf("focusIdx = %d, want fieldClient", got.form.focusIdx) - } - }) - t.Run("default forwards to input", func(t *testing.T) { - got, _ := newM().updateForm(runeKey('x')) - if got.form.inputs[fieldTask].Value() != "x" { - t.Errorf("task input = %q, want %q", got.form.inputs[fieldTask].Value(), "x") - } - }) -} - -// ── updateForm: fieldClient ────────────────────────────────────────────────── - -func TestUpdateForm_ClientField(t *testing.T) { - clients := []*model.Client{mkClient(1, "Acme", 0), mkClient(2, "Beta", 0)} - newM := func() TimersModel { - f := newTimerForm(clients, nil) - f.focusField(fieldClient) // matches both clients since query is empty - return TimersModel{mode: timersModeNew, form: f} - } - - t.Run("tab applies selection and moves to project", func(t *testing.T) { - m := newM() - m.form.clientSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if got.form.focusIdx != fieldProject { - t.Errorf("focusIdx = %d, want fieldProject", got.form.focusIdx) - } - if got.form.clientID == 0 { - t.Error("clientID should be set from the applied selection") - } - }) - t.Run("shift+tab applies selection and moves to task", func(t *testing.T) { - m := newM() - m.form.clientSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got.form.focusIdx != fieldTask { - t.Errorf("focusIdx = %d, want fieldTask", got.form.focusIdx) - } - }) - t.Run("enter applies selection and moves to project", func(t *testing.T) { - m := newM() - m.form.clientSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.form.focusIdx != fieldProject { - t.Errorf("focusIdx = %d, want fieldProject", got.form.focusIdx) - } - }) - t.Run("down moves selection and shows dropdown", func(t *testing.T) { - m := newM() - m.form.clientSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyDown}) - if got.form.clientSel != 1 { - t.Errorf("clientSel = %d, want 1", got.form.clientSel) - } - if !got.form.showClientDrop { - t.Error("showClientDrop should be true after pressing down") - } - }) - t.Run("down at end of list does not overflow", func(t *testing.T) { - m := newM() - m.form.clientSel = len(m.form.clientMatches) - 1 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyDown}) - if got.form.clientSel != len(m.form.clientMatches)-1 { - t.Errorf("clientSel = %d, want to stay at the last index", got.form.clientSel) - } - }) - t.Run("up moves selection back", func(t *testing.T) { - m := newM() - m.form.clientSel = 1 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyUp}) - if got.form.clientSel != 0 { - t.Errorf("clientSel = %d, want 0", got.form.clientSel) - } - }) - t.Run("up at start of list does not underflow", func(t *testing.T) { - m := newM() - m.form.clientSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyUp}) - if got.form.clientSel != 0 { - t.Errorf("clientSel = %d, want to stay at 0", got.form.clientSel) - } - }) - t.Run("default forwards to input and resets resolved id", func(t *testing.T) { - m := newM() - m.form.clientID = 99 - got, _ := m.updateForm(runeKey('z')) - if !strings.Contains(got.form.inputs[fieldClient].Value(), "z") { - t.Errorf("client input = %q, want to contain 'z'", got.form.inputs[fieldClient].Value()) - } - if got.form.clientID != 0 { - t.Errorf("clientID = %d, want reset to 0 after editing text", got.form.clientID) - } - }) -} - -// ── updateForm: fieldProject ────────────────────────────────────────────────── - -func TestUpdateForm_ProjectField(t *testing.T) { - c := mkClient(1, "Acme", 0) - projects := []*model.Project{mkProject(1, "Website", c), mkProject(2, "App", c)} - newM := func() TimersModel { - f := newTimerForm(nil, projects) - f.focusField(fieldProject) - return TimersModel{mode: timersModeNew, form: f} - } - - t.Run("tab applies selection and moves to notes", func(t *testing.T) { - m := newM() - m.form.projectSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if got.form.focusIdx != fieldNotes { - t.Errorf("focusIdx = %d, want fieldNotes", got.form.focusIdx) - } - if got.form.projectID == 0 { - t.Error("projectID should be set from the applied selection") - } - }) - t.Run("shift+tab applies selection and moves to client", func(t *testing.T) { - m := newM() - m.form.projectSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got.form.focusIdx != fieldClient { - t.Errorf("focusIdx = %d, want fieldClient", got.form.focusIdx) - } - }) - t.Run("enter applies selection and moves to notes", func(t *testing.T) { - m := newM() - m.form.projectSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.form.focusIdx != fieldNotes { - t.Errorf("focusIdx = %d, want fieldNotes", got.form.focusIdx) - } - }) - t.Run("down moves selection and shows dropdown", func(t *testing.T) { - m := newM() - m.form.projectSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyDown}) - if got.form.projectSel != 1 { - t.Errorf("projectSel = %d, want 1", got.form.projectSel) - } - if !got.form.showProjectDrop { - t.Error("showProjectDrop should be true after pressing down") - } - }) - t.Run("down at end of list does not overflow", func(t *testing.T) { - m := newM() - m.form.projectSel = len(m.form.projectMatches) - 1 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyDown}) - if got.form.projectSel != len(m.form.projectMatches)-1 { - t.Errorf("projectSel = %d, want to stay at the last index", got.form.projectSel) - } - }) - t.Run("up moves selection back", func(t *testing.T) { - m := newM() - m.form.projectSel = 1 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyUp}) - if got.form.projectSel != 0 { - t.Errorf("projectSel = %d, want 0", got.form.projectSel) - } - }) - t.Run("up at start of list does not underflow", func(t *testing.T) { - m := newM() - m.form.projectSel = 0 - got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyUp}) - if got.form.projectSel != 0 { - t.Errorf("projectSel = %d, want to stay at 0", got.form.projectSel) - } - }) - t.Run("default forwards to input and resets resolved id", func(t *testing.T) { - m := newM() - m.form.projectID = 99 - got, _ := m.updateForm(runeKey('z')) - if !strings.Contains(got.form.inputs[fieldProject].Value(), "z") { - t.Errorf("project input = %q, want to contain 'z'", got.form.inputs[fieldProject].Value()) - } - if got.form.projectID != 0 { - t.Errorf("projectID = %d, want reset to 0 after editing text", got.form.projectID) - } - }) -} - -// ── updateForm: fieldNotes ──────────────────────────────────────────────────── - -func TestUpdateForm_NotesField(t *testing.T) { - newM := func() TimersModel { - f := newTimerForm(nil, nil) - f.focusField(fieldNotes) - return TimersModel{mode: timersModeNew, form: f} - } - - t.Run("tab moves to save", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if got.form.focusIdx != fieldSave { - t.Errorf("focusIdx = %d, want fieldSave", got.form.focusIdx) - } - }) - t.Run("shift+tab moves to project", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got.form.focusIdx != fieldProject { - t.Errorf("focusIdx = %d, want fieldProject", got.form.focusIdx) - } - }) - t.Run("enter moves to save", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.form.focusIdx != fieldSave { - t.Errorf("focusIdx = %d, want fieldSave", got.form.focusIdx) - } - }) - t.Run("default forwards to input", func(t *testing.T) { - got, _ := newM().updateForm(runeKey('n')) - if got.form.inputs[fieldNotes].Value() != "n" { - t.Errorf("notes input = %q, want %q", got.form.inputs[fieldNotes].Value(), "n") - } - }) -} - -// ── updateForm: fieldSave ──────────────────────────────────────────────────── - -func TestUpdateForm_SaveField(t *testing.T) { - newM := func() TimersModel { - f := newTimerForm(nil, nil) - f.focusField(fieldSave) - return TimersModel{mode: timersModeNew, form: f} - } - - t.Run("tab moves to cancel", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if got.form.focusIdx != fieldCancel { - t.Errorf("focusIdx = %d, want fieldCancel", got.form.focusIdx) - } - }) - t.Run("shift+tab moves to notes", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got.form.focusIdx != fieldNotes { - t.Errorf("focusIdx = %d, want fieldNotes", got.form.focusIdx) - } - }) - t.Run("enter dispatches to submitForm", func(t *testing.T) { - d := newTestDB(t) - m := newM() - m.db = d - m.form.inputs[fieldTask].SetValue("Do the thing") - got, cmd := m.updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.mode != timersModeList { - t.Errorf("mode after submit = %v, want timersModeList", got.mode) - } - if cmd == nil { - t.Error("want a non-nil cmd from submitForm") - } - }) -} - -// ── updateForm: fieldCancel ─────────────────────────────────────────────────── - -func TestUpdateForm_CancelField(t *testing.T) { - newM := func() TimersModel { - f := newTimerForm(nil, nil) - f.focusField(fieldCancel) - return TimersModel{mode: timersModeNew, form: f, err: "stale"} - } - - t.Run("tab moves to task", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyTab}) - if got.form.focusIdx != fieldTask { - t.Errorf("focusIdx = %d, want fieldTask", got.form.focusIdx) - } - }) - t.Run("shift+tab moves to save", func(t *testing.T) { - got, _ := newM().updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got.form.focusIdx != fieldSave { - t.Errorf("focusIdx = %d, want fieldSave", got.form.focusIdx) - } - }) - t.Run("enter cancels the form", func(t *testing.T) { - got, cmd := newM().updateForm(tea.KeyMsg{Type: tea.KeyEnter}) - if got.mode != timersModeList { - t.Errorf("mode = %v, want timersModeList", got.mode) - } - if got.err != "" { - t.Errorf("err = %q, want cleared", got.err) - } - if cmd != nil { - t.Error("want nil cmd after cancel") - } - }) -} - -// ── updateConfirm: nil-selection edge case ─────────────────────────────────── - -func TestUpdateConfirm_YKeyWithNoSelection(t *testing.T) { - // filtered is empty (no entries), so selectedEntry() is nil and the "y" - // case must return early without dispatching a delete cmd. - m := TimersModel{mode: timersModeConfirmDelete} - got, cmd := m.updateConfirm(runeKey('y')) - if got.mode != timersModeList { - t.Errorf("mode after 'y' with no selection = %v, want timersModeList", got.mode) - } - if cmd != nil { - t.Error("want nil cmd when there is nothing selected to delete") - } -} - // ── applyClientSelection / applyProjectSelection: remaining branches ──────── func TestApplyClientSelection_NoMatchesIsNoOp(t *testing.T) { @@ -1393,140 +982,6 @@ func TestTogglePaidCmd(t *testing.T) { }) } -// ── submitForm ──────────────────────────────────────────────────────────────── - -func TestSubmitForm_NewTimer_ResolveProjectError(t *testing.T) { - d := newTestDB(t) - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Do work") - f.inputs[fieldClient].SetValue("Acme") // clientID==0, clientName!="" -> ListClients() - m := TimersModel{mode: timersModeNew, form: f, db: d} - - _, cmd := m.submitForm() - if cmd == nil { - t.Fatal("want a non-nil cmd") - } - d.Close() - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("submitForm (new) with a closed db produced %T, want ErrMsg", msg) - } -} - -func TestSubmitForm_NewTimer_ExistingProject(t *testing.T) { - d := newTestDB(t) - c, _ := d.CreateClient("Acme", 0) - p, _ := d.CreateProject(c.ID, "Web") - - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Do work") - f.projectID = p.ID // explicit selection -> resolveProject short-circuits - m := TimersModel{mode: timersModeNew, form: f, db: d} - - _, cmd := m.submitForm() - if cmd == nil { - t.Fatal("want a non-nil cmd") - } - msg := cmd() - invokeBatch(t, msg) - - entries, err := d.ListEntries(0, "", "", true) - if err != nil || len(entries) != 1 { - t.Fatalf("ListEntries = %+v, err=%v, want 1 entry", entries, err) - } - if entries[0].ProjectID != p.ID { - t.Errorf("started entry's ProjectID = %d, want %d", entries[0].ProjectID, p.ID) - } -} - -func TestSubmitForm_NewTimer_Uncategorized(t *testing.T) { - d := newTestDB(t) - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Do work") // no client/project text -> resolvedProjectID==0 - m := TimersModel{mode: timersModeNew, form: f, db: d} - - _, cmd := m.submitForm() - if cmd == nil { - t.Fatal("want a non-nil cmd") - } - msg := cmd() - invokeBatch(t, msg) - - clients, _ := d.ListClients() - found := false - for _, c := range clients { - if c.Name == "Uncategorized" { - found = true - } - } - if !found { - t.Error("want an 'Uncategorized' client to have been created") - } -} - -func TestSubmitForm_Edit_NotFound(t *testing.T) { - d := newTestDB(t) - c, _ := d.CreateClient("Acme", 0) - p, _ := d.CreateProject(c.ID, "Web") - // One real entry exists, but we'll submit an edit for a different (nonexistent) ID. - if _, err := d.StartEntry(p.ID, "existing"); err != nil { - t.Fatalf("StartEntry: %v", err) - } - - f := newTimerForm(nil, nil) - f.entryID = 99999 - f.inputs[fieldTask].SetValue("Updated task") - m := TimersModel{mode: timersModeEdit, form: f, db: d} - - _, cmd := m.submitForm() - if cmd == nil { - t.Fatal("want a non-nil cmd") - } - msg := cmd() - errMsg, ok := msg.(ErrMsg) - if !ok { - t.Fatalf("got %T, want ErrMsg", msg) - } - if string(errMsg) != "Entry not found" { - t.Errorf("err = %q, want %q", errMsg, "Entry not found") - } -} - -func TestSubmitForm_Edit_Success(t *testing.T) { - d := newTestDB(t) - c, _ := d.CreateClient("Acme", 0) - p, _ := d.CreateProject(c.ID, "Web") - entry, err := d.StartEntry(p.ID, "original task") - if err != nil { - t.Fatalf("StartEntry: %v", err) - } - if err := d.StopEntry(entry.ID); err != nil { - t.Fatalf("StopEntry: %v", err) - } - - f := newTimerForm(nil, nil) - f.entryID = entry.ID - f.inputs[fieldTask].SetValue("Updated task") - f.inputs[fieldNotes].SetValue("Updated notes") - f.projectID = p.ID - m := TimersModel{mode: timersModeEdit, form: f, db: d} - - _, cmd := m.submitForm() - if cmd == nil { - t.Fatal("want a non-nil cmd") - } - msg := cmd() - invokeBatch(t, msg) - - entries, err := d.ListEntries(0, "", "", true) - if err != nil || len(entries) != 1 { - t.Fatalf("ListEntries = %+v, err=%v, want 1 entry", entries, err) - } - if entries[0].Task != "Updated task" || entries[0].Notes != "Updated notes" { - t.Errorf("entry after edit = %+v, want task/notes updated", entries[0]) - } -} - // ── mustLoadEntries ─────────────────────────────────────────────────────────── func TestMustLoadEntries(t *testing.T) { @@ -1702,141 +1157,38 @@ func TestStartCmd_StartEntryError(t *testing.T) { } } -// ── submitForm: remaining error branches, isolated one call at a time ─────── - -func TestSubmitForm_NewTimer_StopAllRunningError(t *testing.T) { - d := newTestDB(t) - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Do work") // client/project blank -> resolveProject skips the DB entirely - m := TimersModel{mode: timersModeNew, form: f, db: d} - - _, cmd := m.submitForm() - if cmd == nil { - t.Fatal("want a non-nil cmd") - } - d.Close() // makes StopAllRunning fail without resolveProject having touched the db - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("got %T, want ErrMsg from StopAllRunning failing", msg) - } -} - -func TestSubmitForm_NewTimer_StartEntryErrorWithResolvedProject(t *testing.T) { - d := newTestDB(t) - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Do work") - f.projectID = 99999 // explicit selection short-circuits resolveProject; FK violation on StartEntry - m := TimersModel{mode: timersModeNew, form: f, db: d} - - _, cmd := m.submitForm() - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("got %T, want ErrMsg from StartEntry's FK violation", msg) - } -} - -func TestSubmitForm_NewTimer_EnsureUncategorizedProjectError(t *testing.T) { - d, path := newTestDBAtPath(t) - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Do work") // blank client/project -> ensureUncategorizedProject path - m := TimersModel{mode: timersModeNew, form: f, db: d} - _, cmd := m.submitForm() - - // Drop clients (not entries) so StopAllRunning still succeeds but - // ensureUncategorizedProject's ListClients() call fails. - dropTableRaw(t, path, "clients") - - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("got %T, want ErrMsg from ensureUncategorizedProject failing", msg) - } -} - -func TestSubmitForm_Edit_ResolveProjectError(t *testing.T) { - d := newTestDB(t) - f := newTimerForm(nil, nil) - f.entryID = 1 - f.inputs[fieldTask].SetValue("Updated task") - f.inputs[fieldClient].SetValue("Acme") // clientID==0, clientName!="" -> ListClients() - m := TimersModel{mode: timersModeEdit, form: f, db: d} - - _, cmd := m.submitForm() - d.Close() - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("got %T, want ErrMsg from resolveProject failing", msg) - } -} - -func TestSubmitForm_Edit_ListEntriesError(t *testing.T) { - d, path := newTestDBAtPath(t) - c, _ := d.CreateClient("Acme", 0) - p, _ := d.CreateProject(c.ID, "Web") - - f := newTimerForm(nil, nil) - f.entryID = 1 - f.inputs[fieldTask].SetValue("Updated task") - f.projectID = p.ID // short-circuits resolveProject, no DB touch - m := TimersModel{mode: timersModeEdit, form: f, db: d} - - dropTableRaw(t, path, "entries") - - _, cmd := m.submitForm() - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("got %T, want ErrMsg from ListEntries failing", msg) - } -} - -func TestSubmitForm_Edit_UpdateEntryError(t *testing.T) { - d := newTestDB(t) - c, _ := d.CreateClient("Acme", 0) - p, _ := d.CreateProject(c.ID, "Web") - entry, err := d.StartEntry(p.ID, "original task") - if err != nil { - t.Fatalf("StartEntry: %v", err) - } - - f := newTimerForm(nil, nil) - f.entryID = entry.ID - f.inputs[fieldTask].SetValue("Updated task") - f.projectID = 99999 // resolves via short-circuit; FK violation on UpdateEntry - m := TimersModel{mode: timersModeEdit, form: f, db: d} - - _, cmd := m.submitForm() - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("got %T, want ErrMsg from UpdateEntry's FK violation", msg) - } -} - // ── View / viewList / viewEmptyState ───────────────────────────────────────── func TestView_DispatchesByMode(t *testing.T) { f := newTimerForm(nil, nil) newMode := TimersModel{mode: timersModeNew, form: f, width: 100, height: 30} - if got := newMode.View(); !strings.Contains(got, "New Timer") { + if got := newMode.View(); !strings.Contains(got, "New timer") { t.Errorf("View() in new-form mode should render the form, got %q", got) } editForm := f editForm.entryID = 42 editMode := TimersModel{mode: timersModeEdit, form: editForm, width: 100, height: 30} - if got := editMode.View(); !strings.Contains(got, "Edit Entry") { + if got := editMode.View(); !strings.Contains(got, "Edit entry") { t.Errorf("View() in edit-form mode should render the form, got %q", got) } - listMode := TimersModel{mode: timersModeList, width: 100, height: 30} - if got := listMode.View(); !strings.Contains(got, "No entries yet") { - t.Errorf("View() in list mode with no entries should render the empty state, got %q", got) + listMode := TimersModel{mode: timersModeList, width: 100, height: 30, loaded: true} + if got := listMode.View(); !strings.Contains(got, "Nothing tracked yet") { + t.Errorf("View() in list mode with no entries should render the first-run screen, got %q", got) } } func TestViewList_EmptyEntries(t *testing.T) { - m := TimersModel{width: 100, height: 30} - got := m.viewList() - if !strings.Contains(got, "No entries yet") { - t.Errorf("viewList() with no entries at all = %q, want the 'no entries yet' empty state", got) + m := TimersModel{width: 100, height: 30, loaded: true} + got := plain(m.viewList()) + for _, want := range []string{"╭┴───┴╮", "Nothing tracked yet", "Press n to start your first timer.", "n New timer", "Tip: the aliasOS bar widget starts and stops these timers too."} { + if !strings.Contains(got, want) { + t.Errorf("viewList() with no entries at all is missing %q:\n%s", want, got) + } + } + if lines := strings.Split(got, "\n"); len(lines) != m.innerHeight() { + t.Errorf("first-run screen is %d rows, want the body's %d", len(lines), m.innerHeight()) } } @@ -1937,7 +1289,7 @@ func TestViewList_ScrollIndicators(t *testing.T) { } } -func TestViewList_ConfirmDeleteModal(t *testing.T) { +func TestView_ConfirmDeleteModal(t *testing.T) { c := mkClient(1, "Acme", 0) p := mkProject(1, "Web", c) e := mkEntry(1, p, "delete me", time.Now(), 30) @@ -1945,11 +1297,12 @@ func TestViewList_ConfirmDeleteModal(t *testing.T) { m.recomputeFiltered() m.cursor = 0 - got := m.viewList() - if !strings.Contains(got, "Delete") || !strings.Contains(got, "confirm") { - t.Errorf("viewList() in confirm-delete mode should overlay the delete modal, got:\n%s", got) + m.deleteID = e.ID + got := plain(m.View()) + if !strings.Contains(got, "Delete entry?") || !strings.Contains(got, "Keep it") || !strings.Contains(got, "“delete me”") { + t.Errorf("View() in confirm-delete mode should overlay the delete modal, got:\n%s", got) } - if !strings.Contains(got, "This cannot be undone") { + if !strings.Contains(got, "This can’t be undone.") { t.Errorf("viewList() confirm-delete modal should show the warning, got:\n%s", got) } // The list itself must still be visible around/behind the modal — the @@ -2139,173 +1492,6 @@ func TestViewList_HeightStaysConstantAcrossStickyHeaderBoundary(t *testing.T) { } } -// ── viewForm ────────────────────────────────────────────────────────────────── - -func TestViewForm_NewVsEditTitle(t *testing.T) { - f := newTimerForm(nil, nil) - newM := TimersModel{mode: timersModeNew, form: f} - if got := newM.viewForm(); !strings.Contains(got, "New Timer") { - t.Errorf("viewForm() for a new entry should say 'New Timer', got %q", got) - } - - f2 := f - f2.entryID = 42 - editM := TimersModel{mode: timersModeEdit, form: f2} - if got := editM.viewForm(); !strings.Contains(got, "Edit Entry") { - t.Errorf("viewForm() for an existing entry should say 'Edit Entry', got %q", got) - } -} - -// TestRenderFormField_LabelLineStructure checks the label and input text -// land together on line 0 (with only the border's dashes on line 1) — -// lipgloss.Top alignment already got this right on its own, unlike the -// date-range filter bar's Center-alignment bug, so this is a sanity check -// rather than a regression test for that specific failure mode. -func TestRenderFormField_LabelLineStructure(t *testing.T) { - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Fix nav bug") - - got := f.renderFormField("Task", fieldTask) - lines := strings.Split(got, "\n") - if len(lines) != 2 { - t.Fatalf("renderFormField produced %d lines, want 2 (text line + border line):\n%s", len(lines), got) - } - - textLine, borderLine := lines[0], lines[1] - if !strings.Contains(textLine, "Task") || !strings.Contains(textLine, "Fix nav bug") { - t.Errorf("line 0 (text line) missing label/value, got %q", textLine) - } - if strings.Contains(borderLine, "Task") || strings.Contains(borderLine, "Fix nav bug") { - t.Errorf("line 1 (border line) should not contain the label/value, got %q", borderLine) - } - if !strings.Contains(borderLine, "─") { - t.Errorf("line 1 (border line) should contain the input box's underline, got %q", borderLine) - } -} - -// TestRenderFormField_NoUnstyledBackgroundGap is the actual regression test: -// the label (1 line) is shorter than the input box (2 lines: text + border), -// so lipgloss.JoinHorizontal used to auto-pad the label with a genuinely -// unstyled blank row under it — visible as a gap of the terminal's default -// color next to the box's border line. Top alignment already put the label -// text on the right line (see TestRenderFormField_LabelLineStructure), so -// only unstyledCellCount can actually catch this; a text-position check -// can't. -func TestRenderFormField_NoUnstyledBackgroundGap(t *testing.T) { - f := newTimerForm(nil, nil) - f.inputs[fieldTask].SetValue("Fix nav bug") - - var got string - n := unstyledCellCount(t, func() string { - got = f.renderFormField("Task", fieldTask) - return got - }) - if n > 0 { - t.Errorf("renderFormField has %d unstyled cell(s), want 0:\n%s", n, got) - } -} - -// TestRenderFormField_PicksUpLiveThemeChange guards against a real bug: a -// textinput.Model's own internal styles (PromptStyle/TextStyle/ -// PlaceholderStyle/Cursor styles) are set once, at construction -// (makeTextInput), from the theme active at that moment — they aren't among -// the package Style* vars RefreshTheme recomputes on a live theme change. -// Without refreshInputStyle re-applying them on every render, a form opened -// before a theme switch (e.g. an aliasos theme swap picked up mid-session by -// theme.Watch) would keep showing its input fields' old background -// indefinitely, even though everything else in the view updates. -func TestRenderFormField_PicksUpLiveThemeChange(t *testing.T) { - withTestPalette(t, theme.Palette{ - Primary: "#91b0de", Accent: "#9dc6e9", Success: "#99c2ed", - Warning: "#a4cbf7", Danger: "#c79ea9", Text: "#c2d9e9", - Dim: "#b7d2e5", Subtle: "#899eac", Bg: "#010101", - BgAlt: "#0f1720", Border: "#5f6468", Highlight: "#afcfff", - }) - f := newTimerForm(nil, nil) // bakes its inputs' styles under Bg=#010101 - - // Skips the placeholder's leading "W": textinput renders that first rune - // under a separate (cursor-position) style span, so it isn't a reliable - // probe point for the plain PlaceholderStyle background this test cares - // about. - placeholder := "hat are you working on?" - forceTrueColor(t) - before := f.renderFormField("Task", fieldTask) - if got := activeBackgroundAt(before, placeholder); got != "1;1;1" { - t.Fatalf("before switch: background at placeholder = %q, want 1;1;1 (Bg=#010101)", got) - } - - // Live theme switch — same form, no recreation, exactly like a running - // app's theme.CheckReload()/theme.Watch() firing while this form is open. - withTestPalette(t, theme.Palette{ - Primary: "#91b0de", Accent: "#9dc6e9", Success: "#99c2ed", - Warning: "#a4cbf7", Danger: "#c79ea9", Text: "#c2d9e9", - Dim: "#b7d2e5", Subtle: "#899eac", Bg: "#020202", - BgAlt: "#0f1720", Border: "#5f6468", Highlight: "#afcfff", - }) - - after := f.renderFormField("Task", fieldTask) - if got := activeBackgroundAt(after, placeholder); got != "2;2;2" { - t.Errorf("after switch: background at placeholder = %q, want 2;2;2 (Bg=#020202) — the field is still showing the old theme's background", got) - } -} - -func TestViewForm_ClientDropdownVisible(t *testing.T) { - clients := []*model.Client{mkClient(1, "Acme", 0), mkClient(2, "Beta", 0)} - f := newTimerForm(clients, nil) - f.focusField(fieldClient) // matches both clients (empty query) -> showClientDrop true - m := TimersModel{mode: timersModeNew, form: f} - got := m.viewForm() - if !strings.Contains(got, "Acme") { - t.Errorf("viewForm() with the client dropdown open should list matching clients, got %q", got) - } -} - -func TestViewForm_ProjectDropdownVisible(t *testing.T) { - c := mkClient(1, "Acme", 0) - projects := []*model.Project{mkProject(1, "Website", c), mkProject(2, "App", c)} - f := newTimerForm(nil, projects) - f.focusField(fieldProject) - m := TimersModel{mode: timersModeNew, form: f} - got := m.viewForm() - if !strings.Contains(got, "Website") { - t.Errorf("viewForm() with the project dropdown open should list matching projects, got %q", got) - } -} - -func TestViewForm_ErrLine(t *testing.T) { - f := newTimerForm(nil, nil) - m := TimersModel{mode: timersModeNew, form: f, err: "something broke"} - got := m.viewForm() - if !strings.Contains(got, "something broke") { - t.Errorf("viewForm() with a set err should render it, got %q", got) - } -} - -// ── renderDropdown ──────────────────────────────────────────────────────────── - -func TestRenderDropdown_FewItems(t *testing.T) { - items := []dropdownItem{{id: 0, label: `+ Create "New"`}, {id: 1, label: "Existing"}} - // sel=1 selects the second (nonzero-id) item, leaving the first - // (id==0, "create new") item unselected — exercises both the - // unselected-id-0 style branch and the unselected-nonzero-id branch. - got := renderDropdown(items, 1) - if !strings.Contains(got, "New") || !strings.Contains(got, "Existing") { - t.Errorf("renderDropdown with <=7 items should render all of them, got %q", got) - } -} - -func TestRenderDropdown_ManyItemsWindowed(t *testing.T) { - var items []dropdownItem - for i := 0; i < 20; i++ { - items = append(items, dropdownItem{id: int64(i + 1), label: "item"}) - } - sel := 19 // near the end -> exercises the "start := sel-4" windowing clamp - got := renderDropdown(items, sel) - if got == "" { - t.Fatal("renderDropdown produced empty output") - } -} - // ── statusLabel / invoiceLabel / billingStr ────────────────────────────────── func TestInvoiceLabel(t *testing.T) { @@ -2454,24 +1640,6 @@ func TestRenderDayHeaderLine_NarrowGapClamped(t *testing.T) { } } -// ── viewForm: save/cancel button focus styling ─────────────────────────────── - -func TestViewForm_SaveAndCancelButtonFocus(t *testing.T) { - saveFocused := newTimerForm(nil, nil) - saveFocused.focusField(fieldSave) - m := TimersModel{mode: timersModeNew, form: saveFocused} - if got := m.viewForm(); !strings.Contains(got, "Save & Start") { - t.Errorf("viewForm() with Save focused should still render the Save button, got %q", got) - } - - cancelFocused := newTimerForm(nil, nil) - cancelFocused.focusField(fieldCancel) - m2 := TimersModel{mode: timersModeNew, form: cancelFocused} - if got := m2.viewForm(); !strings.Contains(got, "Cancel") { - t.Errorf("viewForm() with Cancel focused should still render the Cancel button, got %q", got) - } -} - // Regression: the list view aliases j/k to Up/Down, and the form's Client and // Project dropdowns used to reuse those bindings, so typing "j" or "k" moved // the dropdown selection instead of inserting the letter. diff --git a/internal/ui/views/timers_view.go b/internal/ui/views/timers_view.go index 61620df..22174aa 100644 --- a/internal/ui/views/timers_view.go +++ b/internal/ui/views/timers_view.go @@ -880,6 +880,9 @@ func (m TimersModel) viewList() string { func (m TimersModel) viewListAt(now time.Time) string { m.clampOffset() // m is a copy: this only aligns the window drawn here w := m.innerWidth() + if m.firstRun() { + return m.viewFirstRun() + } var out []string if m.wide() { out = m.heroWide(w, now) @@ -923,12 +926,7 @@ func (m TimersModel) viewListAt(now time.Time) string { } body := strings.Join(out, "\n") - switch { - case m.mode == timersModeConfirmDelete: - if e := m.selectedEntry(); e != nil { - body = centerOverlay(body, renderConfirmModal(fmt.Sprintf(`Delete "%s"?`, truncate(e.Task, 44)))) - } - case m.detailOpen && !m.wide(): + if m.detailOpen && !m.wide() { if e := m.selectedEntry(); e != nil { if box := m.renderDetailBox(e, theme.DetailWidth, m.innerHeight(), now); box != nil { body = centerOverlay(body, strings.Join(box, "\n")) @@ -938,12 +936,59 @@ func (m TimersModel) viewListAt(now time.Time) string { return body } +// viewEmptyState is the list's place when the range shows no entries. func (m TimersModel) viewEmptyState() string { - if len(m.entries) == 0 { - return StyleTitle.Render("No entries yet.") + "\n\n" + - StyleMuted.Render("Press n to start your first timer.") + "\n" + - StyleMuted.Render("Client and project can be created right from the form.") - } return StyleTitle.Render("No entries for this range.") + "\n\n" + StyleMuted.Render("Press t for today, a for all time, or f to pick a custom range.") } + +// firstRunMark is the stopwatch drawn on the first-run screen. +var firstRunMark = []string{ + " ╭───╮ ", + " ╭┴───┴╮ ", + " │ ╷ │ ", + " │ ╰─ │ ", + " ╰─────╯ ", +} + +// viewFirstRun fills the tab before anything has been tracked: the mark, +// one sentence, one action, and a tip, centred. +func (m TimersModel) viewFirstRun() string { + w, h := m.innerWidth(), m.innerHeight() + center := func(s string, fg lipgloss.Color, bg lipgloss.Color, bold bool) string { + s = truncate(s, w) + left := (w - ansi.StringWidth(s)) / 2 + return blankLine(left) + renderSegs(cBg, seg{s: s, fg: fg, bg: bg, bold: bold}) + blankLine(w-left-ansi.StringWidth(s)) + } + var rows []boxRow + for _, l := range firstRunMark { + rows = append(rows, boxRow{center(l, cHighlight, "", false), dropKeep}) + } + rows = append(rows, + boxRow{blankLine(w), dropGap}, boxRow{blankLine(w), dropMargin}, + boxRow{center("Nothing tracked yet", cText, "", true), dropKeep}, + boxRow{blankLine(w), dropGap}, + ) + for _, l := range wrapWords("Press n to start your first timer. Clients and projects are created as you type.", w) { + rows = append(rows, boxRow{center(l, cDim, "", false), dropKeep}) + } + rows = append(rows, + boxRow{blankLine(w), dropGap}, boxRow{blankLine(w), dropMargin}, + boxRow{center(" n New timer ", cBg, cPrimary, true), dropKeep}, + boxRow{blankLine(w), dropGap}, boxRow{blankLine(w), dropMargin}, + ) + for _, l := range wrapWords("Tip: the aliasOS bar widget starts and stops these timers too.", w) { + rows = append(rows, boxRow{center(l, cSubtle, "", false), dropHint}) + } + lines := fitRows(rows, h) + top := max(0, (h-len(lines))/2) + out := make([]string, 0, h) + for range top { + out = append(out, blankLine(w)) + } + out = append(out, lines...) + for len(out) < h { + out = append(out, blankLine(w)) + } + return strings.Join(out, "\n") +} diff --git a/landing/tokens.css b/landing/tokens.css index 646de09..e8ee8bb 100644 --- a/landing/tokens.css +++ b/landing/tokens.css @@ -12,6 +12,7 @@ --color-bg-alt: #252E35; --color-border: #5F6468; --color-highlight: #AFCFFF; + --color-backdrop: #3E464C; --color-surface: #111D26; --color-code-bg: #0A1319; --color-kbd-fill: rgba(255,255,255,0.03); diff --git a/landing/tokens.js b/landing/tokens.js index df995c5..411ff0e 100644 --- a/landing/tokens.js +++ b/landing/tokens.js @@ -14,6 +14,7 @@ window.notchTokens = { bgalt: '#252E35', line: '#5F6468', highlight: '#AFCFFF', + backdrop: '#3E464C', surface: '#111D26', codebg: '#0A1319', kbdfill: 'rgba(255,255,255,0.03)',