diff --git a/README.md b/README.md index 2be4e1c..13f02c8 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` | Compact layout (under 120 columns, or under 23 rows): 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..d23fda9 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -316,13 +316,33 @@ 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"}, + {"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"}, + {"tui-col-earned", "ColEarned"}, + {"tui-hero-rows", "HeroRows"}, + {"tui-hero-rows-compact", "HeroRowsCompact"}, + } { + 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) { @@ -331,6 +351,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 e5aaa33..1a3f07f 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." }, @@ -59,7 +59,25 @@ "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. 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." }, + { "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). 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." } ] }, @@ -97,10 +115,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": { @@ -111,22 +129,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 0eecfa5..df7b217 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. @@ -46,16 +48,87 @@ 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. 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 +// 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 + +// 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 + +// 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/app.go b/internal/ui/app.go index 80eb73c..16ed5aa 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 @@ -22,31 +23,25 @@ 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 -// 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). 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 +56,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. @@ -264,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() } } @@ -341,286 +341,199 @@ 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(), 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. -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 { - if i == m.activeTab { - tabParts = append(tabParts, activeSty.Render(name)) - } else { - tabParts = append(tabParts, inactiveSty.Render(name)) - } - } - 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 - } - - 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) +// 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)) } -// 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) +// 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) } -// 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) -} +// tabLabel is one tab in the tab bar: " 1 Timers ". +func tabLabel(i int) string { return fmt.Sprintf(" %d %s ", i+1, tabNames[i]) } -// 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) -} +func wordmark() string { return theme.GlyphWordmark + " notch" } -func (m AppModel) renderHotkeyBar() string { - pad := 2 - inner := max(10, m.width-pad*2) - capStyle := hotkeyKeyCapStyle() - sepStyle := lipgloss.NewStyle().Background(appColorBg).Foreground(appColorSubtle) +// 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 +} - 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)) +func (m AppModel) tabStrip(level int) tabStrip { + bg := appColorBgAlt + mark, gap := wordmark(), strings.Repeat(" ", theme.WordmarkGap) + if level >= 2 { + mark, gap = theme.GlyphWordmark, strings.Repeat(" ", theme.TabGap) } - - globalWidth := 0 - for i, h := range hotkeyGlobal { - globalWidth += hotkeyChipWidth(h) + 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 { - globalWidth += lipgloss.Width(hotkeySep) + st.s += paint(strings.Repeat(" ", theme.TabGap), appColorText, bg, false) + col += theme.TabGap } - } - - // 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 - for i, h := range m.activeViewHelp() { - cw := hotkeyChipWidth(h) - if i > 0 { - cw += lipgloss.Width(hotkeySep) + num, name, _ := strings.Cut(strings.TrimSpace(tabLabel(i)), " ") + nameFg, bold := appColorDim, false + if i == m.activeTab { + nameFg, bold = appColorText, true + } else if level >= 1 { + name = "" } - if w+cw > maxContext { - break + 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) } - w += cw - context = append(context, h) - } - - combined := renderRow(hotkeyGlobal) - if len(context) > 0 { - combined = renderRow(context) + sepStyle.Render(hotkeySep) + combined + st.s += paint(" ", appColorText, bg, false) + if i == m.activeTab { + st.underFrom, st.underTo = col, col+lipgloss.Width(label) + } + col += lipgloss.Width(label) } - - return lipgloss.NewStyle(). - Width(m.width). - Padding(1, pad). - // PaddingTop(1). - Align(lipgloss.Center). - Background(appColorBg). - Foreground(appColorSubtle). - Render(combined) + st.width = col + return st } -// 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 +// 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 pill string + if r := m.running; r != nil { + // 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 { + pill = paint(theme.GlyphLive+" idle", appColorSubtle, bg, false) } + pillW := lipgloss.Width(pill) + theme.Margin - rightBudget := 62 - if inner-rightBudget < 20 { - rightBudget = inner / 3 + st := m.tabStrip(0) + for level := 1; level <= 2 && st.width+1+pillW > m.width; level++ { + st = m.tabStrip(level) } - 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)) - } + 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-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(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) + return line + "\n" + ruleLine +} + +// hotkeySep separates hotkey chips in the hotkey line. +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 { + return paint(" "+h.Key+" ", appColorText, appColorBgAlt, true) + + paint(" "+h.Label, appColorSubtle, appColorBg, false) +} - // ── 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 +func hotkeyChipWidth(h views.Hotkey) int { + return lipgloss.Width(h.Key) + 2 + 1 + lipgloss.Width(h.Label) +} + +// renderBottomBar renders a rule, then one line: the active view's keys +// 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) + + var msg string switch { case m.err != "": - rightText = "✖ " + m.err - rightStyle = barBg.Foreground(appColorDanger).Bold(true) + msg = paint(truncateStr("✕ "+m.err, inner), appColorDanger, bg, 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) + msg = paint(truncateStr("✓ "+m.statusMsg, inner), appColorGreen, bg, false) + } + room := inner + if msg != "" { + room -= lipgloss.Width(msg) + theme.KeyGap } - right := rightStyle.Render(truncateStr(rightText, rightBudget)) - lw := lipgloss.Width(left) - rw := lipgloss.Width(right) - gap := inner - lw - rw - if gap < 2 { - gap = 2 + // 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"}) { + cw := hotkeyChipWidth(h) + if i > 0 { + cw += len(hotkeySep) + } + if w+cw > room { + break + } + if i > 0 { + keys += paint(hotkeySep, appColorSubtle, bg, false) + } + keys += renderHotkeyChip(h) + w += cw } - 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) } +// 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. @@ -650,7 +563,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..a4458b4 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" @@ -137,37 +139,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 := theme.Margin + lipgloss.Width(wordmark()) + theme.WordmarkGap + for i := 0; i < tab; i++ { + 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))) { + t.Errorf("tab %d: rule %q should underline exactly %q", tab, string(rule), tabLabel(tab)) + } } } @@ -237,14 +251,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 +269,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 +296,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 +327,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 +347,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 +423,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 +431,214 @@ 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) + } +} + +// 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) + } +} + +// 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) + 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) + } +} + +// 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 bc451ec..702f4f6 100644 --- a/internal/ui/layout_gen.go +++ b/internal/ui/layout_gen.go @@ -6,7 +6,21 @@ 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 + +// 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). 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/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/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 0b3fb2c..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 @@ -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..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) { @@ -154,10 +157,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/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 6b519d4..bc530e4 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,28 @@ 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 +} + +// 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 +// a tab switch, so coming back shows the list. +func (m TimersModel) CloseDetail() TimersModel { + m.detailOpen = false + return m } type timersPreset int @@ -376,6 +365,7 @@ const ( timersPresetToday timersPreset = iota timersPresetYesterday timersPresetWeek + timersPresetMonth timersPresetAll timersPresetCustom ) @@ -404,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 @@ -445,12 +440,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 @@ -479,32 +473,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()) @@ -515,7 +485,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 +510,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 +518,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 @@ -644,7 +591,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: @@ -659,16 +606,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"}, } } } @@ -683,10 +635,17 @@ func (m TimersModel) Update(msg tea.Msg) (TimersModel, tea.Cmd) { switch msg := msg.(type) { case timerEntriesMsg: - m.entries = []*model.Entry(msg) - m.recomputeFiltered() - m.clampOffset() - return m, nil + // 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). + var keepID int64 + if e := m.selectedEntry(); e != nil { + keepID = e.ID + } + 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) @@ -724,10 +683,12 @@ 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): if e := m.selectedEntry(); e != nil { + m.detailOpen = false return m, m.openFormCmd(e.ID) } @@ -762,21 +723,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() @@ -785,21 +736,27 @@ 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.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() { + 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 - m.fromInput.SetValue("") - m.toInput.SetValue("") - m.cursor = 0 - m.recomputeFiltered() + m.setRange(timersPresetAll, "", "") case key.Matches(msg, timersKeys.Filter): m.mode = timersModeFilter @@ -811,6 +768,34 @@ 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) { + m.preset = p + m.dateFrom, m.dateTo = from, to + 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() +} + // openFormCmd loads clients+projects then opens the form. func (m TimersModel) openFormCmd(entryID int64) tea.Cmd { return func() tea.Msg { @@ -1025,6 +1010,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 @@ -1047,14 +1033,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: @@ -1102,12 +1084,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") }, } } @@ -1297,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") }, @@ -1395,14 +1376,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 +1398,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 +1441,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 +1585,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 +1599,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_start_test.go b/internal/ui/views/timers_start_test.go new file mode 100644 index 0000000..2083200 --- /dev/null +++ b/internal/ui/views/timers_start_test.go @@ -0,0 +1,116 @@ +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) + } + } +} + +// 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") + } +} diff --git a/internal/ui/views/timers_test.go b/internal/ui/views/timers_test.go index 327e362..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()) } } @@ -624,28 +619,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 +650,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 +1909,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 +1920,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 +1928,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 +1952,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 +1983,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 +2016,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 +2051,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 @@ -2194,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++ { @@ -2205,7 +2075,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 +2122,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 +2308,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 +2330,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 +2341,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 +2393,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) @@ -2633,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 new file mode 100644 index 0000000..61620df --- /dev/null +++ b/internal/ui/views/timers_view.go @@ -0,0 +1,949 @@ +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" + "github.com/charmbracelet/x/ansi" +) + +// ── 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 +} + +// 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 durationAt(e, now).Hours() * rate, true +} + +func earnedText(e *model.Entry, now time.Time) string { + if x, ok := earned(e, now); 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 +} + +// 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 (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 { + t.d += durationAt(e, now) + if v, ok := earned(e, now); ok { + t.x += v + t.paid = true + } + } + t.x = status.Cents(t.x) + return t +} + +// 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) + } + 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 ──────────────────────────────────────────────────────────────────── + +// 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) } + +// 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() - theme.PaneGap - theme.DetailWidth + } + return m.innerWidth() +} + +// 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 = theme.ColDuration + tGap = theme.ColGap + tStatus = theme.ColStatus + tEarned = theme.ColEarned + tTrail = theme.ColTrail +) + +// 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 (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 theme.HeroRows + } + return theme.HeroRowsCompact +} + +func (m TimersModel) fixedRows() int { + rows := m.heroRows() + chipRows + 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 [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(durationAt(r, now))) + meta := "since " + clockTime(r.StartTime) + if rate := status.HourlyRate(r); rate != 0 { + 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}}} + 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 := range left { + 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 [theme.HeroRowsCompact - 2][2][]seg + if r := m.runningEntry(); r != nil { + 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{ + {{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 { + 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} + 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() { + 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} + switch m.preset { + case timersPresetMonth: + chips = []rangeChip{today, week, month, all} + case timersPresetYesterday: + chips = []rangeChip{today, yesterday, week, all} + } + 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: " "}, seg{s: c.key, fg: cSubtle}, 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}) +} + +// 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: friendlyDayAt(day, h.now), fg: cPrimary, bold: true}}, + []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 { + 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(durationAt(e, now)), 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, now), tEarned), fg: cDim}, + ) + return spread(tw, bg, segs, nil) +} + +func (m TimersModel) renderListFoot(tw int, now time.Time) []string { + n := len(m.filtered) + 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 " + all.text(), bold: true}, {s: strings.Repeat(" ", tTrail)}}), + } +} + +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, 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() + 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(e.StartTime.Local(), tw, h)) + rows++ + } + for _, l := range visible { + if l.kind == timersLineHeader { + out = append(out, m.renderDayHeaderLine(l.day, tw, h)) + } else { + out = append(out, m.renderEntryRow(m.filtered[l.entryIdx], l.entryIdx == m.cursor, tw, now)) + } + rows++ + } + if len(lines) > budget { + for ; rows < budget; rows++ { + out = append(out, blankLine(tw)) + } + } + return append(out, m.renderListFoot(tw, now)...) +} + +// ── 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"}} +} + +// 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 +) + +// 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) + 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, drop int) boxRow { + value.s = truncate(value.s, valueW) + if value.fg == "" { + value.fg = cDim + } + return boxRow{row(seg{s: fit(label, labelW), fg: cSubtle}, value), drop} + } + + 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 + } + } + + 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) > theme.DetailNoteRows { + notes = notes[:theme.DetailNoteRows] + notes[len(notes)-1] = truncate(notes[len(notes)-1]+" …", valueW) + } + for i, n := range notes { + label, drop := "", dropMoreNotes + if i == 0 { + label, drop = "Notes", dropDate + } + box = append(box, field(label, seg{s: n}, drop)) + } + box = append(box, boxRow{row(), dropSpacer}, boxRow{row(seg{s: strings.Repeat("─", max(0, inner-2)), fg: cBorder}), dropRule}) + for _, k := range detailKeys(e) { + box = append(box, boxRow{row(seg{s: " " + k[0] + " ", bg: cBgAlt, bold: true}, seg{s: " " + k[1], fg: cSubtle}), 0}) + } + box = append(box, boxRow{row(), dropSpacing}, boxRow{boxBottom(w), 0}) + return fitBox(box, rows) +} + +// 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 + } + 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:]...) + } + out := make([]string, len(box)) + for i, r := range box { + out[i] = r.s + } + return out +} + +// 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 { + if line != "" { + out = append(out, line) + line = "" + } + 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 == "": + 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, now) + if m.wide() { + var pane []string + if e := m.selectedEntry(); e != nil { + 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) + if i < len(list) { + l = list[i] + } + if i < len(pane) { + p = pane[i] + } + out = append(out, l+blankLine(theme.PaneGap)+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 { + if box := m.renderDetailBox(e, theme.DetailWidth, m.innerHeight(), now); box != nil { + body = centerOverlay(body, strings.Join(box, "\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..866f3f2 --- /dev/null +++ b/internal/ui/views/timers_view_test.go @@ -0,0 +1,533 @@ +package views + +import ( + "fmt" + "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. 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(`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) { + 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 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) + 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()) + } + 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 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) + 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(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) + } + } +} + +// 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) + } +} + +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) + } +} + +// 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") + } +} 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: '' },