From fe92496f95ab7e11f10d78e77190ae7031548e1d Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 08:00:10 -0700 Subject: [PATCH 01/13] Redesign the TUI's chrome and Timers screen (ALI-2615) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tab bar now carries the ◷ notch wordmark, numbered tabs with a primary underline, and the running pill on every tab. The bottom is a rule and one line of keys with the latest status at the right. The Timers list gains a hero (NOW TRACKING, block-digit elapsed time, today, this week and unbilled), range chips (t w m a f), day groups with subtotals, status glyphs, a detail pane at 120 columns and wider, and a compact layout below that with a summary line and enter for details. New keys: m (this month), r (resume), enter (details). Layout sizes come from design/tokens.json (tui-margin, tui-wide, tui-detail-width; tui-chrome-rows is now 4). --- README.md | 12 +- design/build/main.go | 19 +- design/tokens.json | 13 +- internal/theme/tokens_gen.go | 22 +- internal/ui/app.go | 359 ++++------- internal/ui/app_test.go | 129 ++-- internal/ui/layout_gen.go | 8 +- internal/ui/render_test.go | 120 ++++ internal/ui/views/common.go | 4 +- internal/ui/views/common_test.go | 8 +- internal/ui/views/timers.go | 399 ++---------- internal/ui/views/timers_test.go | 212 +------ internal/ui/views/timers_view.go | 850 ++++++++++++++++++++++++++ internal/ui/views/timers_view_test.go | 262 ++++++++ 14 files changed, 1546 insertions(+), 871 deletions(-) create mode 100644 internal/ui/render_test.go create mode 100644 internal/ui/views/timers_view.go create mode 100644 internal/ui/views/timers_view_test.go diff --git a/README.md b/README.md index 2be4e1c..761b8f2 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Track time entries, manage clients and projects, set billing rates, mark work as ## Features -- **Timer tracking** — start/stop timers on tasks, see the live elapsed time in the bottom status bar +- **Timer tracking** — start/stop timers on tasks, see the live elapsed time in the tab bar on every tab - **Clients & Projects** — full CRUD, clients on their own tab with project management next door - **Billing rates** — set an hourly rate per client; earnings calculated automatically - **Invoice & payment tracking** — mark entries as invoiced and/or paid @@ -217,6 +217,11 @@ That rewrites the generated files (marked as generated; never edit them by hand) | `space` | Start / stop selected entry's timer | | `i` | Toggle invoiced status | | `p` | Toggle paid status (entry must be invoiced first) | +| `r` | Resume: start the selected entry's task again | +| `t` / `w` / `m` / `a` | Range: today, this week, this month, all time | +| `y` | Range: yesterday | +| `f` | Range: custom dates | +| `enter` | Under 120 columns: open the selected entry's details | | `esc` | Cancel / back | ### New / Edit timer form @@ -329,16 +334,17 @@ notch/ │ └── db.go # SQLite persistence (modernc.org/sqlite, pure Go) ├── theme/ │ ├── theme.go # Palette type, desktop theme and theme.conf loading, live reload - │ └── tokens_gen.go # Generated: the built-in palette, glyphs and gutter + │ └── tokens_gen.go # Generated: the built-in palette, glyphs and TUI layout sizes ├── status/ │ └── status.go # `notch status` output formatting (text/JSON) └── ui/ - ├── app.go # Root Bubble Tea model, tab router, header/footer + ├── app.go # Root Bubble Tea model, tab router, tab bar and hotkey line ├── styles.go # Layout helpers (content width and padding) ├── layout_gen.go # Generated: layout constants (max width, chrome rows) └── views/ ├── common.go # Shared types, messages, styles, key maps, helpers ├── timers.go # Timers tab — list, start/stop, edit, invoice/pay + ├── timers_view.go # Timers list screen: hero, range chips, day groups, detail pane ├── projects.go # Projects tab — flat project list w/ client picker ├── clients.go # Clients tab — client CRUD with billing rate └── reports.go # Reports tab — date-filtered summary + cards diff --git a/design/build/main.go b/design/build/main.go index 1e8b579..b5a1865 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -316,13 +316,20 @@ func renderPalette(t *Tokens) ([]byte, error) { fmt.Fprintf(&b, "\t%s = %q\n", goName(tok.Name), v) } b.WriteString(")\n\n") - gutter, err := integer(t.Spacing, "tui-gutter") - if err != nil { - return nil, err + for _, c := range []struct{ token, name string }{ + {"tui-gutter", "Gutter"}, + {"tui-margin", "Margin"}, + {"tui-wide", "WideMin"}, + {"tui-detail-width", "DetailWidth"}, + } { + v, err := integer(t.Spacing, c.token) + if err != nil { + return nil, err + } + b.WriteString(comment("", c.name+" ("+c.token+"). "+usage(t.Spacing, c.token))) + fmt.Fprintf(&b, "const %s = %d\n\n", c.name, v) } - b.WriteString(comment("", "Gutter (tui-gutter). "+usage(t.Spacing, "tui-gutter"))) - fmt.Fprintf(&b, "const Gutter = %d\n", gutter) - return format.Source([]byte(b.String())) + return format.Source([]byte(strings.TrimRight(b.String(), "\n") + "\n")) } func renderLayout(t *Tokens) ([]byte, error) { diff --git a/design/tokens.json b/design/tokens.json index e5aaa33..9634e40 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -59,7 +59,10 @@ "tokens": [ { "name": "tui-max-width", "value": 150, "usage": "TUI: the widest the centred content column gets, in cells. Wider terminals pad both sides." }, { "name": "tui-gutter", "value": 2, "usage": "TUI: columns before every list row for the row cursor (glyph-cursor and a space). Report columns leave the same room." }, - { "name": "tui-chrome-rows", "value": 9, "usage": "TUI: rows taken by the top bar, hotkey bar and footer (3 each, measured from their real output). Content gets the rest." }, + { "name": "tui-margin", "value": 2, "usage": "TUI: blank columns on each side of the content column, and before the tab bar's wordmark." }, + { "name": "tui-wide", "value": 120, "usage": "TUI: the narrowest terminal that gets the wide layout: the Timers hero with block digits, the CLIENT › PROJECT column and the entry detail pane. Narrower terminals get the compact layout." }, + { "name": "tui-detail-width", "value": 42, "usage": "TUI: the entry detail pane's width, borders included, beside the Timers list in the wide layout." }, + { "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." }, { "name": "panel-padding", "value": "14px", "usage": "Bar panel: inner padding, from aliasOS's KeyboardPanel." } ] }, @@ -97,10 +100,10 @@ { "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-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. Redesign (ALI-2615): not drawn yet." }, - { "name": "glyph-invoiced", "value": "◐", "usage": "Status: invoiced, not paid. Redesign (ALI-2615): not drawn yet." }, - { "name": "glyph-paid", "value": "●", "usage": "Status: paid. Redesign (ALI-2615): not drawn yet." }, - { "name": "glyph-running", "value": "▶", "usage": "Status: the timer is running. Redesign (ALI-2615): not drawn yet." } + { "name": "glyph-unbilled", "value": "○", "usage": "Status: not invoiced yet, in subtle." }, + { "name": "glyph-invoiced", "value": "◐", "usage": "Status: invoiced, not paid, in accent." }, + { "name": "glyph-paid", "value": "●", "usage": "Status: paid, in success." }, + { "name": "glyph-running", "value": "▶", "usage": "Status: the timer is running, in success; also marks the running timer in the compact hero." } ] }, "contrast": { diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index 0eecfa5..b3e4858 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -46,16 +46,30 @@ const ( GlyphCursor = "▌" // The dot in the footer: in the running pill, and in subtle when idle. GlyphLive = "●" - // Status: not invoiced yet. Redesign (ALI-2615): not drawn yet. + // Status: not invoiced yet, in subtle. GlyphUnbilled = "○" - // Status: invoiced, not paid. Redesign (ALI-2615): not drawn yet. + // Status: invoiced, not paid, in accent. GlyphInvoiced = "◐" - // Status: paid. Redesign (ALI-2615): not drawn yet. + // Status: paid, in success. GlyphPaid = "●" - // Status: the timer is running. Redesign (ALI-2615): not drawn yet. + // Status: the timer is running, in success; also marks the running timer in + // the compact hero. GlyphRunning = "▶" ) // Gutter (tui-gutter). TUI: columns before every list row for the row cursor // (glyph-cursor and a space). Report columns leave the same room. const Gutter = 2 + +// Margin (tui-margin). TUI: blank columns on each side of the content column, +// and before the tab bar's wordmark. +const Margin = 2 + +// WideMin (tui-wide). TUI: the narrowest terminal that gets the wide layout: +// the Timers hero with block digits, the CLIENT › PROJECT column and the +// entry detail pane. Narrower terminals get the compact layout. +const WideMin = 120 + +// DetailWidth (tui-detail-width). TUI: the entry detail pane's width, borders +// included, beside the Timers list in the wide layout. +const DetailWidth = 42 diff --git a/internal/ui/app.go b/internal/ui/app.go index 80eb73c..e757b34 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -22,13 +22,6 @@ const ( TabReports = 3 ) -// hotkeySep separates hotkey chips in the hotkey bar. -const hotkeySep = " · " - -// hotkeyGlobal lists the hotkeys shown on every tab, appended after the -// active view's contextual keys in the hotkey bar. -var hotkeyGlobal = []views.Hotkey{{Key: "1-4", Label: "tabs"}, {Key: "q", Label: "quit"}} - var tabNames = []string{"Timers", "Projects", "Clients", "Reports"} // palette mirrors views/common.go's theme.Colors — kept as its own copy since @@ -38,15 +31,16 @@ var tabNames = []string{"Timers", "Projects", "Clients", "Reports"} // this copy in sync with theme.Colors — called at init and again whenever // theme.CheckReload reports a change (see the TickMsg handler below). var ( - appColorPrimary lipgloss.Color - appColorGreen lipgloss.Color - appColorDanger lipgloss.Color - appColorDim lipgloss.Color - appColorSubtle lipgloss.Color - appColorText lipgloss.Color - appColorBg lipgloss.Color - appColorBgAlt lipgloss.Color - appColorBorder lipgloss.Color + appColorPrimary lipgloss.Color + appColorGreen lipgloss.Color + appColorDanger lipgloss.Color + appColorDim lipgloss.Color + appColorSubtle lipgloss.Color + appColorText lipgloss.Color + appColorBg lipgloss.Color + appColorBgAlt lipgloss.Color + appColorBorder lipgloss.Color + appColorHighlight lipgloss.Color ) func init() { refreshAppTheme() } @@ -61,6 +55,7 @@ func refreshAppTheme() { appColorBg = theme.Colors.Bg appColorBgAlt = theme.Colors.BgAlt appColorBorder = theme.Colors.Border + appColorHighlight = theme.Colors.Highlight } // TickMsg is sent every second to update the running timer display. @@ -345,271 +340,129 @@ func (m AppModel) View() string { return lipgloss.JoinVertical(lipgloss.Left, m.renderTopBar(), m.renderBody(), - m.renderHotkeyBar(), - m.renderFooter(), + m.renderBottomBar(), ) } -// renderTopBar renders a full-width bar with: app name | tabs centered. -// Keep it simple: build a plain string, then render it once in a styled container. +// paint renders s in fg on bg, bold or not. Every fragment of a bar carries +// its own background: each Render ends with an SGR reset, so an unstyled +// gap would show the terminal's default background instead of the bar's. +func paint(s string, fg, bg lipgloss.Color, bold bool) string { + return lipgloss.NewStyle().Foreground(fg).Background(bg).Bold(bold).Render(s) +} + +// tabLabel is one tab in the tab bar: " 1 Timers ". +func tabLabel(i int) string { return fmt.Sprintf(" %d %s ", i+1, tabNames[i]) } + +// tabsStart is the column the first tab starts at: the margin, the +// wordmark and a gap. +func tabsStart() int { + return theme.Margin + lipgloss.Width(wordmark()) + 4 +} + +func wordmark() string { return theme.GlyphWordmark + " notch" } + +// renderTopBar renders the tab bar and the rule under it: the wordmark, the +// numbered tabs, and the running timer (or idle) on the right; the rule +// carries a primary underline under the active tab. func (m AppModel) renderTopBar() string { - // Every fragment below carries an explicit Background(appColorBgAlt): each - // .Render() call emits its own trailing SGR reset, so once fragments are - // concatenated into `line` and handed to the outer Background()-wrapped - // style, any fragment (or raw gap) without its own background would show - // the terminal's default background instead of the bar color. - barBg := lipgloss.NewStyle().Background(appColorBgAlt) - - // ── app name (left) ─────────────────────────────────────────────────────── - // Muted wordmark, no icon: accent color is reserved for things that are - // actually interactive (the active tab, buttons), and a clock glyph next - // to the name was more clutter than identity. appColorDim (the inactive - // tab color) reads as quieter/more minimal here than full-brightness - // appColorText, which in some themes is close enough to the active-tab - // color to compete with it for attention. - appName := barBg. - Foreground(appColorDim). - Bold(true). - Padding(0, 1). - Render("Notch") - - // ── tabs (center) ───────────────────────────────────────────────────────── - activeSty := barBg. - Foreground(appColorText). - Bold(true). - Padding(0, 2) - inactiveSty := barBg. - Foreground(appColorDim). - Padding(0, 2) - sepSty := barBg.Foreground(appColorSubtle) - - var tabParts []string - for i, name := range tabNames { + bg := appColorBgAlt + left := paint(strings.Repeat(" ", theme.Margin), appColorText, bg, false) + + paint(wordmark(), appColorHighlight, bg, true) + + paint(" ", appColorText, bg, false) + var underFrom, underTo int + col := tabsStart() + for i := range tabNames { + if i > 0 { + left += paint(" ", appColorText, bg, false) + col += 2 + } + label := tabLabel(i) + num, name, _ := strings.Cut(strings.TrimSpace(label), " ") + nameFg, bold := appColorDim, false if i == m.activeTab { - tabParts = append(tabParts, activeSty.Render(name)) - } else { - tabParts = append(tabParts, inactiveSty.Render(name)) + nameFg, bold = appColorText, true + underFrom, underTo = col, col+lipgloss.Width(label) } + left += paint(" ", appColorText, bg, false) + paint(num, appColorSubtle, bg, false) + + paint(" ", appColorText, bg, false) + paint(name, nameFg, bg, bold) + paint(" ", appColorText, bg, false) + col += lipgloss.Width(label) } - tabRow := strings.Join(tabParts, sepSty.Render(" │ ")) - // ── layout: logo flush left, tabs centred on the full window width ─────── - appW := lipgloss.Width(appName) - tabW := lipgloss.Width(tabRow) - - // left of tabs = (m.width - tabW)/2; the logo occupies appW of that, so the - // gap between logo and tabs is that offset minus the logo width. - leftGap := (m.width-tabW)/2 - appW - if leftGap < 0 { - leftGap = 0 + margin := paint(strings.Repeat(" ", theme.Margin), appColorText, bg, false) + var right string + if r := m.running; r != nil { + pill := paint(" "+theme.GlyphLive+" "+model.FormatDuration(r.Duration())+" ", appColorBg, appColorGreen, true) + room := m.width - lipgloss.Width(left) - lipgloss.Width(pill) - theme.Margin - 3 + if room >= 4 { + right = paint(truncateStr(r.Task, room)+" ", appColorText, bg, false) + } + right += pill + margin + } else { + right = paint(theme.GlyphLive+" idle", appColorSubtle, bg, false) + margin } - - line := appName + barBg.Render(strings.Repeat(" ", leftGap)) + tabRow - - // Render the whole line once inside the bar container (padding adds top/bottom rows) - return lipgloss.NewStyle(). - Background(appColorBgAlt). - Foreground(appColorText). - Width(m.width). - Padding(1, 0). - Render(line) + gap := max(1, m.width-lipgloss.Width(left)-lipgloss.Width(right)) + line := left + paint(strings.Repeat(" ", gap), appColorText, bg, false) + right + line = lipgloss.NewStyle().MaxWidth(m.width).Render(line) + + underFrom, underTo = min(underFrom, m.width), min(underTo, m.width) + ruleLine := paint(strings.Repeat("─", underFrom), appColorBorder, appColorBg, false) + + paint(strings.Repeat("━", underTo-underFrom), appColorPrimary, appColorBg, false) + + paint(strings.Repeat("─", max(0, m.width-underTo)), appColorBorder, appColorBg, false) + return line + "\n" + ruleLine } -// renderHotkeyBar renders a full-width, fixed-position row of hotkeys: the -// active view's contextual keys and the global app keys as a single centered -// line. Unlike renderFooter, its content depends only on m.activeTab + that -// view's current mode — never on transient state (errors/status/busy) — so -// it never moves with content length and is never overwritten by a status -// message. -// hotkeyKeyCapStyle renders a hotkey's Key in a small boxed "cap" — a -// background-filled rectangle — so it reads as a distinct button separate -// from its plain-text label, the common hotkey-bar convention. -func hotkeyKeyCapStyle() lipgloss.Style { - return lipgloss.NewStyle(). - Bold(true). - Foreground(appColorText). - Background(appColorBgAlt). - Padding(0, 1) -} +// hotkeySep separates hotkey chips in the hotkey line. +const hotkeySep = " " -// renderHotkeyChip renders one "[key] label" pair using capStyle for the -// boxed key and appColorSubtle for the label. -func renderHotkeyChip(h views.Hotkey, capStyle lipgloss.Style) string { - return capStyle.Render(h.Key) + - lipgloss.NewStyle().Background(appColorBg).Foreground(appColorSubtle).Render(" "+h.Label) +// renderHotkeyChip renders one key: its cap (the key on bg_alt) and label. +func renderHotkeyChip(h views.Hotkey) string { + return paint(" "+h.Key+" ", appColorText, appColorBgAlt, true) + + paint(" "+h.Label, appColorSubtle, appColorBg, false) } -// hotkeyChipWidth returns the rendered width of h as drawn by renderHotkeyChip. func hotkeyChipWidth(h views.Hotkey) int { - return lipgloss.Width(h.Key) + 2 /* cap padding */ + 1 /* space */ + lipgloss.Width(h.Label) + return lipgloss.Width(h.Key) + 2 + 1 + lipgloss.Width(h.Label) } -func (m AppModel) renderHotkeyBar() string { - pad := 2 - inner := max(10, m.width-pad*2) - capStyle := hotkeyKeyCapStyle() - sepStyle := lipgloss.NewStyle().Background(appColorBg).Foreground(appColorSubtle) +// renderBottomBar renders a rule, then one line: the active view's keys +// on the left and the latest status or error on the right. Keys that don't +// fit are dropped whole, from the end, never cut mid-chip; the message is +// truncated instead of the keys when both can't fit. +func (m AppModel) renderBottomBar() string { + bg := appColorBg + inner := max(10, m.width-2*theme.Margin) - renderRow := func(hs []views.Hotkey) string { - parts := make([]string, len(hs)) - for i, h := range hs { - parts[i] = renderHotkeyChip(h, capStyle) - } - return strings.Join(parts, sepStyle.Render(hotkeySep)) - } - - globalWidth := 0 - for i, h := range hotkeyGlobal { - globalWidth += hotkeyChipWidth(h) - if i > 0 { - globalWidth += lipgloss.Width(hotkeySep) - } + var msg string + switch { + case m.err != "": + msg = paint(truncateStr("✕ "+m.err, inner/2), appColorDanger, bg, true) + case m.statusMsg != "": + msg = paint(truncateStr("✓ "+m.statusMsg, inner/2), appColorGreen, bg, false) } + room := inner - lipgloss.Width(msg) - 2 - // Context hotkeys are dropped wholesale (never mid-chip truncated) once - // they no longer fit, so a narrow terminal never cuts a key cap in half. - maxContext := max(0, inner-globalWidth-lipgloss.Width(hotkeySep)) - var context []views.Hotkey - w := 0 + keys, w := "", 0 for i, h := range m.activeViewHelp() { cw := hotkeyChipWidth(h) if i > 0 { - cw += lipgloss.Width(hotkeySep) + cw += len(hotkeySep) } - if w+cw > maxContext { + if w+cw > room { break } - w += cw - context = append(context, h) - } - - combined := renderRow(hotkeyGlobal) - if len(context) > 0 { - combined = renderRow(context) + sepStyle.Render(hotkeySep) + combined - } - - return lipgloss.NewStyle(). - Width(m.width). - Padding(1, pad). - // PaddingTop(1). - Align(lipgloss.Center). - Background(appColorBg). - Foreground(appColorSubtle). - Render(combined) -} - -// renderFooter renders a full-width status bar: the running timer on the left, -// errors/status/help on the right. -func (m AppModel) renderFooter() string { - pad := 2 - inner := m.width - pad*2 - if inner < 10 { - inner = 10 - } - - rightBudget := 62 - if inner-rightBudget < 20 { - rightBudget = inner / 3 - } - if rightBudget < 10 { - rightBudget = 10 - } - - // Every fragment below carries an explicit Background(appColorBgAlt) for the - // same reason as renderTopBar: each .Render() ends with its own SGR reset, - // so an un-backgrounded fragment (or raw gap) would show the terminal's - // default background instead of the bar color once concatenated together. - barBg := lipgloss.NewStyle().Background(appColorBgAlt) - - // ── left: running timer (or idle hint) ──────────────────────────────────── - // The running box below has Padding(0, 2), so its "●" sits two columns in - // from its own left edge — the idle "●" gets the same two-column inset so - // the dot lands in the exact same spot either way. - var left string - if m.running == nil { - left = barBg.Render(" ") + barBg.Foreground(appColorSubtle).Render(theme.GlyphLive) + - barBg.Render(" ") + barBg.Foreground(appColorDim).Render("idle") - } else { - r := m.running - pill := lipgloss.NewStyle(). - Background(appColorGreen). - Foreground(appColorBg). - Bold(true). - Padding(0, 2). - Render(theme.GlyphLive + " " + model.FormatDuration(r.Duration())) - pillW := lipgloss.Width(pill) - - leftBudget := inner - rightBudget - 2 - if leftBudget < pillW { - leftBudget = pillW - } - - taskMax := leftBudget - pillW - 4 - if taskMax < 4 { - taskMax = 4 - } - task := barBg. - Foreground(appColorText). - Bold(true). - Render(truncateStr(r.Task, taskMax)) - left = pill + barBg.Render(" ") + task - - if r.Project != nil { - rest := leftBudget - lipgloss.Width(left) - 2 - if rest >= 6 { - left += barBg.Render(" ") + barBg. - Foreground(appColorDim). - Render(truncateStr(r.Project.Client.Name+" › "+r.Project.Name, rest)) - } + if i > 0 { + keys += paint(hotkeySep, appColorSubtle, bg, false) } + keys += renderHotkeyChip(h) + w += cw } - // ── right: error, status, or busy-mode hint ─────────────────────────────── - // Hotkeys live in the dedicated bar rendered by renderHotkeyBar(), one row - // up — so when idle (no error/status, view not busy) this is intentionally - // blank rather than falling back to a generic hotkey list. - var rightText string - var rightStyle lipgloss.Style - switch { - case m.err != "": - rightText = "✖ " + m.err - rightStyle = barBg.Foreground(appColorDanger).Bold(true) - case m.statusMsg != "": - rightText = "✔ " + m.statusMsg - rightStyle = barBg.Foreground(appColorGreen).Bold(true) - case m.activeViewBusy(): - rightText = "enter confirm · esc cancel · tab next field" - rightStyle = barBg.Foreground(appColorSubtle) - } - right := rightStyle.Render(truncateStr(rightText, rightBudget)) - - lw := lipgloss.Width(left) - rw := lipgloss.Width(right) - gap := inner - lw - rw - if gap < 2 { - gap = 2 - } - - line := left + barBg.Render(strings.Repeat(" ", gap)) + right - - // A top border visually separates this bar from the hotkey bar directly - // above it; BorderBackground must be set explicitly (it's a separate - // property from Background, see renderSummaryCards in reports.go for the - // same rule) or the border row shows the terminal's default background. - // Padding is asymmetric (top=0, bottom=1): the border row itself already - // reads as visual space above the content, so a symmetric Padding(1, pad) - // stacked on top of it made the gap above content look taller than the - // gap below. Dropping the top padding balances the two, and slims the bar - // by one row. - return lipgloss.NewStyle(). - Background(appColorBgAlt). - Foreground(appColorDim). - Width(m.width). - // Border(lipgloss.NormalBorder(), true, false, false, false). - // BorderForeground(appColorSubtle). - // BorderBackground(appColorBgAlt). - Padding(1, pad). - Render(line) + 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 + ruleLine := paint(strings.Repeat("─", m.width), appColorBorder, bg, false) + return ruleLine + "\n" + lipgloss.NewStyle().MaxWidth(m.width).Render(line) } func truncateStr(s string, max int) string { @@ -650,7 +503,7 @@ func (m AppModel) renderBody() string { Height(ch). MaxHeight(ch). Background(appColorBg). - Padding(1, 3). + Padding(1, theme.Margin). Render(view) // Skip gutters only when the column truly fills the whole row (m.width diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index 488fd03..757e8ff 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -137,37 +137,49 @@ func TestRenderBars_MatchWidth(t *testing.T) { for _, w := range []int{40, 80, 120, 200} { m.width = w m.height = 40 - if got := lipgloss.Width(m.renderTopBar()); got != w { - t.Errorf("renderTopBar width at m.width=%d = %d, want %d", w, got, w) - } - if got := lipgloss.Width(m.renderHotkeyBar()); got != w { - t.Errorf("renderHotkeyBar width at m.width=%d = %d, want %d", w, got, w) - } - if got := lipgloss.Width(m.renderFooter()); got != w { - t.Errorf("renderFooter width at m.width=%d = %d, want %d", w, got, w) + for name, bar := range map[string]string{"top": m.renderTopBar(), "bottom": m.renderBottomBar()} { + for i, line := range strings.Split(bar, "\n") { + if got := lipgloss.Width(line); got != w { + t.Errorf("%s bar line %d at m.width=%d is %d wide, want %d", name, i, w, got, w) + } + } } } } -// TestRenderTopBar_PlainWordmarkNoIcon guards a deliberate design choice: the -// top bar used to render "⏱ Notch" in the bright accent color; it's now a -// plain "Notch" wordmark, since the clock glyph read as clutter rather than -// identity and the accent color is reserved for things that are actually -// interactive (the active tab, buttons). -func TestRenderTopBar_PlainWordmarkNoIcon(t *testing.T) { +// The tab bar has the ◷ notch wordmark, the numbered tabs, and a primary +// underline under the active tab's label in the rule below. +func TestRenderTopBar_WordmarkTabsAndUnderline(t *testing.T) { d := newTestDB(t) m, err := New(d) if err != nil { t.Fatalf("New: %v", err) } - m.width, m.height = 80, 40 + m.width, m.height = 140, 40 - got := m.renderTopBar() - if !strings.Contains(got, "Notch") { - t.Errorf("renderTopBar() missing wordmark, got %q", got) + lines := strings.Split(plainText(m.renderTopBar()), "\n") + if len(lines) != 2 { + t.Fatalf("top bar has %d lines, want 2", len(lines)) } - if strings.Contains(got, "⏱") { - t.Errorf("renderTopBar() still contains the clock icon, want a plain wordmark: %q", got) + if !strings.HasPrefix(lines[0], " "+theme.GlyphWordmark+" notch") { + t.Errorf("tab bar starts %q, want the margin and the wordmark", lines[0]) + } + for i := range tabNames { + if !strings.Contains(lines[0], tabLabel(i)) { + t.Errorf("tab bar is missing %q: %q", tabLabel(i), lines[0]) + } + } + for _, tab := range []int{TabTimers, TabReports} { + m.activeTab = tab + rule := []rune(strings.Split(plainText(m.renderTopBar()), "\n")[1]) + col := tabsStart() + for i := 0; i < tab; i++ { + col += len([]rune(tabLabel(i))) + 2 + } + under := string(rule[col : col+len([]rune(tabLabel(tab)))]) + if strings.Trim(under, "━") != "" || strings.Count(string(rule), "━") != len([]rune(tabLabel(tab))) { + t.Errorf("tab %d: rule %q should underline exactly %q", tab, string(rule), tabLabel(tab)) + } } } @@ -237,14 +249,8 @@ func withTestPalette(t *testing.T, p theme.Palette) { views.RefreshTheme() } -// TestRenderTopBar_WordmarkUsesInactiveTabColor guards the wordmark's color -// choice: it went through two revisions in the same session (bright -// accent -> plain cText -> this) because cText itself still read as "one of -// the brighter colors" against some themes. appColorDim is the same color -// already used for inactive tab labels, so the wordmark now reads as a -// quiet, de-emphasized element rather than competing with the active tab or -// any button for attention. -func TestRenderTopBar_WordmarkUsesInactiveTabColor(t *testing.T) { +// The wordmark is drawn in highlight, as the brand board specifies. +func TestRenderTopBar_WordmarkUsesHighlight(t *testing.T) { withTestPalette(t, theme.Palette{ Primary: "#111111", Accent: "#222222", Success: "#333333", Warning: "#444444", Danger: "#555555", Text: "#e5e4e8", @@ -261,8 +267,8 @@ func TestRenderTopBar_WordmarkUsesInactiveTabColor(t *testing.T) { forceTrueColor(t) got := m.renderTopBar() - if fg := activeForegroundAt(got, "Notch"); fg != "172;171;174" { - t.Errorf("wordmark foreground = %q, want 172;171;174 (Dim, matching the inactive-tab color)", fg) + if fg := activeForegroundAt(got, "notch"); fg != "102;102;102" { + t.Errorf("wordmark foreground = %q, want 102;102;102 (Highlight)", fg) } } @@ -288,13 +294,10 @@ func TestChromeRows_MatchesActualBarHeights(t *testing.T) { m.width, m.height = 100, 40 top := lipgloss.Height(m.renderTopBar()) - hotkey := lipgloss.Height(m.renderHotkeyBar()) - footer := lipgloss.Height(m.renderFooter()) - total := top + hotkey + footer - - if total != ChromeRows { - t.Errorf("actual chrome height = %d (top=%d hotkey=%d footer=%d), but ChromeRows = %d", - total, top, hotkey, footer, ChromeRows) + bottom := lipgloss.Height(m.renderBottomBar()) + if total := top + bottom; total != ChromeRows { + t.Errorf("actual chrome height = %d (top=%d bottom=%d), but ChromeRows = %d", + total, top, bottom, ChromeRows) } } @@ -322,7 +325,9 @@ func TestRenderBody_MatchWidth(t *testing.T) { } } -func TestRenderFooter_ShowsRunningTimer(t *testing.T) { +// The running timer's task and elapsed time sit at the right of the tab +// bar, on every tab. +func TestRenderTopBar_ShowsRunningTimer(t *testing.T) { d := newTestDB(t) c, err := d.CreateClient("Acme", 100) if err != nil { @@ -340,14 +345,13 @@ func TestRenderFooter_ShowsRunningTimer(t *testing.T) { if err != nil { t.Fatalf("New: %v", err) } - // 120 rather than a narrower width: the running pill's caps + extra - // padding eat into the task-name budget, so a narrower width would - // truncate "build feature" before this assertion even gets to check it. m.width = 120 - - footer := m.renderFooter() - if !strings.Contains(footer, "build feature") { - t.Errorf("renderFooter() should show the running entry's task, got: %q", footer) + for _, tab := range []int{TabTimers, TabClients} { + m.activeTab = tab + bar := plainText(m.renderTopBar()) + if !strings.Contains(bar, "build feature") || !strings.Contains(bar, theme.GlyphLive+" 0:00:0") { + t.Errorf("tab %d: tab bar should show the running task and its pill, got: %q", tab, bar) + } } } @@ -417,7 +421,7 @@ func TestReportsEntriesView_LongNoteDoesNotOverflow(t *testing.T) { } } -func TestRenderFooter_IdleWhenNoRunningEntry(t *testing.T) { +func TestRenderTopBar_IdleWhenNoRunningEntry(t *testing.T) { d := newTestDB(t) m, err := New(d) if err != nil { @@ -425,8 +429,35 @@ func TestRenderFooter_IdleWhenNoRunningEntry(t *testing.T) { } m.width = 100 - footer := m.renderFooter() - if !strings.Contains(footer, "idle") { - t.Errorf("renderFooter() should show 'idle' with no running entry, got: %q", footer) + if bar := m.renderTopBar(); !strings.Contains(bar, "idle") { + t.Errorf("renderTopBar() should show 'idle' with no running entry, got: %q", bar) + } +} + +// 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.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"`} { + if !strings.Contains(line, want) { + t.Errorf("bottom line %q is missing %q", line, want) + } + } + m.width = 40 + m.err = "Stop the timer before invoicing" + line = strings.Split(plainText(m.renderBottomBar()), "\n")[1] + if !strings.Contains(line, "✕ ") || strings.Count(line, " n new") > 1 { + t.Errorf("narrow bottom line: %q", line) + } + if strings.Contains(line, "start/sto") && !strings.Contains(line, "start/stop") { + t.Errorf("a key was cut mid-chip: %q", line) } } diff --git a/internal/ui/layout_gen.go b/internal/ui/layout_gen.go index bc451ec..8f65133 100644 --- a/internal/ui/layout_gen.go +++ b/internal/ui/layout_gen.go @@ -6,7 +6,7 @@ package ui // gets, in cells. Wider terminals pad both sides. const MaxContentWidth = 150 -// ChromeRows (tui-chrome-rows). TUI: rows taken by the top bar, hotkey bar -// and footer (3 each, measured from their real output). Content gets the -// rest. -const ChromeRows = 9 +// ChromeRows (tui-chrome-rows). 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. +const ChromeRows = 4 diff --git a/internal/ui/render_test.go b/internal/ui/render_test.go new file mode 100644 index 0000000..78a816a --- /dev/null +++ b/internal/ui/render_test.go @@ -0,0 +1,120 @@ +package ui + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "github.com/aliasproject/notch/internal/db" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +var ansiRE = regexp.MustCompile(`\x1b\[[0-9;?]*[A-Za-z]`) + +func plainText(s string) string { return ansiRE.ReplaceAllString(s, "") } + +// seedSample fills d with the design board's sample week: a running timer +// on Harbor & Pine, two more entries today, and earlier ones this week. Days +// before today are placed at fixed clock times; today's finished entries sit +// just before the running timer. +func seedSample(t *testing.T, d *db.DB, now time.Time) { + t.Helper() + client := func(name string, rate float64) int64 { + c, err := d.CreateClient(name, rate) + if err != nil { + t.Fatal(err) + } + return c.ID + } + project := func(clientID int64, name string) int64 { + p, err := d.CreateProject(clientID, name) + if err != nil { + t.Fatal(err) + } + return p.ID + } + harbor, field, internal := client("Harbor & Pine", 120), client("Fieldnote Studio", 95), client("Internal", 0) + web, booking := project(harbor, "Website rebuild"), project(harbor, "Booking app") + brand, notch := project(field, "Brand refresh"), project(internal, "notch") + + add := func(pid int64, task, notes string, start time.Time, d2 time.Duration, invoiced, paid bool) { + end := start.Add(d2) + e, err := d.AddEntry(pid, task, notes, start, &end) + if err != nil { + t.Fatal(err) + } + if invoiced || paid { + e.Invoiced, e.Paid = invoiced, paid + if err := d.UpdateEntry(e); err != nil { + t.Fatal(err) + } + } + } + day := func(back int, h, m int) time.Time { + y, mo, dd := now.AddDate(0, 0, -back).Date() + return time.Date(y, mo, dd, h, m, 0, 0, time.Local) + } + running := now.Add(-(1*time.Hour + 23*time.Minute + 46*time.Second)) + add(web, "Homepage hero and nav", "", running.Add(-4*time.Hour), 105*time.Minute, false, false) + add(brand, "Logo explorations", "Three directions, one to keep.", running.Add(-2*time.Hour), 90*time.Minute, false, false) + add(booking, "Calendar sync bug", "", day(1, 13, 0), 200*time.Minute, true, false) + add(web, "Homepage hero and nav", "", day(1, 9, 0), 105*time.Minute, true, false) + add(notch, "Bar widget panel", "", day(3, 10, 0), 130*time.Minute, false, false) + add(brand, "Moodboard review call", "", day(4, 15, 0), time.Hour, true, true) + if _, err := d.AddEntry(web, "Pricing page layout", "", running, nil); err != nil { + t.Fatal(err) + } +} + +// sampleApp is the app at w×h on the sample data, Timers tab, All range, +// with the cursor on "Logo explorations". +func sampleApp(t *testing.T, w, h int) AppModel { + t.Helper() + d := newTestDB(t) + seedSample(t, d, time.Now()) + m, err := New(d) + if err != nil { + t.Fatal(err) + } + step := func(msg tea.Msg) { + u, _ := m.Update(msg) + m = u.(AppModel) + } + step(tea.WindowSizeMsg{Width: w, Height: h}) + step(m.timers.Init()()) + step(runeKey('a')) + step(runeKey('j')) + step(runeKey('j')) + return m +} + +// TestRenderSample checks the Timers screen fills the terminal exactly at +// the board's two sizes, and writes plain-text renders to +// $NOTCH_RENDER_DIR, when set, for comparing with the design boards. +func TestRenderSample(t *testing.T) { + for _, size := range [][2]int{{140, 40}, {90, 32}} { + w, h := size[0], size[1] + m := sampleApp(t, w, h) + out := m.View() + lines := strings.Split(out, "\n") + if len(lines) != h { + t.Errorf("%d×%d: %d lines, want %d", w, h, len(lines), h) + } + for i, l := range lines { + if lw := lipgloss.Width(l); lw != w { + t.Errorf("%d×%d: line %d is %d wide: %q", w, h, i, lw, plainText(l)) + } + } + if dir := os.Getenv("NOTCH_RENDER_DIR"); dir != "" { + name := filepath.Join(dir, fmt.Sprintf("ali-2615-%dx%d.txt", w, h)) + if err := os.WriteFile(name, []byte(plainText(out)+"\n"), 0o644); err != nil { + t.Fatal(err) + } + } + } +} diff --git a/internal/ui/views/common.go b/internal/ui/views/common.go index 0b3fb2c..90acc71 100644 --- a/internal/ui/views/common.go +++ b/internal/ui/views/common.go @@ -626,10 +626,10 @@ func maxInt(a, b int) int { // usableWidth returns the width available for view content inside the // centered content column, accounting for the column's horizontal padding. func usableWidth(w int) int { - if w <= 6 { + if w <= 2*theme.Margin { return w } - return w - 6 + return w - 2*theme.Margin } // hRule draws a horizontal line using the border color. diff --git a/internal/ui/views/common_test.go b/internal/ui/views/common_test.go index 981815f..d9d641c 100644 --- a/internal/ui/views/common_test.go +++ b/internal/ui/views/common_test.go @@ -154,10 +154,10 @@ func TestUsableWidth(t *testing.T) { want int }{ {0, 0}, - {6, 6}, - {7, 1}, - {20, 14}, - {100, 94}, + {4, 4}, + {5, 1}, + {20, 16}, + {100, 96}, } for _, c := range cases { if got := usableWidth(c.w); got != c.want { diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index 6b519d4..eca3a42 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -7,51 +7,12 @@ import ( "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" - "github.com/aliasproject/notch/internal/theme" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) -// ── Table columns ───────────────────────────────────────────────────────────── -// -// Mirrors the fixed-column + flexible-column layout used by the other three -// views (see ProjectsModel.listColWidths, ReportsModel.mainColWidths): -// short columns get a fixed width, TASK/PROJECT split whatever is left. - -const ( - tColGutter = theme.Gutter - // tColStatus must fit the widest badge renderBadge produces: Padding(0, 1) - // on each side of "INVOICED" (8 chars) = 10. Narrower than that and the - // row overflows past its intended width, which wraps EARNED onto the - // next line instead of truncating. - tColStatus = 12 - tColDuration = 11 - tColEarned = 12 -) - -// listColWidths returns the TASK and PROJECT column widths so the table -// spans the full available content width. PROJECT gets an even split (not a -// smaller share): its cell renders "Client › Project" concatenated, which -// tends to run longer than a single TASK description, so a Task-heavy split -// left PROJECT truncating far more often than TASK did. -func (m TimersModel) listColWidths() (taskCol, projectCol int) { - avail := usableWidth(m.width) - tColGutter - tColStatus - tColDuration - tColEarned - projectCol = avail / 2 - if projectCol < 18 { - projectCol = 18 - } - if projectCol > 44 { - projectCol = 44 - } - taskCol = avail - projectCol - if taskCol < 18 { - taskCol = 18 - } - return taskCol, projectCol -} - // ── Modes ───────────────────────────────────────────────────────────────────── type timersMode int @@ -92,7 +53,10 @@ type timersKeyMap struct { Today key.Binding Yesterday key.Binding Week key.Binding + Month key.Binding All key.Binding + Resume key.Binding + Details key.Binding Filter key.Binding Confirm key.Binding Cancel key.Binding @@ -110,7 +74,10 @@ var timersKeys = timersKeyMap{ Today: key.NewBinding(key.WithKeys("t"), key.WithHelp("t", "today")), Yesterday: key.NewBinding(key.WithKeys("y"), key.WithHelp("y", "yesterday")), Week: key.NewBinding(key.WithKeys("w"), key.WithHelp("w", "this week")), + Month: key.NewBinding(key.WithKeys("m"), key.WithHelp("m", "this month")), All: key.NewBinding(key.WithKeys("a"), key.WithHelp("a", "all time")), + Resume: key.NewBinding(key.WithKeys("r"), key.WithHelp("r", "resume")), + Details: key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "details")), Filter: key.NewBinding(key.WithKeys("f"), key.WithHelp("f", "custom range")), Confirm: key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "confirm")), Cancel: key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "cancel")), @@ -368,6 +335,11 @@ type TimersModel struct { fromInput textinput.Model toInput textinput.Model filterIdx int + + // detailOpen shows the selected entry's detail pane over the list in + // the compact layout (enter opens it, enter or esc closes it). The wide + // layout always shows the pane. + detailOpen bool } type timersPreset int @@ -376,6 +348,7 @@ const ( timersPresetToday timersPreset = iota timersPresetYesterday timersPresetWeek + timersPresetMonth timersPresetAll timersPresetCustom ) @@ -515,7 +488,7 @@ func friendlyDayAt(t, now time.Time) string { case day.Equal(today.AddDate(0, 0, -1)): return "Yesterday" default: - return t.Format("Mon, Jan 2") + return t.Format("Mon Jan 2") } } @@ -540,18 +513,6 @@ func parseLocalDateTime(s string) (t time.Time, ok bool) { return t, err == nil } -// renderDetailPane returns the content below the table: the selected entry's -// detail. Delete confirmation is a floating modal (see viewList) rather than -// a swap of this pane, so it doesn't need a case here. Used by both -// rowsBudget (to size the scroll window) and viewList (to render it), so the -// two stay in sync by construction. -func (m TimersModel) renderDetailPane() string { - if e := m.selectedEntry(); e != nil { - return m.renderDetail(e) - } - return "" -} - // 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 @@ -560,19 +521,8 @@ func (m TimersModel) renderDetailPane() string { // rather than being added on top, so the table's total rendered height // stays constant whether or not the window happens to start mid-day. func (m TimersModel) rowsBudget() int { - detailLines := 1 - if m.selectedEntry() != nil { - detailLines = entryDetailLines - } - // fixed chrome: header + blank + table header + divider + footer divider - // + footer totals row + blank = 7 lines. m.height is the column height - // including its Padding(1, 3), so the usable content area is - // m.height - 2. - budget := m.height - 2 - 7 - detailLines - if budget < 1 { - budget = 1 - } - return budget + // At least two: a sticky day header plus the cursor's row. + return max(2, m.innerHeight()-m.fixedRows()) } // windowEnd returns the end index (exclusive) into lines for the window @@ -659,16 +609,21 @@ func (m TimersModel) Help() []Hotkey { case timersModeFilter: return []Hotkey{{"tab", "switch"}, {"enter", "apply"}, {"esc", "cancel"}} default: + if !m.wide() { + return []Hotkey{ + {"n", "new"}, + {"space", "start/stop"}, + {"e", "edit"}, + {"enter", "details"}, + } + } return []Hotkey{ {"n", "new"}, + {"space", "start/stop"}, {"e", "edit"}, + {"i", "invoiced"}, + {"p", "paid"}, {"d", "delete"}, - {"space", "toggle"}, - {"t", "today"}, - {"y", "yesterday"}, - {"w", "week"}, - {"a", "all"}, - {"f", "range"}, } } } @@ -793,6 +748,29 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { m.cursor = 0 m.recomputeFiltered() + case key.Matches(msg, timersKeys.Month): + now := time.Now().Local() + m.dateFrom = now.Format("2006-01") + "-01" + m.dateTo = now.Format("2006-01-02") + m.preset = timersPresetMonth + m.fromInput.SetValue(m.dateFrom) + m.toInput.SetValue(m.dateTo) + m.cursor = 0 + m.recomputeFiltered() + + case key.Matches(msg, timersKeys.Resume): + if entry := m.selectedEntry(); entry != nil && !entry.IsRunning() { + return m, m.startCmd(entry.ProjectID, entry.Task) + } + + case key.Matches(msg, timersKeys.Details): + // The wide layout always shows the pane, so enter only opens it + // over the compact one. + m.detailOpen = !m.wide() && !m.detailOpen && m.selectedEntry() != nil + + case key.Matches(msg, timersKeys.Cancel): + m.detailOpen = false + case key.Matches(msg, timersKeys.All): m.dateFrom, m.dateTo = "", "" m.preset = timersPresetAll @@ -1395,14 +1373,6 @@ func (m TimersModel) View() string { // ── List view ───────────────────────────────────────────────────────────────── -// renderHeader renders the "Timers · " title line, mirroring -// ReportsModel.renderHeader so the two views read consistently. -func (m TimersModel) renderHeader() string { - return StyleTitle.Render("Timers") + - StyleMuted.Render(" · ") + - StyleMuted.Render(m.rangeLabel()) -} - // rangeLabel describes the currently active filter in friendly terms. For the // four quick-filter presets it names the preset outright ("This Week", "All // time") rather than deriving a label from dateFrom/dateTo — otherwise, once @@ -1425,6 +1395,8 @@ func (m TimersModel) rangeLabelAt(now time.Time) string { return "Yesterday" case timersPresetWeek: return "This Week" + case timersPresetMonth: + return "This Month" case timersPresetAll: return "All time" } @@ -1466,243 +1438,6 @@ func (m TimersModel) renderFilterBar() string { return renderDateFilterBar(m.fromInput, m.toInput, m.filterIdx) } -func (m TimersModel) viewList() string { - header := m.renderHeader() - - if m.mode == timersModeFilter { - return header + "\n\n" + m.renderFilterBar() - } - - if len(m.filtered) == 0 { - return header + "\n\n" + m.viewEmptyState() - } - - // Window the render lines (day headers + entry rows) so long lists scroll - // instead of overflowing the view. - lines := m.buildLines() - budget := m.rowsBudget() - m.clampOffset() - start := m.offset - if start < 0 { - start = 0 - } - - // windowEnd accounts for the sticky day header synthesized below when - // start doesn't already land on one — it takes one of the budgeted - // slots rather than being added on top of it, so the table's rendered - // height stays constant whether or not the window happens to start - // mid-day (see windowEnd's doc comment). - end := windowEnd(lines, start, budget) - visible := lines[start:end] - - taskCol, projectCol := m.listColWidths() - contentW := tColStatus + taskCol + projectCol + tColDuration + tColEarned - - var out []string - // 1-column blank ahead of "Task" reserves the same slot data rows use - // for their "•" notes marker (see below), so the header label and the - // task text beneath it start at the same column either way. - out = append(out, RowPrefix(false)+ - lipgloss.NewStyle().Background(cBg).Render(" ")+ - StyleTableHeader.Width(taskCol-1).Render("Task")+ - StyleTableHeader.Width(projectCol).Render("Project")+ - StyleTableHeader.Width(tColDuration).Align(lipgloss.Right).Render("Duration")+ - StyleTableHeader.Width(tColStatus).Render("Status")+ - StyleTableHeader.Width(tColEarned).Align(lipgloss.Right).Render("Earned")) - - // divider doubles as a scroll indicator (▲ = more above, ▼ = more below). - // It spans the gutter too (unlike the header/data rows, which reserve the - // gutter for the cursor), so its width is the full row width, derived from - // the actual column widths so it stays aligned even when minimums clamp. - divW := tColGutter + contentW - runes := []rune(strings.Repeat("─", divW)) - if start > 0 { - runes[0] = '▲' - } - if end < len(lines) { - runes[divW-1] = '▼' - } - out = append(out, StyleTableDiv.Render(string(runes))) - chromeLines := len(out) // column titles + divider, not table rows - - // Sticky day header: if the window's top row continues a day whose real - // header line scrolled off above, synthesize a copy of it here so you - // can always tell which day you're looking at while scrolling — it - // switches to the next day's header once that day's own entries reach - // the top of the window, same as buildLines' real ones do. rowsBudget - // always reserves a row for this, so it never has to compete with the - // last entry row for space. - if len(visible) > 0 && visible[0].kind != timersLineHeader { - e := m.filtered[visible[0].entryIdx] - sticky := timersLine{kind: timersLineHeader, day: e.StartTime.Local()} - out = append(out, m.renderDayHeaderLine(sticky, contentW)) - } - - for _, l := range visible { - if l.kind == timersLineHeader { - out = append(out, m.renderDayHeaderLine(l, contentW)) - continue - } - - e := m.filtered[l.entryIdx] - sel := l.entryIdx == m.cursor - - var base lipgloss.Style - switch { - case sel: - base = StyleTableRowSel - case e.IsRunning(): - base = StyleTableRowRun - default: - base = StyleTableRow - } - - // A "•" marks entries with notes — the only other place notes show - // is the detail pane below (for whichever row is selected) or the - // edit form, so without this a row's notes are easy to miss unless - // you happen to select that exact row. It's rendered as its own - // fixed-style cell (mirrors statusCell below) rather than folded - // into `task` under `base`: `base` goes Bold when a row is - // selected, and a bold vs regular glyph can render at a subtly - // different width in some terminal fonts — enough that the task - // text visibly shifted by a fraction of a column depending on - // whether its row was selected. A fixed, never-bold style keeps the - // marker's width identical either way. - noteMarker := " " - if e.Notes != "" { - noteMarker = "•" - } - // rowBg mirrors `base`'s own background (cBgAlt when selected, cBg - // otherwise) so the fixed-style cells below — which need a color of - // their own independent of `base` — still complete the selected - // row's tint instead of leaving a plain-cBg gap in it. - rowBg := cBg - if sel { - rowBg = cBgAlt - } - // noteCell is exactly 1 column — `base` already adds its own - // 1-column left pad via Padding(0,1), which supplies the gap - // before the task text, so no extra space is added here. - noteCell := lipgloss.NewStyle().Foreground(cAccent).Background(rowBg).Render(noteMarker) - task := truncate(e.Task, taskCol-4) - proj := "" - if e.Project != nil { - proj = truncate(e.Project.Client.Name+" › "+e.Project.Name, projectCol-3) - } - dur := model.FormatDuration(e.Duration()) - - var earned string - if e.Project == nil || e.Project.Client == nil || e.Project.Client.HourlyRate == 0 { - earned = "—" - } else { - earned = fmt.Sprintf("$%.2f", e.Earnings(e.Project.Client.HourlyRate)) - } - - // The status cell always renders its own fixed foreground (not - // `base`'s) so the PAID/INVOICED badge — and the muted "pending" - // text for everything else — keeps its own color regardless of row - // selection; only its background follows rowBg, to complete the - // selected row's tint. - statusCell := lipgloss.NewStyle().Background(rowBg).Width(tColStatus).Render(statusLabel(e, rowBg)) - - out = append(out, RowPrefix(sel)+ - noteCell+ - base.Width(taskCol-1).Render(task)+ - base.Width(projectCol).Render(proj)+ - base.Width(tColDuration).Align(lipgloss.Right).Render(dur)+ - statusCell+ - base.Width(tColEarned).Align(lipgloss.Right).Render(earned)) - } - - // Scrolled to the very bottom with the last day's header at the top of - // the window, no sticky header is synthesized but windowEnd still runs - // out of lines, leaving the window one row short of the budget. Pad it - // with blank rows so the table keeps the same height while scrolling. - // (A list that fits without scrolling just renders at its natural height.) - if len(lines) > budget { - blank := RowPrefix(false) + lipgloss.NewStyle().Background(cBg).Render(strings.Repeat(" ", contentW)) - for rows := len(out) - chromeLines; rows < budget; rows++ { - out = append(out, blank) - } - } - - out = append(out, m.renderFooterTotals(contentW)...) - - tableStr := strings.Join(out, "\n") - detail := m.renderDetailPane() - - body := header + "\n\n" + tableStr + "\n\n" + detail - - if m.mode == timersModeConfirmDelete { - if e := m.selectedEntry(); e != nil { - body = centerOverlay(body, renderConfirmModal(fmt.Sprintf(`Delete "%s"?`, truncate(e.Task, 44)))) - } - } - - return body -} - -// renderDayHeaderLine renders a day-group separator: just the friendly day -// label, aligned to the same gutter+content width as the entry rows below -// it. See the "Day grouping" comment above buildLines for why this doesn't -// carry a per-day total any more. -func (m TimersModel) renderDayHeaderLine(l timersLine, contentW int) string { - label := StylePrimary.Render(friendlyDay(l.day)) - gap := contentW - lipgloss.Width(label) - if gap < 0 { - gap = 0 - } - blank := lipgloss.NewStyle().Background(cBg).Render(strings.Repeat(" ", gap)) - return RowPrefix(false) + label + blank -} - -// renderFooterTotals renders the table's closing divider and a single grand -// total row combining every currently filtered entry, regardless of how many -// distinct days it spans — e.g. selecting "This Week" shows one combined -// total here rather than a separate one under each day. -func (m TimersModel) renderFooterTotals(contentW int) []string { - dur, earned := m.filteredTotals() - totals := StyleMuted.Render("Total ") + - StyleSuccess.Render(model.FormatDuration(dur)) + - StyleMuted.Render(" · ") + - StyleSuccess.Render(fmt.Sprintf("$%.2f", earned)) - - gap := contentW - lipgloss.Width(totals) - if gap < 0 { - gap = 0 - } - blank := lipgloss.NewStyle().Background(cBg).Render(strings.Repeat(" ", gap)) - - divW := tColGutter + contentW - divider := StyleTableDiv.Render(strings.Repeat("─", divW)) - - return []string{divider, RowPrefix(false) + blank + totals} -} - -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.") -} - -func (m TimersModel) renderDetail(e *model.Entry) string { - // date line - started := e.StartTime.Local().Format("Jan 2, 2006 3:04 PM") - dateLine := StyleMuted.Render("Started ") + StyleTableRow.Render(started) - if e.EndTime != nil { - dateLine += StyleMuted.Render(" – ") + StyleTableRow.Render(e.EndTime.Local().Format("3:04 PM")) - } - - notesLine := StyleMuted.Render(noteDetailLabel) + formatNoteDetail(e.Notes, usableWidth(m.width)) - statusLine := StyleMuted.Render("Status ") + invoiceLabel(e) - - return strings.Join([]string{dateLine, notesLine, statusLine}, "\n") -} - // ── Form view ───────────────────────────────────────────────────────────────── func (m TimersModel) viewForm() string { @@ -1847,28 +1582,9 @@ func renderDropdown(items []dropdownItem, sel int) string { // ── Helpers ─────────────────────────────────────────────────────────────────── -// statusLabel renders the entry's billing status. PAID/INVOICED get a -// colored badge; pending (the unflagged default — same term as invoiceLabel's -// default case, in the detail pane below the table) gets plain muted text -// rather than a badge, so the two flagged states still stand out and pending -// rows don't read as if every entry needs attention. -// statusLabel renders the entry's status cell. The PAID/INVOICED cases are -// badges with their own fixed fill color, unaffected by row selection by -// design (same as elsewhere); the plain "pending" text has no fill of its -// own, so it takes bg explicitly to match the row's own background (cBgAlt -// when selected, cBg otherwise — see statusCell's rowBg) instead of always -// baking in cBg and leaving a mismatched patch behind the word when selected. -func statusLabel(e *model.Entry, bg lipgloss.Color) string { - switch { - case e.Paid: - return renderBadge("PAID", cGreen) - case e.Invoiced: - return renderBadge("INVOICED", cAccent) - default: - return lipgloss.NewStyle().Foreground(cDim).Background(bg).Render("pending") - } -} - +// invoiceLabel renders an entry's billing status for the Reports tab's +// entry detail: PAID or INVOICED as a badge, otherwise "pending" and the +// keys that change it. func invoiceLabel(e *model.Entry) string { switch { case e.Paid: @@ -1880,11 +1596,4 @@ func invoiceLabel(e *model.Entry) string { } } -func billingStr(e *model.Entry) string { - if e.Project == nil || e.Project.Client == nil || e.Project.Client.HourlyRate == 0 { - return StyleMuted.Render("—") - } - return fmt.Sprintf("$%.2f", e.Earnings(e.Project.Client.HourlyRate)) -} - var _ = time.Second diff --git a/internal/ui/views/timers_test.go b/internal/ui/views/timers_test.go index 327e362..a9e43f8 100644 --- a/internal/ui/views/timers_test.go +++ b/internal/ui/views/timers_test.go @@ -624,28 +624,6 @@ func TestInit(t *testing.T) { } } -func TestListColWidths(t *testing.T) { - // Wide: projectCol clamps to its max of 44. - wide := TimersModel{width: 300} - taskCol, projectCol := wide.listColWidths() - if projectCol != 44 { - t.Errorf("projectCol with very wide view = %d, want clamped to 44", projectCol) - } - if taskCol < 18 { - t.Errorf("taskCol = %d, want >= 18", taskCol) - } - - // Narrow: both columns clamp to their minimum of 18. - narrow := TimersModel{width: 20} - taskCol2, projectCol2 := narrow.listColWidths() - if projectCol2 != 18 { - t.Errorf("projectCol with narrow view = %d, want clamped to 18", projectCol2) - } - if taskCol2 != 18 { - t.Errorf("taskCol with narrow view = %d, want clamped to 18", taskCol2) - } -} - func TestSelectedEntry_OutOfBounds(t *testing.T) { neg := TimersModel{cursor: -1} if e := neg.selectedEntry(); e != nil { @@ -677,8 +655,8 @@ func TestFriendlyDay(t *testing.T) { t.Errorf("friendlyDay(yesterday) = %q, want %q", got, "Yesterday") } older := today.AddDate(0, 0, -10) - if got := friendlyDayAt(older, now); got != older.Format("Mon, Jan 2") { - t.Errorf("friendlyDay(10 days ago) = %q, want %q", got, older.Format("Mon, Jan 2")) + if got := friendlyDayAt(older, now); got != older.Format("Mon Jan 2") { + t.Errorf("friendlyDay(10 days ago) = %q, want %q", got, older.Format("Mon Jan 2")) } } @@ -1936,45 +1914,6 @@ func TestViewList_Populated(t *testing.T) { } } -// TestViewList_NoteMarker checks the "• " prefix that flags a row as having -// notes — the only other places notes show are the detail pane (for -// whichever single row is currently selected) and the edit form, so without -// a marker in the table itself, a row's notes are easy to miss unless you -// happen to select that exact row. -func TestViewList_NoteMarker(t *testing.T) { - c := mkClient(1, "Acme", 0) - p := mkProject(1, "Web", c) - base := time.Date(2024, 5, 1, 9, 0, 0, 0, time.Local) - - withNotes := mkEntry(1, p, "has notes task", base.Add(time.Hour), 30) - withNotes.Notes = "important context" - withoutNotes := mkEntry(2, p, "plain task", base, 30) - - m := TimersModel{width: 120, height: 30, entries: []*model.Entry{withNotes, withoutNotes}} - m.recomputeFiltered() - got := m.viewList() - - lines := strings.Split(got, "\n") - var notedLine, plainLine string - for _, l := range lines { - if strings.Contains(l, "has notes task") { - notedLine = l - } - if strings.Contains(l, "plain task") { - plainLine = l - } - } - if notedLine == "" || plainLine == "" { - t.Fatalf("could not find both task rows in output:\n%s", got) - } - if !strings.Contains(notedLine, "• has notes task") { - t.Errorf("row for entry with notes should show the '• ' marker directly before its task text, got %q", notedLine) - } - if strings.Contains(plainLine, "•") { - t.Errorf("row for entry without notes should not show the marker, got %q", plainLine) - } -} - func TestViewList_ScrollIndicators(t *testing.T) { c := mkClient(1, "Acme", 0) p := mkProject(1, "Web", c) @@ -1986,7 +1925,7 @@ func TestViewList_ScrollIndicators(t *testing.T) { // Small height forces scrolling. Cursor at the top -> offset 0, "more // below" (▼) but not "more above". - top := TimersModel{width: 120, height: 12, entries: entries, cursor: 0} + top := TimersModel{width: 120, height: 18, entries: entries, cursor: 0} top.recomputeFiltered() gotTop := top.viewList() if !strings.Contains(gotTop, "▼") { @@ -1994,7 +1933,7 @@ func TestViewList_ScrollIndicators(t *testing.T) { } // Cursor at the bottom -> offset > 0, "more above" (▲). - bottom := TimersModel{width: 120, height: 12, entries: entries, cursor: len(entries) - 1} + bottom := TimersModel{width: 120, height: 18, entries: entries, cursor: len(entries) - 1} bottom.recomputeFiltered() bottom.cursor = len(bottom.filtered) - 1 gotBottom := bottom.viewList() @@ -2018,82 +1957,18 @@ func TestViewList_ConfirmDeleteModal(t *testing.T) { if !strings.Contains(got, "This cannot be undone") { t.Errorf("viewList() confirm-delete modal should show the warning, got:\n%s", got) } - // The table itself must still be visible around/behind the modal — the - // whole point of an overlay vs. the old full-pane swap. The modal is - // centered over the table and covers the middle columns of this narrow - // test width, so check header cells past its right edge instead of ones - // it happens to sit on top of. - if !strings.Contains(got, "Status") || !strings.Contains(got, "Earned") { + // The list itself must still be visible around/behind the modal — the + // whole point of an overlay vs. a full-pane swap. The modal is centered + // over the list, so check rows above and below it. + if !strings.Contains(got, "Range") || !strings.Contains(got, "1 entry") { t.Errorf("viewList() in confirm-delete mode should still show the table underneath the modal, got:\n%s", got) } } // ── renderDetailPane ────────────────────────────────────────────────────────── -func TestRenderDetailPane_Branches(t *testing.T) { - c := mkClient(1, "Acme", 0) - p := mkProject(1, "Web", c) - e := mkEntry(1, p, "t", time.Now(), 30) - - // Confirm-delete no longer swaps this pane for a warning — that's now a - // floating modal (see viewList/renderConfirmModal) — so it renders the - // same selected-entry detail as any other mode. - deleting := TimersModel{mode: timersModeConfirmDelete, filtered: []*model.Entry{e}, cursor: 0} - if got := deleting.renderDetailPane(); got == "" { - t.Error("renderDetailPane in confirm-delete mode with a selected entry should still render its detail") - } - - selected := TimersModel{filtered: []*model.Entry{e}, cursor: 0} - if got := selected.renderDetailPane(); got == "" { - t.Error("renderDetailPane with a selected entry should render its detail, got empty string") - } - - none := TimersModel{} - if got := none.renderDetailPane(); got != "" { - t.Errorf("renderDetailPane with nothing selected = %q, want empty string", got) - } -} - // ── renderDetail ────────────────────────────────────────────────────────────── -func TestRenderDetail_Variants(t *testing.T) { - c := mkClient(1, "Acme", 50) - p := mkProject(1, "Web", c) - m := TimersModel{width: 100} - - t.Run("running, no notes", func(t *testing.T) { - e := mkRunningEntry(1, p, "task", time.Now()) - out := m.renderDetail(e) - lines := strings.Split(out, "\n") - if len(lines) != entryDetailLines { - t.Errorf("renderDetail for a running entry with no notes should still render %d fixed lines (with a placeholder Notes line), got %d: %q", entryDetailLines, len(lines), out) - } - if !strings.Contains(out, "Notes") { - t.Errorf("renderDetail should always include a Notes line (placeholder when empty), got %q", out) - } - }) - t.Run("finished with notes", func(t *testing.T) { - e := mkEntry(2, p, "task", time.Now().Add(-time.Hour), 30) - e.Notes = "hello world" - out := m.renderDetail(e) - if !strings.Contains(out, "hello world") { - t.Errorf("renderDetail should include notes, got %q", out) - } - if !strings.Contains(out, "–") { - t.Errorf("renderDetail for a finished entry should show an end-time separator, got %q", out) - } - }) - t.Run("long notes truncate instead of wrapping", func(t *testing.T) { - e := mkEntry(3, p, "task", time.Now().Add(-time.Hour), 30) - e.Notes = strings.Repeat("a very long note that would wrap ", 10) - out := m.renderDetail(e) - lines := strings.Split(out, "\n") - if len(lines) != entryDetailLines { - t.Errorf("renderDetail with a long note should still render %d fixed lines, got %d: %q", entryDetailLines, len(lines), out) - } - }) -} - // ── rowsBudget / clampOffset ────────────────────────────────────────────────── func TestRowsBudget(t *testing.T) { @@ -2113,8 +1988,8 @@ func TestRowsBudget(t *testing.T) { } tiny := TimersModel{height: 0} - if got := tiny.rowsBudget(); got != 1 { - t.Errorf("rowsBudget() with a tiny height = %d, want clamped to 1", got) + if got := tiny.rowsBudget(); got != 2 { + t.Errorf("rowsBudget() with a tiny height = %d, want clamped to 2 (a sticky day header and the cursor's row)", got) } } @@ -2146,7 +2021,7 @@ func TestClampOffset(t *testing.T) { for i := 0; i < 20; i++ { many = append(many, mkEntry(int64(i+1), p, "t", base.Add(time.Duration(i)*time.Hour), 10)) } - scroll := TimersModel{height: 15, filtered: many, cursor: len(many) - 1} + scroll := TimersModel{height: 19, filtered: many, cursor: len(many) - 1} scroll.clampOffset() if scroll.offset <= 0 { t.Errorf("clampOffset with cursor at the bottom: offset = %d, want > 0", scroll.offset) @@ -2181,7 +2056,7 @@ func TestClampOffset(t *testing.T) { // scrolled off, so it should stay visible for every cursor position within // a group, switching only once the cursor crosses into the next group. // -// Entries are on fixed past dates so friendlyDay returns "Mon, Jan +// Entries are on fixed past dates so friendlyDay returns "Mon Jan // 2"-style labels instead of "Today"/"Yesterday" — the latter would also // match the unrelated "Timers · Today" range-label in the title (m.preset // defaults to timersPresetToday), making a text search ambiguous. dayA is @@ -2205,7 +2080,7 @@ func TestViewList_DayHeaderStaysStickyWhileScrolling(t *testing.T) { entries = append(entries, mkEntry(int64(i+100), p, fmt.Sprintf("b-%d", i), dayB.Add(-time.Duration(i)*time.Hour), 10)) } - m := TimersModel{width: 100, height: 15, entries: entries} + m := TimersModel{width: 100, height: 19, entries: entries} m.recomputeFiltered() // Walk the cursor down through every entry of group A one row at a @@ -2252,7 +2127,7 @@ func TestViewList_HeightStaysConstantAcrossStickyHeaderBoundary(t *testing.T) { entries = append(entries, mkEntry(int64(i+1), p, fmt.Sprintf("t-%d", i), base.Add(-time.Duration(i)*time.Hour), 10)) } - m := TimersModel{width: 100, height: 15, entries: entries} + m := TimersModel{width: 100, height: 19, entries: entries} m.recomputeFiltered() var heights []int @@ -2438,38 +2313,6 @@ func TestRenderDropdown_ManyItemsWindowed(t *testing.T) { // ── statusLabel / invoiceLabel / billingStr ────────────────────────────────── -func TestStatusLabel(t *testing.T) { - c := mkClient(1, "Acme", 50) - p := mkProject(1, "Web", c) - - // Running is unflagged (like any other pending entry) — no badge, just - // muted "pending" text; the row's own green highlight already conveys - // that it's running. - running := mkRunningEntry(1, p, "t", time.Now()) - if got := statusLabel(running, cBg); !strings.Contains(got, "pending") { - t.Errorf("statusLabel(running, cBg) = %q, want it to mention 'pending'", got) - } - - paid := mkEntry(2, p, "t", time.Now().Add(-time.Hour), 30) - paid.Invoiced, paid.Paid = true, true - if got := statusLabel(paid, cBg); !strings.Contains(got, "PAID") { - t.Errorf("statusLabel(paid, cBg) = %q, want it to mention 'PAID'", got) - } - - invoiced := mkEntry(3, p, "t", time.Now().Add(-time.Hour), 30) - invoiced.Invoiced = true - if got := statusLabel(invoiced, cBg); !strings.Contains(got, "INVOICED") { - t.Errorf("statusLabel(invoiced, cBg) = %q, want it to mention 'INVOICED'", got) - } - - // Pending is the unflagged default — plain muted text, no badge, same - // term invoiceLabel's default case uses in the detail pane. - pending := mkEntry(4, p, "t", time.Now().Add(-time.Hour), 30) - if got := statusLabel(pending, cBg); !strings.Contains(got, "pending") { - t.Errorf("statusLabel(pending, cBg) = %q, want it to mention 'pending'", got) - } -} - func TestInvoiceLabel(t *testing.T) { c := mkClient(1, "Acme", 50) p := mkProject(1, "Web", c) @@ -2492,29 +2335,6 @@ func TestInvoiceLabel(t *testing.T) { } } -func TestBillingStr(t *testing.T) { - c := mkClient(1, "Acme", 50) - p := mkProject(1, "Web", c) - free := mkClient(2, "Freebie", 0) - pFree := mkProject(2, "OSS", free) - - billable := mkEntry(1, p, "t", time.Now().Add(-time.Hour), 60) - if got := billingStr(billable); got != "$50.00" { - t.Errorf("billingStr(1hr @ $50/hr) = %q, want %q", got, "$50.00") - } - - zeroRate := mkEntry(2, pFree, "t", time.Now().Add(-time.Hour), 30) - if got := billingStr(zeroRate); got != "—" { - t.Errorf("billingStr(zero rate) = %q, want %q", got, "—") - } - - noProject := mkEntry(3, p, "t", time.Now().Add(-time.Hour), 30) - noProject.Project = nil - if got := billingStr(noProject); got != "—" { - t.Errorf("billingStr(no project) = %q, want %q", got, "—") - } -} - // ── clampOffset: stale offset from a shrunk list ───────────────────────────── func TestClampOffset_StaleOffsetClampedToNewRange(t *testing.T) { @@ -2526,7 +2346,7 @@ func TestClampOffset_StaleOffsetClampedToNewRange(t *testing.T) { many = append(many, mkEntry(int64(i+1), p, "t", base.Add(time.Duration(i)*time.Hour), 10)) } - m := TimersModel{height: 15, filtered: many, cursor: len(many) - 1} + m := TimersModel{height: 19, filtered: many, cursor: len(many) - 1} m.clampOffset() if m.offset == 0 { t.Fatal("expected a nonzero offset after scrolling to the bottom of a long list") @@ -2578,7 +2398,7 @@ func TestClampOffset_NegativeOffsetDefensivelyClamped(t *testing.T) { many = append(many, mkEntry(int64(i+1), p, "t", base.Add(time.Duration(i)*time.Hour), 10)) } - m := TimersModel{height: 15, filtered: many, cursor: -1, offset: -50} + m := TimersModel{height: 19, filtered: many, cursor: -1, offset: -50} m.clampOffset() if m.offset < 0 { t.Errorf("offset = %d, want clamped to >= 0", m.offset) diff --git a/internal/ui/views/timers_view.go b/internal/ui/views/timers_view.go new file mode 100644 index 0000000..4a388d7 --- /dev/null +++ b/internal/ui/views/timers_view.go @@ -0,0 +1,850 @@ +package views + +// The Timers tab's list screen (ALI-2615), drawn from the design canvas's +// "Redesign · TUI · Timers" (140×40) and "90 columns" boards: +// +// - a hero for the running timer: block-digit elapsed time, and today's, +// this week's and unbilled totals beside it; +// - range chips (t w m a f); +// - the entries grouped by day, each day with its subtotal, and a total; +// - at theme.WideMin columns and up, the selected entry's detail pane; +// below that, a compact hero, no CLIENT › PROJECT column, and a one-line +// summary of the selected entry (enter opens the detail pane over it). +// +// Status reads as a glyph and a word (○ unbilled, ◐ invoiced, ● paid, +// ▶ running), so colour is never the only signal. + +import ( + "fmt" + "strings" + "time" + + "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/status" + "github.com/aliasproject/notch/internal/theme" + "github.com/charmbracelet/lipgloss" +) + +// ── Styled segments ─────────────────────────────────────────────────────────── +// +// Every visible character, spaces included, carries an explicit background: +// lipgloss drops leading unstyled whitespace when the body column re-renders +// a line, and an unstyled gap would show the terminal's own background. + +type seg struct { + s string + fg lipgloss.Color // "" means cText + bg lipgloss.Color // "" means the line's background + bold bool +} + +func segsWidth(segs []seg) int { + w := 0 + for _, s := range segs { + w += lipgloss.Width(s.s) + } + return w +} + +func renderSegs(bg lipgloss.Color, segs ...seg) string { + var b strings.Builder + for _, s := range segs { + if s.s == "" { + continue + } + st := lipgloss.NewStyle().Background(bg).Foreground(cText) + if s.bg != "" { + st = st.Background(s.bg) + } + if s.fg != "" { + st = st.Foreground(s.fg) + } + if s.bold { + st = st.Bold(true) + } + b.WriteString(st.Render(s.s)) + } + return b.String() +} + +// spread lays left out from the start of a w-wide line and right against its +// end, filling the gap with bg. The caller keeps the two from overlapping. +func spread(w int, bg lipgloss.Color, left, right []seg) string { + gap := w - segsWidth(left) - segsWidth(right) + if gap < 0 { + gap = 0 + } + return renderSegs(bg, left...) + renderSegs(bg, seg{s: strings.Repeat(" ", gap)}) + renderSegs(bg, right...) +} + +func blankLine(w int) string { + return renderSegs(cBg, seg{s: strings.Repeat(" ", max(0, w))}) +} + +// fit truncates s to w cells and pads it to exactly w. +func fit(s string, w int) string { + s = truncate(s, w) + return s + strings.Repeat(" ", max(0, w-lipgloss.Width(s))) +} + +// fitRight truncates s to w cells and right-aligns it in w. +func fitRight(s string, w int) string { + s = truncate(s, w) + return strings.Repeat(" ", max(0, w-lipgloss.Width(s))) + s +} + +// ── Money and time ──────────────────────────────────────────────────────────── + +// formatMoney renders an amount as "$1,057.50". +func formatMoney(x float64) string { + s := fmt.Sprintf("%.2f", status.Cents(x)) + neg := strings.HasPrefix(s, "-") + s = strings.TrimPrefix(s, "-") + whole, frac, _ := strings.Cut(s, ".") + var b strings.Builder + for i, r := range whole { + if i > 0 && (len(whole)-i)%3 == 0 { + b.WriteByte(',') + } + b.WriteRune(r) + } + out := "$" + b.String() + "." + frac + if neg { + out = "-" + out + } + return out +} + +// formatRate renders an hourly rate as "$120/h", dropping zero cents. +func formatRate(r float64) string { + m := formatMoney(r) + return strings.TrimSuffix(m, ".00") + "/h" +} + +func clockTime(t time.Time) string { return t.Local().Format("3:04 PM") } + +// entryTimes is an entry's start and end, "11:00 AM – 12:30 PM", or +// "2:12 PM – now" while it runs. sep goes between them. +func entryTimes(e *model.Entry, sep string) string { + end := "now" + if e.EndTime != nil { + end = clockTime(*e.EndTime) + } + return clockTime(e.StartTime) + sep + end +} + +// earned is e's earnings at its client's usable rate, and whether it has a +// rate at all. +func earned(e *model.Entry) (float64, bool) { + rate := status.HourlyRate(e) + if rate == 0 { + return 0, false + } + return e.Earnings(rate), true +} + +func earnedText(e *model.Entry) string { + if x, ok := earned(e); ok { + return formatMoney(x) + } + return "—" +} + +func placeText(e *model.Entry) string { + if e.Project == nil { + return "" + } + if e.Project.Client == nil { + return e.Project.Name + } + return e.Project.Client.Name + " › " + e.Project.Name +} + +// entryStatus is e's status glyph and word, and the colour it's drawn in. +func entryStatus(e *model.Entry) (string, lipgloss.Color) { + switch { + case e.IsRunning(): + return theme.GlyphRunning + " running", cGreen + case e.Paid: + return theme.GlyphPaid + " paid", cGreen + case e.Invoiced: + return theme.GlyphInvoiced + " invoiced", cAccent + default: + return theme.GlyphUnbilled + " unbilled", cSubtle + } +} + +// ── Block digits ────────────────────────────────────────────────────────────── + +// blockGlyphs draws digits three cells wide and three rows tall in half +// blocks, as on the board. +var blockGlyphs = map[rune][3]string{ + '0': {"█▀█", "█ █", "█▄█"}, + '1': {"▀█ ", " █ ", "▄█▄"}, + '2': {"▀▀█", "█▀▀", "█▄▄"}, + '3': {"▀▀█", " ▀█", "▄▄█"}, + '4': {"█ █", "▀▀█", " █"}, + '5': {"█▀▀", "▀▀█", "▄▄█"}, + '6': {"█▀▀", "█▀█", "█▄█"}, + '7': {"▀▀█", " █", " █"}, + '8': {"█▀█", "█▀█", "█▄█"}, + '9': {"█▀█", "▀▀█", "▄▄█"}, + ':': {" ", "▀", "▀"}, +} + +// blockText renders s ("1:23:46") as three rows of block digits, one +// column apart. +func blockText(s string) [3]string { + var rows [3][]string + for _, r := range s { + g, ok := blockGlyphs[r] + if !ok { + continue + } + for i := range rows { + rows[i] = append(rows[i], g[i]) + } + } + var out [3]string + for i := range rows { + out[i] = strings.Join(rows[i], " ") + } + return out +} + +// ── Totals ──────────────────────────────────────────────────────────────────── + +// heroTotals is the hero's today, this week and unbilled. Today and the +// week include the running timer's time so far, clipped to midnight and to +// Monday, so they tick with it; unbilled counts finished entries only, like +// `notch summary`. +type heroTotals struct { + today, week time.Duration + unbilled float64 +} + +func (m TimersModel) heroTotalsAt(now time.Time) heroTotals { + s := status.Summarize(m.entries, m.entries, now) + t := heroTotals{ + today: time.Duration(s.TodaySeconds) * time.Second, + week: time.Duration(s.WeekSeconds) * time.Second, + unbilled: s.Unbilled, + } + if r := m.runningEntry(); r != nil { + t.today += clipSince(r.StartTime, status.StartOfDay(now), now) + t.week += clipSince(r.StartTime, status.StartOfWeek(now), now) + } + return t +} + +// clipSince is the part of [start, now] after from. +func clipSince(start, from, now time.Time) time.Duration { + if start.Before(from) { + start = from + } + if !now.After(start) { + return 0 + } + return now.Sub(start).Truncate(time.Second) +} + +func (m TimersModel) runningEntry() *model.Entry { + for _, e := range m.entries { + if e.IsRunning() { + return e + } + } + return nil +} + +// dayTotals sums the filtered entries of one local day: their time, and +// their earnings rounded once, with ok false if none of them has a rate. +func (m TimersModel) dayTotals(day string) (time.Duration, float64, bool) { + return sumEntries(m.filtered, func(e *model.Entry) bool { + return e.StartTime.Local().Format("2006-01-02") == day + }) +} + +func sumEntries(es []*model.Entry, keep func(*model.Entry) bool) (time.Duration, float64, bool) { + var d time.Duration + var x float64 + any := false + for _, e := range es { + if !keep(e) { + continue + } + d += e.Duration() + if v, ok := earned(e); ok { + x += v + any = true + } + } + return d, status.Cents(x), any +} + +func totalsText(d time.Duration, x float64, ok bool) string { + money := "—" + if ok { + money = formatMoney(x) + } + return model.FormatDuration(d) + " · " + money +} + +// ── Layout ──────────────────────────────────────────────────────────────────── + +// wide reports whether the view gets the wide layout (theme.WideMin columns +// and up, as wide as the terminal's content column). +func (m TimersModel) wide() bool { return m.width >= theme.WideMin } + +// innerWidth is the content column's width inside its margins. +func (m TimersModel) innerWidth() int { return usableWidth(m.width) } + +// innerHeight is the content column's height inside its top and bottom +// padding. +func (m TimersModel) innerHeight() int { return max(1, m.height-2) } + +// tableWidth is the list's width: all of it in the compact layout, and what +// the detail pane and its two-column gap leave in the wide one. +func (m TimersModel) tableWidth() int { + if m.wide() { + return m.innerWidth() - 2 - theme.DetailWidth + } + return m.innerWidth() +} + +// Fixed list columns: the cursor gutter and the space after it, then +// DURATION, a gap, STATUS (wide layout), EARNED and a trailing space. +const ( + tLead = theme.Gutter + 1 + tDuration = 10 + tGap = 2 + tStatus = 12 + tEarned = 10 + tTrail = 1 +) + +// tableCols returns the flexible column widths: TASK, CLIENT › PROJECT +// (0 in the compact layout) and STATUS. +func (m TimersModel) tableCols() (task, place, stat int) { + tw := m.tableWidth() + if m.wide() { + flex := max(2, tw-tLead-tDuration-tGap-tStatus-tEarned-tTrail) + place = flex/2 - 1 + return flex - place, place, tStatus + } + flex := max(2, tw-tLead-tDuration-tGap-tEarned-tTrail) + stat = max(tStatus, flex*5/12) + return max(1, flex-stat), 0, stat +} + +// Fixed rows around the list: the hero (6 rows wide, 4 compact), a blank, +// the range chips and a blank; then the column titles and a rule above the +// rows, and a rule and the totals below. The compact layout also keeps a +// blank and two summary rows at the bottom. +func (m TimersModel) heroRows() int { + if m.wide() { + return 6 + } + return 4 +} + +func (m TimersModel) fixedRows() int { + rows := m.heroRows() + 3 + 2 + 2 + if !m.wide() { + rows += 3 + } + return rows +} + +// ── Hero ────────────────────────────────────────────────────────────────────── + +func boxTop(w int) string { + return renderSegs(cBg, seg{s: "╭" + strings.Repeat("─", max(0, w-2)) + "╮", fg: cBorder}) +} + +func boxBottom(w int) string { + return renderSegs(cBg, seg{s: "╰" + strings.Repeat("─", max(0, w-2)) + "╯", fg: cBorder}) +} + +func boxSide() seg { return seg{s: "│", fg: cBorder} } + +func (m TimersModel) heroWide(w int, now time.Time) []string { + t := m.heroTotalsAt(now) + stats := [3][2]string{ + {"Today", model.FormatDuration(t.today)}, + {"This week", model.FormatDuration(t.week)}, + {"Unbilled", formatMoney(t.unbilled)}, + } + labelW, valueW := 0, 0 + for _, s := range stats { + labelW = max(labelW, lipgloss.Width(s[0])) + valueW = max(valueW, lipgloss.Width(s[1])) + } + // At least a "$1,000.00" wide, so the column doesn't shift as totals + // grow past a thousand. + valueW = max(valueW, lipgloss.Width(formatMoney(1000))) + statsW := 1 + labelW + 2 + valueW + 2 + leftW := max(10, w-2-1-statsW) + + var left [4][2][]seg // per row: left-aligned and right-aligned parts + if r := m.runningEntry(); r != nil { + digits := blockText(model.FormatDuration(r.Duration())) + meta := "since " + clockTime(r.StartTime) + if rate := status.HourlyRate(r); rate != 0 { + meta += " · " + formatRate(rate) + " · " + formatMoney(r.Earnings(rate)) + " so far" + } + textW := max(1, leftW-2-lipgloss.Width(digits[0])-4) + left[0] = [2][]seg{{{s: "NOW TRACKING", fg: cGreen, bold: true}}, {{s: digits[0], fg: cGreen, bold: true}}} + left[1] = [2][]seg{{{s: truncate(r.Task, textW), bold: true}}, {{s: digits[1], fg: cGreen, bold: true}}} + left[2] = [2][]seg{{{s: truncate(placeText(r), textW), fg: cDim}}, {{s: digits[2], fg: cGreen, bold: true}}} + left[3] = [2][]seg{{{s: truncate(meta, textW), fg: cSubtle}}, {{s: "elapsed", fg: cSubtle}}} + } else { + textW := max(1, leftW-4) + left[0] = [2][]seg{{{s: "NOT TRACKING", fg: cSubtle, bold: true}}, nil} + left[1] = [2][]seg{{{s: "Nothing is running", bold: true}}, nil} + left[2] = [2][]seg{{{s: truncate("n starts a timer · r resumes the selected entry", textW), fg: cDim}}, nil} + } + + out := []string{boxTop(w)} + for i := 0; i < 4; i++ { + row := renderSegs(cBg, boxSide()) + + spread(leftW, cBg, append([]seg{{s: " "}}, left[i][0]...), append(left[i][1], seg{s: " "})) + + renderSegs(cBg, boxSide()) + var statSegs []seg + if i < 3 { + valFg := cText + if i == 2 { + valFg = cAmber + } + statSegs = []seg{ + {s: " " + fit(stats[i][0], labelW), fg: cSubtle}, + {s: " " + fitRight(stats[i][1], valueW), fg: valFg, bold: true}, + {s: " "}, + } + } + row += spread(statsW, cBg, statSegs, nil) + renderSegs(cBg, boxSide()) + out = append(out, row) + } + return append(out, boxBottom(w)) +} + +func (m TimersModel) heroCompact(w int, now time.Time) []string { + t := m.heroTotalsAt(now) + inner := max(10, w-2) + today := "today " + model.FormatDuration(t.today) + var rows [2][2][]seg + if r := m.runningEntry(); r != nil { + elapsed := model.FormatDuration(r.Duration()) + taskW := max(1, inner-2-2-lipgloss.Width(elapsed)-4) + placeW := max(1, inner-4-lipgloss.Width(today)-4) + rows[0] = [2][]seg{ + {{s: " "}, {s: theme.GlyphRunning + " ", fg: cGreen, bold: true}, {s: truncate(r.Task, taskW), bold: true}}, + {{s: elapsed, fg: cGreen, bold: true}, {s: " "}}, + } + rows[1] = [2][]seg{ + {{s: " "}, {s: truncate(placeText(r), placeW), fg: cDim}}, + {{s: today, fg: cSubtle}, {s: " "}}, + } + } else { + rows[0] = [2][]seg{{{s: " "}, {s: "Nothing is running", bold: true}}, {{s: " "}}} + rows[1] = [2][]seg{{{s: " "}, {s: "n starts a timer", fg: cDim}}, {{s: today, fg: cSubtle}, {s: " "}}} + } + out := []string{boxTop(w)} + for _, r := range rows { + out = append(out, renderSegs(cBg, boxSide())+spread(inner, cBg, r[0], r[1])+renderSegs(cBg, boxSide())) + } + return append(out, boxBottom(w)) +} + +// ── Range chips ─────────────────────────────────────────────────────────────── + +type rangeChip struct { + label string + preset timersPreset +} + +func (m TimersModel) rangeChips() []rangeChip { + if m.wide() { + return []rangeChip{ + {"Today", timersPresetToday}, {"Week", timersPresetWeek}, {"Month", timersPresetMonth}, + {"All", timersPresetAll}, {"Custom…", timersPresetCustom}, + } + } + chips := []rangeChip{ + {"Today", timersPresetToday}, {"Week", timersPresetWeek}, {"All", timersPresetAll}, + } + // A preset with no chip of its own here (Month, or y's Yesterday) still + // shows while it's the active one. + switch m.preset { + case timersPresetMonth: + chips = append(chips[:2], rangeChip{"Month", timersPresetMonth}, chips[2]) + case timersPresetYesterday: + chips = append([]rangeChip{chips[0], {"Yesterday", timersPresetYesterday}}, chips[1:]...) + } + return append(chips, rangeChip{"…", timersPresetCustom}) +} + +func (m TimersModel) renderRangeChips(w int, now time.Time) string { + left := []seg{{s: "Range", fg: cSubtle}, {s: " "}} + for _, c := range m.rangeChips() { + chip := seg{s: " " + c.label + " ", fg: cDim} + if c.preset == m.preset { + chip = seg{s: chip.s, fg: cBg, bg: cPrimary, bold: true} + } + left = append(left, seg{s: " "}, chip) + } + var right []seg + if m.preset == timersPresetCustom || m.preset == timersPresetYesterday { + right = []seg{{s: truncate(m.rangeLabelAt(now), max(0, w-segsWidth(left)-2)), fg: cSubtle}} + } + return spread(w, cBg, left, right) +} + +// ── List ────────────────────────────────────────────────────────────────────── + +func (m TimersModel) renderTableHead(tw int) []string { + task, place, stat := m.tableCols() + segs := []seg{{s: strings.Repeat(" ", tLead)}, {s: fit("TASK", task), fg: cSubtle, bold: true}} + if place > 0 { + segs = append(segs, seg{s: fit("CLIENT › PROJECT", place), fg: cSubtle, bold: true}) + } + segs = append(segs, + seg{s: fitRight("DURATION", tDuration), fg: cSubtle, bold: true}, + seg{s: strings.Repeat(" ", tGap)}, + seg{s: fit("STATUS", stat), fg: cSubtle, bold: true}, + seg{s: fitRight("EARNED", tEarned), fg: cSubtle, bold: true}, + ) + return []string{spread(tw, cBg, segs, nil)} +} + +// rule draws a tw-wide rule, with ▲ and ▼ at its ends when more rows are +// above or below the window. +func rule(tw int, above, below bool) string { + runes := []rune(strings.Repeat("─", max(1, tw))) + if above { + runes[0] = '▲' + } + if below { + runes[len(runes)-1] = '▼' + } + return renderSegs(cBg, seg{s: string(runes), fg: cBorder}) +} + +func (m TimersModel) renderDayHeaderLine(l timersLine, tw int) string { + d, x, ok := m.dayTotals(l.day.Format("2006-01-02")) + return spread(tw, cBg, + []seg{{s: " "}, {s: friendlyDay(l.day), fg: cPrimary, bold: true}}, + []seg{{s: totalsText(d, x, ok), fg: cSubtle}, {s: " "}}) +} + +func (m TimersModel) renderEntryRow(e *model.Entry, sel bool, tw int) string { + task, place, stat := m.tableCols() + bg := cBg + lead := seg{s: strings.Repeat(" ", tLead)} + if sel { + bg = cBgAlt + lead = seg{s: theme.GlyphCursor + strings.Repeat(" ", tLead-lipgloss.Width(theme.GlyphCursor)), fg: cPrimary} + } + durSeg := seg{s: fitRight(model.FormatDuration(e.Duration()), tDuration)} + if e.IsRunning() { + durSeg.fg, durSeg.bold = cGreen, true + } + statText, statFg := entryStatus(e) + segs := []seg{lead, {s: fit(truncate(e.Task, max(1, task-2)), task), bold: sel}} + if place > 0 { + segs = append(segs, seg{s: fit(placeText(e), place), fg: cDim}) + } + segs = append(segs, + durSeg, + seg{s: strings.Repeat(" ", tGap)}, + seg{s: fit(statText, stat), fg: statFg}, + seg{s: fitRight(earnedText(e), tEarned), fg: cDim}, + ) + return spread(tw, bg, segs, nil) +} + +func (m TimersModel) renderListFoot(tw int) []string { + n := len(m.filtered) + d, x, ok := sumEntries(m.filtered, func(*model.Entry) bool { return true }) + return []string{ + rule(tw, false, false), + spread(tw, cBg, + []seg{{s: " "}, {s: fmt.Sprintf("%d %s", n, plural(n, "entry", "entries")), fg: cSubtle}}, + []seg{{s: "Total " + totalsText(d, x, ok), bold: true}, {s: " "}}), + } +} + +func plural(n int, one, many string) string { + if n == 1 { + return one + } + return many +} + +// renderList is the list's column titles, its window of day headers and +// entries (with a sticky day header when the window starts mid-day), and +// the totals: always the same height while scrolling. +func (m TimersModel) renderList(tw int) []string { + out := m.renderTableHead(tw) + lines := m.buildLines() + budget := m.rowsBudget() + start := max(0, m.offset) + end := windowEnd(lines, start, budget) + visible := lines[start:end] + out = append(out, rule(tw, start > 0, end < len(lines))) + rows := 0 + if len(visible) > 0 && visible[0].kind != timersLineHeader { + e := m.filtered[visible[0].entryIdx] + out = append(out, m.renderDayHeaderLine(timersLine{kind: timersLineHeader, day: e.StartTime.Local()}, tw)) + rows++ + } + for _, l := range visible { + if l.kind == timersLineHeader { + out = append(out, m.renderDayHeaderLine(l, tw)) + } else { + out = append(out, m.renderEntryRow(m.filtered[l.entryIdx], l.entryIdx == m.cursor, tw)) + } + rows++ + } + if len(lines) > budget { + for ; rows < budget; rows++ { + out = append(out, blankLine(tw)) + } + } + return append(out, m.renderListFoot(tw)...) +} + +// ── Detail pane ─────────────────────────────────────────────────────────────── + +// detailKeys lists the keys the detail pane offers for e. +func detailKeys(e *model.Entry) [][2]string { + if e.IsRunning() { + return [][2]string{{"space", "stop"}, {"e", "edit"}, {"d", "delete"}} + } + inv, paid := "mark invoiced", "mark paid" + if e.Invoiced { + inv = "unmark invoiced" + } + if e.Paid { + paid = "unmark paid" + } + return [][2]string{{"i", inv}, {"p", paid}, {"e", "edit"}, {"r", "resume"}, {"d", "delete"}} +} + +// detailNoteRows caps how many rows the Notes field takes in the pane. +const detailNoteRows = 3 + +func (m TimersModel) renderDetailBox(e *model.Entry, w int) []string { + inner := max(10, w-2) + const labelW = 10 + valueW := max(1, inner-2-labelW) + side := renderSegs(cBg, boxSide()) + row := func(segs ...seg) string { + return side + spread(inner, cBg, append([]seg{{s: " "}}, segs...), []seg{{s: " "}}) + side + } + field := func(label string, value seg) string { + value.s = truncate(value.s, valueW) + if value.fg == "" { + value.fg = cDim + } + return row(seg{s: fit(label, labelW), fg: cSubtle}, value) + } + + title := " Entry " + top := renderSegs(cBg, + seg{s: "╭─", fg: cBorder}, seg{s: title, bold: true}, + seg{s: strings.Repeat("─", max(0, w-3-lipgloss.Width(title))) + "╮", fg: cBorder}) + + statText, statFg := entryStatus(e) + rate := "—" + if r := status.HourlyRate(e); r != 0 { + rate = formatRate(r) + } + client, project := "—", "—" + if e.Project != nil { + project = e.Project.Name + if e.Project.Client != nil { + client = e.Project.Client.Name + } + } + earnedSeg := seg{s: earnedText(e), fg: cText, bold: true} + + out := []string{top, row(), + field("Task", seg{s: e.Task, fg: cText, bold: true}), + field("Client", seg{s: client}), + field("Project", seg{s: project}), + field("Date", seg{s: e.StartTime.Local().Format("Mon, Jan 2")}), + field("Time", seg{s: entryTimes(e, " – ")}), + field("Duration", seg{s: model.FormatDuration(e.Duration())}), + field("Rate", seg{s: rate}), + field("Earned", earnedSeg), + field("Status", seg{s: statText, fg: statFg}), + } + notes := wrapWords(strings.TrimSpace(e.Notes), valueW) + if len(notes) == 0 { + notes = []string{"—"} + } + if len(notes) > detailNoteRows { + notes = notes[:detailNoteRows] + notes[detailNoteRows-1] = truncate(notes[detailNoteRows-1]+" …", valueW) + } + for i, n := range notes { + label := "" + if i == 0 { + label = "Notes" + } + out = append(out, field(label, seg{s: n})) + } + out = append(out, row(), row(seg{s: strings.Repeat("─", max(0, inner-2)), fg: cBorder})) + for _, k := range detailKeys(e) { + out = append(out, row(seg{s: " " + k[0] + " ", bg: cBgAlt, bold: true}, seg{s: " " + k[1], fg: cSubtle})) + } + return append(out, row(), boxBottom(w)) +} + +// fitPane keeps a detail box within rows on a short terminal: it drops +// the key list (its rule, keys and the blank after them) first, then cuts +// the fields and closes the box. +func fitPane(box []string, rows, keys int) []string { + if rows <= 0 || len(box) <= rows { + return box + } + // The key block is the rule, the keys and a blank, just above the + // bottom border. + if cut := keys + 2; len(box)-cut <= rows && len(box) > cut+1 { + return append(append([]string{}, box[:len(box)-1-cut]...), box[len(box)-1]) + } + if rows < 3 { + return nil + } + return append(append([]string{}, box[:rows-1]...), box[len(box)-1]) +} + +// wrapWords wraps s into lines of at most w cells, breaking at spaces and +// hard-breaking words longer than w. Line breaks in s start new lines. +func wrapWords(s string, w int) []string { + if s == "" || w <= 0 { + return nil + } + var out []string + for _, para := range strings.Split(s, "\n") { + line := "" + for _, word := range strings.Fields(para) { + for lipgloss.Width(word) > w { + r := []rune(word) + if line != "" { + out = append(out, line) + line = "" + } + out = append(out, string(r[:w])) + word = string(r[w:]) + } + switch { + case line == "": + line = word + case lipgloss.Width(line)+1+lipgloss.Width(word) <= w: + line += " " + word + default: + out = append(out, line) + line = word + } + } + if line != "" { + out = append(out, line) + } + } + return out +} + +// renderSummary is the compact layout's one-line summary of the selected +// entry, and the hint to open its detail pane. +func (m TimersModel) renderSummary(w int) []string { + e := m.selectedEntry() + if e == nil { + return []string{blankLine(w), blankLine(w)} + } + task := truncate(e.Task, max(1, w/2)) + rest := " · " + placeText(e) + " · " + entryTimes(e, "–") + if placeText(e) == "" { + rest = " · " + entryTimes(e, "–") + } + return []string{ + spread(w, cBg, []seg{{s: task, bold: true}, {s: truncate(rest, max(0, w-lipgloss.Width(task))), fg: cDim}}, nil), + spread(w, cBg, []seg{{s: "enter for details", fg: cSubtle}}, nil), + } +} + +// ── Assembly ────────────────────────────────────────────────────────────────── + +func (m TimersModel) viewList() string { + return m.viewListAt(time.Now()) +} + +func (m TimersModel) viewListAt(now time.Time) string { + m.clampOffset() // m is a copy: this only aligns the window drawn here + w := m.innerWidth() + var out []string + if m.wide() { + out = m.heroWide(w, now) + } else { + out = m.heroCompact(w, now) + } + out = append(out, blankLine(w), m.renderRangeChips(w, now), blankLine(w)) + + switch { + case m.mode == timersModeFilter: + out = append(out, strings.Split(m.renderFilterBar(), "\n")...) + return strings.Join(out, "\n") + case len(m.filtered) == 0: + out = append(out, strings.Split(m.viewEmptyState(), "\n")...) + return strings.Join(out, "\n") + } + + tw := m.tableWidth() + list := m.renderList(tw) + if m.wide() { + var pane []string + if e := m.selectedEntry(); e != nil { + pane = fitPane(m.renderDetailBox(e, theme.DetailWidth), m.innerHeight()-len(out), len(detailKeys(e))) + } + for i := 0; i < max(len(list), len(pane)); i++ { + l, p := blankLine(tw), blankLine(theme.DetailWidth) + if i < len(list) { + l = list[i] + } + if i < len(pane) { + p = pane[i] + } + out = append(out, l+blankLine(2)+p) + } + } else { + out = append(out, list...) + for len(out) < m.innerHeight()-2 { + out = append(out, blankLine(w)) + } + out = append(out, m.renderSummary(w)...) + } + 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 e := m.selectedEntry(); e != nil { + body = centerOverlay(body, strings.Join(m.renderDetailBox(e, theme.DetailWidth), "\n")) + } + } + return body +} + +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.") +} diff --git a/internal/ui/views/timers_view_test.go b/internal/ui/views/timers_view_test.go new file mode 100644 index 0000000..5100d46 --- /dev/null +++ b/internal/ui/views/timers_view_test.go @@ -0,0 +1,262 @@ +package views + +import ( + "regexp" + "strings" + "testing" + "time" + + "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/theme" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +var viewANSI = regexp.MustCompile(`\x1b\[[0-9;?]*[A-Za-z]`) + +func plain(s string) string { return viewANSI.ReplaceAllString(s, "") } + +// boardTimers is the design board's sample on fixed past days (so "Today" +// never races midnight), with a running timer started 1:23:46 ago, the All +// range, and the cursor on "Logo explorations". +func boardTimers(width, height int) TimersModel { + harbor, field, internal := mkClient(1, "Harbor & Pine", 120), mkClient(2, "Fieldnote Studio", 95), mkClient(3, "Internal", 0) + web, booking := mkProject(1, "Website rebuild", harbor), mkProject(2, "Booking app", harbor) + brand, notch := mkProject(3, "Brand refresh", field), mkProject(4, "notch", internal) + day := func(y int, mo time.Month, d, h, min int) time.Time { + return time.Date(y, mo, d, h, min, 0, 0, time.Local) + } + + logo := mkEntry(2, brand, "Logo explorations", day(2024, 12, 3, 11, 0), 90) + logo.Notes = "Three directions, one to keep." + invoiced1 := mkEntry(4, booking, "Calendar sync bug", day(2024, 12, 2, 13, 0), 200) + invoiced1.Invoiced = true + invoiced2 := mkEntry(5, web, "Homepage hero and nav", day(2024, 12, 2, 9, 0), 105) + invoiced2.Invoiced = true + paid := mkEntry(7, brand, "Moodboard review call", day(2024, 11, 30, 15, 0), 60) + paid.Invoiced, paid.Paid = true, true + entries := []*model.Entry{ + mkRunningEntry(1, web, "Pricing page layout", time.Now().Add(-(83*time.Minute + 46*time.Second))), + logo, + mkEntry(3, web, "Homepage hero and nav", day(2024, 12, 3, 9, 0), 105), + invoiced1, invoiced2, + mkEntry(6, notch, "Bar widget panel", day(2024, 12, 1, 10, 0), 130), + paid, + } + m := NewTimers(nil) + m.SetSize(width, height) + m, _ = m.Update(timerEntriesMsg(entries)) + m, _ = m.Update(runeKey('a')) + m, _ = m.Update(runeKey('j')) + return m +} + +func TestBlockText_MatchesBoard(t *testing.T) { + got := blockText("1:23:46") + want := [3]string{ + "▀█ ▀▀█ ▀▀█ █ █ █▀▀", + " █ ▀ █▀▀ ▀█ ▀ ▀▀█ █▀█", + "▄█▄ ▀ █▄▄ ▄▄█ ▀ █ █▄█", + } + if got != want { + t.Errorf("blockText(1:23:46) =\n%s\nwant\n%s", strings.Join(got[:], "\n"), strings.Join(want[:], "\n")) + } + for r, g := range blockGlyphs { + if r != ':' && (lipgloss.Width(g[0]) != 3 || lipgloss.Width(g[1]) != 3 || lipgloss.Width(g[2]) != 3) { + t.Errorf("glyph %q isn't 3 cells wide on every row: %q", r, g) + } + } +} + +func TestFormatMoney(t *testing.T) { + for x, want := range map[float64]string{ + 0: "$0.00", 5: "$5.00", 167.533: "$167.53", 1057.5: "$1,057.50", + 1234567.891: "$1,234,567.89", -42.5: "-$42.50", + } { + if got := formatMoney(x); got != want { + t.Errorf("formatMoney(%v) = %q, want %q", x, got, want) + } + } + if got := formatRate(120); got != "$120/h" { + t.Errorf("formatRate(120) = %q", got) + } + if got := formatRate(87.5); got != "$87.50/h" { + t.Errorf("formatRate(87.5) = %q", got) + } +} + +// Each day's header carries its subtotal: time and money, or "—" when no +// entry that day has a rate. +func TestDayHeaders_ShowSubtotals(t *testing.T) { + m := boardTimers(140, 36) + got := plain(m.viewListAt(time.Now())) + for _, want := range []*regexp.Regexp{ + regexp.MustCompile(`Mon Dec 2 +5:05:00 · \$610\.00`), + regexp.MustCompile(`Sun Dec 1 +2:10:00 · —`), + regexp.MustCompile(`Sat Nov 30 +1:00:00 · \$95\.00`), + regexp.MustCompile(`7 entries +Total `), + } { + if !want.MatchString(got) { + t.Errorf("list should match %s, got:\n%s", want, got) + } + } +} + +func TestViewList_WideLayout(t *testing.T) { + m := boardTimers(140, 36) + out := m.viewListAt(time.Now()) + lines := strings.Split(out, "\n") + if len(lines) > m.innerHeight() { + t.Errorf("%d lines, more than the %d available", len(lines), m.innerHeight()) + } + for i, l := range lines { + if w := lipgloss.Width(l); w != m.innerWidth() { + t.Errorf("line %d is %d wide, want %d: %q", i, w, m.innerWidth(), plain(l)) + } + } + got := plain(out) + for _, want := range []string{ + "NOW TRACKING", "Pricing page layout", "Harbor & Pine › Website rebuild", "$120/h", + blockText("1:23:4")[0][:10], "Today", "This week", "Unbilled", + "Range", "Custom…", "CLIENT › PROJECT", "DURATION", "STATUS", "EARNED", + theme.GlyphRunning + " running", theme.GlyphUnbilled + " unbilled", + theme.GlyphInvoiced + " invoiced", theme.GlyphPaid + " paid", + "╭─ Entry ", "Logo explorations", "Three directions, one", "i mark invoiced", "r resume", + } { + if !strings.Contains(got, want) { + t.Errorf("wide layout is missing %q:\n%s", want, got) + } + } + if strings.Contains(got, "enter for details") { + t.Error("wide layout shows the compact summary") + } + // The selected row has the cursor glyph and is the only row with it. + if n := strings.Count(got, theme.GlyphCursor); n != 1 { + t.Errorf("%d cursor glyphs, want 1", n) + } + if !regexp.MustCompile(theme.GlyphCursor + ` Logo explorations`).MatchString(got) { + t.Error("the cursor isn't on the selected row") + } +} + +func TestViewList_CompactLayout(t *testing.T) { + m := boardTimers(90, 28) + out := m.viewListAt(time.Now()) + lines := strings.Split(out, "\n") + if len(lines) != m.innerHeight() { + t.Errorf("%d lines, want exactly %d (the summary sits at the bottom)", len(lines), m.innerHeight()) + } + for i, l := range lines { + if w := lipgloss.Width(l); w != m.innerWidth() { + t.Errorf("line %d is %d wide, want %d: %q", i, w, m.innerWidth(), plain(l)) + } + } + got := plain(out) + for _, want := range []string{"▶ Pricing page layout", "today ", "TASK", "STATUS", "Week", "…", + "Logo explorations · Fieldnote Studio › Brand refresh · 11:00 AM–12:30 PM", "enter for details"} { + if !strings.Contains(got, want) { + t.Errorf("compact layout is missing %q:\n%s", want, got) + } + } + for _, not := range []string{"CLIENT › PROJECT", "NOW TRACKING", "╭─ Entry ", "Custom…", "Month"} { + if strings.Contains(got, not) { + t.Errorf("compact layout shows %q", not) + } + } + + // enter opens the detail pane over the list; esc closes it. + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + if got := plain(m.viewListAt(time.Now())); !strings.Contains(got, "╭─ Entry ") || !strings.Contains(got, "Fieldnote Studio") { + t.Errorf("enter should open the detail pane:\n%s", got) + } + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + if got := plain(m.viewListAt(time.Now())); strings.Contains(got, "╭─ Entry ") { + t.Error("esc should close the detail pane") + } +} + +// The compact layout still shows an active preset that has no chip of its +// own there. +func TestRangeChips_CompactShowsActivePreset(t *testing.T) { + m := boardTimers(90, 28) + m, _ = m.Update(runeKey('m')) + if got := plain(m.renderRangeChips(m.innerWidth(), time.Now())); !strings.Contains(got, " Month ") { + t.Errorf("month preset in the compact layout: chips %q should include Month", got) + } +} + +func TestMonthPreset(t *testing.T) { + m := boardTimers(140, 36) + m, _ = m.Update(runeKey('m')) + now := time.Now() + if m.preset != timersPresetMonth || m.dateFrom != now.Format("2006-01")+"-01" || m.dateTo != now.Format("2006-01-02") { + t.Errorf("m: preset %v, %s..%s; want this month", m.preset, m.dateFrom, m.dateTo) + } +} + +func TestResumeKey(t *testing.T) { + m := boardTimers(140, 36) // cursor on a finished entry + if _, cmd := m.Update(runeKey('r')); cmd == nil { + t.Error("r on a finished entry should start it again") + } + m.cursor = 0 // the running timer + if _, cmd := m.Update(runeKey('r')); cmd != nil { + t.Error("r on the running timer should do nothing") + } +} + +func TestDetailKeys(t *testing.T) { + c := mkClient(1, "Acme", 10) + p := mkProject(1, "Web", c) + running := mkRunningEntry(1, p, "t", time.Now().Add(-time.Minute)) + if keys := detailKeys(running); len(keys) != 3 || keys[0][1] != "stop" { + t.Errorf("running entry's keys: %v", keys) + } + done := mkEntry(2, p, "t", time.Now().Add(-time.Hour), 10) + done.Invoiced = true + keys := detailKeys(done) + if keys[0][1] != "unmark invoiced" || keys[1][1] != "mark paid" { + t.Errorf("invoiced entry's keys: %v", keys) + } +} + +// The hero's today and week include the running timer's time so far; +// unbilled counts finished entries only. +func TestHeroTotals(t *testing.T) { + now := time.Now() + c := mkClient(1, "Acme", 100) + p := mkProject(1, "Web", c) + running := mkRunningEntry(1, p, "live", now.Add(-10*time.Minute)) + m := TimersModel{entries: []*model.Entry{running}} + got := m.heroTotalsAt(now) + if got.today < 9*time.Minute || got.week < got.today || got.unbilled != 0 { + t.Errorf("hero totals %+v: want today and week to include the running 10 minutes, unbilled 0", got) + } +} + +// On a short terminal the wide layout's detail pane drops its key list +// before it would run past the bottom. +func TestDetailPane_FitsShortTerminal(t *testing.T) { + tall := boardTimers(140, 36) + short := boardTimers(140, 26) + if !strings.Contains(plain(tall.viewListAt(time.Now())), "r resume") { + t.Fatal("a tall terminal should show the pane's keys") + } + got := plain(short.viewListAt(time.Now())) + if n := len(strings.Split(got, "\n")); n > short.innerHeight() { + t.Errorf("short terminal: %d lines, more than %d", n, short.innerHeight()) + } + if strings.Contains(got, "r resume") || !strings.Contains(got, "╰") { + t.Errorf("short terminal: the pane should drop its keys and stay closed:\n%s", got) + } +} + +func TestWrapWords(t *testing.T) { + got := wrapWords("Three directions, one to keep.", 21) + if strings.Join(got, "|") != "Three directions, one|to keep." { + t.Errorf("wrapWords = %q", got) + } + if got := wrapWords("abcdefghij", 4); strings.Join(got, "|") != "abcd|efgh|ij" { + t.Errorf("long word: %q", got) + } +} From 50872018239ff5a1b4972702e17abf65b486dabd Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 08:15:15 -0700 Subject: [PATCH 02/13] Move the Timers screen's fixed sizes into the tokens and fix contrast notes (ALI-2615) The list's column widths, the detail pane's label column and note rows, and the hero's row counts were Go literals, outside design/tokens.json. They're tokens now (tui-col-*, tui-detail-label, tui-detail-note-rows, tui-hero-rows*), generated into internal/theme. New tui-min-width (64) and tui-min-height (22) give the smallest terminal the layout fits, measured from the views' real output. The contrast notes said warning draws invoiced status and primary the running timer. In the redesigned Timers list invoiced is accent, running is success, and day headers are primary; warning is left for Reports and the hero's unbilled total. The notes now say so. --- design/build/main.go | 10 +++++++++ design/tokens.json | 30 ++++++++++++++++++--------- internal/theme/tokens_gen.go | 39 +++++++++++++++++++++++++++++++++++- internal/ui/layout_gen.go | 13 ++++++++++++ 4 files changed, 81 insertions(+), 11 deletions(-) diff --git a/design/build/main.go b/design/build/main.go index b5a1865..fddd800 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -321,6 +321,14 @@ func renderPalette(t *Tokens) ([]byte, error) { {"tui-margin", "Margin"}, {"tui-wide", "WideMin"}, {"tui-detail-width", "DetailWidth"}, + {"tui-detail-label", "DetailLabel"}, + {"tui-detail-note-rows", "DetailNoteRows"}, + {"tui-col-duration", "ColDuration"}, + {"tui-col-gap", "ColGap"}, + {"tui-col-status", "ColStatus"}, + {"tui-col-earned", "ColEarned"}, + {"tui-hero-rows", "HeroRows"}, + {"tui-hero-rows-compact", "HeroRowsCompact"}, } { v, err := integer(t.Spacing, c.token) if err != nil { @@ -338,6 +346,8 @@ func renderLayout(t *Tokens) ([]byte, error) { for _, c := range []struct{ token, name string }{ {"tui-max-width", "MaxContentWidth"}, {"tui-chrome-rows", "ChromeRows"}, + {"tui-min-width", "MinWidth"}, + {"tui-min-height", "MinHeight"}, } { v, err := integer(t.Spacing, c.token) if err != nil { diff --git a/design/tokens.json b/design/tokens.json index 9634e40..3ae35b6 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -13,7 +13,7 @@ { "name": "primary", "value": "#91B0DE", "usage": "Active tab, selected-row marker, primary buttons (bg text on it), the running timer. Aether's accent." }, { "name": "accent", "value": "#9DC6E9", "usage": "Field labels, links, code in the landing page. Aether's cyan." }, { "name": "success", "value": "#99C2ED", "usage": "Paid status, the running pill. Aether's green." }, - { "name": "warning", "value": "#A4CBF7", "usage": "Invoiced status, section titles and day headers. Aether's yellow." }, + { "name": "warning", "value": "#A4CBF7", "usage": "Section titles and invoiced status in Reports, and the unbilled total in the Timers hero. (The Timers list draws invoiced in accent and day headers in primary.) Aether's yellow." }, { "name": "danger", "value": "#C79EA9", "usage": "Delete actions and confirm borders, field errors. Aether's red; the only warm hue." }, { "name": "text", "value": "#C2D9E9", "usage": "Body text and values on bg and bg_alt. Aether's light_fg. Tailwind name: ink." }, { "name": "dim", "value": "#B7D2E5", "usage": "Secondary text: meta lines, inactive tabs. Aether's fg." }, @@ -62,6 +62,16 @@ { "name": "tui-margin", "value": 2, "usage": "TUI: blank columns on each side of the content column, and before the tab bar's wordmark." }, { "name": "tui-wide", "value": 120, "usage": "TUI: the narrowest terminal that gets the wide layout: the Timers hero with block digits, the CLIENT › PROJECT column and the entry detail pane. Narrower terminals get the compact layout." }, { "name": "tui-detail-width", "value": 42, "usage": "TUI: the entry detail pane's width, borders included, beside the Timers list in the wide layout." }, + { "name": "tui-col-duration", "value": 10, "usage": "TUI: the Timers list's DURATION column, right-aligned, in cells." }, + { "name": "tui-col-gap", "value": 2, "usage": "TUI: the gap between the Timers list's DURATION and STATUS columns." }, + { "name": "tui-col-status", "value": 12, "usage": "TUI: the Timers list's STATUS column in the wide layout, room for its longest value (◐ invoiced). The compact layout gives STATUS 5/12 of the flexible width, never less than this." }, + { "name": "tui-col-earned", "value": 10, "usage": "TUI: the Timers list's EARNED column, right-aligned, in cells." }, + { "name": "tui-detail-label", "value": 10, "usage": "TUI: the label column in the entry detail pane (Task, Client, Duration…)." }, + { "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-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). 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." }, { "name": "panel-padding", "value": "14px", "usage": "Bar panel: inner padding, from aliasOS's KeyboardPanel." } ] @@ -114,22 +124,22 @@ { "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": "primary", "bg": "bg", "min": 4.5, "usage": "Active tab and the running timer." }, - { "fg": "accent", "bg": "bg", "min": 4.5, "usage": "Field labels and links." }, - { "fg": "success", "bg": "bg", "min": 4.5, "usage": "Paid status." }, - { "fg": "warning", "bg": "bg", "min": 4.5, "usage": "Section titles and invoiced status." }, + { "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": "highlight", "bg": "bg", "min": 4.5, "usage": "Wordmark and elapsed time." }, - { "fg": "bg", "bg": "primary", "min": 4.5, "usage": "Primary button label." }, + { "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." }, { "fg": "bg", "bg": "accent", "min": 4.5, "usage": "Accent chip label." }, { "fg": "border", "bg": "bg", "min": 3, "usage": "Rules and box borders." }, { "fg": "primary", "bg": "bg_alt", "min": 4.5, "usage": "Selected row marker and the primary label in modals." }, - { "fg": "accent", "bg": "bg_alt", "min": 4.5, "usage": "Field labels inside modals." }, - { "fg": "success", "bg": "bg_alt", "min": 4.5, "usage": "Paid status on the selected row." }, - { "fg": "warning", "bg": "bg_alt", "min": 4.5, "usage": "Invoiced status on the selected row." }, - { "fg": "highlight", "bg": "bg_alt", "min": 4.5, "usage": "Elapsed time on the selected row and in the panel." }, + { "fg": "accent", "bg": "bg_alt", "min": 4.5, "usage": "Field labels inside modals, and invoiced status on the Timers list's selected row." }, + { "fg": "success", "bg": "bg_alt", "min": 4.5, "usage": "Paid and running status on the selected row." }, + { "fg": "warning", "bg": "bg_alt", "min": 4.5, "usage": "Invoiced status on the selected row in Reports." }, + { "fg": "highlight", "bg": "bg_alt", "min": 4.5, "usage": "The wordmark in the tab bar, and elapsed time in the panel." }, { "fg": "dim", "bg": "surface", "min": 4.5, "usage": "Landing page secondary text in cards." }, { "fg": "highlight", "bg": "surface", "min": 4.5, "usage": "Landing page emphasis and the mark in cards." }, { "fg": "danger", "bg": "surface", "min": 4.5, "usage": "Landing page feature icons in danger." }, diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index b3e4858..cac88b6 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -13,7 +13,9 @@ var Default = Palette{ Accent: "#9DC6E9", // Paid status, the running pill. Aether's green. Success: "#99C2ED", - // Invoiced status, section titles and day headers. Aether's yellow. + // Section titles and invoiced status in Reports, and the unbilled total in + // the Timers hero. (The Timers list draws invoiced in accent and day headers + // in primary.) Aether's yellow. Warning: "#A4CBF7", // Delete actions and confirm borders, field errors. Aether's red; the only // warm hue. @@ -73,3 +75,38 @@ const WideMin = 120 // DetailWidth (tui-detail-width). TUI: the entry detail pane's width, borders // included, beside the Timers list in the wide layout. const DetailWidth = 42 + +// DetailLabel (tui-detail-label). TUI: the label column in the entry detail +// pane (Task, Client, Duration…). +const DetailLabel = 10 + +// DetailNoteRows (tui-detail-note-rows). TUI: the most rows an entry's notes +// take in the detail pane; longer notes end in an ellipsis. +const DetailNoteRows = 3 + +// ColDuration (tui-col-duration). TUI: the Timers list's DURATION column, +// right-aligned, in cells. +const ColDuration = 10 + +// ColGap (tui-col-gap). TUI: the gap between the Timers list's DURATION and +// STATUS columns. +const ColGap = 2 + +// ColStatus (tui-col-status). TUI: the Timers list's STATUS column in the +// wide layout, room for its longest value (◐ invoiced). The compact layout +// gives STATUS 5/12 of the flexible width, never less than this. +const ColStatus = 12 + +// ColEarned (tui-col-earned). TUI: the Timers list's EARNED column, +// right-aligned, in cells. +const ColEarned = 10 + +// HeroRows (tui-hero-rows). 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. +const HeroRows = 6 + +// HeroRowsCompact (tui-hero-rows-compact). TUI: rows the compact Timers hero +// takes, borders included: the task and elapsed time, then the place and +// today's total. +const HeroRowsCompact = 4 diff --git a/internal/ui/layout_gen.go b/internal/ui/layout_gen.go index 8f65133..22444ec 100644 --- a/internal/ui/layout_gen.go +++ b/internal/ui/layout_gen.go @@ -10,3 +10,16 @@ const MaxContentWidth = 150 // 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. const ChromeRows = 4 + +// MinWidth (tui-min-width). 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. +const MinWidth = 64 + +// MinHeight (tui-min-height). 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). Shorter terminals get a centred "Terminal too small" +// message. +const MinHeight = 22 From c28a0ff1874ce70df2f5b4512fa8ad4a83a14ce2 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 08:15:15 -0700 Subject: [PATCH 03/13] Fix width, fit and selection bugs in the Timers redesign (ALI-2615) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Text was cut by rune count, so CJK and emoji ran past their columns and could push the running pill off the tab bar. truncate and truncateStr now cut by display width, as does wrapWords. - The compact details overlay and the wide detail pane weren't fitted to the body: at 80x24 the overlay lost its bottom border and keys, and a short wide terminal could overflow. The box now drops spacing and lesser fields first, keeping its borders, the task and every key, and isn't drawn when even those don't fit. - The range keys and r had no place on screen. Each range chip now shows its key, and r resume stays in the pane and the overlay. - Range keys reset the cursor but not the scroll offset. - On a narrow tab bar the pill was clipped. The task name goes first, then the inactive tabs' names, then the wordmark's name. - Below 64x22 the layout wrapped over itself; it now shows a centred "Terminal too small" note. - The details stayed open after an edit, a delete or a tab switch. - A reload moved the cursor by index. It now follows the selected entry by ID, and after r or space starts a timer, selects the new one. - The hero, the rows, the day subtotals and the pill each read the clock separately and some rounded, so Today could show 4:38:46 above a 4:38:47 subtotal. They now share one now and whole seconds. - Day subtotals now line up in two right-aligned columns, "—" included. - q quit is back at the end of the key line, the first key dropped. - Removed the unused filteredTotals and friendlyDay, and comments that named removed functions. --- internal/ui/app.go | 122 +++++++--- internal/ui/app_test.go | 137 +++++++++++ internal/ui/views/clients.go | 2 +- internal/ui/views/common.go | 20 +- internal/ui/views/common_test.go | 3 + internal/ui/views/projects.go | 2 +- internal/ui/views/reports.go | 2 +- internal/ui/views/timers.go | 127 +++++------ internal/ui/views/timers_test.go | 34 ++- internal/ui/views/timers_view.go | 314 ++++++++++++++++---------- internal/ui/views/timers_view_test.go | 235 ++++++++++++++++++- 11 files changed, 737 insertions(+), 261 deletions(-) diff --git a/internal/ui/app.go b/internal/ui/app.go index e757b34..9b561cb 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -12,6 +12,7 @@ import ( "github.com/charmbracelet/bubbles/key" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" ) // Tab indices @@ -259,15 +260,19 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, tea.Quit case key.Matches(msg, appKeys.Tab1): m.activeTab = TabTimers + m.timers = m.timers.CloseDetail() return m, m.timers.Init() case key.Matches(msg, appKeys.Tab2): m.activeTab = TabProjects + m.timers = m.timers.CloseDetail() return m, m.projects.Init() case key.Matches(msg, appKeys.Tab3): m.activeTab = TabClients + m.timers = m.timers.CloseDetail() return m, m.clients.Init() case key.Matches(msg, appKeys.Tab4): m.activeTab = TabReports + m.timers = m.timers.CloseDetail() return m, m.reports.Init() } } @@ -336,6 +341,9 @@ func (m AppModel) View() string { if m.width == 0 { return "" } + if m.width < MinWidth || m.height < MinHeight { + return m.viewTooSmall() + } return lipgloss.JoinVertical(lipgloss.Left, m.renderTopBar(), @@ -344,6 +352,16 @@ func (m AppModel) View() string { ) } +// viewTooSmall fills the terminal with a centred note of the size notch +// needs, instead of a layout that would wrap and overlap below it. +func (m AppModel) viewTooSmall() string { + msg := truncateStr("Terminal too small", m.width) + "\n" + + truncateStr(fmt.Sprintf("need at least %d×%d", MinWidth, MinHeight), m.width) + return lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, + lipgloss.NewStyle().Foreground(appColorText).Background(appColorBg).Align(lipgloss.Center).Render(msg), + lipgloss.WithWhitespaceBackground(appColorBg)) +} + // paint renders s in fg on bg, bold or not. Every fragment of a bar carries // its own background: each Render ends with an SGR reset, so an unstyled // gap would show the terminal's default background instead of the bar's. @@ -362,50 +380,88 @@ func tabsStart() int { func wordmark() string { return theme.GlyphWordmark + " notch" } -// renderTopBar renders the tab bar and the rule under it: the wordmark, the -// numbered tabs, and the running timer (or idle) on the right; the rule -// carries a primary underline under the active tab. -func (m AppModel) renderTopBar() string { +// tabStrip is the tab bar's left side at one level of compression: 0 is the +// full wordmark and tab names; 1 keeps only the active tab's name; 2 also +// shortens the wordmark to its mark. under is the active tab's columns, for +// the underline in the rule below. +type tabStrip struct { + s string + width int + underFrom, underTo int +} + +func (m AppModel) tabStrip(level int) tabStrip { bg := appColorBgAlt - left := paint(strings.Repeat(" ", theme.Margin), appColorText, bg, false) + - paint(wordmark(), appColorHighlight, bg, true) + - paint(" ", appColorText, bg, false) - var underFrom, underTo int - col := tabsStart() + mark, gap := wordmark(), " " + if level >= 2 { + mark, gap = theme.GlyphWordmark, " " + } + st := tabStrip{s: paint(strings.Repeat(" ", theme.Margin), appColorText, bg, false) + + paint(mark, appColorHighlight, bg, true) + paint(gap, appColorText, bg, false)} + col := theme.Margin + lipgloss.Width(mark) + len(gap) for i := range tabNames { if i > 0 { - left += paint(" ", appColorText, bg, false) + st.s += paint(" ", appColorText, bg, false) col += 2 } - label := tabLabel(i) - num, name, _ := strings.Cut(strings.TrimSpace(label), " ") + num, name, _ := strings.Cut(strings.TrimSpace(tabLabel(i)), " ") nameFg, bold := appColorDim, false if i == m.activeTab { nameFg, bold = appColorText, true - underFrom, underTo = col, col+lipgloss.Width(label) + } else if level >= 1 { + name = "" + } + label := " " + num + " " + st.s += paint(" ", appColorText, bg, false) + paint(num, appColorSubtle, bg, false) + if name != "" { + label += name + " " + st.s += paint(" ", appColorText, bg, false) + paint(name, nameFg, bg, bold) + } + st.s += paint(" ", appColorText, bg, false) + if i == m.activeTab { + st.underFrom, st.underTo = col, col+lipgloss.Width(label) } - left += paint(" ", appColorText, bg, false) + paint(num, appColorSubtle, bg, false) + - paint(" ", appColorText, bg, false) + paint(name, nameFg, bg, bold) + paint(" ", appColorText, bg, false) col += lipgloss.Width(label) } + st.width = col + return st +} +// renderTopBar renders the tab bar and the rule under it: the wordmark, the +// numbered tabs, and the running timer (or idle) on the right; the rule +// carries a primary underline under the active tab. The running pill comes +// first: when the bar is short, the task name goes, then the inactive tabs' +// names, then the wordmark's name. +func (m AppModel) renderTopBar() string { + bg := appColorBgAlt margin := paint(strings.Repeat(" ", theme.Margin), appColorText, bg, false) - var right string + var pill string if r := m.running; r != nil { - pill := paint(" "+theme.GlyphLive+" "+model.FormatDuration(r.Duration())+" ", appColorBg, appColorGreen, true) - room := m.width - lipgloss.Width(left) - lipgloss.Width(pill) - theme.Margin - 3 - if room >= 4 { - right = paint(truncateStr(r.Task, room)+" ", appColorText, bg, false) - } - right += pill + margin + // Whole seconds, cut rather than rounded, like the Timers view's + // hero and rows, so the pill never runs a second ahead of them. + elapsed := max(0, time.Since(r.StartTime).Truncate(time.Second)) + pill = paint(" "+theme.GlyphLive+" "+model.FormatDuration(elapsed)+" ", appColorBg, appColorGreen, true) } else { - right = paint(theme.GlyphLive+" idle", appColorSubtle, bg, false) + margin + pill = paint(theme.GlyphLive+" idle", appColorSubtle, bg, false) + } + pillW := lipgloss.Width(pill) + theme.Margin + + st := m.tabStrip(0) + for level := 1; level <= 2 && st.width+1+pillW > m.width; level++ { + st = m.tabStrip(level) + } + + right := pill + margin + if r := m.running; r != nil { + if room := m.width - st.width - pillW - 3; room >= 4 { + right = paint(truncateStr(r.Task, room)+" ", appColorText, bg, false) + right + } } - gap := max(1, m.width-lipgloss.Width(left)-lipgloss.Width(right)) - line := left + paint(strings.Repeat(" ", gap), appColorText, bg, false) + right + gap := max(1, m.width-st.width-lipgloss.Width(right)) + line := st.s + paint(strings.Repeat(" ", gap), appColorText, bg, false) + right line = lipgloss.NewStyle().MaxWidth(m.width).Render(line) - underFrom, underTo = min(underFrom, m.width), min(underTo, m.width) + underFrom, underTo := min(st.underFrom, m.width), min(st.underTo, m.width) ruleLine := paint(strings.Repeat("─", underFrom), appColorBorder, appColorBg, false) + paint(strings.Repeat("━", underTo-underFrom), appColorPrimary, appColorBg, false) + paint(strings.Repeat("─", max(0, m.width-underTo)), appColorBorder, appColorBg, false) @@ -442,8 +498,10 @@ func (m AppModel) renderBottomBar() string { } room := inner - lipgloss.Width(msg) - 2 + // q quit comes last, so it's the first key dropped when the line is + // short. keys, w := "", 0 - for i, h := range m.activeViewHelp() { + for i, h := range append(m.activeViewHelp(), views.Hotkey{Key: "q", Label: "quit"}) { cw := hotkeyChipWidth(h) if i > 0 { cw += len(hotkeySep) @@ -465,15 +523,19 @@ func (m AppModel) renderBottomBar() string { return ruleLine + "\n" + lipgloss.NewStyle().MaxWidth(m.width).Render(line) } +// truncateStr cuts s to at most max terminal cells, ending in "…" when it +// cuts. Like views' truncate, it counts display width, not runes. func truncateStr(s string, max int) string { if max <= 0 { return "" } - runes := []rune(s) - if len(runes) <= max { + if ansi.StringWidth(s) <= max { return s } - return string(runes[:max-1]) + "…" + if max == 1 { + return ansi.Truncate(s, 1, "") + } + return ansi.Truncate(s, max, "…") } // renderBody renders the centered content column. diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index 757e8ff..3c794e5 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -1,10 +1,12 @@ package ui import ( + "fmt" "path/filepath" "regexp" "strings" "testing" + "time" "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/theme" @@ -461,3 +463,138 @@ func TestRenderBottomBar_KeysAndStatus(t *testing.T) { t.Errorf("a key was cut mid-chip: %q", line) } } + +// The running pill keeps its place on a short tab bar: the task name goes +// first, then the inactive tabs' names, then the wordmark's name. +func TestRenderTopBar_PillHasPriority(t *testing.T) { + m := sampleApp(t, 140, 40) + for _, w := range []int{MinWidth, 70, 80, 100, 140} { + m.width = w + for _, tab := range []int{TabTimers, TabProjects, TabReports} { + m.activeTab = tab + lines := strings.Split(plainText(m.renderTopBar()), "\n") + if got := lipgloss.Width(lines[0]); got != w { + t.Errorf("%d cols: tab bar is %d wide", w, got) + } + if !regexp.MustCompile(theme.GlyphLive + ` \d+:\d\d:\d\d $`).MatchString(lines[0]) { + t.Errorf("%d cols, tab %d: the pill is cut: %q", w, tab, lines[0]) + } + if !strings.Contains(lines[0], tabNames[tab]) { + t.Errorf("%d cols: the active tab's name is gone: %q", w, lines[0]) + } + // The underline sits under the active tab's label. + rule := []rune(lines[1]) + from := strings.IndexRune(string(rule), '━') + label := []rune(lines[0])[len([]rune(string(rule)[:from])):] + if from < 0 || !strings.HasPrefix(string(label), fmt.Sprintf(" %d %s ", tab+1, tabNames[tab])) { + t.Errorf("%d cols, tab %d: underline at %d doesn't sit under the tab: %q / %q", w, tab, from, lines[0], lines[1]) + } + } + } + m.width, m.activeTab = 140, TabTimers + if bar := plainText(m.renderTopBar()); !strings.Contains(bar, "◷ notch") || !strings.Contains(bar, "2 Projects") || !strings.Contains(bar, "Pricing page layout") { + t.Errorf("a wide bar should keep everything: %q", bar) + } +} + +// A task in wide characters is cut by display width, so it can't push the +// pill off the bar. +func TestRenderTopBar_WideCharacterTask(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 100) + p, _ := d.CreateProject(c.ID, "Website") + if _, err := d.StartEntry(p.ID, "日本語のとても長いタスク名前をここに書きます🎉🎉🎉🎉🎉🎉"); err != nil { + t.Fatal(err) + } + m, err := New(d) + if err != nil { + t.Fatal(err) + } + m.running, _ = d.GetRunningEntry() + for _, w := range []int{80, 100} { + m.width = w + line := strings.Split(plainText(m.renderTopBar()), "\n")[0] + if lipgloss.Width(line) != w || !regexp.MustCompile(theme.GlyphLive+` \d+:\d\d:\d\d $`).MatchString(line) { + t.Errorf("%d cols: %q (%d wide)", w, line, lipgloss.Width(line)) + } + } + if got := truncateStr("日本語テキスト", 5); got != "日本…" { + t.Errorf("truncateStr by width = %q, want 日本…", got) + } +} + +// Below the minimum size the whole screen is a centred note, not a layout +// that wraps over itself. +func TestView_TooSmall(t *testing.T) { + for _, sz := range [][2]int{{MinWidth - 1, 40}, {120, MinHeight - 1}, {20, 5}} { + m := sampleApp(t, sz[0], sz[1]) + out := m.View() + lines := strings.Split(out, "\n") + if len(lines) != sz[1] { + t.Errorf("%v: %d lines", sz, len(lines)) + } + for _, l := range lines { + if lipgloss.Width(l) != sz[0] { + t.Errorf("%v: a line is %d wide", sz, lipgloss.Width(l)) + } + } + got := plainText(out) + want := fmt.Sprintf("need at least %d×%d", MinWidth, MinHeight) + if sz[0] >= lipgloss.Width(want) && (!strings.Contains(got, "Terminal too small") || !strings.Contains(got, want)) { + t.Errorf("%v: no too-small note:\n%s", sz, got) + } + if strings.Contains(got, "TASK") { + t.Errorf("%v: the layout still draws", sz) + } + } + m := sampleApp(t, MinWidth, MinHeight) + if got := plainText(m.View()); strings.Contains(got, "Terminal too small") || !strings.Contains(got, "TASK") { + t.Errorf("at exactly the minimum the layout should draw:\n%s", got) + } +} + +// q quit ends the key line when there's room, and is the first key dropped. +func TestRenderBottomBar_Quit(t *testing.T) { + m := sampleApp(t, 140, 40) + if line := plainText(m.renderBottomBar()); !strings.Contains(line, "d delete q quit") { + t.Errorf("wide key line should end in q quit: %q", line) + } + m.width = 75 + line := plainText(m.renderBottomBar()) + if strings.Contains(line, "q quit") || !strings.Contains(line, "e edit") { + t.Errorf("a short key line should drop q quit first: %q", line) + } +} + +// Switching tabs closes the compact layout's details. +func TestTabSwitch_ClosesDetails(t *testing.T) { + m := sampleApp(t, 90, 32) + step := func(msg tea.Msg) { + u, _ := m.Update(msg) + m = u.(AppModel) + } + for _, k := range []rune{'1', '2', '3', '4'} { + step(runeKey('1')) + step(tea.KeyMsg{Type: tea.KeyEnter}) + if !strings.Contains(plainText(m.View()), "╭─ Entry") { + t.Fatal("setup: enter should open the details") + } + step(runeKey(k)) + step(runeKey('1')) + if strings.Contains(plainText(m.View()), "╭─ Entry") { + t.Errorf("after switching to tab %c and back, the details are still open", k) + } + } +} + +// The pill cuts the running time to whole seconds, as the Timers view does, +// so the two never disagree by a rounded-up second. +func TestRenderTopBar_PillTruncatesSeconds(t *testing.T) { + m := sampleApp(t, 140, 40) + r := *m.running + r.StartTime = time.Now().Add(-(time.Minute + 700*time.Millisecond)) + m.running = &r + if bar := plainText(m.renderTopBar()); !strings.Contains(bar, theme.GlyphLive+" 0:01:00 ") { + t.Errorf("pill should read 0:01:00 for 1m0.7s: %q", bar) + } +} diff --git a/internal/ui/views/clients.go b/internal/ui/views/clients.go index 3862300..42b00b1 100644 --- a/internal/ui/views/clients.go +++ b/internal/ui/views/clients.go @@ -61,7 +61,7 @@ func (m ClientsModel) IsBusy() bool { } // Help returns the contextual hotkey string for the view's current mode, for -// display in the app-level hotkey bar (see app.go renderHotkeyBar). +// display in the app-level hotkey bar (see app.go renderBottomBar). func (m ClientsModel) Help() []Hotkey { switch m.mode { case clientModeForm: diff --git a/internal/ui/views/common.go b/internal/ui/views/common.go index 90acc71..197603a 100644 --- a/internal/ui/views/common.go +++ b/internal/ui/views/common.go @@ -43,7 +43,7 @@ type RunningChangedMsg struct{} type ReloadMsg struct{} // Hotkey is one key/label pair returned by a view's Help(), for display in -// the app-level hotkey bar (see app.go renderHotkeyBar). Key holds the raw +// the app-level hotkey bar (see app.go renderBottomBar). Key holds the raw // key name(s) (e.g. "n", "tab / shift+tab") which the bar renders inside its // own boxed cap, separate from Label's plain descriptive text. type Hotkey struct { @@ -333,24 +333,24 @@ func renderBadge(text string, bg lipgloss.Color) string { // ── Shared utilities ────────────────────────────────────────────────────────── +// truncate cuts s to at most max terminal cells, ending in "…" when it cuts. +// It counts display width, not runes: CJK and most emoji take two cells. func truncate(s string, max int) string { if max <= 0 { return "" } - runes := []rune(s) - if len(runes) <= max { + if ansi.StringWidth(s) <= max { return s } - if max <= 1 { - return string(runes[:max]) + if max == 1 { + return ansi.Truncate(s, 1, "") } - return string(runes[:max-1]) + "…" + return ansi.Truncate(s, max, "…") } -// entryDetailLines is the fixed height of an entry detail pane (Started/ -// Notes/Status — see TimersModel.renderDetail and -// ReportsModel.renderEntryDetail). Both must always emit exactly this many -// lines, note or no note, so that rowsBudget/entriesRowsBudget's table +// entryDetailLines is the fixed height of the Reports entry detail pane +// (Started/Notes/Status — see ReportsModel.renderEntryDetail). It must always +// emit exactly this many lines, note or no note, so that rowsBudget/entriesRowsBudget's table // window never grows or shrinks depending on which row happens to be // selected. const entryDetailLines = 3 diff --git a/internal/ui/views/common_test.go b/internal/ui/views/common_test.go index d9d641c..2e16317 100644 --- a/internal/ui/views/common_test.go +++ b/internal/ui/views/common_test.go @@ -138,6 +138,9 @@ func TestTruncate(t *testing.T) { {"shorter than max", "hi", 10, "hi"}, {"truncates with ellipsis", "hello world", 5, "hell…"}, {"rune-aware truncation", "héllo world", 3, "hé…"}, + {"wide characters count two cells", "日本語テキスト", 5, "日本…"}, + {"emoji count two cells", "🎉🎉🎉", 4, "🎉…"}, + {"a wide character that doesn't fit", "日本", 1, ""}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { diff --git a/internal/ui/views/projects.go b/internal/ui/views/projects.go index 5ed702f..bcb1c2f 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -84,7 +84,7 @@ func (m ProjectsModel) IsBusy() bool { } // Help returns the contextual hotkey string for the view's current mode, for -// display in the app-level hotkey bar (see app.go renderHotkeyBar). +// display in the app-level hotkey bar (see app.go renderBottomBar). func (m ProjectsModel) Help() []Hotkey { switch m.mode { case projectsModeNewProject, projectsModeEditProject: diff --git a/internal/ui/views/reports.go b/internal/ui/views/reports.go index d1db3fc..fef94d9 100644 --- a/internal/ui/views/reports.go +++ b/internal/ui/views/reports.go @@ -98,7 +98,7 @@ func (m ReportsModel) IsBusy() bool { } // Help returns the contextual hotkey string for the view's current mode, for -// display in the app-level hotkey bar (see app.go renderHotkeyBar). +// display in the app-level hotkey bar (see app.go renderBottomBar). func (m ReportsModel) Help() []Hotkey { switch m.mode { case reportsModeFilter: diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index eca3a42..1d310b6 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -340,6 +340,18 @@ type TimersModel struct { // the compact layout (enter opens it, enter or esc closes it). The wide // layout always shows the pane. detailOpen bool + + // selectRunning moves the cursor to the running entry when the next + // entry list arrives: set when r or space starts a timer, so the new + // entry is the one selected. + selectRunning bool +} + +// CloseDetail closes the compact layout's detail pane; the app calls it on +// a tab switch, so coming back shows the list. +func (m TimersModel) CloseDetail() TimersModel { + m.detailOpen = false + return m } type timersPreset int @@ -418,12 +430,11 @@ func (m *TimersModel) recomputeFiltered() { // ── Day grouping ────────────────────────────────────────────────────────────── // // The list is rendered as a sequence of "lines": a day-header line (just the -// day label — see renderDayHeaderLine) followed by that day's entry rows. +// day label and its subtotal — see renderDayHeaderLine) followed by that day's entry rows. // Since `filtered` is sorted DESC by start time, a day's entries are always -// contiguous, so this needs only a single pass. There's no per-day total any -// more: on a multi-day filter (e.g. "This Week") repeating a Total line under -// every day read as cluttered, so there's one grand total in the table's -// footer instead (see filteredTotals/renderFooterTotals). +// contiguous, so this needs only a single pass. Each day header carries the +// day's subtotal, and the footer the range's total (see renderDayHeaderLine +// and renderListFoot in timers_view.go). type timersLineKind int @@ -452,32 +463,8 @@ func (m TimersModel) buildLines() []timersLine { return lines } -// filteredTotals sums duration/earnings across every currently filtered -// entry, regardless of day — the grand total shown in the table's footer -// row (see renderFooterTotals). The currently-running entry, if any, is -// included: its Duration()/Earnings() are already live (see -// model.Entry.Duration), so the total ticks up in step with that entry's own -// row above it rather than appearing "frozen" while its row keeps counting. -func (m TimersModel) filteredTotals() (time.Duration, float64) { - var dur time.Duration - var earned float64 - for _, e := range m.filtered { - dur += e.Duration() - if e.Project != nil && e.Project.Client != nil { - earned += e.Earnings(e.Project.Client.HourlyRate) - } - } - return dur, earned -} - -// friendlyDay formats a local calendar day as "Today", "Yesterday", or -// "Mon, Jan 2". -func friendlyDay(t time.Time) string { - return friendlyDayAt(t, time.Now()) -} - -// friendlyDayAt is friendlyDay relative to now instead of the wall clock, -// so tests can pin "today" rather than racing midnight. +// friendlyDayAt formats a local calendar day as "Today", "Yesterday" or +// "Mon Jan 2" relative to now, as the Timers list's day headers show it. func friendlyDayAt(t, now time.Time) string { now = now.Local() today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) @@ -594,7 +581,7 @@ func (m TimersModel) IsBusy() bool { } // Help returns the contextual hotkey string for the view's current mode, for -// display in the app-level hotkey bar (see app.go renderHotkeyBar). +// display in the app-level hotkey bar (see app.go renderBottomBar). func (m TimersModel) Help() []Hotkey { switch m.mode { case timersModeNew, timersModeEdit: @@ -638,8 +625,26 @@ func (m TimersModel) Update(msg tea.Msg) (TimersModel, tea.Cmd) { switch msg := msg.(type) { case timerEntriesMsg: + // Keep the cursor on the same entry, by ID, when the list reloads + // (a tick, another process's change, or this view's own action); + // after r or space starts a timer, move it to the new running one. + var keepID int64 + if e := m.selectedEntry(); e != nil { + keepID = e.ID + } m.entries = []*model.Entry(msg) m.recomputeFiltered() + want := func(e *model.Entry) bool { return e.ID == keepID } + if m.selectRunning { + want = func(e *model.Entry) bool { return e.IsRunning() } + m.selectRunning = false + } + for i, e := range m.filtered { + if want(e) { + m.cursor = i + break + } + } m.clampOffset() return m, nil @@ -683,6 +688,7 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { case key.Matches(msg, timersKeys.Edit): if e := m.selectedEntry(); e != nil { + m.detailOpen = false return m, m.openFormCmd(e.ID) } @@ -696,6 +702,7 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { if entry.IsRunning() { return m, m.stopCmd(entry.ID) } + m.selectRunning = true return m, m.startCmd(entry.ProjectID, entry.Task) } @@ -717,21 +724,11 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { case key.Matches(msg, timersKeys.Today): today := time.Now().Local().Format("2006-01-02") - m.dateFrom, m.dateTo = today, today - m.preset = timersPresetToday - m.fromInput.SetValue(today) - m.toInput.SetValue(today) - m.cursor = 0 - m.recomputeFiltered() + m.setRange(timersPresetToday, today, today) case key.Matches(msg, timersKeys.Yesterday): yesterday := time.Now().Local().AddDate(0, 0, -1).Format("2006-01-02") - m.dateFrom, m.dateTo = yesterday, yesterday - m.preset = timersPresetYesterday - m.fromInput.SetValue(yesterday) - m.toInput.SetValue(yesterday) - m.cursor = 0 - m.recomputeFiltered() + m.setRange(timersPresetYesterday, yesterday, yesterday) case key.Matches(msg, timersKeys.Week): now := time.Now().Local() @@ -740,26 +737,15 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { weekday = 7 } monday := now.AddDate(0, 0, -(weekday - 1)) - m.dateFrom = monday.Format("2006-01-02") - m.dateTo = now.Format("2006-01-02") - m.preset = timersPresetWeek - m.fromInput.SetValue(m.dateFrom) - m.toInput.SetValue(m.dateTo) - m.cursor = 0 - m.recomputeFiltered() + m.setRange(timersPresetWeek, monday.Format("2006-01-02"), now.Format("2006-01-02")) case key.Matches(msg, timersKeys.Month): now := time.Now().Local() - m.dateFrom = now.Format("2006-01") + "-01" - m.dateTo = now.Format("2006-01-02") - m.preset = timersPresetMonth - m.fromInput.SetValue(m.dateFrom) - m.toInput.SetValue(m.dateTo) - m.cursor = 0 - m.recomputeFiltered() + m.setRange(timersPresetMonth, now.Format("2006-01")+"-01", now.Format("2006-01-02")) case key.Matches(msg, timersKeys.Resume): if entry := m.selectedEntry(); entry != nil && !entry.IsRunning() { + m.selectRunning = true return m, m.startCmd(entry.ProjectID, entry.Task) } @@ -772,12 +758,7 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { m.detailOpen = false case key.Matches(msg, timersKeys.All): - m.dateFrom, m.dateTo = "", "" - m.preset = timersPresetAll - m.fromInput.SetValue("") - m.toInput.SetValue("") - m.cursor = 0 - m.recomputeFiltered() + m.setRange(timersPresetAll, "", "") case key.Matches(msg, timersKeys.Filter): m.mode = timersModeFilter @@ -789,6 +770,17 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { return m, nil } +// setRange shows the entries from from to to ("YYYY-MM-DD", "" for no +// bound), with the list scrolled back to its first entry. +func (m *TimersModel) setRange(p timersPreset, from, to string) { + m.preset = p + m.dateFrom, m.dateTo = from, to + m.fromInput.SetValue(from) + m.toInput.SetValue(to) + m.cursor, m.offset = 0, 0 + m.recomputeFiltered() +} + // openFormCmd loads clients+projects then opens the form. func (m TimersModel) openFormCmd(entryID int64) tea.Cmd { return func() tea.Msg { @@ -1003,6 +995,7 @@ func (m TimersModel) updateConfirm(msg tea.KeyMsg) (TimersModel, tea.Cmd) { // clients.go/projects.go's confirm-delete dispatch. case msg.String() == "y", msg.String() == "Y": m.mode = timersModeList + m.detailOpen = false e := m.selectedEntry() if e == nil { return m, nil @@ -1025,14 +1018,10 @@ func (m TimersModel) updateFilter(msg tea.KeyMsg) (TimersModel, tea.Cmd) { return m, nil case key.Matches(msg, timersKeys.Confirm): - m.dateFrom = strings.TrimSpace(m.fromInput.Value()) - m.dateTo = strings.TrimSpace(m.toInput.Value()) - m.preset = timersPresetCustom m.mode = timersModeList m.fromInput.Blur() m.toInput.Blur() - m.cursor = 0 - m.recomputeFiltered() + m.setRange(timersPresetCustom, strings.TrimSpace(m.fromInput.Value()), strings.TrimSpace(m.toInput.Value())) return m, nil case msg.Type == tea.KeyTab, msg.Type == tea.KeyShiftTab: diff --git a/internal/ui/views/timers_test.go b/internal/ui/views/timers_test.go index a9e43f8..554d22d 100644 --- a/internal/ui/views/timers_test.go +++ b/internal/ui/views/timers_test.go @@ -116,7 +116,7 @@ func TestRecomputeFiltered_ClampsCursor(t *testing.T) { } } -// ── buildLines / filteredTotals ─────────────────────────────────────────────── +// ── buildLines / sumEntries ─────────────────────────────────────────────── func TestBuildLines_GroupsByDay(t *testing.T) { c := mkClient(1, "Acme", 60) @@ -144,26 +144,21 @@ func TestBuildLines_GroupsByDay(t *testing.T) { } } -func TestFilteredTotals_IncludesRunningEntry(t *testing.T) { +// The footer total covers every filtered entry, across days, running one +// included at its time so far. +func TestSumEntries_IncludesRunningEntry(t *testing.T) { c := mkClient(1, "Acme", 60) // $60/hr p := mkProject(1, "Website", c) - // Entries deliberately span two different days — filteredTotals combines - // everything currently filtered regardless of day (that's the whole - // point: it backs the table's single footer total rather than a per-day - // one), unlike the old day-scoped dayTotals it replaced. + now := time.Date(2024, 5, 2, 12, 0, 0, 0, time.Local) finished := mkEntry(1, p, "a", time.Date(2024, 5, 1, 9, 0, 0, 0, time.Local), 30) // 30 min => $30 - running := mkRunningEntry(2, p, "b", time.Now().Add(-10*time.Minute)) + running := mkRunningEntry(2, p, "b", now.Add(-10*time.Minute)) // 10 min => $10 - m := TimersModel{filtered: []*model.Entry{finished, running}} - dur, earned := m.filteredTotals() - - wantDur := 30*time.Minute + running.Duration() - if dur < wantDur-time.Second || dur > wantDur+time.Second { - t.Errorf("filteredTotals duration = %v, want ~%v", dur, wantDur) + got := sumEntries([]*model.Entry{finished, running}, now) + if got.d != 40*time.Minute || got.x != 40 || !got.paid { + t.Errorf("sumEntries = %+v, want 40m, $40", got) } - wantEarned := 30.0 + running.Earnings(60) - if earned < wantEarned-0.05 || earned > wantEarned+0.05 { - t.Errorf("filteredTotals earnings = %v, want ~%v", earned, wantEarned) + if got.text() != "0:40:00 · $40.00" { + t.Errorf("text = %q", got.text()) } } @@ -2069,8 +2064,8 @@ func TestViewList_DayHeaderStaysStickyWhileScrolling(t *testing.T) { dayA := time.Date(2024, 5, 10, 20, 0, 0, 0, time.Local) dayB := dayA.AddDate(0, 0, -1) - labelA := friendlyDay(dayA) - labelB := friendlyDay(dayB) + labelA := friendlyDayAt(dayA, time.Now()) + labelB := friendlyDayAt(dayB, time.Now()) var entries []*model.Entry for i := 0; i < 8; i++ { @@ -2453,8 +2448,7 @@ func TestViewList_PaidAndInvoicedStatuses(t *testing.T) { func TestRenderDayHeaderLine_NarrowGapClamped(t *testing.T) { m := TimersModel{} - l := timersLine{day: time.Now()} - got := m.renderDayHeaderLine(l, 5) // contentW too small -> gap clamps to 0 + got := m.renderDayHeaderLine(time.Now(), 5, dayHeads{now: time.Now()}) // contentW too small -> gap clamps to 0 if got == "" { t.Fatal("renderDayHeaderLine produced empty output") } diff --git a/internal/ui/views/timers_view.go b/internal/ui/views/timers_view.go index 4a388d7..4be588d 100644 --- a/internal/ui/views/timers_view.go +++ b/internal/ui/views/timers_view.go @@ -23,6 +23,7 @@ import ( "github.com/aliasproject/notch/internal/status" "github.com/aliasproject/notch/internal/theme" "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" ) // ── Styled segments ─────────────────────────────────────────────────────────── @@ -133,18 +134,28 @@ func entryTimes(e *model.Entry, sep string) string { return clockTime(e.StartTime) + sep + end } -// earned is e's earnings at its client's usable rate, and whether it has a -// rate at all. -func earned(e *model.Entry) (float64, bool) { +// durationAt is e's length at now: a running entry's time so far, in whole +// seconds, so the hero, the rows and the day subtotals drawn from one now +// always agree. +func durationAt(e *model.Entry, now time.Time) time.Duration { + if e.EndTime != nil { + return e.EndTime.Sub(e.StartTime) + } + return max(0, now.Sub(e.StartTime).Truncate(time.Second)) +} + +// earned is e's earnings at now at its client's usable rate, and whether it +// has a rate at all. +func earned(e *model.Entry, now time.Time) (float64, bool) { rate := status.HourlyRate(e) if rate == 0 { return 0, false } - return e.Earnings(rate), true + return durationAt(e, now).Hours() * rate, true } -func earnedText(e *model.Entry) string { - if x, ok := earned(e); ok { +func earnedText(e *model.Entry, now time.Time) string { + if x, ok := earned(e, now); ok { return formatMoney(x) } return "—" @@ -257,37 +268,55 @@ func (m TimersModel) runningEntry() *model.Entry { return nil } -// dayTotals sums the filtered entries of one local day: their time, and -// their earnings rounded once, with ok false if none of them has a rate. -func (m TimersModel) dayTotals(day string) (time.Duration, float64, bool) { - return sumEntries(m.filtered, func(e *model.Entry) bool { - return e.StartTime.Local().Format("2006-01-02") == day - }) +// total is a set of entries' time, and their earnings rounded once, with +// paid false if none of them has a rate. +type total struct { + d time.Duration + x float64 + paid bool +} + +func (t total) duration() string { return model.FormatDuration(t.d) } + +func (t total) money() string { + if !t.paid { + return "—" + } + return formatMoney(t.x) } -func sumEntries(es []*model.Entry, keep func(*model.Entry) bool) (time.Duration, float64, bool) { - var d time.Duration - var x float64 - any := false +func (t total) text() string { return t.duration() + " · " + t.money() } + +func sumEntries(es []*model.Entry, now time.Time) total { + var t total for _, e := range es { - if !keep(e) { - continue - } - d += e.Duration() - if v, ok := earned(e); ok { - x += v - any = true + t.d += durationAt(e, now) + if v, ok := earned(e, now); ok { + t.x += v + t.paid = true } } - return d, status.Cents(x), any + t.x = status.Cents(t.x) + return t } -func totalsText(d time.Duration, x float64, ok bool) string { - money := "—" - if ok { - money = formatMoney(x) +// dayTotals sums the filtered entries by local day ("2006-01-02"), and +// returns the widest duration and amount among them, so every day header's +// subtotal lines up in the same two columns. +func (m TimersModel) dayTotals(now time.Time) (days map[string]total, durW, moneyW int) { + byDay := map[string][]*model.Entry{} + for _, e := range m.filtered { + k := e.StartTime.Local().Format("2006-01-02") + byDay[k] = append(byDay[k], e) } - return model.FormatDuration(d) + " · " + money + days = make(map[string]total, len(byDay)) + for k, es := range byDay { + t := sumEntries(es, now) + days[k] = t + durW = max(durW, lipgloss.Width(t.duration())) + moneyW = max(moneyW, lipgloss.Width(t.money())) + } + return days, durW, moneyW } // ── Layout ──────────────────────────────────────────────────────────────────── @@ -312,14 +341,14 @@ func (m TimersModel) tableWidth() int { return m.innerWidth() } -// Fixed list columns: the cursor gutter and the space after it, then -// DURATION, a gap, STATUS (wide layout), EARNED and a trailing space. +// Fixed list columns (design/tokens.json): the cursor gutter and the space +// after it, then DURATION, a gap, STATUS, EARNED and a trailing space. const ( tLead = theme.Gutter + 1 - tDuration = 10 - tGap = 2 - tStatus = 12 - tEarned = 10 + tDuration = theme.ColDuration + tGap = theme.ColGap + tStatus = theme.ColStatus + tEarned = theme.ColEarned tTrail = 1 ) @@ -337,15 +366,16 @@ func (m TimersModel) tableCols() (task, place, stat int) { return max(1, flex-stat), 0, stat } -// Fixed rows around the list: the hero (6 rows wide, 4 compact), a blank, +// Fixed rows around the list: the hero (tui-hero-rows, or +// tui-hero-rows-compact), a blank, // the range chips and a blank; then the column titles and a rule above the // rows, and a rule and the totals below. The compact layout also keeps a // blank and two summary rows at the bottom. func (m TimersModel) heroRows() int { if m.wide() { - return 6 + return theme.HeroRows } - return 4 + return theme.HeroRowsCompact } func (m TimersModel) fixedRows() int { @@ -386,12 +416,13 @@ func (m TimersModel) heroWide(w int, now time.Time) []string { statsW := 1 + labelW + 2 + valueW + 2 leftW := max(10, w-2-1-statsW) - var left [4][2][]seg // per row: left-aligned and right-aligned parts + var left [theme.HeroRows - 2][2][]seg // per row inside the borders: left- and right-aligned parts if r := m.runningEntry(); r != nil { - digits := blockText(model.FormatDuration(r.Duration())) + digits := blockText(model.FormatDuration(durationAt(r, now))) meta := "since " + clockTime(r.StartTime) if rate := status.HourlyRate(r); rate != 0 { - meta += " · " + formatRate(rate) + " · " + formatMoney(r.Earnings(rate)) + " so far" + x, _ := earned(r, now) + meta += " · " + formatRate(rate) + " · " + formatMoney(x) + " so far" } textW := max(1, leftW-2-lipgloss.Width(digits[0])-4) left[0] = [2][]seg{{{s: "NOW TRACKING", fg: cGreen, bold: true}}, {{s: digits[0], fg: cGreen, bold: true}}} @@ -406,7 +437,7 @@ func (m TimersModel) heroWide(w int, now time.Time) []string { } out := []string{boxTop(w)} - for i := 0; i < 4; i++ { + for i := range left { row := renderSegs(cBg, boxSide()) + spread(leftW, cBg, append([]seg{{s: " "}}, left[i][0]...), append(left[i][1], seg{s: " "})) + renderSegs(cBg, boxSide()) @@ -432,9 +463,9 @@ func (m TimersModel) heroCompact(w int, now time.Time) []string { t := m.heroTotalsAt(now) inner := max(10, w-2) today := "today " + model.FormatDuration(t.today) - var rows [2][2][]seg + var rows [theme.HeroRowsCompact - 2][2][]seg if r := m.runningEntry(); r != nil { - elapsed := model.FormatDuration(r.Duration()) + elapsed := model.FormatDuration(durationAt(r, now)) taskW := max(1, inner-2-2-lipgloss.Width(elapsed)-4) placeW := max(1, inner-4-lipgloss.Width(today)-4) rows[0] = [2][]seg{ @@ -459,39 +490,40 @@ func (m TimersModel) heroCompact(w int, now time.Time) []string { // ── Range chips ─────────────────────────────────────────────────────────────── type rangeChip struct { - label string - preset timersPreset + key, label string + preset timersPreset } func (m TimersModel) rangeChips() []rangeChip { + today := rangeChip{"t", "Today", timersPresetToday} + week := rangeChip{"w", "Week", timersPresetWeek} + month := rangeChip{"m", "Month", timersPresetMonth} + all := rangeChip{"a", "All", timersPresetAll} if m.wide() { - return []rangeChip{ - {"Today", timersPresetToday}, {"Week", timersPresetWeek}, {"Month", timersPresetMonth}, - {"All", timersPresetAll}, {"Custom…", timersPresetCustom}, - } - } - chips := []rangeChip{ - {"Today", timersPresetToday}, {"Week", timersPresetWeek}, {"All", timersPresetAll}, + return []rangeChip{today, week, month, all, {"f", "Custom…", timersPresetCustom}} } + chips := []rangeChip{today, week, all} // A preset with no chip of its own here (Month, or y's Yesterday) still // shows while it's the active one. switch m.preset { case timersPresetMonth: - chips = append(chips[:2], rangeChip{"Month", timersPresetMonth}, chips[2]) + chips = []rangeChip{today, week, month, all} case timersPresetYesterday: - chips = append([]rangeChip{chips[0], {"Yesterday", timersPresetYesterday}}, chips[1:]...) + chips = []rangeChip{today, {"y", "Yesterday", timersPresetYesterday}, week, all} } - return append(chips, rangeChip{"…", timersPresetCustom}) + return append(chips, rangeChip{"f", "…", timersPresetCustom}) } func (m TimersModel) renderRangeChips(w int, now time.Time) string { left := []seg{{s: "Range", fg: cSubtle}, {s: " "}} + // Each chip's key sits just before it, in subtle, so the range keys + // stay on screen. for _, c := range m.rangeChips() { chip := seg{s: " " + c.label + " ", fg: cDim} if c.preset == m.preset { chip = seg{s: chip.s, fg: cBg, bg: cPrimary, bold: true} } - left = append(left, seg{s: " "}, chip) + left = append(left, seg{s: " "}, seg{s: c.key, fg: cSubtle}, chip) } var right []seg if m.preset == timersPresetCustom || m.preset == timersPresetYesterday { @@ -530,14 +562,22 @@ func rule(tw int, above, below bool) string { return renderSegs(cBg, seg{s: string(runes), fg: cBorder}) } -func (m TimersModel) renderDayHeaderLine(l timersLine, tw int) string { - d, x, ok := m.dayTotals(l.day.Format("2006-01-02")) +// dayHeads is what every day header in one frame shares: the subtotals and +// the widths that line their two columns up. +type dayHeads struct { + days map[string]total + durW, moneyW int + now time.Time +} + +func (m TimersModel) renderDayHeaderLine(day time.Time, tw int, h dayHeads) string { + t := h.days[day.Format("2006-01-02")] return spread(tw, cBg, - []seg{{s: " "}, {s: friendlyDay(l.day), fg: cPrimary, bold: true}}, - []seg{{s: totalsText(d, x, ok), fg: cSubtle}, {s: " "}}) + []seg{{s: " "}, {s: friendlyDayAt(day, h.now), fg: cPrimary, bold: true}}, + []seg{{s: fitRight(t.duration(), h.durW) + " · " + fitRight(t.money(), h.moneyW), fg: cSubtle}, {s: " "}}) } -func (m TimersModel) renderEntryRow(e *model.Entry, sel bool, tw int) string { +func (m TimersModel) renderEntryRow(e *model.Entry, sel bool, tw int, now time.Time) string { task, place, stat := m.tableCols() bg := cBg lead := seg{s: strings.Repeat(" ", tLead)} @@ -545,7 +585,7 @@ func (m TimersModel) renderEntryRow(e *model.Entry, sel bool, tw int) string { bg = cBgAlt lead = seg{s: theme.GlyphCursor + strings.Repeat(" ", tLead-lipgloss.Width(theme.GlyphCursor)), fg: cPrimary} } - durSeg := seg{s: fitRight(model.FormatDuration(e.Duration()), tDuration)} + durSeg := seg{s: fitRight(model.FormatDuration(durationAt(e, now)), tDuration)} if e.IsRunning() { durSeg.fg, durSeg.bold = cGreen, true } @@ -558,19 +598,19 @@ func (m TimersModel) renderEntryRow(e *model.Entry, sel bool, tw int) string { durSeg, seg{s: strings.Repeat(" ", tGap)}, seg{s: fit(statText, stat), fg: statFg}, - seg{s: fitRight(earnedText(e), tEarned), fg: cDim}, + seg{s: fitRight(earnedText(e, now), tEarned), fg: cDim}, ) return spread(tw, bg, segs, nil) } -func (m TimersModel) renderListFoot(tw int) []string { +func (m TimersModel) renderListFoot(tw int, now time.Time) []string { n := len(m.filtered) - d, x, ok := sumEntries(m.filtered, func(*model.Entry) bool { return true }) + all := sumEntries(m.filtered, now) return []string{ rule(tw, false, false), spread(tw, cBg, []seg{{s: " "}, {s: fmt.Sprintf("%d %s", n, plural(n, "entry", "entries")), fg: cSubtle}}, - []seg{{s: "Total " + totalsText(d, x, ok), bold: true}, {s: " "}}), + []seg{{s: "Total " + all.text(), bold: true}, {s: " "}}), } } @@ -584,7 +624,9 @@ func plural(n int, one, many string) string { // renderList is the list's column titles, its window of day headers and // entries (with a sticky day header when the window starts mid-day), and // the totals: always the same height while scrolling. -func (m TimersModel) renderList(tw int) []string { +func (m TimersModel) renderList(tw int, now time.Time) []string { + h := dayHeads{now: now} + h.days, h.durW, h.moneyW = m.dayTotals(now) out := m.renderTableHead(tw) lines := m.buildLines() budget := m.rowsBudget() @@ -595,14 +637,14 @@ func (m TimersModel) renderList(tw int) []string { rows := 0 if len(visible) > 0 && visible[0].kind != timersLineHeader { e := m.filtered[visible[0].entryIdx] - out = append(out, m.renderDayHeaderLine(timersLine{kind: timersLineHeader, day: e.StartTime.Local()}, tw)) + out = append(out, m.renderDayHeaderLine(e.StartTime.Local(), tw, h)) rows++ } for _, l := range visible { if l.kind == timersLineHeader { - out = append(out, m.renderDayHeaderLine(l, tw)) + out = append(out, m.renderDayHeaderLine(l.day, tw, h)) } else { - out = append(out, m.renderEntryRow(m.filtered[l.entryIdx], l.entryIdx == m.cursor, tw)) + out = append(out, m.renderEntryRow(m.filtered[l.entryIdx], l.entryIdx == m.cursor, tw, now)) } rows++ } @@ -611,7 +653,7 @@ func (m TimersModel) renderList(tw int) []string { out = append(out, blankLine(tw)) } } - return append(out, m.renderListFoot(tw)...) + return append(out, m.renderListFoot(tw, now)...) } // ── Detail pane ─────────────────────────────────────────────────────────────── @@ -631,23 +673,47 @@ func detailKeys(e *model.Entry) [][2]string { return [][2]string{{"i", inv}, {"p", paid}, {"e", "edit"}, {"r", "resume"}, {"d", "delete"}} } -// detailNoteRows caps how many rows the Notes field takes in the pane. -const detailNoteRows = 3 +// boxRow is one row of the detail box and how readily it goes when the box +// must fit fewer rows: 0 never goes (the borders, the task and the keys); +// higher numbers go first. +type boxRow struct { + s string + drop int +} + +// Drop ranks, highest first: spacing, then the extra lines of a long note, +// then the fields the list or summary already shows, then the rest. The +// borders, the task and the keys always stay, so the box stays closed and +// every key stays reachable. +const ( + dropSpacing = 9 + dropMoreNotes = 8 + dropSpacer = 7 + dropRate = 6 + dropPlace = 5 + dropDate = 4 + dropRule = 3 + dropMoney = 2 + dropCore = 1 +) -func (m TimersModel) renderDetailBox(e *model.Entry, w int) []string { +// renderDetailBox draws e's detail box w wide and at most rows tall, +// dropping rows by rank to fit (see boxRow). It returns nil when even the +// borders, the task and the keys don't fit, or rows is 0 or less. +func (m TimersModel) renderDetailBox(e *model.Entry, w, rows int, now time.Time) []string { inner := max(10, w-2) - const labelW = 10 + labelW := theme.DetailLabel valueW := max(1, inner-2-labelW) side := renderSegs(cBg, boxSide()) row := func(segs ...seg) string { return side + spread(inner, cBg, append([]seg{{s: " "}}, segs...), []seg{{s: " "}}) + side } - field := func(label string, value seg) string { + field := func(label string, value seg, drop int) boxRow { value.s = truncate(value.s, valueW) if value.fg == "" { value.fg = cDim } - return row(seg{s: fit(label, labelW), fg: cSubtle}, value) + return boxRow{row(seg{s: fit(label, labelW), fg: cSubtle}, value), drop} } title := " Entry " @@ -667,57 +733,66 @@ func (m TimersModel) renderDetailBox(e *model.Entry, w int) []string { client = e.Project.Client.Name } } - earnedSeg := seg{s: earnedText(e), fg: cText, bold: true} - out := []string{top, row(), - field("Task", seg{s: e.Task, fg: cText, bold: true}), - field("Client", seg{s: client}), - field("Project", seg{s: project}), - field("Date", seg{s: e.StartTime.Local().Format("Mon, Jan 2")}), - field("Time", seg{s: entryTimes(e, " – ")}), - field("Duration", seg{s: model.FormatDuration(e.Duration())}), - field("Rate", seg{s: rate}), - field("Earned", earnedSeg), - field("Status", seg{s: statText, fg: statFg}), + box := []boxRow{{top, 0}, {row(), dropSpacing}, + field("Task", seg{s: e.Task, fg: cText, bold: true}, 0), + field("Client", seg{s: client}, dropPlace), + field("Project", seg{s: project}, dropPlace), + field("Date", seg{s: e.StartTime.Local().Format("Mon, Jan 2")}, dropDate), + field("Time", seg{s: entryTimes(e, " – ")}, dropCore), + field("Duration", seg{s: model.FormatDuration(durationAt(e, now))}, dropRate), + field("Rate", seg{s: rate}, dropRate), + field("Earned", seg{s: earnedText(e, now), fg: cText, bold: true}, dropMoney), + field("Status", seg{s: statText, fg: statFg}, dropCore), } notes := wrapWords(strings.TrimSpace(e.Notes), valueW) if len(notes) == 0 { notes = []string{"—"} } - if len(notes) > detailNoteRows { - notes = notes[:detailNoteRows] - notes[detailNoteRows-1] = truncate(notes[detailNoteRows-1]+" …", valueW) + if len(notes) > theme.DetailNoteRows { + notes = notes[:theme.DetailNoteRows] + notes[len(notes)-1] = truncate(notes[len(notes)-1]+" …", valueW) } for i, n := range notes { - label := "" + label, drop := "", dropMoreNotes if i == 0 { - label = "Notes" + label, drop = "Notes", dropDate } - out = append(out, field(label, seg{s: n})) + box = append(box, field(label, seg{s: n}, drop)) } - out = append(out, row(), row(seg{s: strings.Repeat("─", max(0, inner-2)), fg: cBorder})) + box = append(box, boxRow{row(), dropSpacer}, boxRow{row(seg{s: strings.Repeat("─", max(0, inner-2)), fg: cBorder}), dropRule}) for _, k := range detailKeys(e) { - out = append(out, row(seg{s: " " + k[0] + " ", bg: cBgAlt, bold: true}, seg{s: " " + k[1], fg: cSubtle})) + box = append(box, boxRow{row(seg{s: " " + k[0] + " ", bg: cBgAlt, bold: true}, seg{s: " " + k[1], fg: cSubtle}), 0}) } - return append(out, row(), boxBottom(w)) + box = append(box, boxRow{row(), dropSpacing}, boxRow{boxBottom(w), 0}) + return fitBox(box, rows) } -// fitPane keeps a detail box within rows on a short terminal: it drops -// the key list (its rule, keys and the blank after them) first, then cuts -// the fields and closes the box. -func fitPane(box []string, rows, keys int) []string { - if rows <= 0 || len(box) <= rows { - return box +// fitBox drops rows from box, highest rank first and the last of a rank +// first, until it fits in rows. It returns nil when it can't, and for rows +// of 0 or less: no box at all rather than one past the bottom. +func fitBox(box []boxRow, rows int) []string { + if rows <= 0 { + return nil } - // The key block is the rule, the keys and a blank, just above the - // bottom border. - if cut := keys + 2; len(box)-cut <= rows && len(box) > cut+1 { - return append(append([]string{}, box[:len(box)-1-cut]...), box[len(box)-1]) + box = append([]boxRow(nil), box...) + for len(box) > rows { + at := -1 + for i, r := range box { + if r.drop > 0 && (at < 0 || r.drop >= box[at].drop) { + at = i + } + } + if at < 0 { + return nil + } + box = append(box[:at], box[at+1:]...) } - if rows < 3 { - return nil + out := make([]string, len(box)) + for i, r := range box { + out[i] = r.s } - return append(append([]string{}, box[:rows-1]...), box[len(box)-1]) + return out } // wrapWords wraps s into lines of at most w cells, breaking at spaces and @@ -731,13 +806,16 @@ func wrapWords(s string, w int) []string { line := "" for _, word := range strings.Fields(para) { for lipgloss.Width(word) > w { - r := []rune(word) if line != "" { out = append(out, line) line = "" } - out = append(out, string(r[:w])) - word = string(r[w:]) + head := ansi.Truncate(word, w, "") + if head == "" { // a character wider than w + head = string([]rune(word)[:1]) + } + out = append(out, head) + word = strings.TrimPrefix(word, head) } switch { case line == "": @@ -801,11 +879,11 @@ func (m TimersModel) viewListAt(now time.Time) string { } tw := m.tableWidth() - list := m.renderList(tw) + list := m.renderList(tw, now) if m.wide() { var pane []string if e := m.selectedEntry(); e != nil { - pane = fitPane(m.renderDetailBox(e, theme.DetailWidth), m.innerHeight()-len(out), len(detailKeys(e))) + pane = m.renderDetailBox(e, theme.DetailWidth, m.innerHeight()-len(out), now) } for i := 0; i < max(len(list), len(pane)); i++ { l, p := blankLine(tw), blankLine(theme.DetailWidth) @@ -833,7 +911,9 @@ func (m TimersModel) viewListAt(now time.Time) string { } case m.detailOpen && !m.wide(): if e := m.selectedEntry(); e != nil { - body = centerOverlay(body, strings.Join(m.renderDetailBox(e, theme.DetailWidth), "\n")) + if box := m.renderDetailBox(e, theme.DetailWidth, m.innerHeight(), now); box != nil { + body = centerOverlay(body, strings.Join(box, "\n")) + } } } return body diff --git a/internal/ui/views/timers_view_test.go b/internal/ui/views/timers_view_test.go index 5100d46..941573b 100644 --- a/internal/ui/views/timers_view_test.go +++ b/internal/ui/views/timers_view_test.go @@ -86,20 +86,56 @@ func TestFormatMoney(t *testing.T) { } // Each day's header carries its subtotal: time and money, or "—" when no -// entry that day has a rate. -func TestDayHeaders_ShowSubtotals(t *testing.T) { +// entry that day has a rate. The subtotals line up in two right-aligned +// columns, "—" included. +func TestDayHeaders_ShowAlignedSubtotals(t *testing.T) { m := boardTimers(140, 36) got := plain(m.viewListAt(time.Now())) for _, want := range []*regexp.Regexp{ - regexp.MustCompile(`Mon Dec 2 +5:05:00 · \$610\.00`), - regexp.MustCompile(`Sun Dec 1 +2:10:00 · —`), - regexp.MustCompile(`Sat Nov 30 +1:00:00 · \$95\.00`), + regexp.MustCompile(`Mon Dec 2 +5:05:00 · \$610\.00 `), + regexp.MustCompile(`Sun Dec 1 +2:10:00 · +— `), + regexp.MustCompile(`Sat Nov 30 +1:00:00 · +\$95\.00 `), regexp.MustCompile(`7 entries +Total `), } { if !want.MatchString(got) { t.Errorf("list should match %s, got:\n%s", want, got) } } + dot := -1 + for _, l := range strings.Split(got, "\n") { + if !regexp.MustCompile(`^ (Today|Mon Dec 2|Sun Dec 1|Sat Nov 30) `).MatchString(l) { + continue + } + col := len([]rune(l[:strings.Index(l, "·")])) + if dot >= 0 && col != dot { + t.Errorf("day header %q has its · at column %d, others at %d", l, col, dot) + } + dot = col + } + if dot < 0 { + t.Fatal("no day headers found") + } +} + +// The hero and the list take every running time from the same now, so the +// hero's Today and today's subtotal can't differ by a second. +func TestHeroAndDaySubtotal_AgreeOnRunningTime(t *testing.T) { + m := boardTimers(140, 36) + now := time.Now() + for i, e := range m.entries { + if e.IsRunning() { + r := *e + r.StartTime = now.Add(-(83*time.Minute + 46*time.Second + 600*time.Millisecond)) + m.entries[i] = &r + } + } + m.recomputeFiltered() + got := plain(m.viewListAt(now)) + hero := regexp.MustCompile(`Today +(\d+:\d\d:\d\d)`).FindStringSubmatch(got) + day := regexp.MustCompile(`(?m)^ Today +(\d+:\d\d:\d\d) ·`).FindStringSubmatch(got) + if hero == nil || day == nil || hero[1] != day[1] || hero[1] != "1:23:46" { + t.Errorf("hero Today %v and the Today subtotal %v should both be 1:23:46:\n%s", hero, day, got) + } } func TestViewList_WideLayout(t *testing.T) { @@ -234,20 +270,195 @@ func TestHeroTotals(t *testing.T) { } } -// On a short terminal the wide layout's detail pane drops its key list -// before it would run past the bottom. +// On a short terminal the wide layout's detail pane drops spacing and +// lesser fields to fit, keeping its borders and every key; with no room at +// all it isn't drawn. func TestDetailPane_FitsShortTerminal(t *testing.T) { tall := boardTimers(140, 36) - short := boardTimers(140, 26) - if !strings.Contains(plain(tall.viewListAt(time.Now())), "r resume") { - t.Fatal("a tall terminal should show the pane's keys") + if got := plain(tall.viewListAt(time.Now())); !strings.Contains(got, "Rate ") || !strings.Contains(got, "r resume") { + t.Fatalf("a tall terminal should show the whole pane:\n%s", got) } + short := boardTimers(140, 26) got := plain(short.viewListAt(time.Now())) if n := len(strings.Split(got, "\n")); n > short.innerHeight() { t.Errorf("short terminal: %d lines, more than %d", n, short.innerHeight()) } - if strings.Contains(got, "r resume") || !strings.Contains(got, "╰") { - t.Errorf("short terminal: the pane should drop its keys and stay closed:\n%s", got) + for _, want := range []string{"╭─ Entry", "Logo explorations", "i mark invoiced", "r resume", "d delete"} { + if !strings.Contains(got, want) { + t.Errorf("short terminal: the pane lost %q:\n%s", want, got) + } + } + if strings.Contains(got, "Rate ") || strings.Count(got, "╰") != 2 { // the hero's and the pane's + t.Errorf("short terminal: the pane should drop Rate and stay closed:\n%s", got) + } + + tiny := boardTimers(140, 10) + if got := plain(tiny.viewListAt(time.Now())); strings.Contains(got, "╭─ Entry") { + t.Errorf("no room for the pane: it should be hidden:\n%s", got) + } +} + +func TestFitBox(t *testing.T) { + box := []boxRow{{"top", 0}, {"blank", dropSpacing}, {"task", 0}, {"rate", dropRate}, {"key", 0}, {"bottom", 0}} + for rows, want := range map[int]string{ + -3: "", 0: "", 3: "", + 4: "top|task|key|bottom", 5: "top|task|rate|key|bottom", 6: "top|blank|task|rate|key|bottom", 9: "top|blank|task|rate|key|bottom", + } { + if got := strings.Join(fitBox(box, rows), "|"); got != want { + t.Errorf("fitBox(rows=%d) = %q, want %q", rows, got, want) + } + } +} + +// At 80×24 (a 20-row body) the compact layout's details still fit: border, +// task and every key, with lesser rows dropped. +func TestDetailOverlay_FitsBody(t *testing.T) { + m := boardTimers(80, 20) + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + got := plain(m.viewListAt(time.Now())) + lines := strings.Split(got, "\n") + if len(lines) != m.innerHeight() { + t.Errorf("%d lines, want %d", len(lines), m.innerHeight()) + } + // The box's top and bottom corners share a column. + top, bottom, col := -1, -1, -1 + for i, l := range lines { + r := []rune(l) + if j := strings.Index(l, "╭─ Entry"); j >= 0 && top < 0 { + top, col = i, len([]rune(l[:j])) + } else if top >= 0 && bottom < 0 && col < len(r) && r[col] == '╰' { + bottom = i + } + } + if top < 0 || bottom < 0 { + t.Fatalf("the overlay should open and close inside the body:\n%s", got) + } + var box string + for _, l := range lines[top : bottom+1] { + box += string([]rune(l)[col:col+theme.DetailWidth]) + "\n" + } + for _, want := range []string{"Logo explorations", "i mark invoiced", "p mark paid", "e edit", "r resume", "d delete"} { + if !strings.Contains(box, want) { + t.Errorf("overlay lost %q:\n%s", want, box) + } + } +} + +// Each range chip shows its key, so t w m a f (and y) stay discoverable. +func TestRangeChips_ShowKeys(t *testing.T) { + wide := boardTimers(140, 36) + got := plain(wide.renderRangeChips(wide.innerWidth(), time.Now())) + for _, want := range []string{"t Today ", "w Week ", "m Month ", "a All ", "f Custom… "} { + if !strings.Contains(got, want) { + t.Errorf("wide chips %q are missing %q", got, want) + } + } + compact := boardTimers(90, 28) + compact, _ = compact.Update(runeKey('y')) + got = plain(compact.renderRangeChips(compact.innerWidth(), time.Now())) + for _, want := range []string{"t Today ", "y Yesterday ", "w Week ", "a All ", "f … "} { + if !strings.Contains(got, want) { + t.Errorf("compact chips %q are missing %q", got, want) + } + } +} + +// A range key scrolls the list back to its top as well as moving the cursor. +func TestRangeKey_ResetsOffset(t *testing.T) { + m := boardTimers(90, 22) + for range m.filtered { + m, _ = m.Update(runeKey('j')) + } + if m.offset == 0 { + t.Fatal("setup: the list should have scrolled") + } + for _, k := range []rune{'a', 't', 'w', 'm', 'y'} { + m.offset, m.cursor = 5, 3 + m, _ = m.Update(runeKey(k)) + if m.offset != 0 || m.cursor != 0 { + t.Errorf("%c: offset %d, cursor %d; want 0, 0", k, m.offset, m.cursor) + } + } +} + +// The compact details close when an edit or delete starts from them. +func TestDetailOpen_ClearedByEditAndDelete(t *testing.T) { + m := boardTimers(90, 28) + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m, _ = m.Update(runeKey('e')) + if m.detailOpen { + t.Error("e should close the details") + } + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m, _ = m.Update(runeKey('d')) + m, _ = m.Update(runeKey('y')) + if m.detailOpen { + t.Error("confirming a delete should close the details") + } + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + if m = m.CloseDetail(); m.detailOpen { + t.Error("CloseDetail should close the details") + } +} + +// A reload keeps the cursor on the same entry; after r or space starts a +// timer, the reload selects the new running entry. +func TestReload_KeepsSelectionByID(t *testing.T) { + m := boardTimers(140, 36) // cursor on "Logo explorations", ID 2 + c := mkClient(9, "New", 50) + newer := mkEntry(99, mkProject(9, "P", c), "Arrived from elsewhere", time.Now().Add(-time.Hour), 5) + m, _ = m.Update(timerEntriesMsg(append([]*model.Entry{newer}, m.entries...))) + if e := m.selectedEntry(); e == nil || e.ID != 2 { + t.Fatalf("after a reload the cursor is on %+v, want entry 2", e) + } + + for _, k := range []tea.KeyMsg{runeKey('r'), {Type: tea.KeySpace, Runes: []rune{' '}}} { + m := m + m, _ = m.Update(k) + // The started timer comes back as a new running entry; the old one + // is stopped. + var reloaded []*model.Entry + for _, e := range m.entries { + e := *e + if e.IsRunning() { + end := time.Now() + e.EndTime = &end + } + reloaded = append(reloaded, &e) + } + started := mkRunningEntry(100, m.selectedEntry().Project, m.selectedEntry().Task, time.Now()) + m, _ = m.Update(timerEntriesMsg(append([]*model.Entry{started}, reloaded...))) + if e := m.selectedEntry(); e == nil || e.ID != 100 { + t.Errorf("%q: after the start, the cursor is on %+v, want the new running entry", k.String(), e) + } + } +} + +// Rows cut long text by display width, not runes, so wide characters +// can't push a row past its columns. +func TestRows_WideCharactersStayInColumns(t *testing.T) { + for _, w := range []int{140, 90} { + m := boardTimers(w, 36) + for _, e := range m.entries { + e.Task = "日本語のタスク名がとても長い場合 🎉🎉🎉🎉" + } + m.entries[1].Project.Client.Name = "株式会社サンプルクライアント" + for i, l := range strings.Split(m.viewListAt(time.Now()), "\n") { + if got := lipgloss.Width(l); got != m.innerWidth() { + t.Errorf("%d cols, line %d is %d wide, want %d: %q", w, i, got, m.innerWidth(), plain(l)) + } + } + } +} + +func TestHeroRows_FromTokens(t *testing.T) { + m := boardTimers(140, 36) + if got := len(m.heroWide(m.innerWidth(), time.Now())); got != theme.HeroRows { + t.Errorf("wide hero is %d rows, want %d", got, theme.HeroRows) + } + c := boardTimers(90, 28) + if got := len(c.heroCompact(c.innerWidth(), time.Now())); got != theme.HeroRowsCompact { + t.Errorf("compact hero is %d rows, want %d", got, theme.HeroRowsCompact) } } From 61a8efe11154d4687c0d5716446b36dacedefc5a Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 08:24:36 -0700 Subject: [PATCH 04/13] Select a started timer by its ID, not by a flag in the model (ALI-2615) r and space set selectRunning on the model, and whichever entry list arrived next used it up. A failed start left it set, so the next unrelated reload jumped the cursor to whatever was running; a watcher reload landing between StopAllRunning and StartEntry used it up before the new entry existed, so the start's own list didn't select it. startCmd now returns timerStartedMsg with the new entry's ID, and only that message selects it. Nothing is left in the model to go stale. --- internal/ui/views/timers.go | 65 +++++++++++-------- internal/ui/views/timers_start_test.go | 86 ++++++++++++++++++++++++++ internal/ui/views/timers_view_test.go | 64 ++++++++++++++++++- 3 files changed, 188 insertions(+), 27 deletions(-) create mode 100644 internal/ui/views/timers_start_test.go diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index 1d310b6..7798321 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -340,11 +340,16 @@ type TimersModel struct { // the compact layout (enter opens it, enter or esc closes it). The wide // layout always shows the pane. detailOpen bool +} - // selectRunning moves the cursor to the running entry when the next - // entry list arrives: set when r or space starts a timer, so the new - // entry is the one selected. - selectRunning bool +// timerStartedMsg is the entry list after this view started a timer, with +// the new entry's ID, so that list (and no other) selects it. Carrying the +// ID in the message, not in model state, means a failed start leaves +// nothing behind, and a reload landing before the new entry exists can't +// use the selection up. +type timerStartedMsg struct { + entries []*model.Entry + id int64 } // CloseDetail closes the compact layout's detail pane; the app calls it on @@ -389,6 +394,11 @@ func NewTimers(database *db.DB) TimersModel { func (m *TimersModel) SetSize(w, h int) { m.width = w m.height = h + // The wide layout always shows the pane, so an overlay opened while + // compact closes rather than coming back after a later narrowing. + if m.wide() { + m.detailOpen = false + } } // selectedEntry returns the entry under the cursor, or nil if filtered is @@ -626,27 +636,16 @@ func (m TimersModel) Update(msg tea.Msg) (TimersModel, tea.Cmd) { case timerEntriesMsg: // Keep the cursor on the same entry, by ID, when the list reloads - // (a tick, another process's change, or this view's own action); - // after r or space starts a timer, move it to the new running one. + // (a tick, another process's change, or this view's own action). var keepID int64 if e := m.selectedEntry(); e != nil { keepID = e.ID } - m.entries = []*model.Entry(msg) - m.recomputeFiltered() - want := func(e *model.Entry) bool { return e.ID == keepID } - if m.selectRunning { - want = func(e *model.Entry) bool { return e.IsRunning() } - m.selectRunning = false - } - for i, e := range m.filtered { - if want(e) { - m.cursor = i - break - } - } - m.clampOffset() - return m, nil + return m.setEntries(msg, keepID), nil + + case timerStartedMsg: + // After r or space starts a timer, select the new entry. + return m.setEntries(msg.entries, msg.id), nil case openFormMsg: m = m.handleOpenForm(msg) @@ -684,6 +683,7 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { } case key.Matches(msg, timersKeys.New): + m.detailOpen = false return m, m.openFormCmd(0) case key.Matches(msg, timersKeys.Edit): @@ -702,7 +702,6 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { if entry.IsRunning() { return m, m.stopCmd(entry.ID) } - m.selectRunning = true return m, m.startCmd(entry.ProjectID, entry.Task) } @@ -745,7 +744,6 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { case key.Matches(msg, timersKeys.Resume): if entry := m.selectedEntry(); entry != nil && !entry.IsRunning() { - m.selectRunning = true return m, m.startCmd(entry.ProjectID, entry.Task) } @@ -770,6 +768,22 @@ func (m TimersModel) updateList(msg tea.KeyMsg) (TimersModel, tea.Cmd) { return m, nil } +// setEntries replaces the entry list and puts the cursor on the entry with +// ID id when the range shows it (otherwise where recomputeFiltered clamps +// it). +func (m TimersModel) setEntries(entries []*model.Entry, id int64) TimersModel { + m.entries = entries + m.recomputeFiltered() + for i, e := range m.filtered { + if e.ID == id { + m.cursor = i + break + } + } + m.clampOffset() + return m +} + // setRange shows the entries from from to to ("YYYY-MM-DD", "" for no // bound), with the list scrolled back to its first entry. func (m *TimersModel) setRange(p timersPreset, from, to string) { @@ -1069,12 +1083,13 @@ func (m TimersModel) startCmd(projectID int64, task string) tea.Cmd { if err := m.db.StopAllRunning(); err != nil { return ErrMsg(err.Error()) } - if _, err := m.db.StartEntry(projectID, task); err != nil { + e, err := m.db.StartEntry(projectID, task) + if err != nil { return ErrMsg(err.Error()) } return tea.BatchMsg{ func() tea.Msg { return RunningChangedMsg{} }, - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, + func() tea.Msg { return timerStartedMsg{entries: mustLoadEntries(m.db), id: e.ID} }, func() tea.Msg { return StatusMsg("Timer started") }, } } diff --git a/internal/ui/views/timers_start_test.go b/internal/ui/views/timers_start_test.go new file mode 100644 index 0000000..300e90b --- /dev/null +++ b/internal/ui/views/timers_start_test.go @@ -0,0 +1,86 @@ +package views + +import ( + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" +) + +// startRaceTimers is a Timers list on a real database with two finished +// entries, the All range, and the cursor on the older one ("older"). +func startRaceTimers(t *testing.T) TimersModel { + t.Helper() + d := newTestDB(t) + c, err := d.CreateClient("Acme", 100) + if err != nil { + t.Fatal(err) + } + p, err := d.CreateProject(c.ID, "Web") + if err != nil { + t.Fatal(err) + } + now := time.Now() + for i, task := range []string{"older", "newer"} { + start := now.Add(-time.Duration(4-i) * time.Hour) + end := start.Add(30 * time.Minute) + if _, err := d.AddEntry(p.ID, task, "", start, &end); err != nil { + t.Fatal(err) + } + } + m := NewTimers(d) + m.SetSize(140, 36) + m, _ = m.Update(loadTimerEntriesCmd(d)()) + m, _ = m.Update(runeKey('a')) + m, _ = m.Update(runeKey('j')) + if e := m.selectedEntry(); e == nil || e.Task != "older" { + t.Fatalf("setup: cursor on %+v, want older", e) + } + return m +} + +// feed runs cmd and every command it batches, feeding each message to m. +func feed(m TimersModel, cmd tea.Cmd) TimersModel { + if cmd == nil { + return m + } + switch msg := cmd().(type) { + case tea.BatchMsg: + for _, c := range msg { + m = feed(m, c) + } + default: + m, _ = m.Update(msg) + } + return m +} + +// A start that fails leaves nothing behind: a later reload, even one with a +// timer another process started, keeps the cursor where it was. +func TestStart_FailedStartDoesNotMoveLaterReloads(t *testing.T) { + m := startRaceTimers(t) + m, _ = m.Update(runeKey('r')) // its command fails: never run it + m, _ = m.Update(ErrMsg("database is locked")) + if _, err := m.db.StartEntry(m.entries[0].ProjectID, "from the bar widget"); err != nil { + t.Fatal(err) + } + m, _ = m.Update(loadTimerEntriesCmd(m.db)()) + if e := m.selectedEntry(); e == nil || e.Task != "older" { + t.Errorf("after a failed start and an unrelated reload, the cursor is on %+v, want older", e) + } +} + +// A watcher reload that lands before the new entry exists doesn't use up +// the start's selection: the start's own result still selects the new entry. +func TestStart_SelectsNewEntryDespiteEarlierReload(t *testing.T) { + for _, k := range []tea.KeyMsg{runeKey('r'), {Type: tea.KeySpace, Runes: []rune{' '}}} { + m := startRaceTimers(t) + m, cmd := m.Update(k) + m, _ = m.Update(loadTimerEntriesCmd(m.db)()) // the watcher, first + m = feed(m, cmd) + e := m.selectedEntry() + if e == nil || !e.IsRunning() || e.Task != "older" { + t.Errorf("%q: after the start, the cursor is on %+v, want the new running \"older\"", k.String(), e) + } + } +} diff --git a/internal/ui/views/timers_view_test.go b/internal/ui/views/timers_view_test.go index 941573b..866f3f2 100644 --- a/internal/ui/views/timers_view_test.go +++ b/internal/ui/views/timers_view_test.go @@ -1,6 +1,7 @@ package views import ( + "fmt" "regexp" "strings" "testing" @@ -402,7 +403,8 @@ func TestDetailOpen_ClearedByEditAndDelete(t *testing.T) { } // A reload keeps the cursor on the same entry; after r or space starts a -// timer, the reload selects the new running entry. +// timer, the start's own result selects the new entry. (The races around +// that are in timers_start_test.go.) func TestReload_KeepsSelectionByID(t *testing.T) { m := boardTimers(140, 36) // cursor on "Logo explorations", ID 2 c := mkClient(9, "New", 50) @@ -427,7 +429,7 @@ func TestReload_KeepsSelectionByID(t *testing.T) { reloaded = append(reloaded, &e) } started := mkRunningEntry(100, m.selectedEntry().Project, m.selectedEntry().Task, time.Now()) - m, _ = m.Update(timerEntriesMsg(append([]*model.Entry{started}, reloaded...))) + m, _ = m.Update(timerStartedMsg{entries: append([]*model.Entry{started}, reloaded...), id: started.ID}) if e := m.selectedEntry(); e == nil || e.ID != 100 { t.Errorf("%q: after the start, the cursor is on %+v, want the new running entry", k.String(), e) } @@ -471,3 +473,61 @@ func TestWrapWords(t *testing.T) { t.Errorf("long word: %q", got) } } + +// The wide layout needs the width and the rows for its pane: one row short, +// a wide terminal gets the compact layout instead of a blank pane column. +func TestWide_NeedsRoomForThePane(t *testing.T) { + // innerHeight = height-2; the pane starts below the hero and the chips. + need := theme.HeroRows + chipRows + paneMinRows() + 2 + short := boardTimers(130, need-1) + got := plain(short.viewListAt(time.Now())) + if short.wide() || strings.Contains(got, "NOW TRACKING") || !strings.Contains(got, "enter for details") { + t.Errorf("130×%d should get the compact layout:\n%s", need-1, got) + } + tall := boardTimers(130, need) + got = plain(tall.viewListAt(time.Now())) + for _, want := range []string{"NOW TRACKING", "╭─ Entry", "Logo explorations", "i mark invoiced", "d delete"} { + if !tall.wide() || !strings.Contains(got, want) { + t.Errorf("130×%d should get the wide layout with the whole pane (missing %q):\n%s", need, want, got) + } + } + if n := len(strings.Split(got, "\n")); n > tall.innerHeight() { + t.Errorf("130×%d: %d lines, more than %d", need, n, tall.innerHeight()) + } +} + +// y's Yesterday shows as the active chip in the wide layout too. +func TestRangeChips_WideYesterday(t *testing.T) { + m := boardTimers(140, 36) + m, _ = m.Update(runeKey('y')) + got := m.renderRangeChips(m.innerWidth(), time.Now()) + if !strings.Contains(plain(got), "y Yesterday ") { + t.Errorf("wide chips after y: %q", plain(got)) + } + forceTrueColor(t) + got = m.renderRangeChips(m.innerWidth(), time.Now()) + var r, g, b int + fmt.Sscanf(string(cPrimary), "#%02x%02x%02x", &r, &g, &b) + primary := fmt.Sprintf("%d;%d;%d", r, g, b) + if bg := activeBackgroundAt(got, "Yesterday"); bg != primary { + t.Errorf("the Yesterday chip's background is %q, want primary %s", bg, primary) + } +} + +// The compact details close when a new-timer form opens, and when the +// terminal widens into the wide layout (so they don't come back on a later +// narrowing). +func TestDetailOpen_ClearedByNewAndWidening(t *testing.T) { + m := boardTimers(90, 28) + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m, _ = m.Update(runeKey('n')) + if m.detailOpen { + t.Error("n should close the details") + } + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.SetSize(140, 36) + m.SetSize(90, 28) + if m.detailOpen { + t.Error("widening and narrowing again should leave the details closed") + } +} From 4f53cef9440f50ad4b335dfa90ab4e38cffd8736 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 08:24:36 -0700 Subject: [PATCH 05/13] Fit the wide layout's height, and fix chip, message and detail gaps (ALI-2615) - At 120+ columns and 22 rows the wide layout left 7 rows for an 8-row detail pane, so the pane column went blank. The wide layout now also needs the rows for the pane (23 at the hero's height); shorter wide terminals get the compact layout, with details over the list. - Status and error messages were cut to half the line, even with keys to spare. The message now takes the room it needs and the keys fill the rest. - After y at 120+ columns no range chip was highlighted. The wide chips now show Yesterday while it's active, as the compact ones do. - The compact details survived n (new timer) and a widen-then-narrow. Both now close them. - The pane gap, the list's trailing column, and the tab bar and key line gaps were literals. They're tokens now (tui-pane-gap, tui-col-trail, tui-wordmark-gap, tui-tab-gap, tui-key-gap). - Removed the test-only tabsStart and a comment naming the removed footer, and the landing page no longer says the elapsed time is in the bottom status bar. --- design/build/main.go | 5 ++++ design/tokens.json | 9 +++++-- internal/theme/tokens_gen.go | 24 ++++++++++++++++- internal/ui/app.go | 33 ++++++++++------------- internal/ui/app_test.go | 30 +++++++++++++++++++-- internal/ui/layout_gen.go | 5 ++-- internal/ui/views/timers_view.go | 45 +++++++++++++++++++++++--------- landing/index.html | 2 +- 8 files changed, 113 insertions(+), 40 deletions(-) diff --git a/design/build/main.go b/design/build/main.go index fddd800..d23fda9 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -323,6 +323,11 @@ func renderPalette(t *Tokens) ([]byte, error) { {"tui-detail-width", "DetailWidth"}, {"tui-detail-label", "DetailLabel"}, {"tui-detail-note-rows", "DetailNoteRows"}, + {"tui-pane-gap", "PaneGap"}, + {"tui-col-trail", "ColTrail"}, + {"tui-wordmark-gap", "WordmarkGap"}, + {"tui-tab-gap", "TabGap"}, + {"tui-key-gap", "KeyGap"}, {"tui-col-duration", "ColDuration"}, {"tui-col-gap", "ColGap"}, {"tui-col-status", "ColStatus"}, diff --git a/design/tokens.json b/design/tokens.json index 3ae35b6..1a3f07f 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -60,8 +60,13 @@ { "name": "tui-max-width", "value": 150, "usage": "TUI: the widest the centred content column gets, in cells. Wider terminals pad both sides." }, { "name": "tui-gutter", "value": 2, "usage": "TUI: columns before every list row for the row cursor (glyph-cursor and a space). Report columns leave the same room." }, { "name": "tui-margin", "value": 2, "usage": "TUI: blank columns on each side of the content column, and before the tab bar's wordmark." }, - { "name": "tui-wide", "value": 120, "usage": "TUI: the narrowest terminal that gets the wide layout: the Timers hero with block digits, the CLIENT › PROJECT column and the entry detail pane. Narrower terminals get the compact layout." }, + { "name": "tui-wide", "value": 120, "usage": "TUI: the narrowest terminal that gets the wide layout: the Timers hero with block digits, the CLIENT › PROJECT column and the entry detail pane. The wide layout also needs 23 rows, so the pane fits its borders, the task and its five keys below the hero and range chips (computed in timers_view.go's wide()); narrower or shorter terminals get the compact layout." }, { "name": "tui-detail-width", "value": 42, "usage": "TUI: the entry detail pane's width, borders included, beside the Timers list in the wide layout." }, + { "name": "tui-pane-gap", "value": 2, "usage": "TUI: blank columns between the Timers list and the entry detail pane in the wide layout." }, + { "name": "tui-col-trail", "value": 1, "usage": "TUI: the blank column after the Timers list's last column, day subtotals and total." }, + { "name": "tui-wordmark-gap", "value": 4, "usage": "TUI: blank columns between the wordmark and the first tab in the tab bar." }, + { "name": "tui-tab-gap", "value": 2, "usage": "TUI: blank columns between tabs, and after the wordmark's mark when a narrow tab bar shortens it." }, + { "name": "tui-key-gap", "value": 3, "usage": "TUI: blank columns between keys on the hotkey line." }, { "name": "tui-col-duration", "value": 10, "usage": "TUI: the Timers list's DURATION column, right-aligned, in cells." }, { "name": "tui-col-gap", "value": 2, "usage": "TUI: the gap between the Timers list's DURATION and STATUS columns." }, { "name": "tui-col-status", "value": 12, "usage": "TUI: the Timers list's STATUS column in the wide layout, room for its longest value (◐ invoiced). The compact layout gives STATUS 5/12 of the flexible width, never less than this." }, @@ -71,7 +76,7 @@ { "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-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). Shorter 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." }, { "name": "panel-padding", "value": "14px", "usage": "Bar panel: inner padding, from aliasOS's KeyboardPanel." } ] diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index cac88b6..df7b217 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -69,7 +69,10 @@ const Margin = 2 // WideMin (tui-wide). TUI: the narrowest terminal that gets the wide layout: // the Timers hero with block digits, the CLIENT › PROJECT column and the -// entry detail pane. Narrower terminals get the compact layout. +// entry detail pane. The wide layout also needs 23 rows, so the pane fits its +// borders, the task and its five keys below the hero and range chips +// (computed in timers_view.go's wide()); narrower or shorter terminals get +// the compact layout. const WideMin = 120 // DetailWidth (tui-detail-width). TUI: the entry detail pane's width, borders @@ -84,6 +87,25 @@ const DetailLabel = 10 // take in the detail pane; longer notes end in an ellipsis. const DetailNoteRows = 3 +// PaneGap (tui-pane-gap). TUI: blank columns between the Timers list and the +// entry detail pane in the wide layout. +const PaneGap = 2 + +// ColTrail (tui-col-trail). TUI: the blank column after the Timers list's +// last column, day subtotals and total. +const ColTrail = 1 + +// WordmarkGap (tui-wordmark-gap). TUI: blank columns between the wordmark and +// the first tab in the tab bar. +const WordmarkGap = 4 + +// TabGap (tui-tab-gap). TUI: blank columns between tabs, and after the +// wordmark's mark when a narrow tab bar shortens it. +const TabGap = 2 + +// KeyGap (tui-key-gap). TUI: blank columns between keys on the hotkey line. +const KeyGap = 3 + // ColDuration (tui-col-duration). TUI: the Timers list's DURATION column, // right-aligned, in cells. const ColDuration = 10 diff --git a/internal/ui/app.go b/internal/ui/app.go index 9b561cb..97304f1 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -26,8 +26,8 @@ const ( var tabNames = []string{"Timers", "Projects", "Clients", "Reports"} // palette mirrors views/common.go's theme.Colors — kept as its own copy since -// app.go's bars are self-contained (see renderTopBar/renderFooter/ -// renderHotkeyBar, which rebuild their lipgloss.Styles from these vars on +// app.go's bars are self-contained (see renderTopBar and renderBottomBar, +// which rebuild their lipgloss.Styles from these vars on // every render call, unlike views' cached Style* vars). refreshAppTheme keeps // this copy in sync with theme.Colors — called at init and again whenever // theme.CheckReload reports a change (see the TickMsg handler below). @@ -372,12 +372,6 @@ func paint(s string, fg, bg lipgloss.Color, bold bool) string { // tabLabel is one tab in the tab bar: " 1 Timers ". func tabLabel(i int) string { return fmt.Sprintf(" %d %s ", i+1, tabNames[i]) } -// tabsStart is the column the first tab starts at: the margin, the -// wordmark and a gap. -func tabsStart() int { - return theme.Margin + lipgloss.Width(wordmark()) + 4 -} - func wordmark() string { return theme.GlyphWordmark + " notch" } // tabStrip is the tab bar's left side at one level of compression: 0 is the @@ -392,17 +386,17 @@ type tabStrip struct { func (m AppModel) tabStrip(level int) tabStrip { bg := appColorBgAlt - mark, gap := wordmark(), " " + mark, gap := wordmark(), strings.Repeat(" ", theme.WordmarkGap) if level >= 2 { - mark, gap = theme.GlyphWordmark, " " + mark, gap = theme.GlyphWordmark, strings.Repeat(" ", theme.TabGap) } st := tabStrip{s: paint(strings.Repeat(" ", theme.Margin), appColorText, bg, false) + paint(mark, appColorHighlight, bg, true) + paint(gap, appColorText, bg, false)} col := theme.Margin + lipgloss.Width(mark) + len(gap) for i := range tabNames { if i > 0 { - st.s += paint(" ", appColorText, bg, false) - col += 2 + st.s += paint(strings.Repeat(" ", theme.TabGap), appColorText, bg, false) + col += theme.TabGap } num, name, _ := strings.Cut(strings.TrimSpace(tabLabel(i)), " ") nameFg, bold := appColorDim, false @@ -469,7 +463,7 @@ func (m AppModel) renderTopBar() string { } // hotkeySep separates hotkey chips in the hotkey line. -const hotkeySep = " " +var hotkeySep = strings.Repeat(" ", theme.KeyGap) // renderHotkeyChip renders one key: its cap (the key on bg_alt) and label. func renderHotkeyChip(h views.Hotkey) string { @@ -482,9 +476,10 @@ func hotkeyChipWidth(h views.Hotkey) int { } // renderBottomBar renders a rule, then one line: the active view's keys -// on the left and the latest status or error on the right. Keys that don't -// fit are dropped whole, from the end, never cut mid-chip; the message is -// truncated instead of the keys when both can't fit. +// on the left and the latest status or error on the right. The message +// comes first: it takes the room it needs (cut only past the whole line), +// and the keys get what's left, dropped whole from the end, never cut +// mid-chip. func (m AppModel) renderBottomBar() string { bg := appColorBg inner := max(10, m.width-2*theme.Margin) @@ -492,11 +487,11 @@ func (m AppModel) renderBottomBar() string { var msg string switch { case m.err != "": - msg = paint(truncateStr("✕ "+m.err, inner/2), appColorDanger, bg, true) + msg = paint(truncateStr("✕ "+m.err, inner), appColorDanger, bg, true) case m.statusMsg != "": - msg = paint(truncateStr("✓ "+m.statusMsg, inner/2), appColorGreen, bg, false) + msg = paint(truncateStr("✓ "+m.statusMsg, inner), appColorGreen, bg, false) } - room := inner - lipgloss.Width(msg) - 2 + room := inner - lipgloss.Width(msg) - theme.KeyGap // q quit comes last, so it's the first key dropped when the line is // short. diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index 3c794e5..f8d6814 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -174,9 +174,9 @@ func TestRenderTopBar_WordmarkTabsAndUnderline(t *testing.T) { for _, tab := range []int{TabTimers, TabReports} { m.activeTab = tab rule := []rune(strings.Split(plainText(m.renderTopBar()), "\n")[1]) - col := tabsStart() + col := theme.Margin + lipgloss.Width(wordmark()) + theme.WordmarkGap for i := 0; i < tab; i++ { - col += len([]rune(tabLabel(i))) + 2 + col += len([]rune(tabLabel(i))) + theme.TabGap } under := string(rule[col : col+len([]rune(tabLabel(tab)))]) if strings.Trim(under, "━") != "" || strings.Count(string(rule), "━") != len([]rune(tabLabel(tab))) { @@ -598,3 +598,29 @@ func TestRenderTopBar_PillTruncatesSeconds(t *testing.T) { t.Errorf("pill should read 0:01:00 for 1m0.7s: %q", bar) } } + +// A status or error message takes the room it needs before the keys do. +func TestRenderBottomBar_MessageBeforeKeys(t *testing.T) { + m := sampleApp(t, MinWidth, 30) + m.err = "Mark as invoiced first (press i)" + line := strings.Split(plainText(m.renderBottomBar()), "\n")[1] + if !strings.Contains(line, "✕ Mark as invoiced first (press i)") { + t.Errorf("%d cols: the error is cut: %q", MinWidth, line) + } + if lipgloss.Width(line) != MinWidth { + t.Errorf("line is %d wide", lipgloss.Width(line)) + } +} + +// At 22 rows a wide terminal gets the compact Timers layout, every key +// reachable; at 23 the wide one, with its whole pane. +func TestView_WideNeedsRows(t *testing.T) { + short := plainText(sampleApp(t, 130, MinHeight).View()) + if strings.Contains(short, "NOW TRACKING") || !strings.Contains(short, "enter for details") { + t.Errorf("130×%d should be compact:\n%s", MinHeight, short) + } + tall := plainText(sampleApp(t, 130, MinHeight+1).View()) + if !strings.Contains(tall, "NOW TRACKING") || !strings.Contains(tall, "d delete") { + t.Errorf("130×%d should be wide with the whole pane:\n%s", MinHeight+1, tall) + } +} diff --git a/internal/ui/layout_gen.go b/internal/ui/layout_gen.go index 22444ec..702f4f6 100644 --- a/internal/ui/layout_gen.go +++ b/internal/ui/layout_gen.go @@ -20,6 +20,7 @@ const MinWidth = 64 // MinHeight (tui-min-height). 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). Shorter terminals get a centred "Terminal too small" -// message. +// 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. const MinHeight = 22 diff --git a/internal/ui/views/timers_view.go b/internal/ui/views/timers_view.go index 4be588d..61620df 100644 --- a/internal/ui/views/timers_view.go +++ b/internal/ui/views/timers_view.go @@ -321,9 +321,23 @@ func (m TimersModel) dayTotals(now time.Time) (days map[string]total, durW, mone // ── Layout ──────────────────────────────────────────────────────────────────── -// wide reports whether the view gets the wide layout (theme.WideMin columns -// and up, as wide as the terminal's content column). -func (m TimersModel) wide() bool { return m.width >= theme.WideMin } +// chipRows is the blank, the range chips and the blank under the hero. +const chipRows = 3 + +// paneMinRows is the least the detail pane shrinks to (see renderDetailBox): +// its two borders, the task, and the most keys an entry offers. +func paneMinRows() int { + finished := &model.Entry{EndTime: &time.Time{}} + return 3 + len(detailKeys(finished)) +} + +// wide reports whether the view gets the wide layout: theme.WideMin columns +// and up, and tall enough for the detail pane to fit below the hero and +// the range chips. Shorter terminals get the compact layout, whose details +// open over the list, rather than a wide one with a blank pane. +func (m TimersModel) wide() bool { + return m.width >= theme.WideMin && m.innerHeight()-theme.HeroRows-chipRows >= paneMinRows() +} // innerWidth is the content column's width inside its margins. func (m TimersModel) innerWidth() int { return usableWidth(m.width) } @@ -336,7 +350,7 @@ func (m TimersModel) innerHeight() int { return max(1, m.height-2) } // the detail pane and its two-column gap leave in the wide one. func (m TimersModel) tableWidth() int { if m.wide() { - return m.innerWidth() - 2 - theme.DetailWidth + return m.innerWidth() - theme.PaneGap - theme.DetailWidth } return m.innerWidth() } @@ -349,7 +363,7 @@ const ( tGap = theme.ColGap tStatus = theme.ColStatus tEarned = theme.ColEarned - tTrail = 1 + tTrail = theme.ColTrail ) // tableCols returns the flexible column widths: TASK, CLIENT › PROJECT @@ -379,7 +393,7 @@ func (m TimersModel) heroRows() int { } func (m TimersModel) fixedRows() int { - rows := m.heroRows() + 3 + 2 + 2 + rows := m.heroRows() + chipRows + 2 + 2 if !m.wide() { rows += 3 } @@ -499,17 +513,22 @@ func (m TimersModel) rangeChips() []rangeChip { week := rangeChip{"w", "Week", timersPresetWeek} month := rangeChip{"m", "Month", timersPresetMonth} all := rangeChip{"a", "All", timersPresetAll} + yesterday := rangeChip{"y", "Yesterday", timersPresetYesterday} + // A preset with no chip of its own (y's Yesterday, and Month in the + // compact layout) still shows while it's the active one. if m.wide() { - return []rangeChip{today, week, month, all, {"f", "Custom…", timersPresetCustom}} + chips := []rangeChip{today, week, month, all} + if m.preset == timersPresetYesterday { + chips = []rangeChip{today, yesterday, week, month, all} + } + return append(chips, rangeChip{"f", "Custom…", timersPresetCustom}) } chips := []rangeChip{today, week, all} - // A preset with no chip of its own here (Month, or y's Yesterday) still - // shows while it's the active one. switch m.preset { case timersPresetMonth: chips = []rangeChip{today, week, month, all} case timersPresetYesterday: - chips = []rangeChip{today, {"y", "Yesterday", timersPresetYesterday}, week, all} + chips = []rangeChip{today, yesterday, week, all} } return append(chips, rangeChip{"f", "…", timersPresetCustom}) } @@ -574,7 +593,7 @@ func (m TimersModel) renderDayHeaderLine(day time.Time, tw int, h dayHeads) stri t := h.days[day.Format("2006-01-02")] return spread(tw, cBg, []seg{{s: " "}, {s: friendlyDayAt(day, h.now), fg: cPrimary, bold: true}}, - []seg{{s: fitRight(t.duration(), h.durW) + " · " + fitRight(t.money(), h.moneyW), fg: cSubtle}, {s: " "}}) + []seg{{s: fitRight(t.duration(), h.durW) + " · " + fitRight(t.money(), h.moneyW), fg: cSubtle}, {s: strings.Repeat(" ", tTrail)}}) } func (m TimersModel) renderEntryRow(e *model.Entry, sel bool, tw int, now time.Time) string { @@ -610,7 +629,7 @@ func (m TimersModel) renderListFoot(tw int, now time.Time) []string { rule(tw, false, false), spread(tw, cBg, []seg{{s: " "}, {s: fmt.Sprintf("%d %s", n, plural(n, "entry", "entries")), fg: cSubtle}}, - []seg{{s: "Total " + all.text(), bold: true}, {s: " "}}), + []seg{{s: "Total " + all.text(), bold: true}, {s: strings.Repeat(" ", tTrail)}}), } } @@ -893,7 +912,7 @@ func (m TimersModel) viewListAt(now time.Time) string { if i < len(pane) { p = pane[i] } - out = append(out, l+blankLine(2)+p) + out = append(out, l+blankLine(theme.PaneGap)+p) } } else { out = append(out, list...) diff --git a/landing/index.html b/landing/index.html index 8823a08..8bb6df9 100644 --- a/landing/index.html +++ b/landing/index.html @@ -360,7 +360,7 @@

' }, + { title: "Timer tracking", desc: "Start and stop timers per task; the live elapsed time shows in the tab bar on every tab.", color: window.notchTokens.tailwind.primary, icon: '' }, { title: "Clients & Projects", desc: "Full CRUD on both — clients get their own tab, with project management right next door.", color: window.notchTokens.tailwind.accent, icon: '' }, { title: "Billing rates", desc: "Set an hourly rate per client. Earnings calculate automatically as time is logged.", color: window.notchTokens.tailwind.success, icon: '' }, { title: "Invoicing & payments", desc: "Mark entries as invoiced and/or paid as work moves through your pipeline.", color: window.notchTokens.tailwind.warning, icon: '' }, From 315e9f789b0ec3a2d0ebe5f054ef7ca6ba5f528d Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 08:31:55 -0700 Subject: [PATCH 06/13] Select form-started timers; close details on a range change (ALI-2615) - The new-timer form discarded StartEntry's result and sent a plain reload, so unlike r and space it left the cursor on the old entry. It now sends timerStartedMsg with the new entry's ID. - A range key kept the compact details open, so they reopened on the new range's first entry. setRange now closes them. - With no message, the key line still reserved the 3-column gap that separates keys from a message, dropping q quit when the keys fit exactly. - README: enter opens details in the compact layout, which now includes wide terminals under 23 rows. --- README.md | 2 +- internal/ui/app.go | 5 ++++- internal/ui/app_test.go | 18 ++++++++++++++++ internal/ui/views/timers.go | 17 +++++++-------- internal/ui/views/timers_start_test.go | 30 ++++++++++++++++++++++++++ 5 files changed, 61 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 761b8f2..13f02c8 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ That rewrites the generated files (marked as generated; never edit them by hand) | `t` / `w` / `m` / `a` | Range: today, this week, this month, all time | | `y` | Range: yesterday | | `f` | Range: custom dates | -| `enter` | Under 120 columns: open the selected entry's details | +| `enter` | Compact layout (under 120 columns, or under 23 rows): open the selected entry's details | | `esc` | Cancel / back | ### New / Edit timer form diff --git a/internal/ui/app.go b/internal/ui/app.go index 97304f1..16ed5aa 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -491,7 +491,10 @@ func (m AppModel) renderBottomBar() string { case m.statusMsg != "": msg = paint(truncateStr("✓ "+m.statusMsg, inner), appColorGreen, bg, false) } - room := inner - lipgloss.Width(msg) - theme.KeyGap + room := inner + if msg != "" { + room -= lipgloss.Width(msg) + theme.KeyGap + } // q quit comes last, so it's the first key dropped when the line is // short. diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index f8d6814..a4458b4 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -566,6 +566,24 @@ func TestRenderBottomBar_Quit(t *testing.T) { } } +// With no message, every chip that fits is shown: the key gap is only +// kept between the keys and a message. +func TestRenderBottomBar_NoMessageNoGap(t *testing.T) { + m := sampleApp(t, 140, 40) + m.err, m.statusMsg = "", "" + need := 0 + for i, h := range append(m.activeViewHelp(), views.Hotkey{Key: "q", Label: "quit"}) { + if i > 0 { + need += len(hotkeySep) + } + need += hotkeyChipWidth(h) + } + m.width = need + 2*theme.Margin // every key, exactly + if line := plainText(m.renderBottomBar()); !strings.Contains(line, "q quit") { + t.Errorf("at %d columns the keys fit exactly, but q quit was dropped: %q", m.width, line) + } +} + // Switching tabs closes the compact layout's details. func TestTabSwitch_ClosesDetails(t *testing.T) { m := sampleApp(t, 90, 32) diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index 7798321..bc530e4 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -792,6 +792,7 @@ func (m *TimersModel) setRange(p timersPreset, from, to string) { m.fromInput.SetValue(from) m.toInput.SetValue(to) m.cursor, m.offset = 0, 0 + m.detailOpen = false // it would reopen on the new range's first entry m.recomputeFiltered() } @@ -1279,23 +1280,21 @@ func (m TimersModel) submitForm() (TimersModel, tea.Cmd) { if err := m.db.StopAllRunning(); err != nil { return ErrMsg(err.Error()) } - if resolvedProjectID > 0 { - if _, err := m.db.StartEntry(resolvedProjectID, v.task); err != nil { - return ErrMsg(err.Error()) - } - } else { + if resolvedProjectID <= 0 { // No project — start with a placeholder project pid, err := m.db.EnsureUncategorizedProject() if err != nil { return ErrMsg(err.Error()) } - if _, err := m.db.StartEntry(pid, v.task); 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 timerEntriesMsg(mustLoadEntries(m.db)) }, + 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") }, diff --git a/internal/ui/views/timers_start_test.go b/internal/ui/views/timers_start_test.go index 300e90b..2083200 100644 --- a/internal/ui/views/timers_start_test.go +++ b/internal/ui/views/timers_start_test.go @@ -84,3 +84,33 @@ func TestStart_SelectsNewEntryDespiteEarlierReload(t *testing.T) { } } } + +// A timer started from the new-timer form is selected, like one started +// with r or space. +func TestStart_FormSelectsNewEntry(t *testing.T) { + m := startRaceTimers(t) + m, _ = m.Update(runeKey('n')) + 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 = 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) + } +} + +// Changing the range closes the compact details, which would otherwise +// reopen on the new range's first entry. +func TestSetRange_ClosesDetails(t *testing.T) { + m := startRaceTimers(t) + m.SetSize(90, 28) + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + if !m.detailOpen { + t.Fatal("setup: enter should open the details") + } + m, _ = m.Update(runeKey('t')) + if m.detailOpen { + t.Error("a range key should close the details") + } +} From 1d87f365cb1b914ce13217541145e5df306927fe Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:02:54 -0700 Subject: [PATCH 07/13] Modal forms with field errors, delete confirm and the keys sheet (ALI-2616) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The TUI's forms were full-screen pages with one error line at the bottom and an unfocused button at 1.91:1. They now open as centred modals over the dimmed screen, following the design canvas's RdTuiNew, RdTuiEdit, RdTuiDelete, RdTuiHelp and RdTuiEmpty boards. - Fields sit on a bg_alt strip; the focused one gets a primary ▌. Client and Project suggest as you type, ending with "+ Create". - Errors sit under their field with ✕, and the status line counts them. Validation matches the CLI: no future times, no end before the start. - New timer has Start (blank is now, or a past time) and End, saves Notes, and reads `task @client/project` through internal/quickadd. - Every start (form, r, space) goes through db.AddEntry, so stopping the running timer and starting the next is one write. A start before the running timer's shows as a Start error. - Edit entry gains Invoiced and Paid toggles and Delete entry. - Delete confirms name the entry with its time, with Delete and Keep it. - ? opens every key, grouped by tab; a first run shows a welcome screen. - Clients and Projects use the same modal and confirm. - New backdrop token for the dimmed screen; the bg-on-danger pair is added to the contrast checks. --- README.md | 1 + design/build/main.go | 11 +- design/tokens.json | 18 +- internal/theme/theme.go | 12 + internal/theme/theme_test.go | 7 +- internal/theme/tokens_gen.go | 42 ++ internal/ui/app.go | 61 ++ internal/ui/app_test.go | 8 +- internal/ui/modal_test.go | 104 +++ internal/ui/views/clients.go | 235 ++++--- internal/ui/views/clients_test.go | 178 +++-- internal/ui/views/common.go | 79 +-- internal/ui/views/common_test.go | 67 +- internal/ui/views/keys.go | 139 ++++ internal/ui/views/modal.go | 360 ++++++++++ internal/ui/views/projects.go | 363 ++++++---- internal/ui/views/projects_test.go | 116 +-- internal/ui/views/reports.go | 71 +- internal/ui/views/timer_form.go | 706 +++++++++++++++++++ internal/ui/views/timer_form_test.go | 903 ++++++++++++++++++++++++ internal/ui/views/timers.go | 932 +++++-------------------- internal/ui/views/timers_start_test.go | 2 +- internal/ui/views/timers_test.go | 868 +---------------------- internal/ui/views/timers_view.go | 67 +- landing/tokens.css | 1 + landing/tokens.js | 1 + 26 files changed, 3177 insertions(+), 2175 deletions(-) create mode 100644 internal/ui/modal_test.go create mode 100644 internal/ui/views/keys.go create mode 100644 internal/ui/views/modal.go create mode 100644 internal/ui/views/timer_form.go create mode 100644 internal/ui/views/timer_form_test.go 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..6ac9002 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,15 @@ 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"}, } { v, err := integer(t.Spacing, c.token) if err != nil { diff --git a/design/tokens.json b/design/tokens.json index 1a3f07f..5401615 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 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,15 @@ { "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-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." }, @@ -124,17 +134,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/theme/theme.go b/internal/theme/theme.go index fca9103..ebabdf9 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 @@ -226,6 +229,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 +392,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..c75a74a 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) diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index df7b217..0828bf2 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -38,6 +38,10 @@ 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 + // gets border mixed 60% over bg. + Backdrop: "#3E464C", } // Status and brand glyphs. @@ -132,3 +136,41 @@ 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 diff --git a/internal/ui/app.go b/internal/ui/app.go index 16ed5aa..157a6c0 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): @@ -335,6 +347,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 +515,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 != "": @@ -514,6 +546,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 +592,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 +658,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 +674,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..85665d7 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -439,13 +439,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..887a4ab --- /dev/null +++ b/internal/ui/modal_test.go @@ -0,0 +1,104 @@ +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) + } +} diff --git a/internal/ui/views/clients.go b/internal/ui/views/clients.go index 42b00b1..258dac7 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,13 @@ 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). + deleteFocused bool } type clientMode int @@ -40,7 +45,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 +84,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"}} } @@ -122,6 +141,7 @@ 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 } } return m, nil @@ -131,53 +151,79 @@ 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): default: - m.mode = clientModeList + return m, nil } - return m, nil + m.mode = clientModeList + if !del || len(m.clients) == 0 { + return m, nil + } + id := m.clients[m.cursor].ID + if err := m.db.DeleteClient(id); err != nil { + return m, ErrCmd(fmt.Sprintf("delete client: %v", err)) + } + return m, tea.Batch( + loadClientsCmd(m.db), + loadProjectsData(m.db), + StatusCmd("Client deleted."), + ) } // -- Form helpers ------------------------------------------------------------ @@ -185,8 +231,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, 36) + rate := makeTextInput("0, or a rate like 95", 12, 36) if c != nil { name.SetValue(c.Name) @@ -200,13 +246,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,13 +259,15 @@ 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 } @@ -229,12 +276,16 @@ func (m ClientsModel) submitForm() (ClientsModel, tea.Cmd) { } else { 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 +297,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 +373,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 { +// viewConfirm is the delete confirm for the selected client. +func (m ClientsModel) viewConfirm(w, h int) []string { if len(m.clients) == 0 { - return "" + 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..9e53061 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") } } @@ -376,8 +413,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 +509,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 +527,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 +557,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 +622,80 @@ 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, + width: 100, + height: 30, cursor: 0, - clients: []*model.Client{{ID: 1, Name: "Acme"}}, + clients: []*model.Client{{ID: 1, Name: "Acme", HourlyRate: 95}}, } - out := m.View() - for _, want := range []string{`Delete "Acme"?`, "y confirm esc cancel"} { + 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}} + 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) + } +} 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..7c7d9e3 --- /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 three). +func keySheetRows(w int) (rows []string, inner int) { + cols := 3 + 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..3b06383 --- /dev/null +++ b/internal/ui/views/modal.go @@ -0,0 +1,360 @@ +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 { + rows = append([]boxRow(nil), rows...) + for len(rows) > n { + at := -1 + for i, r := range rows { + if r.drop > 0 && (at < 0 || r.drop >= rows[at].drop) { + at = i + } + } + if at < 0 { + break + } + rows = append(rows[:at], rows[at+1:]...) + } + out := make([]string, len(rows)) + for i, r := range rows { + out[i] = r.s + } + return out +} + +// 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 + under []string // rows drawn from the field's column (suggestions) +} + +type formModal struct { + title string + fields []modalField + left []modalButton + right []modalButton + hint string // subtle, at the right end of the button row +} + +// modalInner is a modal's width inside its border, for a body w wide. +func modalInner(want, w int) int { + return max(20, 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(8, 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. +func (fm formModal) render(w, h int) []string { + inner := modalInner(theme.ModalWidth, w) + sw := stripWidth(inner) + indent := blankLine(theme.ModalIndent) + under := blankLine(fieldCol()) + textCol := blankLine(fieldCol() + 1) + + rows := []boxRow{{blankLine(inner), dropMargin}} + 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) + } + rows = append(rows, boxRow{padTo(indent+label+value, inner), dropKeep}) + for _, u := range f.under { + rows = append(rows, boxRow{padTo(under+u, 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}) + } + } + rows = append(rows, + boxRow{blankLine(inner), dropGap}, + boxRow{buttonRow(inner, fm.left, fm.right, fm.hint), dropKeep}, + boxRow{blankLine(inner), dropMargin}, + ) + return modalFrame(fm.title, cText, cPrimary, inner, fitRows(rows, h-2)) +} + +// 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. + ti.Width = max(1, w-3) + 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: the items +// (the selected one in bg on primary), and how to choose. It shows at most +// tui-suggest-rows items, scrolled to keep the selection in view. +func suggestions(items []dropdownItem, sel, fieldW int) []string { + w := min(theme.SuggestWidth, fieldW) + inner := w - 2 + start := max(0, min(sel-theme.SuggestRows/2, len(items)-theme.SuggestRows)) + end := min(len(items), start+theme.SuggestRows) + 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 { + item = seg{s: fit(" "+items[i].label, inner), fg: cBg, bg: cPrimary, bold: true} + } + out = append(out, renderSegs(cBg, edge, item, edge)) + } + out = append(out, + renderSegs(cBg, edge, seg{s: fit(" ↑↓ choose · enter pick", inner), fg: cSubtle}, edge), + renderSegs(cBg, seg{s: "╰" + strings.Repeat("─", inner) + "╯", fg: cBorder}), + ) + return out +} + +// ── 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..37a1f47 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,13 @@ 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). + deleteFocused bool } func NewProjects(database *db.DB) ProjectsModel { @@ -88,14 +106,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"}} } @@ -174,10 +191,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): @@ -189,17 +205,16 @@ func (m ProjectsModel) updateList(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { } m.mode = projectsModeEditProject 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 } } return m, nil @@ -207,107 +222,129 @@ 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 = 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 { @@ -316,14 +353,30 @@ func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { } p.ClientID = m.clientID p.Name = name - if err := m.db.UpdateProject(p); err != nil { - m.err = err.Error() - return m, nil - } - m.mode = projectsModeList - return m, tea.Batch(loadProjectsData(m.db), StatusCmd("Project updated")) + err = m.db.UpdateProject(p) + 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) { @@ -348,7 +401,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,7 +409,7 @@ 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. @@ -392,9 +445,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 +509,55 @@ 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) if m.focusedInput == projFieldClient && m.showClientDrop && len(m.clientMatches) > 0 { - b.WriteString(renderDropdown(m.clientMatches, m.clientSel) + "\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") + client.under = suggestions(m.clientMatches, m.clientSel, sw) } - - 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.selectedProject() + 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 +570,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, 44) if clientName != "" { client.SetValue(clientName) } - name := textinput.New() - name.Placeholder = "Project name" - name.CharLimit = 64 + name := makeTextInput("Website rebuild", 64, 44) 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..f6c0f96 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)") @@ -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") @@ -834,8 +847,8 @@ func TestProjectsSaveForm_EditError(t *testing.T) { } 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") @@ -1048,23 +1061,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}, 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,29 +1096,39 @@ 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) } diff --git a/internal/ui/views/reports.go b/internal/ui/views/reports.go index fef94d9..0b1ddb9 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 } @@ -348,14 +340,14 @@ func (m ReportsModel) updateEditEntry(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { // 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 +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.editForm.errs = nil m.mode = reportsModeEntries - m.editFormErr = "" return m, submitEditEntryCmd(m.db, m.editForm.entryID, v, m.loadCmd()) } @@ -401,27 +393,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 +474,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 +747,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 +766,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 +1002,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..8064a78 --- /dev/null +++ b/internal/ui/views/timer_form.go @@ -0,0 +1,706 @@ +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 ( + "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." + 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) + + 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 + + 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, 44) + inputs[fieldClient] = makeTextInput("type to find or create", 64, 44) + inputs[fieldProject] = makeTextInput("type to find or create", 64, 44) + inputs[fieldStart] = makeTextInput("now", 20, 44) + inputs[fieldEnd] = makeTextInput("blank keeps it running", 20, 44) + inputs[fieldNotes] = makeTextInput("optional", 500, 44) + 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.inputs[fieldStart].SetValue(e.StartTime.Local().Format("2006-01-02 15:04")) + f.inputs[fieldStart].Placeholder = "2026-12-03 09:05" + if e.EndTime != nil { + f.inputs[fieldEnd].SetValue(e.EndTime.Local().Format("2006-01-02 15:04")) + 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.rebuildClientMatches() + f.rebuildProjectMatches() +} + +// ── 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) + f.clientMatches = nil + exact := false + for _, c := range f.allClients { + switch { + case strings.EqualFold(c.Name, typed): + exact = true + f.clientMatches = append([]dropdownItem{{id: c.ID, label: c.Name}}, f.clientMatches...) + case query == "" || strings.Contains(strings.ToLower(c.Name), query): + f.clientMatches = append(f.clientMatches, dropdownItem{id: c.ID, label: c.Name}) + } + } + if typed != "" && !exact { + f.clientMatches = append(f.clientMatches, dropdownItem{id: 0, label: fmt.Sprintf("+ Create “%s”", typed)}) + } + if f.clientSel >= len(f.clientMatches) { + f.clientSel = 0 + } +} + +// 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 := false + for _, p := range f.allProjects { + if f.clientID != 0 && p.ClientID != f.clientID { + continue + } + label := p.Name + if f.clientID == 0 && p.Client != nil { + label = p.Client.Name + " › " + p.Name + } + switch { + case strings.EqualFold(p.Name, typed): + exact = true + f.projectMatches = append([]dropdownItem{{id: p.ID, label: label}}, f.projectMatches...) + case query == "" || strings.Contains(strings.ToLower(p.Name), query): + f.projectMatches = append(f.projectMatches, dropdownItem{id: p.ID, label: label}) + } + } + if typed != "" && !exact { + f.projectMatches = append(f.projectMatches, dropdownItem{id: 0, label: fmt.Sprintf("+ Create “%s”", typed)}) + } + 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 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) { + 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: + if f.showClientDrop { + f.applyClientSelection() + } + case fieldProject: + if f.showProjectDrop { + 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.clientSel = moveSel(f.clientSel, len(f.clientMatches), up, f.showClientDrop) + f.showClientDrop = len(f.clientMatches) > 0 + case fieldProject: + 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.clearProject() + f.rebuildClientMatches() + f.rebuildProjectMatches() + f.showClientDrop = strings.TrimSpace(f.inputs[fieldClient].Value()) != "" && len(f.clientMatches) > 0 + case fieldProject: + f.projectID = 0 + 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 +} + +// 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 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 + } + v.notes = strings.TrimSpace(f.inputs[fieldNotes].Value()) + v.invoiced, v.paid = f.invoiced, f.paid + + 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: + t, ok := parseFormTime(startText, now) + 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: + t, ok := parseFormTime(endText, now) + 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.entryID != 0 && 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 means today. +func parseFormTime(s string, now 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 + } + } + 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 { + day := now.Local() + return time.Date(day.Year(), day.Month(), day.Day(), t.Hour(), t.Minute(), 0, 0, time.Local), true + } + } + return time.Time{}, false +} + +// submitEditEntryCmd finds or creates the client and project, then writes +// v to the entry entryID. Timers and Reports both save Edit entry with it; +// extra are the caller's reloads, run with the "Entry updated" status. +func submitEditEntryCmd(database *db.DB, entryID int64, v timerFormValues, extra ...tea.Cmd) 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()) + } + 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 + target.StartTime = v.start + target.EndTime = v.end + target.Invoiced, target.Paid = v.invoiced, v.paid + if resolvedProjectID > 0 { + target.ProjectID = resolvedProjectID + } + if err := database.UpdateEntry(target); err != nil { + return ErrMsg(err.Error()) + } + batch := make(tea.BatchMsg, 0, len(extra)+2) + batch = append(batch, RunningChangedCmd()) + batch = append(batch, extra...) + batch = append(batch, StatusCmd("Entry updated")) + return batch + } +} + +// ── 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) + if f.focusIdx == fieldClient && f.showClientDrop && len(f.clientMatches) > 0 { + client.under = suggestions(f.clientMatches, f.clientSel, sw) + } + project := field("Project", fieldProject) + if f.focusIdx == fieldProject && f.showProjectDrop && len(f.projectMatches) > 0 { + project.under = suggestions(f.projectMatches, f.projectSel, sw) + } + 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"} + 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..ecdf2d6 --- /dev/null +++ b/internal/ui/views/timer_form_test.go @@ -0,0 +1,903 @@ +package views + +import ( + "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("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("10:30 AM") + 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) + if !ok || !got.Equal(want) { + t.Errorf("parseFormTime(%q) = %v, %v; want %v", in, got, ok, want) + } + } + if _, ok := parseFormTime("half nine", 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 } + +func TestSubmitEditEntryCmd_Errors(t *testing.T) { + d := newTestDB(t) + v := timerFormValues{task: "x", start: time.Now().Add(-time.Hour)} + if msgs := runCmd(t, submitEditEntryCmd(d, 999, v)); len(msgs) != 1 || msgs[0] != ErrMsg("Entry not found") { + t.Errorf("missing entry: msgs = %v, want Entry not found", msgs) + } + e, _ := d.AddEntry(mustUncategorized(t, d), "t", "", time.Now().Add(-time.Hour), nil) + v.projectID = 99999 // the foreign key fails + if msgs := runCmd(t, submitEditEntryCmd(d, e.ID, v)); len(msgs) != 1 { + t.Errorf("bad project: msgs = %v, want one ErrMsg", msgs) + } else if _, ok := msgs[0].(ErrMsg); !ok { + t.Errorf("bad project: msg = %T, want ErrMsg", msgs[0]) + } +} + +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()) + for _, want := range []string{"│ 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} + if h := m.Help(); len(h) != 2 || h[0] != (Hotkey{"n", "new timer"}) || h[1] != (Hotkey{"3", "add a client first"}) { + t.Errorf("first-run Help() = %v", 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) +} diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index bc530e4..3e36d5f 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -1,7 +1,7 @@ package views import ( - "fmt" + "errors" "strings" "time" @@ -10,7 +10,6 @@ import ( "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" ) // ── Modes ───────────────────────────────────────────────────────────────────── @@ -25,20 +24,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 +68,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 { @@ -320,6 +82,13 @@ type TimersModel struct { 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 +268,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 +352,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 len(m.entries) == 0 { + return []Hotkey{{"n", "new timer"}, {"3", "add a client first"}} + } if !m.wide() { return []Hotkey{ {"n", "new"}, @@ -693,8 +451,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 +581,51 @@ 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": - m.mode = timersModeList - m.detailOpen = false - e := m.selectedEntry() - if e == nil { - return m, nil - } - return m, m.deleteCmd(e.ID) + del = true case key.Matches(msg, timersKeys.Cancel): + 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 + if m.deleteFromForm { + m.mode = timersModeEdit + } + return m, nil } - return m, nil + m.mode = timersModeList + m.detailOpen = false + return m, m.deleteCmd(m.deleteID) } // ── Filter update ───────────────────────────────────────────────────────────── @@ -1081,10 +687,8 @@ 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()) } @@ -1145,168 +749,72 @@ func (m TimersModel) togglePaidCmd(e *model.Entry) tea.Cmd { } } -// 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 -} +// saveAndStart is the New timer form's save button. +const saveAndStart = "Save & start" -// 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" - } - 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 - } - if v.newStart != nil && v.newEnd != nil && v.newEnd.Before(*v.newStart) { - return v, "End time must not be before the start time" - } +// 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 } - return v, "" -} + m.form.errs = nil -// 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 { - return func() tea.Msg { - resolvedProjectID, err := database.ResolveOrCreateProject(v.clientID, v.clientName, v.projectID, v.projectName) - if err != nil { - return ErrMsg(err.Error()) - } + if m.form.entryID != 0 { + m.mode = timersModeList + m.err = "" + return m, submitEditEntryCmd(m.db, m.form.entryID, v, + func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, + loadProjectsData(m.db), + loadClientsCmd(m.db), + ) + } - entries, err := database.ListEntries(0, "", "", true) + // 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 ErrMsg(err.Error()) - } - var target *model.Entry - for _, e := range entries { - if e.ID == entryID { - target = e - break - } + return m, ErrCmd(err.Error()) } - 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) + if running != nil && running.StartTime.After(v.start) { + m.form.errs = fieldErrors{fieldStart: errRunningLater} + return m, nil } - batch = append(batch, func() tea.Msg { return StatusMsg("Entry updated") }) - return batch } -} - -// 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 + 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 = "" - - 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") }, - } - } - } - - // Edit existing entry - return m, submitEditEntryCmd(m.db, f.entryID, v, - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, - loadProjectsCmd(m.db, 0), + status := "Timer started" + if v.end != nil { + status = "Entry added" + } + return m, tea.Batch( + RunningChangedCmd(), + func() tea.Msg { return timerStartedMsg{entries: mustLoadEntries(m.db), id: e.ID} }, + loadProjectsData(m.db), loadClientsCmd(m.db), + StatusCmd(status), ) } @@ -1315,47 +823,28 @@ 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. func (m TimersModel) handleOpenForm(msg openFormMsg) TimersModel { f := newTimerForm(msg.clients, msg.projects) - f.entryID = msg.entryID - - // Pre-populate for edit + m.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) - } - } + var e *model.Entry + for _, x := range m.entries { + if x.ID == msg.entryID { + e = x break } } - f.rebuildClientMatches() - f.rebuildProjectMatches() - } - - m.form = f - if msg.entryID == 0 { - m.mode = timersModeNew - } else { + if e == nil { + return m + } + f.fill(e) + f.canDelete = true m.mode = timersModeEdit } + m.form = f m.err = "" return m } @@ -1363,15 +852,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 +965,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..ad4313b 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) + 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) + 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..a59c43d 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 len(m.entries) == 0 && m.mode != timersModeFilter { + 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)', From 86f0e2a5f0ae89317cf609ad43ecf1d43cbdd869 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:14:29 -0700 Subject: [PATCH 08/13] Fix stale entries, suggestion layout and edit times in the modal forms (ALI-2616) Review round 1 on PR #15 found these problems: - Opening Edit entry for an entry another process had just deleted left the tab in New mode with an empty form. The mode is now set only once the entry is found, and the status says "That entry no longer exists". - A delete confirm whose entry disappeared stayed in confirm mode with no dialog. A reload now closes it, with the same status. - Suggestions were rows added to the modal and never dropped, so on a short terminal the box outgrew the body and lost its buttons and bottom border, and it re-centred (the fields jumped) whenever they opened. They now float over the rows below their field, capped at the button row, and the modal keeps room under its last suggesting field, so its size and place don't change. - Tab out of Client or Project took the highlighted suggestion even for a partly typed name, so typing "Fieldnote" to create a client gave "Fieldnote Studio". Tab now takes a suggestion only when the arrows chose one or the text is a name exactly; typing resets the selection. Enter on an open list still picks. - Clearing Client and Project in Edit entry kept the old project while saying "Entry updated". Blank now means the uncategorized project, as for `notch start` and a new timer. - A refused project rename (name taken) changed the shared *Project before saving, so the list showed the clashing name. It edits a copy now. Clients already saved a new struct. - A stopped entry with End cleared and Invoiced ticked also said "Stop the timer before invoicing it". That error is for running entries only. - A bare time in Edit entry ("9:30") was read as today, moving an older entry to today. It's now read on the entry's own day. - Every edit zeroed the seconds of Start and End, since the fields hold minutes. A field left as filled keeps its stored time. - Hard-coded sizes (modal and strip minimums, field width, keys sheet columns) move to tokens with usage notes. --- design/build/main.go | 4 + design/tokens.json | 4 + internal/theme/tokens_gen.go | 16 +++ internal/ui/views/clients.go | 4 +- internal/ui/views/keys.go | 4 +- internal/ui/views/modal.go | 120 ++++++++++++++----- internal/ui/views/projects.go | 18 +-- internal/ui/views/projects_test.go | 4 + internal/ui/views/timer_form.go | 101 ++++++++++++---- internal/ui/views/timer_form_test.go | 173 ++++++++++++++++++++++++++- internal/ui/views/timers.go | 40 +++++-- 11 files changed, 411 insertions(+), 77 deletions(-) diff --git a/design/build/main.go b/design/build/main.go index 6ac9002..ecb9071 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -343,6 +343,10 @@ func renderPalette(t *Tokens) ([]byte, error) { {"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 5401615..406aa24 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -85,6 +85,10 @@ { "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." }, diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index 0828bf2..6547efb 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -174,3 +174,19 @@ 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/views/clients.go b/internal/ui/views/clients.go index 258dac7..65c162e 100644 --- a/internal/ui/views/clients.go +++ b/internal/ui/views/clients.go @@ -231,8 +231,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("Harbor & Pine", 120, 36) - rate := makeTextInput("0, or a rate like 95", 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) diff --git a/internal/ui/views/keys.go b/internal/ui/views/keys.go index 7c7d9e3..200c7ce 100644 --- a/internal/ui/views/keys.go +++ b/internal/ui/views/keys.go @@ -77,9 +77,9 @@ func keySheetColumns(cols int) [][]string { } // keySheetRows is the sheet's content for a body w wide: rows inner cells -// wide, as many columns as fit (up to three). +// wide, as many columns as fit (up to tui-keys-cols). func keySheetRows(w int) (rows []string, inner int) { - cols := 3 + 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-- diff --git a/internal/ui/views/modal.go b/internal/ui/views/modal.go index 3b06383..c12c724 100644 --- a/internal/ui/views/modal.go +++ b/internal/ui/views/modal.go @@ -82,24 +82,33 @@ func modalFrame(title string, titleFg, edge lipgloss.Color, inner int, rows []st // 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 { - rows = append([]boxRow(nil), rows...) - for len(rows) > n { + 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, r := range rows { - if r.drop > 0 && (at < 0 || r.drop >= rows[at].drop) { + 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 } - rows = append(rows[:at], rows[at+1:]...) - } - out := make([]string, len(rows)) - for i, r := range rows { - out[i] = r.s + keep = append(keep[:at], keep[at+1:]...) } - return out + return keep } // Drop ranks for modal rows, highest first: the blank rows at the top and @@ -181,9 +190,13 @@ type modalField struct { 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 - under []string // rows drawn from the field's column (suggestions) + 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 { @@ -196,7 +209,7 @@ type formModal struct { // modalInner is a modal's width inside its border, for a body w wide. func modalInner(want, w int) int { - return max(20, min(want, w)) - 2 + return max(theme.ModalMinWidth, min(want, w)) - 2 } // fieldCol is where a form modal's fields start: after the indent, the @@ -205,19 +218,24 @@ 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(8, inner-fieldCol()-theme.ModalIndent) + 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) - under := blankLine(fieldCol()) 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}) @@ -234,10 +252,13 @@ func (fm formModal) render(w, h int) []string { if f.strip { value = padStrip(value, sw) } - rows = append(rows, boxRow{padTo(indent+label+value, inner), dropKeep}) - for _, u := range f.under { - rows = append(rows, boxRow{padTo(under+u, inner), dropKeep}) + 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. @@ -254,12 +275,37 @@ func (fm formModal) render(w, h int) []string { 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}) + buttonsAt = len(rows) rows = append(rows, - boxRow{blankLine(inner), dropGap}, boxRow{buttonRow(inner, fm.left, fm.right, fm.hint), dropKeep}, boxRow{blankLine(inner), dropMargin}, ) - return modalFrame(fm.title, cText, cPrimary, inner, fitRows(rows, h-2)) + 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, @@ -296,14 +342,25 @@ func toggle(label string, on, focused bool) string { return renderSegs(cBg, focusMark(focused), seg{s: box + label}) } -// suggestions draws the box under a Client or Project field: the items -// (the selected one in bg on primary), and how to choose. It shows at most -// tui-suggest-rows items, scrolled to keep the selection in view. -func suggestions(items []dropdownItem, sel, fieldW int) []string { +// 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 - start := max(0, min(sel-theme.SuggestRows/2, len(items)-theme.SuggestRows)) - end := min(len(items), start+theme.SuggestRows) + 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++ { @@ -313,11 +370,10 @@ func suggestions(items []dropdownItem, sel, fieldW int) []string { } out = append(out, renderSegs(cBg, edge, item, edge)) } - out = append(out, - renderSegs(cBg, edge, seg{s: fit(" ↑↓ choose · enter pick", inner), fg: cSubtle}, edge), - renderSegs(cBg, seg{s: "╰" + strings.Repeat("─", inner) + "╯", fg: cBorder}), - ) - return out + 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 ──────────────────────────────────────────────────────────── diff --git a/internal/ui/views/projects.go b/internal/ui/views/projects.go index 37a1f47..8d2bf12 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -276,7 +276,7 @@ func (m ProjectsModel) updateForm(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { } delete(m.errs, m.focusedInput) if m.focusedInput == projFieldClient { - m.clientID = 0 + m.clientID, m.clientSel = 0, 0 m.rebuildClientMatches() m.showClientDrop = strings.TrimSpace(m.inputs[projFieldClient].Value()) != "" && len(m.clientMatches) > 0 } @@ -351,9 +351,12 @@ func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { m.mode = projectsModeList return m, nil } - p.ClientID = m.clientID - p.Name = name - err = m.db.UpdateProject(p) + // Edit a copy: the list shares p, and a refused rename mustn't + // show there. + edited := *p + edited.ClientID = m.clientID + edited.Name = name + err = m.db.UpdateProject(&edited) status = "Project updated" default: return m, nil @@ -523,8 +526,9 @@ func (m ProjectsModel) viewForm(w, h int) []string { } } client := field("Client", projFieldClient) + client.suggests = true if m.focusedInput == projFieldClient && m.showClientDrop && len(m.clientMatches) > 0 { - client.under = suggestions(m.clientMatches, m.clientSel, sw) + client.suggest = func(n int) []string { return suggestions(m.clientMatches, m.clientSel, sw, n) } } title := "New project" if m.mode == projectsModeEditProject { @@ -570,12 +574,12 @@ func (m ProjectsModel) selectedProject() *model.Project { } func makeProjectInputs(p *model.Project, clientName string) []textinput.Model { - client := makeTextInput("type to find a client", 64, 44) + client := makeTextInput("type to find a client", 64, theme.FieldWidth) if clientName != "" { client.SetValue(clientName) } - name := makeTextInput("Website rebuild", 64, 44) + 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 f6c0f96..7d6f77d 100644 --- a/internal/ui/views/projects_test.go +++ b/internal/ui/views/projects_test.go @@ -853,6 +853,10 @@ func TestProjectsSaveForm_EditError(t *testing.T) { 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 } diff --git a/internal/ui/views/timer_form.go b/internal/ui/views/timer_form.go index 8064a78..bc79d70 100644 --- a/internal/ui/views/timer_form.go +++ b/internal/ui/views/timer_form.go @@ -93,6 +93,13 @@ type timerForm struct { running bool // editing a running entry: End can stay blank canDelete bool // offer Delete entry (the Timers tab) + // The entry's stored times and the text Start and End were filled + // with: a field left as filled keeps its stored time, seconds and all, + // and a bare time of day is read on the entry's own day. + origStart time.Time + origEnd *time.Time + filledStart, filledEnd string + inputs [fieldInputs]textinput.Model focusIdx int @@ -109,6 +116,13 @@ type timerForm struct { 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 + invoiced, paid bool errs fieldErrors @@ -116,12 +130,12 @@ type timerForm struct { func newTimerForm(clients []*model.Client, projects []*model.Project) timerForm { var inputs [fieldInputs]textinput.Model - inputs[fieldTask] = makeTextInput("what you're working on", 200, 44) - inputs[fieldClient] = makeTextInput("type to find or create", 64, 44) - inputs[fieldProject] = makeTextInput("type to find or create", 64, 44) - inputs[fieldStart] = makeTextInput("now", 20, 44) - inputs[fieldEnd] = makeTextInput("blank keeps it running", 20, 44) - inputs[fieldNotes] = makeTextInput("optional", 500, 44) + 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{ @@ -142,10 +156,13 @@ func (f *timerForm) fill(e *model.Entry) { f.invoiced, f.paid = e.Invoiced, e.Paid 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")) + f.origStart, f.origEnd = e.StartTime, e.EndTime + 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.inputs[fieldEnd].SetValue(e.EndTime.Local().Format("2006-01-02 15:04")) + 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" @@ -173,7 +190,7 @@ func (f *timerForm) rebuildClientMatches() { exact := false for _, c := range f.allClients { switch { - case strings.EqualFold(c.Name, typed): + case typed != "" && strings.EqualFold(c.Name, typed): exact = true f.clientMatches = append([]dropdownItem{{id: c.ID, label: c.Name}}, f.clientMatches...) case query == "" || strings.Contains(strings.ToLower(c.Name), query): @@ -183,6 +200,7 @@ func (f *timerForm) rebuildClientMatches() { 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 } @@ -205,7 +223,7 @@ func (f *timerForm) rebuildProjectMatches() { label = p.Client.Name + " › " + p.Name } switch { - case strings.EqualFold(p.Name, typed): + case typed != "" && strings.EqualFold(p.Name, typed): exact = true f.projectMatches = append([]dropdownItem{{id: p.ID, label: label}}, f.projectMatches...) case query == "" || strings.Contains(strings.ToLower(p.Name), query): @@ -215,6 +233,7 @@ func (f *timerForm) rebuildProjectMatches() { if typed != "" && !exact { f.projectMatches = append(f.projectMatches, dropdownItem{id: 0, label: fmt.Sprintf("+ Create “%s”", typed)}) } + f.projectExact = exact if f.projectSel >= len(f.projectMatches) { f.projectSel = 0 } @@ -334,6 +353,7 @@ func (f *timerForm) step(d int) int { // 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() } @@ -351,11 +371,19 @@ func (f *timerForm) leave() { case fieldTask: f.applyQuickAdd() case fieldClient: - if f.showClientDrop { + switch { + case f.showClientDrop && f.choseClient: + f.applyClientSelection() + case f.clientExact && f.clientID == 0: + f.clientSel = 0 f.applyClientSelection() } case fieldProject: - if f.showProjectDrop { + switch { + case f.showProjectDrop && f.choseProject: + f.applyProjectSelection() + case f.projectExact && f.projectID == 0: + f.projectSel = 0 f.applyProjectSelection() } } @@ -428,9 +456,11 @@ func updateTimerFormFields(f *timerForm, msg tea.KeyMsg) (action string, cmd tea 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 } @@ -464,12 +494,14 @@ func updateTimerFormFields(f *timerForm, msg tea.KeyMsg) (action string, cmd tea 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 } @@ -533,7 +565,14 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel case startNow: v.start, startOK = now, true default: - t, ok := parseFormTime(startText, now) + day := now + if f.entryID != 0 { + day = f.origStart + } + t, ok := parseFormTime(startText, now, day) + if f.entryID != 0 && startText == f.filledStart { + t, ok = f.origStart, true + } switch { case !ok: errs[fieldStart] = errTimeFormat @@ -553,7 +592,17 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel case f.entryID == 0 && startNow: errs[fieldEnd] = errEndNeedsStart default: - t, ok := parseFormTime(endText, now) + day := now + switch { + case f.origEnd != nil: + day = *f.origEnd + case startOK: + day = v.start + } + t, ok := parseFormTime(endText, now, day) + if f.origEnd != nil && endText == f.filledEnd { + t, ok = *f.origEnd, true + } switch { case !ok: errs[fieldEnd] = errTimeFormat @@ -566,7 +615,7 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel } } - if f.entryID != 0 && v.invoiced && endText == "" { + if f.running && v.invoiced && endText == "" { errs[fieldInvoiced] = errInvoiceRunning } return v, errs @@ -574,8 +623,9 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel // 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 means today. -func parseFormTime(s string, now time.Time) (time.Time, bool) { +// ("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 @@ -591,7 +641,7 @@ func parseFormTime(s string, now time.Time) (time.Time, bool) { } 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 { - day := now.Local() + day := day.Local() return time.Date(day.Year(), day.Month(), day.Day(), t.Hour(), t.Minute(), 0, 0, time.Local), true } } @@ -626,9 +676,14 @@ func submitEditEntryCmd(database *db.DB, entryID int64, v timerFormValues, extra target.StartTime = v.start target.EndTime = v.end target.Invoiced, target.Paid = v.invoiced, v.paid - if resolvedProjectID > 0 { - target.ProjectID = resolvedProjectID + // Client and Project both blank means no project, as for + // `notch start` and a new timer: the uncategorized one. + if resolvedProjectID <= 0 { + if resolvedProjectID, err = database.EnsureUncategorizedProject(); err != nil { + return ErrMsg(err.Error()) + } } + target.ProjectID = resolvedProjectID if err := database.UpdateEntry(target); err != nil { return ErrMsg(err.Error()) } @@ -658,12 +713,14 @@ func (f timerForm) view(w, h int, saveLabel string) []string { } task := field("Task", fieldTask) client := field("Client", fieldClient) + client.suggests = true if f.focusIdx == fieldClient && f.showClientDrop && len(f.clientMatches) > 0 { - client.under = suggestions(f.clientMatches, f.clientSel, sw) + client.suggest = func(n int) []string { return suggestions(f.clientMatches, f.clientSel, sw, n) } } project := field("Project", fieldProject) + project.suggests = true if f.focusIdx == fieldProject && f.showProjectDrop && len(f.projectMatches) > 0 { - project.under = suggestions(f.projectMatches, f.projectSel, sw) + 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} diff --git a/internal/ui/views/timer_form_test.go b/internal/ui/views/timer_form_test.go index ecdf2d6..a831355 100644 --- a/internal/ui/views/timer_form_test.go +++ b/internal/ui/views/timer_form_test.go @@ -349,12 +349,12 @@ func TestParseFormTime(t *testing.T) { "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) + 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); ok { + if _, ok := parseFormTime("half nine", now, now); ok { t.Error("parseFormTime should refuse text that isn't a time") } } @@ -901,3 +901,172 @@ 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 TestSubmitEditEntryCmd_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 := timerFormValues{task: "t", start: start, end: ptrTime(start.Add(time.Hour))} + runCmd(t, submitEditEntryCmd(d, e.ID, v)) + entries, _ := d.ListEntries(0, "", "", true) + if uncategorized := mustUncategorized(t, d); entries[0].ProjectID != uncategorized { + t.Errorf("project = %d, want the uncategorized project %d", entries[0].ProjectID, uncategorized) + } +} + +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) + } + }) +} diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index 3e36d5f..12b7743 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -399,13 +399,23 @@ 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) + // The entry a confirm or Edit entry is about may be gone (another + // process deleted it): close them rather than show nothing. + if m.mode == timersModeConfirmDelete && m.entryByID(m.deleteID) == nil { + m.mode = timersModeList + return m, ErrCmd(errEntryGone) + } + return m, nil case timerStartedMsg: // After r or space starts a timer, select the new entry. 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 @@ -818,6 +828,20 @@ func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { ) } +// errEntryGone is the status when an entry is deleted (by another process) +// before its Edit entry or delete confirm opens. +const errEntryGone = "That entry no longer exists" + +// 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 + } + } + return nil +} + func mustLoadEntries(database *db.DB) []*model.Entry { entries, _ := database.ListEntries(0, "", "", true) return entries @@ -826,24 +850,20 @@ func mustLoadEntries(database *db.DB) []*model.Entry { // ── 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) - m.mode = timersModeNew + mode := timersModeNew if msg.entryID != 0 { - var e *model.Entry - for _, x := range m.entries { - if x.ID == msg.entryID { - e = x - break - } - } + e := m.entryByID(msg.entryID) if e == nil { return m } f.fill(e) f.canDelete = true - m.mode = timersModeEdit + mode = timersModeEdit } + m.mode = mode m.form = f m.err = "" return m From d7c7b7ebf3a48f4115bdd1d06c0a0f7fa4e59890 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:22:06 -0700 Subject: [PATCH 09/13] Refuse stale edits, and fix clashing project names and times at midnight (ALI-2616) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 2 on PR #15 found these problems: - With Client blank, a project name used under two clients ("Website" under Acme and Beta) was taken on tab as whichever came first, silently picking a client. Tab now takes an exact name only when one project has it; with several it leaves the text as typed and Project says "2 clients have Website — pick one". - A new timer couldn't cross midnight with bare times. In the New timer form, a bare Start later than now is last night's, and a bare End before the Start is the next day's; both still go through the no-future and end-not-before-start checks. - Saving a stale Edit entry overwrote changes made elsewhere: a timer stopped by the CLI or the bar was restarted, and a deleted entry's client was still created before the save failed. The save now checks the entry first. Gone, it says "That entry no longer exists". Times or running state changed, it keeps the form open with "This entry changed elsewhere — reopen it to edit". Saving is now synchronous, so that error can sit in the form. Edit entry also closes when a reload shows its entry gone, as the reload comment already said. - A kept Start has seconds (09:05:40), so an End typed as "09:05" read as before the Start. A typed time in the kept time's minute is now the same moment: a zero-length entry. --- internal/ui/views/modal.go | 10 ++ internal/ui/views/reports.go | 9 +- internal/ui/views/timer_form.go | 165 ++++++++++++++++------- internal/ui/views/timer_form_test.go | 190 ++++++++++++++++++++++++--- internal/ui/views/timers.go | 19 ++- 5 files changed, 319 insertions(+), 74 deletions(-) diff --git a/internal/ui/views/modal.go b/internal/ui/views/modal.go index c12c724..fe76c7c 100644 --- a/internal/ui/views/modal.go +++ b/internal/ui/views/modal.go @@ -205,6 +205,7 @@ type formModal struct { 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. @@ -283,6 +284,15 @@ func (fm formModal) render(w, h int) []string { } } 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}, diff --git a/internal/ui/views/reports.go b/internal/ui/views/reports.go index 0b1ddb9..b892698 100644 --- a/internal/ui/views/reports.go +++ b/internal/ui/views/reports.go @@ -339,7 +339,7 @@ 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. +// 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 { @@ -347,8 +347,11 @@ func (m ReportsModel) submitEditEntry(now time.Time) (ReportsModel, tea.Cmd) { return m, nil } m.editForm.errs = nil - m.mode = reportsModeEntries - return m, submitEditEntryCmd(m.db, m.editForm.entryID, v, m.loadCmd()) + 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 diff --git a/internal/ui/views/timer_form.go b/internal/ui/views/timer_form.go index bc79d70..93347f5 100644 --- a/internal/ui/views/timer_form.go +++ b/internal/ui/views/timer_form.go @@ -17,6 +17,7 @@ package views // the start. Errors sit under their field. import ( + "errors" "fmt" "strings" "time" @@ -122,6 +123,14 @@ type timerForm struct { // 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 @@ -213,7 +222,7 @@ func (f *timerForm) rebuildProjectMatches() { typed := strings.TrimSpace(f.inputs[fieldProject].Value()) query := strings.ToLower(typed) f.projectMatches = nil - exact := false + exact, exactN := false, 0 for _, p := range f.allProjects { if f.clientID != 0 && p.ClientID != f.clientID { continue @@ -225,6 +234,7 @@ func (f *timerForm) rebuildProjectMatches() { switch { case typed != "" && strings.EqualFold(p.Name, typed): exact = true + exactN++ f.projectMatches = append([]dropdownItem{{id: p.ID, label: label}}, f.projectMatches...) case query == "" || strings.Contains(strings.ToLower(p.Name), query): f.projectMatches = append(f.projectMatches, dropdownItem{id: p.ID, label: label}) @@ -233,7 +243,11 @@ func (f *timerForm) rebuildProjectMatches() { if typed != "" && !exact { f.projectMatches = append(f.projectMatches, dropdownItem{id: 0, label: fmt.Sprintf("+ Create “%s”", typed)}) } - f.projectExact = exact + f.projectExact = exactN == 1 + f.projectClash = 0 + if exactN > 1 { + f.projectClash = exactN + } if f.projectSel >= len(f.projectMatches) { f.projectSel = 0 } @@ -533,6 +547,11 @@ type timerFormValues struct { 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. + wasRunning bool + origStart time.Time + origEnd *time.Time } // validateTimerForm reads f's fields at now. errs maps each field that @@ -555,6 +574,7 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel } v.notes = strings.TrimSpace(f.inputs[fieldNotes].Value()) v.invoiced, v.paid = f.invoiced, f.paid + v.wasRunning, v.origStart, v.origEnd = f.running, f.origStart, f.origEnd startText := strings.TrimSpace(f.inputs[fieldStart].Value()) startNow := startText == "" || strings.EqualFold(startText, "now") @@ -573,6 +593,10 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel if f.entryID != 0 && startText == f.filledStart { t, ok = f.origStart, true } + // A new timer's bare Start later than now is last night's. + if _, bare := parseBareTime(startText, day); ok && bare && f.entryID == 0 && t.After(now) { + t = t.AddDate(0, 0, -1) + } switch { case !ok: errs[fieldStart] = errTimeFormat @@ -600,9 +624,24 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel day = v.start } t, ok := parseFormTime(endText, now, day) - if f.origEnd != nil && endText == f.filledEnd { + endKept := f.origEnd != nil && endText == f.filledEnd + if endKept { t, ok = *f.origEnd, 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 @@ -639,60 +678,85 @@ func parseFormTime(s string, now, day time.Time) (time.Time, bool) { 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 { - day := day.Local() - return time.Date(day.Year(), day.Month(), day.Day(), t.Hour(), t.Minute(), 0, 0, time.Local), true + 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 } -// submitEditEntryCmd finds or creates the client and project, then writes -// v to the entry entryID. Timers and Reports both save Edit entry with it; -// extra are the caller's reloads, run with the "Entry updated" status. -func submitEditEntryCmd(database *db.DB, entryID int64, v timerFormValues, extra ...tea.Cmd) 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()) - } - 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 - target.StartTime = v.start - target.EndTime = v.end - target.Invoiced, target.Paid = v.invoiced, v.paid - // Client and Project both blank means no project, as for - // `notch start` and a new timer: the uncategorized one. - if resolvedProjectID <= 0 { - if resolvedProjectID, err = database.EnsureUncategorizedProject(); err != nil { - return ErrMsg(err.Error()) - } - } - target.ProjectID = resolvedProjectID - if err := database.UpdateEntry(target); err != nil { - return ErrMsg(err.Error()) +var ( + errEditGone = errors.New(errEntryGone) + errEditStale = errors.New(errEntryChanged) +) + +// saveEditEntry writes v to the entry entryID. It checks the entry first, +// before creating any client or project: errEditGone when it's been +// deleted, errEditStale when its times or running state changed elsewhere +// (the CLI or the bar) since the form opened, so a stale form can't +// restart a stopped timer. Then it finds or creates the client and +// project; both blank means the uncategorized project, as for +// `notch start` and a new timer. +func saveEditEntry(database *db.DB, entryID int64, v timerFormValues) error { + entries, err := database.ListEntries(0, "", "", true) + if err != nil { + return err + } + var target *model.Entry + for _, e := range entries { + if e.ID == entryID { + target = e + break } - batch := make(tea.BatchMsg, 0, len(extra)+2) - batch = append(batch, RunningChangedCmd()) - batch = append(batch, extra...) - batch = append(batch, StatusCmd("Entry updated")) - return batch } + if target == nil { + return errEditGone + } + if target.IsRunning() != v.wasRunning || !target.StartTime.Equal(v.origStart) || + (target.EndTime != nil && v.origEnd != nil && !target.EndTime.Equal(*v.origEnd)) { + return errEditStale + } + 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.Task = v.task + target.Notes = v.notes + target.StartTime = v.start + target.EndTime = v.end + target.Invoiced, target.Paid = v.invoiced, v.paid + 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 ────────────────────────────────────────────────────────────────────── @@ -719,6 +783,9 @@ func (f timerForm) view(w, h int, saveLabel string) []string { } project := field("Project", fieldProject) project.suggests = true + if f.projectClash > 1 && f.projectID == 0 { + 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) } } @@ -726,7 +793,7 @@ func (f timerForm) view(w, h int, saveLabel string) []string { 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"} + 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" diff --git a/internal/ui/views/timer_form_test.go b/internal/ui/views/timer_form_test.go index a831355..cc166d9 100644 --- a/internal/ui/views/timer_form_test.go +++ b/internal/ui/views/timer_form_test.go @@ -1,6 +1,7 @@ package views import ( + "errors" "fmt" "regexp" "strconv" @@ -249,7 +250,7 @@ func TestValidateTimerForm_Messages(t *testing.T) { {"start in the future", func() timerForm { f := newTimerForm(nil, nil) f.inputs[fieldTask].SetValue("x") - f.inputs[fieldStart].SetValue("1:00 PM") + f.inputs[fieldStart].SetValue("2026-12-03 1:00 PM") return f }, fieldStart, errStartFuture}, {"end in the future", func() timerForm { @@ -269,7 +270,7 @@ func TestValidateTimerForm_Messages(t *testing.T) { f := newTimerForm(nil, nil) f.inputs[fieldTask].SetValue("x") f.inputs[fieldStart].SetValue("11:00 AM") - f.inputs[fieldEnd].SetValue("10:30 AM") + f.inputs[fieldEnd].SetValue("2026-12-03 10:30") return f }, fieldEnd, errEndBeforeStart}, {"edit: start cleared", func() timerForm { @@ -576,18 +577,100 @@ func TestSubmitForm_EditSavesTimesAndBilling(t *testing.T) { func ptrTime(t time.Time) *time.Time { return &t } -func TestSubmitEditEntryCmd_Errors(t *testing.T) { - d := newTestDB(t) - v := timerFormValues{task: "x", start: time.Now().Add(-time.Hour)} - if msgs := runCmd(t, submitEditEntryCmd(d, 999, v)); len(msgs) != 1 || msgs[0] != ErrMsg("Entry not found") { - t.Errorf("missing entry: msgs = %v, want Entry not found", msgs) +// 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 msgs := runCmd(t, submitEditEntryCmd(d, e.ID, v)); len(msgs) != 1 { - t.Errorf("bad project: msgs = %v, want one ErrMsg", msgs) - } else if _, ok := msgs[0].(ErrMsg); !ok { - t.Errorf("bad project: msg = %T, want ErrMsg", msgs[0]) + 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") + } + } +} + +// A timer stopped by the CLI or the bar while Edit entry is open mustn't +// be restarted by saving the stale form. +func TestSubmitForm_EditRefusesAnEntryChangedElsewhere(t *testing.T) { + d := newTestDB(t) + e, _ := d.AddEntry(mustUncategorized(t, d), "Running", "", time.Now().Add(-time.Hour), nil) + m := NewTimers(d) + m.SetSize(100, 30) + m = m.setEntries(mustLoadEntries(d), e.ID) + m = m.handleOpenForm(openFormMsg{entryID: e.ID}) + if err := d.StopEntry(e.ID); err != nil { + t.Fatal(err) + } + m.form.inputs[fieldTask].SetValue("Renamed") + 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.IsRunning() || s.Task != "Running" { + t.Errorf("stored entry = %+v, want it left stopped and unrenamed", s) + } +} + +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) } } @@ -1013,17 +1096,90 @@ func TestTimerForm_TabKeepsAPartlyTypedNameAndArrowsChoose(t *testing.T) { } } -func TestSubmitEditEntryCmd_BlankClientAndProjectIsUncategorized(t *testing.T) { +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 := timerFormValues{task: "t", start: start, end: ptrTime(start.Add(time.Hour))} - runCmd(t, submitEditEntryCmd(d, e.ID, v)) - entries, _ := d.ListEntries(0, "", "", true) - if uncategorized := mustUncategorized(t, d); entries[0].ProjectID != uncategorized { - t.Errorf("project = %d, want the uncategorized project %d", entries[0].ProjectID, uncategorized) + _, 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) } } diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index 12b7743..05b675f 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -402,7 +402,9 @@ func (m TimersModel) Update(msg tea.Msg) (TimersModel, tea.Cmd) { m = m.setEntries(msg, keepID) // The entry a confirm or Edit entry is about may be gone (another // process deleted it): close them rather than show nothing. - if m.mode == timersModeConfirmDelete && m.entryByID(m.deleteID) == nil { + 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) } @@ -776,13 +778,16 @@ func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { m.form.errs = nil if m.form.entryID != 0 { - m.mode = timersModeList - m.err = "" - return m, submitEditEntryCmd(m.db, m.form.entryID, v, + closeForm, cmd := m.form.submitEdit(m.db, v, func() tea.Msg { return timerEntriesMsg(mustLoadEntries(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; @@ -829,9 +834,13 @@ func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { } // errEntryGone is the status when an entry is deleted (by another process) -// before its Edit entry or delete confirm opens. +// before or while its Edit entry or delete confirm is open. const errEntryGone = "That entry no longer exists" +// 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 { From 1bf72d93bff41632853694a31f0e445b0626fddf Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:35:56 -0700 Subject: [PATCH 10/13] Save only changed fields, delete by ID, and let q type in forms (ALI-2616) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 3 on PR #15 found these problems: - The "2 clients have Website — pick one" hint didn't stop Save, so the entry landed under whichever same-named project came first. With Client blank it's now an error on Project. - With a new client typed ("Zed"), another client's project of the typed name still counted as an exact match, so tab took it and put Client back to that client. A typed client that doesn't exist yet now has no projects to suggest: the project is created under it. - q quit the app even in a form, so typing "quote" in Task lost the form (also on main). In a form or modal only ctrl+c quits now, and the key line says so. - The client and project delete confirms deleted the row under the cursor when confirmed, so a reload under the open modal could delete a different one with its entries. They keep the ID from when they opened, and close with "That client/project no longer exists" when it's gone. - Edit entry wrote every field from its snapshot, silently reverting a CLI --invoiced made while it was open. It now writes only the fields the user changed and keeps the rest as stored, and refuses only when a field the user changed was also changed elsewhere. Saving looks the entry up with a new db.GetEntry rather than loading every entry. - A bare Start later than now always rolled back a day, so "9:05 PM" at 09:30 started a 12-hour-old timer. It rolls back only when an End is given too; alone it's still "in the future". - Quick add ran in Edit entry, rewriting "Reply to @jane about Q4" and creating a client. It's for new timers only. - The first-run key line sent you to add a client first, while the copy says clients are created as you type; it now offers only n. The welcome screen waits for a load that succeeded with no entries, and reloads that fail are errors instead of an empty list. - The selected suggestion was marked by colour alone (WCAG 1.4.1). It now has the cursor glyph too. --- design/tokens.json | 2 +- internal/db/db.go | 23 ++++ internal/db/db_test.go | 26 ++++ internal/theme/tokens_gen.go | 4 +- internal/ui/app.go | 9 +- internal/ui/app_test.go | 19 +-- internal/ui/modal_test.go | 33 +++++ internal/ui/views/clients.go | 35 ++++- internal/ui/views/clients_test.go | 64 +++++++-- internal/ui/views/modal.go | 7 +- internal/ui/views/projects.go | 41 ++++-- internal/ui/views/projects_test.go | 43 +++++-- internal/ui/views/timer_form.go | 185 ++++++++++++++++++--------- internal/ui/views/timer_form_test.go | 176 +++++++++++++++++++++++-- internal/ui/views/timers.go | 41 ++++-- internal/ui/views/timers_test.go | 4 +- internal/ui/views/timers_view.go | 2 +- 17 files changed, 573 insertions(+), 141 deletions(-) diff --git a/design/tokens.json b/design/tokens.json index 406aa24..2991a9b 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -127,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." }, 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/tokens_gen.go b/internal/theme/tokens_gen.go index 6547efb..48645b5 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -48,7 +48,9 @@ var Default = Palette{ 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 = "●" diff --git a/internal/ui/app.go b/internal/ui/app.go index 157a6c0..fd55e9c 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -288,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 } @@ -531,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) diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index 85665d7..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") + } } } diff --git a/internal/ui/modal_test.go b/internal/ui/modal_test.go index 887a4ab..eae7ece 100644 --- a/internal/ui/modal_test.go +++ b/internal/ui/modal_test.go @@ -102,3 +102,36 @@ func TestBottomBar_OffersTheKeysSheet(t *testing.T) { 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 65c162e..3e79676 100644 --- a/internal/ui/views/clients.go +++ b/internal/ui/views/clients.go @@ -30,8 +30,10 @@ type ClientsModel struct { errs fieldErrors // deleteFocused: Delete has the focus in the delete confirm (Keep it - // has it at first). + // 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 @@ -107,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: @@ -142,6 +148,7 @@ func (m ClientsModel) updateList(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { if len(m.clients) > 0 { m.mode = clientModeConfirmDelete m.deleteFocused = false + m.deleteID = m.clients[m.cursor].ID } } return m, nil @@ -212,11 +219,13 @@ func (m ClientsModel) updateConfirm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { return m, nil } m.mode = clientModeList - if !del || len(m.clients) == 0 { + if !del { return m, nil } - id := m.clients[m.cursor].ID - if err := m.db.DeleteClient(id); err != nil { + if m.clientByID(m.deleteID) == nil { + return m, ErrCmd(errClientGone) + } + if err := m.db.DeleteClient(m.deleteID); err != nil { return m, ErrCmd(fmt.Sprintf("delete client: %v", err)) } return m, tea.Batch( @@ -226,6 +235,20 @@ func (m ClientsModel) updateConfirm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { ) } +// 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 ------------------------------------------------------------ func (m ClientsModel) openForm(c *model.Client) ClientsModel { @@ -403,10 +426,10 @@ func (m ClientsModel) viewForm(w, h int) []string { // viewConfirm is the delete confirm for the selected client. func (m ClientsModel) viewConfirm(w, h int) []string { - if len(m.clients) == 0 { + c := m.clientByID(m.deleteID) + if c == nil { return nil } - c := m.clients[m.cursor] return confirmModal{ title: "Delete client?", name: c.Name, diff --git a/internal/ui/views/clients_test.go b/internal/ui/views/clients_test.go index 9e53061..e92b19d 100644 --- a/internal/ui/views/clients_test.go +++ b/internal/ui/views/clients_test.go @@ -246,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) @@ -270,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 { @@ -285,14 +285,14 @@ func TestClientsUpdateConfirm_OtherKeyCancels(t *testing.T) { } } -func TestClientsUpdateConfirm_YWithNoClientsReturnsToList(t *testing.T) { - m := ClientsModel{mode: clientModeConfirmDelete, clients: nil} +func TestClientsUpdateConfirm_YWithTheClientGoneSaysSo(t *testing.T) { + m := ClientsModel{mode: clientModeConfirmDelete, clients: nil, deleteID: 7} 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") + if cmd == nil || cmd() != ErrMsg(errClientGone) { + t.Errorf("want %q when the client is gone", errClientGone) } } @@ -304,7 +304,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) @@ -662,11 +662,12 @@ func TestClientsView_ConfirmModeEmpty(t *testing.T) { func TestClientsView_ConfirmModePopulated(t *testing.T) { m := ClientsModel{ - mode: clientModeConfirmDelete, - width: 100, - height: 30, - cursor: 0, - clients: []*model.Client{{ID: 1, Name: "Acme", HourlyRate: 95}}, + 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"} { @@ -682,7 +683,7 @@ func TestClientsUpdateConfirm_EnterKeepsUntilDeleteHasFocus(t *testing.T) { if err != nil { t.Fatal(err) } - m := ClientsModel{db: d, mode: clientModeConfirmDelete, clients: []*model.Client{c}} + 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) } @@ -699,3 +700,40 @@ func TestClientsUpdateConfirm_EnterKeepsUntilDeleteHasFocus(t *testing.T) { 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) + } +} diff --git a/internal/ui/views/modal.go b/internal/ui/views/modal.go index fe76c7c..b401d4e 100644 --- a/internal/ui/views/modal.go +++ b/internal/ui/views/modal.go @@ -374,14 +374,15 @@ func suggestions(items []dropdownItem, sel, fieldW, maxRows int) []string { 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} + item := seg{s: fit(" "+items[i].label, inner), fg: cDim} if i == sel { - item = seg{s: fit(" "+items[i].label, inner), fg: cBg, bg: cPrimary, bold: true} + // 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)) + 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})) } diff --git a/internal/ui/views/projects.go b/internal/ui/views/projects.go index 8d2bf12..b1426a8 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -84,8 +84,10 @@ type ProjectsModel struct { err string // deleteFocused: Delete has the focus in the delete confirm (Keep it - // has it at first). + // 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 } func NewProjects(database *db.DB) ProjectsModel { @@ -160,6 +162,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: @@ -215,6 +221,7 @@ func (m ProjectsModel) updateList(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { if p := m.selectedProject(); p != nil { m.mode = projectsModeConfirmDelete m.deleteFocused = false + m.deleteID = p.ID } } return m, nil @@ -384,16 +391,30 @@ func (m ProjectsModel) FieldErrors() int { 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-- + if m.projectByID(m.deleteID) == nil { + return m, ErrCmd(errProjectGone) + } + 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. @@ -547,7 +568,7 @@ func (m ProjectsModel) viewForm(w, h int) []string { // viewConfirm is the delete confirm for the selected project. func (m ProjectsModel) viewConfirm(w, h int) []string { - p := m.selectedProject() + p := m.projectByID(m.deleteID) if p == nil { return nil } diff --git a/internal/ui/views/projects_test.go b/internal/ui/views/projects_test.go index 7d6f77d..e10e2af 100644 --- a/internal/ui/views/projects_test.go +++ b/internal/ui/views/projects_test.go @@ -130,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) @@ -150,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) @@ -918,7 +918,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) @@ -949,14 +949,14 @@ func TestProjectsDoDelete_CursorStaysAtZero(t *testing.T) { } } -func TestProjectsDoDelete_NoSelectionIsNoop(t *testing.T) { - m := ProjectsModel{mode: projectsModeConfirmDelete} +func TestProjectsDoDelete_GoneProjectSaysSo(t *testing.T) { + m := ProjectsModel{mode: projectsModeConfirmDelete, deleteID: 7} 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") + if cmd == nil || cmd() != ErrMsg(errProjectGone) { + t.Errorf("want %q when the project is gone", errProjectGone) } } @@ -1069,7 +1069,7 @@ 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}, width: 100, height: 30} + 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) { @@ -1137,3 +1137,30 @@ func TestProjectsRenderField_FocusedAndUnfocused(t *testing.T) { 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) + } +} diff --git a/internal/ui/views/timer_form.go b/internal/ui/views/timer_form.go index 93347f5..0d55436 100644 --- a/internal/ui/views/timer_form.go +++ b/internal/ui/views/timer_form.go @@ -70,16 +70,17 @@ var ( // 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." - errInvoiceRunning = "Stop the timer before invoicing it." + 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 { @@ -94,11 +95,11 @@ type timerForm struct { running bool // editing a running entry: End can stay blank canDelete bool // offer Delete entry (the Timers tab) - // The entry's stored times and the text Start and End were filled - // with: a field left as filled keeps its stored time, seconds and all, - // and a bare time of day is read on the entry's own day. - origStart time.Time - origEnd *time.Time + // 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 @@ -165,7 +166,7 @@ func (f *timerForm) fill(e *model.Entry) { f.invoiced, f.paid = e.Invoiced, e.Paid f.inputs[fieldTask].SetValue(e.Task) f.inputs[fieldNotes].SetValue(e.Notes) - f.origStart, f.origEnd = e.StartTime, e.EndTime + 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" @@ -184,10 +185,32 @@ func (f *timerForm) fill(e *model.Entry) { 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, @@ -223,12 +246,27 @@ func (f *timerForm) rebuildProjectMatches() { 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 + } for _, p := range f.allProjects { - if f.clientID != 0 && p.ClientID != f.clientID { + if newClient || (clientID != 0 && p.ClientID != clientID) { continue } label := p.Name - if f.clientID == 0 && p.Client != nil { + if clientID == 0 && p.Client != nil { label = p.Client.Name + " › " + p.Name } switch { @@ -310,6 +348,9 @@ func (f *timerForm) applyProjectSelection() { // 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 } @@ -549,9 +590,7 @@ type timerFormValues struct { invoiced, paid bool // For Edit entry, the entry as the form found it: the save refuses // if it has changed since. - wasRunning bool - origStart time.Time - origEnd *time.Time + orig entrySnapshot } // validateTimerForm reads f's fields at now. errs maps each field that @@ -562,7 +601,7 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel 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 v.clientName == "" && v.projectName == "" { + 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 @@ -572,9 +611,12 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel 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.wasRunning, v.origStart, v.origEnd = f.running, f.origStart, f.origEnd + v.orig = f.orig startText := strings.TrimSpace(f.inputs[fieldStart].Value()) startNow := startText == "" || strings.EqualFold(startText, "now") @@ -587,14 +629,17 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel default: day := now if f.entryID != 0 { - day = f.origStart + day = f.orig.start } t, ok := parseFormTime(startText, now, day) if f.entryID != 0 && startText == f.filledStart { - t, ok = f.origStart, true + t, ok = f.orig.start, true } - // A new timer's bare Start later than now is last night's. - if _, bare := parseBareTime(startText, day); ok && bare && f.entryID == 0 && t.After(now) { + // 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 { @@ -618,15 +663,15 @@ func validateTimerForm(f timerForm, now time.Time) (v timerFormValues, errs fiel default: day := now switch { - case f.origEnd != nil: - day = *f.origEnd + case f.orig.end != nil: + day = *f.orig.end case startOK: day = v.start } t, ok := parseFormTime(endText, now, day) - endKept := f.origEnd != nil && endText == f.filledEnd + endKept := f.orig.end != nil && endText == f.filledEnd if endKept { - t, ok = *f.origEnd, true + 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) { @@ -699,45 +744,65 @@ var ( errEditStale = errors.New(errEntryChanged) ) -// saveEditEntry writes v to the entry entryID. It checks the entry first, -// before creating any client or project: errEditGone when it's been -// deleted, errEditStale when its times or running state changed elsewhere -// (the CLI or the bar) since the form opened, so a stale form can't -// restart a stopped timer. Then it finds or creates the client and -// project; both blank means the uncategorized project, as for -// `notch start` and a new timer. +// 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 { - entries, err := database.ListEntries(0, "", "", true) + target, err := database.GetEntry(entryID) if err != nil { return err } - var target *model.Entry - for _, e := range entries { - if e.ID == entryID { - target = e - break - } - } if target == nil { return errEditGone } - if target.IsRunning() != v.wasRunning || !target.StartTime.Equal(v.origStart) || - (target.EndTime != nil && v.origEnd != nil && !target.EndTime.Equal(*v.origEnd)) { + o, now := v.orig, snapshotOf(target) + taskCh, notesCh := v.task != o.task, v.notes != o.notes + projectCh := v.projectID != o.projectID + startCh, endCh := !v.start.Equal(o.start), !sameTime(v.end, o.end) + invoicedCh, paidCh := v.invoiced != o.invoiced, v.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)) || + (invoicedCh && now.invoiced != o.invoiced) || (paidCh && now.paid != o.paid) { return errEditStale } - projectID, err := database.ResolveOrCreateProject(v.clientID, v.clientName, v.projectID, v.projectName) - if err == nil && projectID <= 0 { - projectID, err = database.EnsureUncategorizedProject() + if taskCh { + target.Task = v.task } - if err != nil { - return err + if notesCh { + target.Notes = v.notes + } + if startCh { + target.StartTime = v.start + } + if endCh { + target.EndTime = v.end + } + if invoicedCh { + target.Invoiced = v.invoiced + } + if paidCh { + target.Paid = v.paid + } + if target.EndTime != nil && target.EndTime.Before(target.StartTime) { + 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 } - target.Task = v.task - target.Notes = v.notes - target.StartTime = v.start - target.EndTime = v.end - target.Invoiced, target.Paid = v.invoiced, v.paid - target.ProjectID = projectID return database.UpdateEntry(target) } @@ -783,7 +848,7 @@ func (f timerForm) view(w, h int, saveLabel string) []string { } project := field("Project", fieldProject) project.suggests = true - if f.projectClash > 1 && f.projectID == 0 { + 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 { diff --git a/internal/ui/views/timer_form_test.go b/internal/ui/views/timer_form_test.go index cc166d9..6b61f91 100644 --- a/internal/ui/views/timer_form_test.go +++ b/internal/ui/views/timer_form_test.go @@ -631,28 +631,60 @@ func TestSaveEditEntry_GoneEntryCreatesNothing(t *testing.T) { } } -// A timer stopped by the CLI or the bar while Edit entry is open mustn't -// be restarted by saving the stale form. -func TestSubmitForm_EditRefusesAnEntryChangedElsewhere(t *testing.T) { - d := newTestDB(t) - e, _ := d.AddEntry(mustUncategorized(t, d), "Running", "", time.Now().Add(-time.Hour), nil) +// 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) - m = m.handleOpenForm(openFormMsg{entryID: 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.IsRunning() || s.Task != "Running" { - t.Errorf("stored entry = %+v, want it left stopped and unrenamed", s) + 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) } } @@ -846,7 +878,8 @@ func TestView_SuggestionsBox(t *testing.T) { updateTimerFormFields(&m.form, keyTab) typeInto(&m.form, "Harb") text := plain(m.View()) - for _, want := range []string{"│ Harbor & Pine", "│ + Create “Harb”", "↑↓ choose · enter pick"} { + // 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) } @@ -925,9 +958,11 @@ func TestStripInput_PicksUpLiveThemeChange(t *testing.T) { } func TestView_FirstRunHelpAndModal(t *testing.T) { - m := TimersModel{width: 140, height: 36} - if h := m.Help(); len(h) != 2 || h[0] != (Hotkey{"n", "new timer"}) || h[1] != (Hotkey{"3", "add a client first"}) { - t.Errorf("first-run Help() = %v", h) + 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") { @@ -1051,7 +1086,7 @@ func TestView_SuggestionsKeepTheModalStillAndWhole(t *testing.T) { closed := plain(m.View()) typeInto(&m.form, "Har") open := plain(m.View()) - if !strings.Contains(open, "│ Harbor 1") { + if !strings.Contains(open, "Harbor 1") { t.Fatalf("want the suggestions open:\n%s", open) } if top(open) != top(closed) || top(open) < 0 { @@ -1226,3 +1261,118 @@ func TestValidateTimerForm_EditTimes(t *testing.T) { } }) } + +// 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) + } +} diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index 05b675f..d6b7315 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -2,6 +2,7 @@ package views import ( "errors" + "fmt" "strings" "time" @@ -76,6 +77,7 @@ 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 @@ -361,8 +363,8 @@ func (m TimersModel) Help() []Hotkey { case timersModeFilter: return []Hotkey{{"tab", "switch"}, {"enter", "apply"}, {"esc", "cancel"}} default: - if len(m.entries) == 0 { - return []Hotkey{{"n", "new timer"}, {"3", "add a client first"}} + if m.firstRun() { + return []Hotkey{{"n", "new timer"}} } if !m.wide() { return []Hotkey{ @@ -400,6 +402,7 @@ func (m TimersModel) Update(msg tea.Msg) (TimersModel, tea.Cmd) { keepID = e.ID } 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) || @@ -412,6 +415,7 @@ func (m TimersModel) Update(msg tea.Msg) (TimersModel, tea.Cmd) { 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: @@ -691,7 +695,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") }, } } @@ -706,7 +710,7 @@ func (m TimersModel) startCmd(projectID int64, task string) tea.Cmd { } 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") }, } } @@ -719,7 +723,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") }, } } @@ -743,7 +747,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") }, } } @@ -755,7 +759,7 @@ 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") }, } } @@ -779,7 +783,7 @@ func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { if m.form.entryID != 0 { closeForm, cmd := m.form.submitEdit(m.db, v, - func() tea.Msg { return timerEntriesMsg(mustLoadEntries(m.db)) }, + loadTimerEntriesCmd(m.db), loadProjectsData(m.db), loadClientsCmd(m.db), ) @@ -826,13 +830,32 @@ func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { } return m, tea.Batch( RunningChangedCmd(), - func() tea.Msg { return timerStartedMsg{entries: mustLoadEntries(m.db), id: e.ID} }, + loadStartedCmd(m.db, e.ID), loadProjectsData(m.db), loadClientsCmd(m.db), StatusCmd(status), ) } +// 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 { + entries, err := database.ListEntries(0, "", "", true) + if err != nil { + return ErrMsg(fmt.Sprintf("load entries: %v", err)) + } + return timerStartedMsg{entries: entries, id: id} + } +} + +// 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 +} + // 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" diff --git a/internal/ui/views/timers_test.go b/internal/ui/views/timers_test.go index ad4313b..8dc02a2 100644 --- a/internal/ui/views/timers_test.go +++ b/internal/ui/views/timers_test.go @@ -1173,14 +1173,14 @@ func TestView_DispatchesByMode(t *testing.T) { t.Errorf("View() in edit-form mode should render the form, got %q", got) } - listMode := TimersModel{mode: timersModeList, width: 100, height: 30} + 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} + 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) { diff --git a/internal/ui/views/timers_view.go b/internal/ui/views/timers_view.go index a59c43d..22174aa 100644 --- a/internal/ui/views/timers_view.go +++ b/internal/ui/views/timers_view.go @@ -880,7 +880,7 @@ 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 len(m.entries) == 0 && m.mode != timersModeFilter { + if m.firstRun() { return m.viewFirstRun() } var out []string From ba50bb54a2b42aaba5478424ad8cd606e18f8801 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:37:56 -0700 Subject: [PATCH 11/13] Save the client and project edit forms to the record they opened for (ALI-2616) Edit project saved to the project under the cursor at save time, so a reload while the form was open (another process adding or deleting a project) could rename a different project. It now keeps the project's ID when it opens and saves to that one, read fresh from the database. Edit client already saved by its stored ID, but when that client had been deleted elsewhere the save failed with "Save failed: not found" and left the form open on nothing. Both forms now close when their record is gone, with "That client no longer exists" or "That project no longer exists", and reload the list. --- internal/ui/views/clients.go | 7 ++++ internal/ui/views/clients_test.go | 41 ++++++++++++++++++++++++ internal/ui/views/projects.go | 20 +++++++++--- internal/ui/views/projects_test.go | 51 ++++++++++++++++++++---------- 4 files changed, 98 insertions(+), 21 deletions(-) diff --git a/internal/ui/views/clients.go b/internal/ui/views/clients.go index 3e79676..4dab436 100644 --- a/internal/ui/views/clients.go +++ b/internal/ui/views/clients.go @@ -297,6 +297,13 @@ func (m ClientsModel) submitForm() (ClientsModel, tea.Cmd) { 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 errors.Is(err, db.ErrClientNameTaken) { diff --git a/internal/ui/views/clients_test.go b/internal/ui/views/clients_test.go index e92b19d..2be6d6b 100644 --- a/internal/ui/views/clients_test.go +++ b/internal/ui/views/clients_test.go @@ -737,3 +737,44 @@ func TestClientsConfirm_DeletesTheClientItOpenedFor(t *testing.T) { 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/projects.go b/internal/ui/views/projects.go index b1426a8..d098a35 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -88,6 +88,10 @@ type ProjectsModel struct { // 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 { @@ -210,6 +214,7 @@ 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.errs = nil m = m.focus(projFieldClient) @@ -353,13 +358,18 @@ func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { case projectsModeNewProject: _, 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)) + } + if gerr != nil { + return m, ErrCmd(gerr.Error()) } - // Edit a copy: the list shares p, and a refused rename mustn't - // show there. edited := *p edited.ClientID = m.clientID edited.Name = name diff --git a/internal/ui/views/projects_test.go b/internal/ui/views/projects_test.go index e10e2af..22ca683 100644 --- a/internal/ui/views/projects_test.go +++ b/internal/ui/views/projects_test.go @@ -803,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() @@ -843,7 +843,7 @@ 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() @@ -860,26 +860,45 @@ func TestProjectsSaveForm_EditError(t *testing.T) { _ = 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) } } From 20309e74501184d47d7257385a6ffd115309d6c9 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:46:28 -0700 Subject: [PATCH 12/13] Keep billing whole in edit merges, and fix confirms, suggestions and narrow fields (ALI-2616) Review round 4 on PR #15 found these problems: - The Edit entry merge checked invoiced and paid separately, so ticking Paid while the CLI un-invoiced the entry (or the reverse) could store paid without invoiced. Billing is one unit now: a change to either here and either elsewhere is stale. The merged entry also goes through model.ApplyBilling before it's written. - The client and project delete confirms checked the loaded list for a row deleted elsewhere, so a row already gone was "deleted" again and reported as deleted. They ask the database. - The merge compared the stored task and notes untrimmed with the form's trimmed text, so stray spaces counted as a change. - In the Project form, tab took the highlighted client, which wasn't always the exact name: "ACME Corp" sorts before "Acme". An exact name is listed first now, as in the timer form. - n kept the entry in the Projects confirm but not in Clients or Timers. esc and n keep in every confirm. - A theme.conf that changed bg without a backdrop kept the default's backdrop. It's now mixed from bg and border, as for aliasOS themes. - On a narrow terminal the field strip is narrower than the input's own width, so the end of long text and the cursor could be hidden. The input's window is recomputed for the strip each time it draws. --- design/tokens.json | 2 +- internal/theme/theme.go | 8 +++ internal/theme/theme_test.go | 19 ++++++ internal/theme/tokens_gen.go | 5 +- internal/ui/views/clients.go | 11 +++- internal/ui/views/clients_test.go | 17 ++++- internal/ui/views/modal.go | 11 ++++ internal/ui/views/projects.go | 18 ++++-- internal/ui/views/projects_test.go | 57 ++++++++++++++++- internal/ui/views/timer_form.go | 26 +++++--- internal/ui/views/timer_form_test.go | 93 ++++++++++++++++++++++++++++ internal/ui/views/timers.go | 3 +- 12 files changed, 246 insertions(+), 24 deletions(-) diff --git a/design/tokens.json b/design/tokens.json index 2991a9b..e553170 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -22,7 +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 gets border mixed 60% over bg." }, + { "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." } diff --git a/internal/theme/theme.go b/internal/theme/theme.go index ebabdf9..5c72c80 100644 --- a/internal/theme/theme.go +++ b/internal/theme/theme.go @@ -178,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()) @@ -195,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 } diff --git a/internal/theme/theme_test.go b/internal/theme/theme_test.go index c75a74a..9eb16f8 100644 --- a/internal/theme/theme_test.go +++ b/internal/theme/theme_test.go @@ -632,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 48645b5..7ab5770 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -39,8 +39,9 @@ var Default = Palette{ // 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 - // gets border mixed 60% over bg. + // 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", } diff --git a/internal/ui/views/clients.go b/internal/ui/views/clients.go index 4dab436..03e289e 100644 --- a/internal/ui/views/clients.go +++ b/internal/ui/views/clients.go @@ -214,7 +214,8 @@ func (m ClientsModel) updateConfirm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { return m, nil case msg.Type == tea.KeyEnter, msg.String() == " ": del = m.deleteFocused - case key.Matches(msg, formKeys.Cancel): + case key.Matches(msg, formKeys.Cancel), msg.String() == "n", msg.String() == "N": + // esc and n keep it, in every tab's confirm. default: return m, nil } @@ -222,8 +223,12 @@ func (m ClientsModel) updateConfirm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { if !del { return m, nil } - if m.clientByID(m.deleteID) == nil { - return m, ErrCmd(errClientGone) + // 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)) diff --git a/internal/ui/views/clients_test.go b/internal/ui/views/clients_test.go index 2be6d6b..5af04a5 100644 --- a/internal/ui/views/clients_test.go +++ b/internal/ui/views/clients_test.go @@ -286,12 +286,25 @@ func TestClientsUpdateConfirm_OtherKeyCancels(t *testing.T) { } func TestClientsUpdateConfirm_YWithTheClientGoneSaysSo(t *testing.T) { - m := ClientsModel{mode: clientModeConfirmDelete, clients: nil, deleteID: 7} + // 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 || cmd() != ErrMsg(errClientGone) { + 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) } } diff --git a/internal/ui/views/modal.go b/internal/ui/views/modal.go index b401d4e..2ac506d 100644 --- a/internal/ui/views/modal.go +++ b/internal/ui/views/modal.go @@ -335,7 +335,18 @@ func stripInput(ti textinput.Model, w int) string { 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 starting at the cursor when the cursor is left of that. The + // cursor and the text by it always show. + pos := ti.Position() + ti.Width = 0 + ti.CursorEnd() ti.Width = max(1, w-3) + ti.CursorEnd() + ti.SetCursor(pos) v := trimTrailingUnstyledPad(ti.View()) if ansi.StringWidth(v) > w-1 { v = ansi.Truncate(v, w-1, "") diff --git a/internal/ui/views/projects.go b/internal/ui/views/projects.go index d098a35..710bcde 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -401,8 +401,12 @@ func (m ProjectsModel) FieldErrors() int { func (m ProjectsModel) doDelete() (ProjectsModel, tea.Cmd) { m.mode = projectsModeList - if m.projectByID(m.deleteID) == nil { - return m, ErrCmd(errProjectGone) + // 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()) @@ -448,10 +452,16 @@ func (m *ProjectsModel) resolveClientID() error { // rebuildClientMatches filters clients by the current client input text. func (m *ProjectsModel) rebuildClientMatches() { - query := strings.ToLower(strings.TrimSpace(m.inputs[projFieldClient].Value())) + typed := strings.TrimSpace(m.inputs[projFieldClient].Value()) + query := strings.ToLower(typed) m.clientMatches = nil for _, c := range m.clients { - if query == "" || strings.Contains(strings.ToLower(c.Name), query) { + switch { + case typed != "" && strings.EqualFold(c.Name, typed): + // An exact name goes first, so it's what tab and enter take: + // "Acme" stays Acme, not "ACME Corp", which sorts before it. + m.clientMatches = append([]dropdownItem{{id: c.ID, label: c.Name}}, m.clientMatches...) + case query == "" || strings.Contains(strings.ToLower(c.Name), query): m.clientMatches = append(m.clientMatches, dropdownItem{id: c.ID, label: c.Name}) } } diff --git a/internal/ui/views/projects_test.go b/internal/ui/views/projects_test.go index 22ca683..ee73ca0 100644 --- a/internal/ui/views/projects_test.go +++ b/internal/ui/views/projects_test.go @@ -969,12 +969,26 @@ func TestProjectsDoDelete_CursorStaysAtZero(t *testing.T) { } func TestProjectsDoDelete_GoneProjectSaysSo(t *testing.T) { - m := ProjectsModel{mode: projectsModeConfirmDelete, deleteID: 7} + // 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 || cmd() != ErrMsg(errProjectGone) { + 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) } } @@ -1183,3 +1197,42 @@ func TestProjectsConfirm_DeletesTheProjectItOpenedFor(t *testing.T) { 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") + } +} diff --git a/internal/ui/views/timer_form.go b/internal/ui/views/timer_form.go index 0d55436..e4635e7 100644 --- a/internal/ui/views/timer_form.go +++ b/internal/ui/views/timer_form.go @@ -762,14 +762,21 @@ func saveEditEntry(database *db.DB, entryID int64, v timerFormValues) error { return errEditGone } o, now := v.orig, snapshotOf(target) - taskCh, notesCh := v.task != o.task, v.notes != o.notes + // 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) - invoicedCh, paidCh := v.invoiced != o.invoiced, v.paid != o.paid + // 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)) || - (invoicedCh && now.invoiced != o.invoiced) || (paidCh && now.paid != o.paid) { + (billingCh && billingElsewhere) { return errEditStale } if taskCh { @@ -784,15 +791,16 @@ func saveEditEntry(database *db.DB, entryID int64, v timerFormValues) error { if endCh { target.EndTime = v.end } - if invoicedCh { - target.Invoiced = v.invoiced - } - if paidCh { - target.Paid = v.paid - } 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 { diff --git a/internal/ui/views/timer_form_test.go b/internal/ui/views/timer_form_test.go index 6b61f91..85c0986 100644 --- a/internal/ui/views/timer_form_test.go +++ b/internal/ui/views/timer_form_test.go @@ -1376,3 +1376,96 @@ func TestEditEntry_NoQuickAdd(t *testing.T) { 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) + } +} diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index d6b7315..c3ff83f 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -622,7 +622,8 @@ func (m TimersModel) updateConfirm(msg tea.KeyMsg) (TimersModel, tea.Cmd) { switch { case msg.String() == "y", msg.String() == "Y": del = true - case key.Matches(msg, timersKeys.Cancel): + 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 From cdda5cc1dbfbe06533a1cdc721ee7066a43eb20e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 09:52:59 -0700 Subject: [PATCH 13/13] Keep context left of the cursor, and prefer the typed case for exact names (ALI-2616) Review round 5 on PR #15 found two problems: - On a narrow strip, moving the cursor left of the window that ends at the text's end started the window at the cursor, so typing in the middle of a long field showed nothing to its left. The window now starts a quarter of the strip before the cursor (clamped at 0), with the cursor and the text after it still showing. - The exact-name preference matched ignoring case and prepended each match, so with clients "Acme" and "acme", typing "Acme" picked the later "acme". An exact match in the typed case now comes first, then any case, through one helper shared by the timer form (clients and projects) and the Project form. --- internal/ui/views/modal.go | 5 ++-- internal/ui/views/projects.go | 12 +++++---- internal/ui/views/projects_test.go | 19 ++++++++++++++ internal/ui/views/timer_form.go | 37 ++++++++++++++++++++++------ internal/ui/views/timer_form_test.go | 30 ++++++++++++++++++++++ 5 files changed, 89 insertions(+), 14 deletions(-) diff --git a/internal/ui/views/modal.go b/internal/ui/views/modal.go index 2ac506d..a0ad4fa 100644 --- a/internal/ui/views/modal.go +++ b/internal/ui/views/modal.go @@ -339,13 +339,14 @@ func stripInput(ti textinput.Model, w int) string { // 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 starting at the cursor when the cursor is left of that. The - // cursor and the text by it always show. + // 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 { diff --git a/internal/ui/views/projects.go b/internal/ui/views/projects.go index 710bcde..fbd5bbf 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -454,17 +454,19 @@ func (m *ProjectsModel) resolveClientID() error { func (m *ProjectsModel) rebuildClientMatches() { typed := strings.TrimSpace(m.inputs[projFieldClient].Value()) query := strings.ToLower(typed) - m.clientMatches = nil + // 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 { switch { case typed != "" && strings.EqualFold(c.Name, typed): - // An exact name goes first, so it's what tab and enter take: - // "Acme" stays Acme, not "ACME Corp", which sorts before it. - m.clientMatches = append([]dropdownItem{{id: c.ID, label: c.Name}}, m.clientMatches...) + exacts, names = append(exacts, dropdownItem{id: c.ID, label: c.Name}), append(names, c.Name) case query == "" || strings.Contains(strings.ToLower(c.Name), query): - m.clientMatches = append(m.clientMatches, dropdownItem{id: c.ID, label: c.Name}) + 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 } diff --git a/internal/ui/views/projects_test.go b/internal/ui/views/projects_test.go index ee73ca0..f2c288d 100644 --- a/internal/ui/views/projects_test.go +++ b/internal/ui/views/projects_test.go @@ -1236,3 +1236,22 @@ func TestConfirms_NKeeps(t *testing.T) { 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/timer_form.go b/internal/ui/views/timer_form.go index e4635e7..9aa673e 100644 --- a/internal/ui/views/timer_form.go +++ b/internal/ui/views/timer_form.go @@ -218,17 +218,18 @@ func sameTime(a, b *time.Time) bool { func (f *timerForm) rebuildClientMatches() { typed := strings.TrimSpace(f.inputs[fieldClient].Value()) query := strings.ToLower(typed) - f.clientMatches = nil - exact := false + var exacts, rest []dropdownItem + var names []string for _, c := range f.allClients { switch { case typed != "" && strings.EqualFold(c.Name, typed): - exact = true - f.clientMatches = append([]dropdownItem{{id: c.ID, label: c.Name}}, f.clientMatches...) + exacts, names = append(exacts, dropdownItem{id: c.ID, label: c.Name}), append(names, c.Name) case query == "" || strings.Contains(strings.ToLower(c.Name), query): - f.clientMatches = append(f.clientMatches, dropdownItem{id: c.ID, label: c.Name}) + 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)}) } @@ -238,6 +239,25 @@ func (f *timerForm) rebuildClientMatches() { } } +// 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. @@ -261,6 +281,8 @@ func (f *timerForm) rebuildProjectMatches() { } newClient = clientID == 0 } + var exacts, rest []dropdownItem + var names []string for _, p := range f.allProjects { if newClient || (clientID != 0 && p.ClientID != clientID) { continue @@ -273,11 +295,12 @@ func (f *timerForm) rebuildProjectMatches() { case typed != "" && strings.EqualFold(p.Name, typed): exact = true exactN++ - f.projectMatches = append([]dropdownItem{{id: p.ID, label: label}}, f.projectMatches...) + exacts, names = append(exacts, dropdownItem{id: p.ID, label: label}), append(names, p.Name) case query == "" || strings.Contains(strings.ToLower(p.Name), query): - f.projectMatches = append(f.projectMatches, dropdownItem{id: p.ID, label: label}) + 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)}) } diff --git a/internal/ui/views/timer_form_test.go b/internal/ui/views/timer_form_test.go index 85c0986..1898bee 100644 --- a/internal/ui/views/timer_form_test.go +++ b/internal/ui/views/timer_form_test.go @@ -1469,3 +1469,33 @@ func TestSaveEditEntry_WhitespaceIsNotAChange(t *testing.T) { 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) + } + } +}