diff --git a/README.md b/README.md index 7a4b350..221a368 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,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 tab bar on every tab -- **Clients & Projects** — full CRUD, clients on their own tab with project management next door +- **Clients & Projects** — full CRUD on one tab: the clients with this month's hours, earnings and unbilled, and the selected client's projects beside them - **Billing rates** — set an hourly rate per client; earnings calculated automatically - **Invoice & payment tracking** — mark entries as invoiced and/or paid - **Reports** — aggregated hours, earnings, invoice status by project/client with quick date presets @@ -186,11 +186,11 @@ That rewrites the generated files (marked as generated; never edit them by hand) ## Getting Started -1. Press **3** to go to the **Clients** tab → press **n** to create a client and set a billing rate -2. Press **2** to go to the **Projects** tab → press **n** to create a project, selecting its client from the dropdown +1. Press **2** to go to the **Clients** tab → press **n** to create a client and set a billing rate +2. Press **a** to add a project to the selected client 3. Press **1** to go to the **Timers** tab → press **n** to start a new timer 4. Press **space** to stop/restart a timer -5. Press **4** to view **Reports** +5. Press **3** to view **Reports** --- @@ -198,13 +198,13 @@ That rewrites the generated files (marked as generated; never edit them by hand) ### Global -| Key | Action | -| -------------- | ---------------------- | -| `1` | Switch to Timers tab | -| `2` | Switch to Projects tab | -| `3` | Switch to Clients tab | -| `4` | Switch to Reports tab | -| `q` / `ctrl+c` | Quit | +| Key | Action | +| -------------- | --------------------- | +| `1` | Switch to Timers tab | +| `2` | Switch to Clients tab | +| `3` | Switch to Reports tab | +| `?` | Show every key | +| `q` / `ctrl+c` | Quit | ### Timers tab @@ -234,31 +234,29 @@ That rewrites the generated files (marked as generated; never edit them by hand) | `enter` | Confirm field / save form | | `esc` | Cancel | -### Projects tab +### Clients tab -| Key | Action | -| --------- | ---------------------------------------------- | -| `↑` / `k` | Move cursor up | -| `↓` / `j` | Move cursor down | -| `n` | New project (pick a client from the dropdown) | -| `e` | Edit selected project (rename / change client) | -| `d` | Delete selected project (prompts confirmation) | -| `esc` | Cancel form | +The clients, each with its rate and this month's hours, earned and unbilled (unbilled counts every month), beside the selected client's projects, its rate, start date, all-time totals and unbilled. Below 120 columns the list takes the whole width, and `→` opens the projects in its place. -Clients are created and managed on the Clients tab (press **3**). +| Key | Action | +| ------------------------- | ----------------------------------------------------------------------- | +| `↑` / `k`, `↓` / `j` | Move through the clients, or the projects in the projects pane | +| `n` | New client (name and hourly rate) | +| `a` | Add a project to the selected client | +| `e` | Edit the selected client, or in the projects pane the selected project (rename, or move to another client) | +| `d` | Delete the selected client (with its projects and entries), or in the projects pane the selected project (with its entries); both ask first | +| `→` / `enter` | Into the selected client's projects | +| `enter` | In the projects pane: edit the project, or add one on "+ Add project" | +| `←` / `esc` | Back to the clients | -### Clients tab +### Client and project forms -| Key | Action | -| ------------------- | --------------------------------------------------------- | -| `↑` / `k` | Move cursor up | -| `↓` / `j` | Move cursor down | -| `n` | New client | -| `e` | Edit selected client (name + hourly rate) | -| `d` | Delete selected client (cascades to projects and entries) | -| `tab` / `shift+tab` | Move between form fields | -| `enter` | Save | -| `esc` | Cancel | +| Key | Action | +| ------------------- | -------------------------------------------------------- | +| `tab` / `shift+tab` | Move between fields and buttons | +| `↑` / `↓` | Suggestions (when the project form's Client field has focus) | +| `enter` | Save | +| `esc` | Cancel | ### Reports tab @@ -346,8 +344,8 @@ notch/ ├── 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 + ├── clients.go # Clients tab — clients with their totals beside the selected client's projects + ├── projects.go # Project form and delete confirm, opened from the Clients tab └── reports.go # Reports tab — date-filtered summary + cards ``` diff --git a/design/build/main.go b/design/build/main.go index ecb9071..d451280 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -335,6 +335,7 @@ func renderPalette(t *Tokens) ([]byte, error) { {"tui-hero-rows", "HeroRows"}, {"tui-hero-rows-compact", "HeroRowsCompact"}, {"tui-modal-width", "ModalWidth"}, + {"tui-modal-width-narrow", "ModalWidthNarrow"}, {"tui-modal-indent", "ModalIndent"}, {"tui-modal-label", "ModalLabel"}, {"tui-suggest-width", "SuggestWidth"}, @@ -347,6 +348,14 @@ func renderPalette(t *Tokens) ([]byte, error) { {"tui-modal-min-width", "ModalMinWidth"}, {"tui-strip-min", "StripMin"}, {"tui-field-width", "FieldWidth"}, + {"tui-client-name-min", "ClientNameMin"}, + {"tui-client-col-rate", "ClientColRate"}, + {"tui-client-col-hours", "ClientColHours"}, + {"tui-client-col-earned", "ClientColEarned"}, + {"tui-client-col-unbilled", "ClientColUnbilled"}, + {"tui-client-pane-earned", "ClientPaneEarned"}, + {"tui-client-pane-label", "ClientPaneLabel"}, + {"tui-client-pane-gap", "ClientPaneGap"}, } { v, err := integer(t.Spacing, c.token) if err != nil { diff --git a/design/tokens.json b/design/tokens.json index e553170..cdae006 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": "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": "warning", "value": "#A4CBF7", "usage": "Section titles and invoiced status in Reports, the unbilled total in the Timers hero, and unbilled amounts in Clients. (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." }, @@ -61,7 +61,7 @@ { "name": "tui-max-width", "value": 150, "usage": "TUI: the widest the centred content column gets, in cells. Wider terminals pad both sides." }, { "name": "tui-gutter", "value": 2, "usage": "TUI: columns before every list row for the row cursor (glyph-cursor and a space). Report columns leave the same room." }, { "name": "tui-margin", "value": 2, "usage": "TUI: blank columns on each side of the content column, and before the tab bar's wordmark." }, - { "name": "tui-wide", "value": 120, "usage": "TUI: the narrowest terminal that gets the wide layout: the Timers hero with block digits, the CLIENT › PROJECT column and the entry detail pane. 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-wide", "value": 120, "usage": "TUI: the narrowest terminal that gets the wide layout: the Clients list with its projects pane beside it (narrower terminals open the pane in its place with →), and 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." }, @@ -76,7 +76,8 @@ { "name": "tui-detail-note-rows", "value": 3, "usage": "TUI: the most rows an entry's notes take in the detail pane; longer notes end in an ellipsis." }, { "name": "tui-hero-rows", "value": 6, "usage": "TUI: rows the wide Timers hero takes, borders included: four rows for the label, task, place and meta line beside three rows of block digits." }, { "name": "tui-hero-rows-compact", "value": 4, "usage": "TUI: rows the compact Timers hero takes, borders included: the task and elapsed time, then the place and today's total." }, - { "name": "tui-modal-width", "value": 70, "usage": "TUI: a form modal's width, borders included (New timer, Edit entry, the client and project forms). A narrower body gets a modal as wide as the body." }, + { "name": "tui-modal-width", "value": 70, "usage": "TUI: a form modal's width, borders included: New timer, Edit entry, New project and Edit project. The client forms use tui-modal-width-narrow. A narrower body gets a modal as wide as the body." }, + { "name": "tui-modal-width-narrow", "value": 60, "usage": "TUI: the New client and Edit client modals' width, borders included: they hold only Name and Rate ($/h)." }, { "name": "tui-modal-indent", "value": 3, "usage": "TUI: blank columns inside a modal's border before its labels and buttons, and after its fields." }, { "name": "tui-modal-label", "value": 11, "usage": "TUI: a form modal's label column (Task, Client, Rate ($/h)). The focus mark (glyph-cursor) follows it, then the field." }, { "name": "tui-suggest-width", "value": 30, "usage": "TUI: the suggestions box under a Client or Project field, borders included; never wider than the field." }, @@ -86,10 +87,18 @@ { "name": "tui-keys-cap", "value": 11, "usage": "TUI: the key-cap column in the ? keys sheet, room for the shift+tab cap." }, { "name": "tui-keys-gap", "value": 2, "usage": "TUI: blank columns between the ? keys sheet's columns." }, { "name": "tui-keys-cols", "value": 3, "usage": "TUI: the most columns the ? keys sheet uses; it drops to fewer when the body is too narrow for them." }, + { "name": "tui-client-name-min", "value": 16, "usage": "TUI: the narrowest the Clients list's CLIENT column gets in the master-detail layout; the projects pane gives up width before it goes below this." }, + { "name": "tui-client-col-rate", "value": 10, "usage": "TUI: the Clients list's RATE column, right-aligned, in cells, the gap before it included." }, + { "name": "tui-client-col-hours", "value": 11, "usage": "TUI: the HOURS column in the Clients list and its projects pane, right-aligned, in cells, the gap before it included." }, + { "name": "tui-client-col-earned", "value": 12, "usage": "TUI: the Clients list's EARNED column, right-aligned, in cells, the gap before it included." }, + { "name": "tui-client-col-unbilled", "value": 11, "usage": "TUI: the Clients list's UNBILLED column, right-aligned, in cells, the gap before it included." }, + { "name": "tui-client-pane-earned", "value": 13, "usage": "TUI: the EARNED column in the Clients tab's projects pane, right-aligned, in cells, the gap before it included." }, + { "name": "tui-client-pane-label", "value": 15, "usage": "TUI: the label column of the projects pane's client facts (Hourly rate, Since, All time, Unbilled)." }, + { "name": "tui-client-pane-gap", "value": 4, "usage": "TUI: blank columns between the Clients list and its projects pane in the wide layout." }, { "name": "tui-modal-min-width", "value": 20, "usage": "TUI: the narrowest a modal gets, border included, however narrow the body is." }, { "name": "tui-strip-min", "value": 8, "usage": "TUI: the narrowest a form field's bg_alt strip gets in a modal." }, { "name": "tui-field-width", "value": 44, "usage": "TUI: a form field's width when the form opens; the modal sets it to its strip's width each time it draws." }, - { "name": "tui-min-width", "value": 64, "usage": "TUI: the narrowest terminal notch draws, in cells, measured from the views: the widest fixed line is the Projects tab's at 57 cells, 61 with the two margins; the compact Timers range chips need 48. Narrower terminals get a centred \"Terminal too small\" message." }, + { "name": "tui-min-width", "value": 64, "usage": "TUI: the narrowest terminal notch draws, in cells, measured from the views: the Clients list's fixed columns and gutter take 47 cells, leaving its CLIENT column 13 at this width; 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." } @@ -146,7 +155,7 @@ { "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": "warning", "bg": "bg", "min": 4.5, "usage": "Section titles and invoiced status in Reports, the Timers hero's unbilled total, and unbilled amounts in Clients." }, { "fg": "danger", "bg": "bg", "min": 4.5, "usage": "Errors and delete actions." }, { "fg": "danger", "bg": "bg_alt", "min": 4.5, "usage": "The Delete entry button in the edit modal." }, { "fg": "bg", "bg": "danger", "min": 4.5, "usage": "The Delete button in a delete confirm." }, @@ -159,7 +168,7 @@ { "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, 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": "warning", "bg": "bg_alt", "min": 4.5, "usage": "Invoiced status on the selected row in Reports, and the unbilled amount on the selected client." }, { "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." }, diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index 7ab5770..b716dbe 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -13,9 +13,9 @@ var Default = Palette{ Accent: "#9DC6E9", // Paid status, the running pill. Aether's green. Success: "#99C2ED", - // 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. + // Section titles and invoiced status in Reports, the unbilled total in the + // Timers hero, and unbilled amounts in Clients. (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. @@ -75,11 +75,12 @@ const Gutter = 2 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. +// the Clients list with its projects pane beside it (narrower terminals open +// the pane in its place with →), and 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 @@ -140,11 +141,15 @@ const HeroRows = 6 // today's total. const HeroRowsCompact = 4 -// ModalWidth (tui-modal-width). TUI: a form modal's width, borders included -// (New timer, Edit entry, the client and project forms). A narrower body gets -// a modal as wide as the body. +// ModalWidth (tui-modal-width). TUI: a form modal's width, borders included: +// New timer, Edit entry, New project and Edit project. The client forms use +// tui-modal-width-narrow. A narrower body gets a modal as wide as the body. const ModalWidth = 70 +// ModalWidthNarrow (tui-modal-width-narrow). TUI: the New client and Edit +// client modals' width, borders included: they hold only Name and Rate ($/h). +const ModalWidthNarrow = 60 + // ModalIndent (tui-modal-indent). TUI: blank columns inside a modal's border // before its labels and buttons, and after its fields. const ModalIndent = 3 @@ -193,3 +198,38 @@ const StripMin = 8 // FieldWidth (tui-field-width). TUI: a form field's width when the form // opens; the modal sets it to its strip's width each time it draws. const FieldWidth = 44 + +// ClientNameMin (tui-client-name-min). TUI: the narrowest the Clients list's +// CLIENT column gets in the master-detail layout; the projects pane gives up +// width before it goes below this. +const ClientNameMin = 16 + +// ClientColRate (tui-client-col-rate). TUI: the Clients list's RATE column, +// right-aligned, in cells, the gap before it included. +const ClientColRate = 10 + +// ClientColHours (tui-client-col-hours). TUI: the HOURS column in the Clients +// list and its projects pane, right-aligned, in cells, the gap before it +// included. +const ClientColHours = 11 + +// ClientColEarned (tui-client-col-earned). TUI: the Clients list's EARNED +// column, right-aligned, in cells, the gap before it included. +const ClientColEarned = 12 + +// ClientColUnbilled (tui-client-col-unbilled). TUI: the Clients list's +// UNBILLED column, right-aligned, in cells, the gap before it included. +const ClientColUnbilled = 11 + +// ClientPaneEarned (tui-client-pane-earned). TUI: the EARNED column in the +// Clients tab's projects pane, right-aligned, in cells, the gap before it +// included. +const ClientPaneEarned = 13 + +// ClientPaneLabel (tui-client-pane-label). TUI: the label column of the +// projects pane's client facts (Hourly rate, Since, All time, Unbilled). +const ClientPaneLabel = 15 + +// ClientPaneGap (tui-client-pane-gap). TUI: blank columns between the Clients +// list and its projects pane in the wide layout. +const ClientPaneGap = 4 diff --git a/internal/ui/app.go b/internal/ui/app.go index fd55e9c..c674860 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -17,13 +17,12 @@ import ( // Tab indices const ( - TabTimers = 0 - TabProjects = 1 - TabClients = 2 - TabReports = 3 + TabTimers = 0 + TabClients = 1 + TabReports = 2 ) -var tabNames = []string{"Timers", "Projects", "Clients", "Reports"} +var tabNames = []string{"Timers", "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 and renderBottomBar, @@ -139,10 +138,9 @@ type AppModel struct { showKeys bool keysOffset int - timers views.TimersModel - projects views.ProjectsModel - clients views.ClientsModel - reports views.ReportsModel + timers views.TimersModel + clients views.ClientsModel + reports views.ReportsModel } // tickFallbackTicks is how many once-a-second TickMsgs pass between the @@ -155,7 +153,6 @@ type appKeyMap struct { Tab1 key.Binding Tab2 key.Binding Tab3 key.Binding - Tab4 key.Binding Quit key.Binding } @@ -163,7 +160,6 @@ var appKeys = appKeyMap{ Tab1: key.NewBinding(key.WithKeys("1")), Tab2: key.NewBinding(key.WithKeys("2")), Tab3: key.NewBinding(key.WithKeys("3")), - Tab4: key.NewBinding(key.WithKeys("4")), Quit: key.NewBinding(key.WithKeys("q", "ctrl+c")), } @@ -179,7 +175,6 @@ func New(database *db.DB) (AppModel, error) { running: running, dbWatch: db.Watch(database), timers: views.NewTimers(database), - projects: views.NewProjects(database), clients: views.NewClients(database), reports: views.NewReports(database), }, nil @@ -191,7 +186,6 @@ func (m AppModel) Init() tea.Cmd { watchThemeCmd(), m.watchDbCmd(), m.timers.Init(), - m.projects.Init(), m.clients.Init(), m.reports.Init(), ) @@ -207,7 +201,6 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.height = msg.Height cw, ch := m.contentDims() m.timers.SetSize(cw, ch) - m.projects.SetSize(cw, ch) m.clients.SetSize(cw, ch) m.reports.SetSize(cw, ch) return m, nil @@ -247,9 +240,13 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // cursor/offset into bounds -- it doesn't reset them -- so this // doesn't disrupt scrolling/selection while browsing. Broadcast // to every tab regardless of which is active (same as TickMsg's - // own unconditional theme-reload check): the other three tabs + // own unconditional theme-reload check): the other two tabs // simply have no case for timerEntriesMsg and ignore it. cmds = append(cmds, m.timers.Init()) + // The Clients tab's totals come from the entries too. + if m.activeTab == TabClients { + cmds = append(cmds, m.clients.Init()) + } case themeWatchMsg: cmds = append(cmds, watchThemeCmd()) @@ -275,14 +272,10 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { 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): + case key.Matches(msg, appKeys.Tab3): m.activeTab = TabReports m.timers = m.timers.CloseDetail() return m, m.reports.Init() @@ -314,10 +307,6 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { u, c := m.timers.Update(msg) m.timers = u cmds = append(cmds, c) - case TabProjects: - u, c := m.projects.Update(msg) - m.projects = u - cmds = append(cmds, c) case TabClients: u, c := m.clients.Update(msg) m.clients = u @@ -332,17 +321,13 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.timers = u1 cmds = append(cmds, c1) - u2, c2 := m.projects.Update(msg) - m.projects = u2 + u2, c2 := m.clients.Update(msg) + m.clients = u2 cmds = append(cmds, c2) - u3, c3 := m.clients.Update(msg) - m.clients = u3 + u3, c3 := m.reports.Update(msg) + m.reports = u3 cmds = append(cmds, c3) - - u4, c4 := m.reports.Update(msg) - m.reports = u4 - cmds = append(cmds, c4) } return m, tea.Batch(cmds...) @@ -590,8 +575,6 @@ func (m AppModel) renderBody() string { switch m.activeTab { case TabTimers: view = m.timers.View() - case TabProjects: - view = m.projects.View() case TabClients: view = m.clients.View() case TabReports: @@ -650,8 +633,6 @@ func (m AppModel) activeViewBusy() bool { switch m.activeTab { case TabTimers: return m.timers.IsBusy() - case TabProjects: - return m.projects.IsBusy() case TabClients: return m.clients.IsBusy() case TabReports: @@ -669,8 +650,6 @@ func (m AppModel) activeViewHelp() []views.Hotkey { switch m.activeTab { case TabTimers: return m.timers.Help() - case TabProjects: - return m.projects.Help() case TabClients: return m.clients.Help() case TabReports: @@ -685,8 +664,6 @@ func (m AppModel) activeViewFieldErrors() int { switch m.activeTab { case TabTimers: return m.timers.FieldErrors() - case TabProjects: - return m.projects.FieldErrors() case TabClients: return m.clients.FieldErrors() case TabReports: diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index e2b4e53..5855d3c 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -94,9 +94,8 @@ func TestTabSwitching(t *testing.T) { key rune want int }{ - {'2', TabProjects}, - {'3', TabClients}, - {'4', TabReports}, + {'2', TabClients}, + {'3', TabReports}, {'1', TabTimers}, } for _, c := range cases { @@ -459,7 +458,7 @@ 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} { + for _, tab := range []int{TabTimers, TabClients, TabReports} { m.activeTab = tab lines := strings.Split(plainText(m.renderTopBar()), "\n") if got := lipgloss.Width(lines[0]); got != w { @@ -481,7 +480,7 @@ func TestRenderTopBar_PillHasPriority(t *testing.T) { } } 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") { + if bar := plainText(m.renderTopBar()); !strings.Contains(bar, "◷ notch") || !strings.Contains(bar, "2 Clients") || !strings.Contains(bar, "Pricing page layout") { t.Errorf("a wide bar should keep everything: %q", bar) } } diff --git a/internal/ui/clients_test.go b/internal/ui/clients_test.go new file mode 100644 index 0000000..f1386ec --- /dev/null +++ b/internal/ui/clients_test.go @@ -0,0 +1,207 @@ +package ui + +// The Clients tab against the design canvas's "Redesign · TUI · Clients" +// board (ALI-2617): where its columns and pane sit at 140 columns, and the +// list alone, with → opening the pane, at 90. + +import ( + "fmt" + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" +) + +// col is the cell column where needle starts on line, or -1. The sample's +// text is all one cell wide per rune. +func col(line, needle string) int { + i := strings.Index(line, needle) + if i < 0 { + return -1 + } + return len([]rune(line[:i])) +} + +// end is the column after needle's last cell, or -1. +func end(line, needle string) int { + if c := col(line, needle); c >= 0 { + return c + len([]rune(needle)) + } + return -1 +} + +// lineWith is the first line holding needle. +func lineWith(t *testing.T, lines []string, needle string) string { + t.Helper() + for _, l := range lines { + if strings.Contains(l, needle) { + return l + } + } + t.Fatalf("no line holds %q:\n%s", needle, strings.Join(lines, "\n")) + return "" +} + +func TestClientsLayout_140(t *testing.T) { + m := sampleClients(t, 140, 40) + lines := strings.Split(plainText(m.View()), "\n") + + title := lines[3] + if !strings.HasPrefix(title, " Clients 3 clients · this month ") || col(title, "╭─ Fieldnote Studio · projects ─") != 72 || end(title, "╮") != 138 { + t.Errorf("title row: want the title at 2 and the pane from 72 to 137:\n%q", title) + } + head := lines[5] + for _, c := range []struct { + name string + at int + startCol bool + }{ + {"CLIENT", 5, true}, {"RATE", 34, false}, {"HOURS", 45, false}, {"EARNED", 57, false}, {"UNBILLED", 68, false}, + {"PROJECT", 75, true}, + } { + got := end(head, c.name) + if c.startCol { + got = col(head, c.name) + } + if got != c.at { + t.Errorf("%s at %d, want %d (the board's column):\n%q", c.name, got, c.at, head) + } + } + // The pane's HOURS and EARNED come after the list's. + paneHead := string([]rune(head)[72:]) + if e := end(paneHead, "HOURS"); e+72 != 122 { + t.Errorf("pane HOURS ends at %d, want 122:\n%q", e+72, head) + } + if e := end(paneHead, "EARNED"); e+72 != 135 { + t.Errorf("pane EARNED ends at %d, want 135:\n%q", e+72, head) + } + if r := []rune(head); r[72] != '│' || r[137] != '│' { + t.Errorf("pane sides at 72 and 137:\n%q", head) + } + + row := lineWith(t, lines, "▌ Fieldnote Studio") + if col(row, "▌") != 2 || col(row, "Fieldnote Studio") != 5 || end(row, "$95/h") != 34 || end(row, "$142.50") != 57 { + t.Errorf("selected client row off the board's columns:\n%q", row) + } + if l := lineWith(t, lines, "1 project "); col(l, "1 project") != 5 { + t.Errorf("project count at %d, want 5:\n%q", col(l, "1 project"), l) + } + if l := lineWith(t, lines, "Internal"); end(l, "—") != 34 { + t.Errorf("a client with no rate shows — for it:\n%q", l) + } + for _, c := range []struct { + needle string + at int + }{{"+ Add project a", 75}, {"Hourly rate $95.00", 75}, {"Since ", 75}, {"All time 2:30:00 · $237.50", 75}, {"Unbilled $142.50 · 1 entry", 75}} { + if l := lineWith(t, lines, c.needle); col(l, c.needle) != c.at { + t.Errorf("%q at %d, want %d:\n%q", c.needle, col(l, c.needle), c.at, l) + } + } + if l := lineWith(t, lines, "Brand refresh"); col(l, "Brand refresh") != 75 || 72+end(string([]rune(l)[72:]), "$142.50") != 135 { + t.Errorf("project row off the board's columns:\n%q", l) + } + keys := lines[len(lines)-1] + for _, k := range []string{"n new client", "a add project", "e edit", "→ projects", "d delete", "? all keys"} { + if !strings.Contains(keys, k) { + t.Errorf("hotkey line is missing %q: %q", k, keys) + } + } +} + +// At 90 columns the list takes the width; → opens the pane in its place, +// with its own cursor, and ← goes back. +func TestClientsLayout_90(t *testing.T) { + m := sampleClients(t, 90, 32) + lines := strings.Split(plainText(m.View()), "\n") + if strings.Contains(strings.Join(lines, "\n"), "· projects") { + t.Errorf("no pane beside the list at 90 columns:\n%s", strings.Join(lines, "\n")) + } + head := lineWith(t, lines, "CLIENT") + if col(head, "CLIENT") != 5 || end(head, "UNBILLED") != 88 { + t.Errorf("the list should span the width:\n%q", head) + } + + m = m.press(tea.KeyMsg{Type: tea.KeyRight}) + lines = strings.Split(plainText(m.View()), "\n") + top := lines[3] + if col(top, "╭─ Fieldnote Studio · projects ─") != 2 || end(top, "╮") != 88 { + t.Errorf("→ should open the pane across the width:\n%q", top) + } + if l := lineWith(t, lines, "▌ Brand refresh"); col(l, "▌") != 3 { + t.Errorf("the pane's cursor sits in its gutter:\n%q", l) + } + for _, k := range []string{"n new client", "a add project", "e edit", "d delete", "← clients"} { + if !strings.Contains(lines[len(lines)-1], k) { + t.Errorf("the pane's keys at 90 columns should offer %q: %q", k, lines[len(lines)-1]) + } + } + for i, l := range strings.Split(m.View(), "\n") { + if w := len([]rune(plainText(l))); w != 90 { + t.Errorf("line %d is %d wide", i, w) + } + } + + m = m.press(tea.KeyMsg{Type: tea.KeyLeft}) + if strings.Contains(plainText(m.View()), "· projects") { + t.Error("← should go back to the list") + } +} + +// The project form opened from Clients makes the app busy: q types, and +// only ctrl+c quits. +func TestClients_QTypesInTheProjectForm(t *testing.T) { + m := sampleClients(t, 140, 40).press(runeKey('a')) + if !m.activeViewBusy() { + t.Fatal("a should open New project and make the tab busy") + } + u, cmd := m.Update(runeKey('q')) + m = u.(AppModel) + if cmd != nil { + if _, ok := cmd().(tea.QuitMsg); ok { + t.Fatal("q quit from the project form") + } + } + if !strings.Contains(plainText(m.View()), "▌ q") { + t.Errorf("q should type into Name:\n%s", plainText(m.View())) + } + if m.press(runeKey('3')).activeTab != TabClients { + t.Error("3 should type in the form, not switch tabs") + } +} + +// An entry written elsewhere updates the Clients tab's totals while it's +// showing. +func TestClients_ReloadsOnDatabaseChange(t *testing.T) { + m := sampleClients(t, 140, 40) + m.dbWatch = nil // its wait would block the walk below + _, cmd := m.Update(dbWatchMsg{}) + if cmd == nil { + t.Fatal("want reload commands") + } + found := false + var walk func(tea.Msg) + walk = func(msg tea.Msg) { + if b, ok := msg.(tea.BatchMsg); ok { + for _, c := range b { + if c != nil { + walk(c()) + } + } + return + } + found = found || fmt.Sprintf("%T", msg) == "views.clientsDataMsg" + } + walk(tea.BatchMsg{cmd}) + if !found { + t.Error("a database change on the Clients tab should reload it") + } +} + +// The project form's field errors are counted in the status line, as the +// client form's are. +func TestClients_ProjectFormErrorsCountInTheBottomBar(t *testing.T) { + m := sampleClients(t, 140, 40).press(runeKey('a'), tea.KeyMsg{Type: tea.KeyEnter}) + if bar := plainText(m.renderBottomBar()); !strings.Contains(bar, "✕ 1 field needs fixing") { + t.Errorf("want the Name error counted: %q", bar) + } +} diff --git a/internal/ui/layout_gen.go b/internal/ui/layout_gen.go index 702f4f6..8789558 100644 --- a/internal/ui/layout_gen.go +++ b/internal/ui/layout_gen.go @@ -12,9 +12,10 @@ const MaxContentWidth = 150 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. +// cells, measured from the views: the Clients list's fixed columns and gutter +// take 47 cells, leaving its CLIENT column 13 at this width; 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 diff --git a/internal/ui/modal_test.go b/internal/ui/modal_test.go index eae7ece..51036f9 100644 --- a/internal/ui/modal_test.go +++ b/internal/ui/modal_test.go @@ -26,7 +26,7 @@ func TestKeySheet_OpensGroupedByTabAndCloses(t *testing.T) { t.Fatalf("%v: ? should open the keys sheet", size) } view := plainText(m.View()) - for _, want := range []string{"╭─ Keys ─", "EVERYWHERE", "TIMERS", "RANGES", "PROJECTS", "CLIENTS", "REPORTS", "FORMS", "shift+tab", "toggle invoiced", "esc close"} { + for _, want := range []string{"╭─ Keys ─", "EVERYWHERE", "TIMERS", "RANGES", "CLIENTS", "add project", "back to clients", "REPORTS", "FORMS", "shift+tab", "toggle invoiced", "esc close"} { if !strings.Contains(view, want) { t.Errorf("%v: the keys sheet is missing %q:\n%s", size, want, view) } diff --git a/internal/ui/render_test.go b/internal/ui/render_test.go index 78a816a..85e5bc3 100644 --- a/internal/ui/render_test.go +++ b/internal/ui/render_test.go @@ -118,3 +118,41 @@ func TestRenderSample(t *testing.T) { } } } + +// sampleClients is the app at w×h on the sample data, on the Clients tab +// with Harbor & Pine selected. +func sampleClients(t *testing.T, w, h int) AppModel { + t.Helper() + m := sampleApp(t, w, h) + for _, msg := range []tea.Msg{runeKey('2'), m.clients.Init()()} { + u, _ := m.Update(msg) + m = u.(AppModel) + } + return m +} + +// TestRenderClients checks the Clients screen fills the terminal exactly at +// the board's two sizes, and writes plain-text renders to +// $NOTCH_RENDER_DIR, when set. +func TestRenderClients(t *testing.T) { + for _, size := range [][2]int{{140, 40}, {90, 32}} { + w, h := size[0], size[1] + m := sampleClients(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-2617-%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 03e289e..9883eb1 100644 --- a/internal/ui/views/clients.go +++ b/internal/ui/views/clients.go @@ -3,10 +3,13 @@ package views import ( "errors" "fmt" + "math" "strings" + "time" "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/status" "github.com/aliasproject/notch/internal/theme" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" @@ -14,7 +17,12 @@ import ( "github.com/charmbracelet/lipgloss" ) -// ClientsModel manages the Clients tab. +// ClientsModel is the Clients tab (ALI-2617), drawn from the design +// canvas's "Redesign · TUI · Clients" board: the clients, each with its +// rate and this month's hours, earned and unbilled, beside the selected +// client's projects and totals. Projects live here: there's no Projects +// tab. Below theme.WideMin columns the list takes the whole width, and → +// opens the projects pane in its place. type ClientsModel struct { db *db.DB width int @@ -23,6 +31,26 @@ type ClientsModel struct { cursor int mode clientMode + // projects is every project, by client name then project name; stats + // their totals by project ID. + projects []*model.Project + stats map[int64]*projectStats + + // selID is the selected client, so a reload keeps it selected when the + // list reorders. offset is the first client the list shows. + selID int64 + offset int + + // inProjects: the keys go to the projects pane, whose cursor is + // projCursor (len of the client's projects is the "+ Add project" + // row) and whose first row shown is projOffset. + inProjects bool + projCursor int + projOffset int + + // proj is the project form and the project delete confirm. + proj projectsPane + // form fields inputs []textinput.Model focusIdx int // an input, clientFieldSave or clientFieldCancel @@ -62,12 +90,14 @@ const ( errNameRequired = "Enter a name." errRate = "Enter a number, like 95 or 95.50." errClientTaken = "A client with that name already exists." + errNoClientYet = "Add a client first: press n." ) func NewClients(database *db.DB) ClientsModel { return ClientsModel{ db: database, mode: clientModeList, + proj: projectsPane{db: database}, } } @@ -75,28 +105,164 @@ func (m ClientsModel) Init() tea.Cmd { return loadClientsCmd(m.db) } -// IsBusy returns true when the view is in a form or confirmation mode -// and should receive all keystrokes before the root app handles them. +// IsBusy returns true when a form or a confirm is open, and should receive +// all keystrokes before the root app handles them. func (m ClientsModel) IsBusy() bool { - return m.mode != clientModeList + return m.mode != clientModeList || m.proj.IsBusy() } // Help returns the contextual hotkey string for the view's current mode, for // display in the app-level hotkey bar (see app.go renderBottomBar). func (m ClientsModel) Help() []Hotkey { + if m.proj.IsBusy() { + return m.proj.Help() + } switch m.mode { case clientModeForm: return []Hotkey{{"tab", "next field"}, {"enter", "save"}, {"esc", "cancel"}} case clientModeConfirmDelete: return []Hotkey{{"y", "delete"}, {"esc", "keep"}} - default: - return []Hotkey{{"n", "new"}, {"e", "edit"}, {"d", "delete"}, {"↑ / ↓", "navigate"}} } + switch { + case len(m.clients) == 0: + return []Hotkey{{"n", "new client"}} + case m.inProjects: + return []Hotkey{{"n", "new client"}, {"a", "add project"}, {"e", "edit"}, {"d", "delete"}, {"←", "clients"}} + } + return []Hotkey{{"n", "new client"}, {"a", "add project"}, {"e", "edit"}, {"→", "projects"}, {"d", "delete"}} } func (m *ClientsModel) SetSize(w, h int) { m.width = w m.height = h + m.clampOffsets() +} + +// -- Data -------------------------------------------------------------------- + +// clientsDataMsg is everything the tab shows, loaded together. +type clientsDataMsg struct { + clients []*model.Client + projects []*model.Project + stats map[int64]*projectStats +} + +// projectStats is one project's totals: this month's time and earnings and +// its unbilled amount, as the "clients" and "projects" listings count them +// (status.TotalsByProject), and its all-time time and unbilled entries. +// Running timers count in none of them. +type projectStats struct { + status.Totals + allSeconds int64 + unbilledEntries int +} + +func loadClientsCmd(database *db.DB) tea.Cmd { + return func() tea.Msg { return loadClientsData(database, time.Now()) } +} + +// loadClientsData loads the clients, the projects and their totals as of +// now. +func loadClientsData(database *db.DB, now time.Time) tea.Msg { + clients, err := database.ListClients() + if err != nil { + return ErrMsg(fmt.Sprintf("load clients: %v", err)) + } + projects, err := database.ListProjects(0) + if err != nil { + return ErrMsg(fmt.Sprintf("load projects: %v", err)) + } + month, err := database.ListFinishedEntriesOverlapping(status.StartOfMonth(now), now) + if err != nil { + return ErrMsg(fmt.Sprintf("load entries: %v", err)) + } + all, err := database.ListEntries(0, "", "", false) + if err != nil { + return ErrMsg(fmt.Sprintf("load entries: %v", err)) + } + stats := map[int64]*projectStats{} + for id, t := range status.TotalsByProject(month, all, now) { + stats[id] = &projectStats{Totals: *t} + } + for _, e := range all { + if e.EndTime == nil { + continue + } + st := stats[e.ProjectID] + if st == nil { + st = &projectStats{} + stats[e.ProjectID] = st + } + st.allSeconds += int64(e.EndTime.Sub(e.StartTime) / time.Second) + if !e.Invoiced && !e.Paid { + st.unbilledEntries++ + } + } + return clientsDataMsg{clients: clients, projects: projects, stats: stats} +} + +// clientTotals is one client's totals: its projects' added up. +type clientTotals struct { + status.Totals + allSeconds int64 + unbilledEntries int + projects int +} + +func (m ClientsModel) totalsFor(c *model.Client) clientTotals { + var t clientTotals + for _, p := range m.projects { + if p.ClientID != c.ID { + continue + } + t.projects++ + if st := m.stats[p.ID]; st != nil { + t.Add(st.Totals) + t.allSeconds += st.allSeconds + t.unbilledEntries += st.unbilledEntries + } + } + return t +} + +// selected is the client under the cursor, or nil. +func (m ClientsModel) selected() *model.Client { + if m.cursor < 0 || m.cursor >= len(m.clients) { + return nil + } + return m.clients[m.cursor] +} + +// clientProjects is the selected client's projects, in name order. +func (m ClientsModel) clientProjects() []*model.Project { + c := m.selected() + if c == nil { + return nil + } + var out []*model.Project + for _, p := range m.projects { + if p.ClientID == c.ID { + out = append(out, p) + } + } + return out +} + +// selectedProject is the project under the pane's cursor, or nil on the +// "+ Add project" row or outside the pane. +func (m ClientsModel) selectedProject() *model.Project { + ps := m.clientProjects() + if !m.inProjects || m.projCursor < 0 || m.projCursor >= len(ps) { + return nil + } + return ps[m.projCursor] +} + +// pane is the project form and confirm, given the loaded data. +func (m ClientsModel) pane() projectsPane { + p := m.proj + p.db, p.clients, p.projects = m.db, m.clients, m.projects + return p } // -- Update ------------------------------------------------------------------ @@ -104,21 +270,48 @@ func (m *ClientsModel) SetSize(w, h int) { func (m ClientsModel) Update(msg tea.Msg) (ClientsModel, tea.Cmd) { switch msg := msg.(type) { - case clientsLoadedMsg: - m.clients = msg.clients - if m.cursor >= len(m.clients) && m.cursor > 0 { - m.cursor = len(m.clients) - 1 + case clientsDataMsg: + m.clients, m.projects, m.stats = msg.clients, msg.projects, msg.stats + m.cursor = max(0, min(m.cursor, len(m.clients)-1)) + found := false + for i, c := range m.clients { + if c.ID == m.selID { + m.cursor, found = i, true + } } + var cmds []tea.Cmd + // The pane's client is gone: the cursor's neighbour isn't the one + // it showed, so it closes rather than let e or d act on another + // client's projects. + if m.inProjects && !found { + m.inProjects = false + m.projCursor, m.projOffset = 0, 0 + cmds = append(cmds, ErrCmd(errClientGone)) + } + m.selectCursor() + m.projCursor = max(0, min(m.projCursor, len(m.clientProjects()))) + m.clampOffsets() if m.mode == clientModeConfirmDelete && m.clientByID(m.deleteID) == nil { m.mode = clientModeList - return m, ErrCmd(errClientGone) + if len(cmds) == 0 { + cmds = append(cmds, ErrCmd(errClientGone)) + } } - return m, nil + var cmd tea.Cmd + m.proj, cmd = m.pane().setData(m.clients, m.projects) + return m, tea.Batch(append(cmds, cmd)...) case tea.KeyMsg: + if m.proj.IsBusy() { + var cmd tea.Cmd + m.proj, cmd = m.pane().updateForm(msg) + return m, cmd + } switch m.mode { case clientModeList: - return m.updateList(msg) + m, cmd := m.updateList(msg) + m.clampOffsets() + return m, cmd case clientModeForm: return m.updateForm(msg) case clientModeConfirmDelete: @@ -128,32 +321,109 @@ func (m ClientsModel) Update(msg tea.Msg) (ClientsModel, tea.Cmd) { return m, nil } +// selectCursor keeps selID on the client under the cursor. +func (m *ClientsModel) selectCursor() { + m.selID = 0 + if c := m.selected(); c != nil { + m.selID = c.ID + } +} + func (m ClientsModel) updateList(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { + if m.inProjects { + return m.updateProjects(msg) + } switch { case key.Matches(msg, listKeys.Up): if m.cursor > 0 { m.cursor-- + m.projCursor, m.projOffset = 0, 0 } case key.Matches(msg, listKeys.Down): if m.cursor < len(m.clients)-1 { m.cursor++ + m.projCursor, m.projOffset = 0, 0 } case key.Matches(msg, listKeys.New): m = m.openForm(nil) + case key.Matches(msg, clientKeys.AddProject): + return m.addProject() case key.Matches(msg, listKeys.Edit): - if len(m.clients) > 0 { - m = m.openForm(m.clients[m.cursor]) + if c := m.selected(); c != nil { + m = m.openForm(c) } case key.Matches(msg, listKeys.Delete): - if len(m.clients) > 0 { + if c := m.selected(); c != nil { m.mode = clientModeConfirmDelete m.deleteFocused = false - m.deleteID = m.clients[m.cursor].ID + m.deleteID = c.ID + } + case key.Matches(msg, clientKeys.Into): + if m.selected() != nil { + m.inProjects = true + m.projCursor = 0 } } + m.selectCursor() return m, nil } +// updateProjects handles a key in the projects pane: the arrows move +// through the projects and "+ Add project", e and d edit and delete the +// project under the cursor, enter edits it or adds one, and ← or esc go +// back to the clients. +func (m ClientsModel) updateProjects(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { + n := len(m.clientProjects()) + switch { + case key.Matches(msg, listKeys.Up): + m.projCursor = max(0, m.projCursor-1) + case key.Matches(msg, listKeys.Down): + m.projCursor = min(n, m.projCursor+1) + case key.Matches(msg, clientKeys.Back): + m.inProjects = false + case key.Matches(msg, listKeys.New): + m = m.openForm(nil) + case key.Matches(msg, clientKeys.AddProject): + return m.addProject() + case key.Matches(msg, listKeys.Edit), key.Matches(msg, clientKeys.Open): + if p := m.selectedProject(); p != nil { + m.proj = m.pane().openEdit(p) + } else if msg.Type == tea.KeyEnter { + return m.addProject() + } + case key.Matches(msg, listKeys.Delete): + if p := m.selectedProject(); p != nil { + m.proj = m.pane().openDelete(p) + } + } + return m, nil +} + +// addProject opens New project for the selected client. +func (m ClientsModel) addProject() (ClientsModel, tea.Cmd) { + c := m.selected() + if c == nil { + return m, ErrCmd(errNoClientYet) + } + m.proj = m.pane().openNew(c) + return m, nil +} + +// clientKeyMap is the Clients tab's own keys, besides listKeys. +type clientKeyMap struct { + AddProject key.Binding + Into key.Binding + Back key.Binding + Open key.Binding +} + +var clientKeys = clientKeyMap{ + AddProject: key.NewBinding(key.WithKeys("a")), + Into: key.NewBinding(key.WithKeys("right", "l", "enter")), + Back: key.NewBinding(key.WithKeys("left", "h", "esc")), + Open: key.NewBinding(key.WithKeys("enter")), +} + func (m ClientsModel) updateForm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { switch { case key.Matches(msg, formKeys.Cancel): @@ -233,11 +503,8 @@ func (m ClientsModel) updateConfirm(msg tea.KeyMsg) (ClientsModel, tea.Cmd) { if err := m.db.DeleteClient(m.deleteID); err != nil { return m, ErrCmd(fmt.Sprintf("delete client: %v", err)) } - return m, tea.Batch( - loadClientsCmd(m.db), - loadProjectsData(m.db), - StatusCmd("Client deleted."), - ) + m.inProjects = false + return m, tea.Batch(loadClientsCmd(m.db), StatusCmd("Client deleted.")) } // errClientGone is the status when the client a delete confirm is for was @@ -300,7 +567,11 @@ func (m ClientsModel) submitForm() (ClientsModel, tea.Cmd) { } if m.editingID == 0 { - _, err = m.db.CreateClient(name, rate) + var c *model.Client + if c, err = m.db.CreateClient(name, rate); err == nil { + m.selID = c.ID // the new client is selected once it loads + m.inProjects = false + } } else { // Saved to the client the form opened for; deleted elsewhere // meanwhile, the form closes rather than write to nothing. @@ -325,16 +596,15 @@ func (m ClientsModel) submitForm() (ClientsModel, tea.Cmd) { if m.editingID != 0 { action = "updated" } - return m, tea.Batch( - loadClientsCmd(m.db), - loadProjectsCmd(m.db, 0), - StatusCmd(fmt.Sprintf("Client %s.", action)), - ) + return m, tea.Batch(loadClientsCmd(m.db), StatusCmd(fmt.Sprintf("Client %s.", action))) } // FieldErrors is how many fields of the open form need fixing, for the // app's status line. func (m ClientsModel) FieldErrors() int { + if m.proj.IsBusy() { + return m.proj.FieldErrors() + } if m.mode == clientModeForm { return len(m.errs) } @@ -345,10 +615,16 @@ func (m ClientsModel) FieldErrors() int { func (m ClientsModel) View() string { w, h := usableWidth(m.width), max(1, m.height-2) - switch m.mode { - case clientModeForm: + switch { + case m.proj.mode == projectsModeConfirmDelete: + if box := m.pane().viewConfirm(w, h); box != nil { + return modalOver(m.viewList(), w, h, box) + } + case m.proj.IsBusy(): + return modalOver(m.viewList(), w, h, m.pane().viewForm(w, h)) + case m.mode == clientModeForm: return modalOver(m.viewList(), w, h, m.viewForm(w, h)) - case clientModeConfirmDelete: + case m.mode == clientModeConfirmDelete: if box := m.viewConfirm(w, h); box != nil { return modalOver(m.viewList(), w, h, box) } @@ -356,61 +632,338 @@ func (m ClientsModel) View() string { return m.viewList() } -// listColWidths returns the NAME and HOURLY RATE column widths so the list -// spans the full available content width. -func (m ClientsModel) listColWidths() (nameCol, rateCol int) { - avail := usableWidth(m.width) - theme.Gutter - rateCol = 18 - nameCol = avail - rateCol - if nameCol < 24 { - nameCol = 24 +// wide reports whether the projects pane sits beside the list. Narrower, +// the list takes the whole width and the pane opens in its place. +func (m ClientsModel) wide() bool { return m.width >= theme.WideMin } + +// innerHeight is the rows inside the content column's padding. +func (m ClientsModel) innerHeight() int { return max(1, m.height-2) } + +// Fixed list columns (design/tokens.json): the cursor gutter and a space, +// then RATE, HOURS, EARNED and UNBILLED, each with the gap before it. +const ( + cLead = theme.Gutter + 1 + cFixedCol = theme.ClientColRate + theme.ClientColHours + theme.ClientColEarned + theme.ClientColUnbilled +) + +// split is the list's and the projects pane's widths. Wide, they share the +// width, the pane giving way first so CLIENT keeps theme.ClientNameMin; +// narrow, each takes all of it. +func (m ClientsModel) split() (list, pane int) { + w := usableWidth(m.width) + if !m.wide() { + return w, w + } + half := (w - theme.ClientPaneGap) / 2 + pane = max(0, min(half, w-theme.ClientPaneGap-(cLead+theme.ClientNameMin+cFixedCol))) + return w - theme.ClientPaneGap - pane, pane +} + +// listRows is how many clients the list shows at once: each takes two rows +// (its figures, then its project count) under the title, a blank, the +// column titles and a rule. +func (m ClientsModel) listRows() int { return max(1, (m.innerHeight()-4)/2) } + +// paneFixedRows is the projects pane's rows besides its project rows (or +// the "No projects yet." row in their place), counted from the box it +// draws, borders included. +func (m ClientsModel) paneFixedRows() int { + c := m.selected() + if c == nil { + return 0 } - return nameCol, rateCol + box, slots := m.paneBox(c, 10, 0, 0) + return len(box) + 2 - slots } -func (m ClientsModel) viewList() string { - var sb strings.Builder +// paneRows is how many projects the pane shows at once. +func (m ClientsModel) paneRows() int { return max(1, m.innerHeight()-m.paneFixedRows()) } - sb.WriteString(StyleTitle.Render("Clients") + "\n\n") +// clampOffsets scrolls the list and the pane just enough to show their +// cursors. +func (m *ClientsModel) clampOffsets() { + clamp := func(offset, cursor, n, rows int) int { + offset = min(offset, cursor) + if cursor >= offset+rows { + offset = cursor - rows + 1 + } + return max(0, min(offset, n-rows)) + } + m.offset = clamp(m.offset, m.cursor, len(m.clients), m.listRows()) + // The "+ Add project" row is always shown: the cursor on it keeps the + // last project in view. + n := len(m.clientProjects()) + m.projOffset = clamp(m.projOffset, min(m.projCursor, max(0, n-1)), n, m.paneRows()) +} +func (m ClientsModel) viewList() string { + w := usableWidth(m.width) if len(m.clients) == 0 { - sb.WriteString(StyleMuted.Render("No clients yet.") + "\n") - sb.WriteString(StyleHelp.Render("Press n to add one.")) - return sb.String() - } - - // header — Padding(0,1) is on StyleTableHeader so each cell gets 1 space each side - nameCol, rateCol := m.listColWidths() - sb.WriteString( - RowPrefix(false) + - StyleTableHeader.Width(nameCol).Render("Name") + - StyleTableHeader.Width(rateCol).Align(lipgloss.Right).Render("Hourly Rate") + - "\n", - ) - sb.WriteString(StyleTableDiv.Render(strings.Repeat("─", usableWidth(m.width))) + "\n") + return StyleTitle.Render("Clients") + "\n\n" + + StyleMuted.Render("No clients yet.") + "\n" + + StyleHelp.Render("Press n to add one, then a to add its projects.") + } + listW, paneW := m.split() + if !m.wide() { + if m.inProjects { + return strings.Join(m.renderPane(w, m.innerHeight()), "\n") + } + return strings.Join(m.renderList(w), "\n") + } + list := m.renderList(listW) + pane := m.renderPane(paneW, m.innerHeight()) + out := make([]string, max(len(list), len(pane))) + for i := range out { + l, p := blankLine(listW), blankLine(paneW) + if i < len(list) { + l = padTo(list[i], listW) + } + if i < len(pane) { + p = pane[i] + } + out[i] = l + blankLine(theme.ClientPaneGap) + p + } + return strings.Join(out, "\n") +} - for i, c := range m.clients { - sel := i == m.cursor - prefix := RowPrefix(sel) - name := truncate(c.Name, nameCol-3) - rate := fmt.Sprintf("$%.2f / hr", c.HourlyRate) +// moneyOrDash is x as money in at most w cells (0: any width; see +// fitMoney), or "—" for a client with no rate. +func moneyOrDash(x, rate float64, w int) string { + if rate == 0 { + return "—" + } + if w <= 0 { + return formatMoney(x) + } + return fitMoney(x, w) +} + +// fitMoney is x as money in at most w cells, never cut: "$123,456.78", +// then without the cents, "$123,457", then compact, "$123k" or "$1.2M". +func fitMoney(x float64, w int) string { + for _, s := range []string{formatMoney(x), wholeMoney(x)} { + if lipgloss.Width(s) <= w { + return s + } + } + return compactMoney(x) +} + +// fitRate is an hourly rate in at most w cells, shortened like fitMoney. +func fitRate(r float64, w int) string { + for _, s := range []string{formatRate(r), wholeMoney(r) + "/h"} { + if lipgloss.Width(s) <= w { + return s + } + } + return compactMoney(r) + "/h" +} + +// wholeMoney is x rounded to whole dollars: "$123,457". +func wholeMoney(x float64) string { + return strings.TrimSuffix(formatMoney(math.Round(x)), ".00") +} + +// compactMoney is x in thousands or millions: "$950", "$124k", "$1.2M". +func compactMoney(x float64) string { + sign := "" + if x < 0 { + sign, x = "-", -x + } + switch { + case math.Round(x) < 1000: + return sign + fmt.Sprintf("$%.0f", x) + case math.Round(x/1000) < 1000: + return sign + fmt.Sprintf("$%.0fk", x/1000) + case x < 9.95e6: + return sign + strings.Replace(fmt.Sprintf("$%.1fM", x/1e6), ".0M", "M", 1) + default: + return sign + fmt.Sprintf("$%.0fM", x/1e6) + } +} + +func hoursText(seconds int64) string { + return model.FormatDuration(time.Duration(seconds) * time.Second) +} - var s lipgloss.Style +// renderList is the title, the column titles and the window of clients, +// each with its project count under it. +func (m ClientsModel) renderList(lw int) []string { + nameW := max(1, lw-cLead-cFixedCol) + n := len(m.clients) + out := []string{ + spread(lw, cBg, []seg{{s: "Clients", bold: true}, {s: " " + fmt.Sprintf("%d %s · this month", n, plural(n, "client", "clients")), fg: cSubtle}}, nil), + blankLine(lw), + spread(lw, cBg, []seg{ + {s: strings.Repeat(" ", cLead)}, + {s: fit("CLIENT", nameW), fg: cSubtle, bold: true}, + {s: fitRight("RATE", theme.ClientColRate), fg: cSubtle, bold: true}, + {s: fitRight("HOURS", theme.ClientColHours), fg: cSubtle, bold: true}, + {s: fitRight("EARNED", theme.ClientColEarned), fg: cSubtle, bold: true}, + {s: fitRight("UNBILLED", theme.ClientColUnbilled), fg: cSubtle, bold: true}, + }, nil), + } + end := min(n, m.offset+m.listRows()) + out = append(out, rule(lw, m.offset > 0, end < n)) + for i := m.offset; i < end; i++ { + c := m.clients[i] + t := m.totalsFor(c) + rate := model.UsableRate(c.HourlyRate) + sel := i == m.cursor + bg, lead := cBg, seg{s: strings.Repeat(" ", cLead)} if sel { - s = StyleTableRowSel - } else { - s = StyleTableRow + // The pane's own cursor shows where the keys go; this one dims. + markFg := cPrimary + if m.inProjects { + markFg = cSubtle + } + bg = cBgAlt + lead = seg{s: theme.GlyphCursor + strings.Repeat(" ", cLead-lipgloss.Width(theme.GlyphCursor)), fg: markFg} + } + rateText := "—" + if rate != 0 { + rateText = fitRate(rate, theme.ClientColRate-1) } + unbilled := seg{s: fitRight("—", theme.ClientColUnbilled), fg: cSubtle} + if status.Cents(t.Unbilled) > 0 { + unbilled = seg{s: fitRight(fitMoney(t.Unbilled, theme.ClientColUnbilled-1), theme.ClientColUnbilled), fg: cAmber} + } + out = append(out, + spread(lw, bg, []seg{ + lead, + {s: fit(c.Name, nameW), bold: sel}, + {s: fitRight(rateText, theme.ClientColRate), fg: cDim}, + {s: fitRight(hoursText(t.MonthSeconds), theme.ClientColHours)}, + {s: fitRight(moneyOrDash(t.MonthEarned, rate, theme.ClientColEarned-1), theme.ClientColEarned), fg: cDim}, + unbilled, + }, nil), + spread(lw, cBg, []seg{{s: strings.Repeat(" ", cLead)}, {s: projectCount(t.projects), fg: cSubtle}}, nil), + ) + } + return out +} - sb.WriteString(prefix + s.Width(nameCol).Render(name) + s.Width(rateCol).Align(lipgloss.Right).Render(rate) + "\n") +func projectCount(n int) string { + if n == 0 { + return "No projects" } + return fmt.Sprintf("%d %s", n, plural(n, "project", "projects")) +} - return sb.String() +// renderPane is the selected client's box: its projects with this month's +// hours and earned, "+ Add project", and its rate, start date, all-time +// totals and unbilled. Its border is primary while it has the keys. It's +// pw wide and at most rows tall. +func (m ClientsModel) renderPane(pw, rows int) []string { + c := m.selected() + if c == nil || pw < 4 { + return nil + } + start := m.projOffset + end := min(len(m.clientProjects()), start+m.paneRows()) + box, _ := m.paneBox(c, pw-2, start, end) + edge := cBorder + if m.inProjects { + edge = cPrimary + } + return modalFrame(c.Name+" · projects", cText, edge, pw-2, fitRows(box, max(0, rows-2))) +} + +// paneBox is the pane's rows inside its border, inner wide, with projects +// start to end, and how many of them are project rows (or the empty +// pane's "No projects yet."). +func (m ClientsModel) paneBox(c *model.Client, inner, start, end int) ([]boxRow, int) { + pad := strings.Repeat(" ", theme.Gutter) + nameW := max(1, inner-2*theme.Gutter-theme.ClientColHours-theme.ClientPaneEarned) + line := func(bg lipgloss.Color, lead seg, segs ...seg) string { + return spread(inner, bg, append([]seg{lead}, segs...), []seg{{s: pad}}) + } + plain := func(segs ...seg) string { return line(cBg, seg{s: pad}, segs...) } + cursor := func(on bool) (lipgloss.Color, seg) { + if !on { + return cBg, seg{s: pad} + } + return cBgAlt, seg{s: theme.GlyphCursor + strings.Repeat(" ", theme.Gutter-lipgloss.Width(theme.GlyphCursor)), fg: cPrimary} + } + rate := model.UsableRate(c.HourlyRate) + ps := m.clientProjects() + + box := []boxRow{ + {blankLine(inner), dropSpacing}, + {plain( + seg{s: fit("PROJECT", nameW), fg: cSubtle, bold: true}, + seg{s: fitRight("HOURS", theme.ClientColHours), fg: cSubtle, bold: true}, + seg{s: fitRight("EARNED", theme.ClientPaneEarned), fg: cSubtle, bold: true}, + ), dropCore}, + } + more := func(n int, arrow string) boxRow { + if n == 0 { + return boxRow{blankLine(inner), dropSpacing} + } + return boxRow{plain(seg{s: fmt.Sprintf("%s %d more", arrow, n), fg: cSubtle}), dropCore} + } + box = append(box, more(start, "↑")) + slots := end - start + if len(ps) == 0 { + box = append(box, boxRow{plain(seg{s: "No projects yet.", fg: cSubtle}), dropCore}) + slots = 1 + } + for i := start; i < end; i++ { + p := ps[i] + var st projectStats + if s := m.stats[p.ID]; s != nil { + st = *s + } + sel := m.inProjects && i == m.projCursor + bg, lead := cursor(sel) + box = append(box, boxRow{line(bg, lead, + seg{s: fit(p.Name, nameW), bold: sel}, + seg{s: fitRight(hoursText(st.MonthSeconds), theme.ClientColHours)}, + seg{s: fitRight(moneyOrDash(st.MonthEarned, rate, theme.ClientPaneEarned-1), theme.ClientPaneEarned), fg: cDim}, + ), 0}) + } + box = append(box, more(len(ps)-end, "↓")) + addBg, addLead := cursor(m.inProjects && m.projCursor >= len(ps)) + box = append(box, + boxRow{line(addBg, addLead, seg{s: "+ Add project", fg: cPrimary, bold: true}, seg{s: " a", fg: cSubtle}), 0}, + boxRow{blankLine(inner), dropSpacing}, + boxRow{renderSegs(cBg, seg{s: " " + strings.Repeat("─", max(0, inner-2)) + " ", fg: cBorder}), dropRule}, + ) + + t := m.totalsFor(c) + fact := func(label string, value seg, drop int) boxRow { + value.s = truncate(value.s, max(1, inner-2*theme.Gutter-theme.ClientPaneLabel)) + return boxRow{plain(seg{s: fit(label, theme.ClientPaneLabel), fg: cSubtle}, value), drop} + } + rateText := "—" + if rate != 0 { + rateText = formatMoney(rate) + } + since := "—" + if !c.CreatedAt.IsZero() { + since = c.CreatedAt.Local().Format("Jan 2, 2006") + } + unbilled := seg{s: "Nothing unbilled", fg: cSubtle} + if t.unbilledEntries > 0 { + entries := fmt.Sprintf("%d %s", t.unbilledEntries, plural(t.unbilledEntries, "entry", "entries")) + unbilled = seg{s: entries, fg: cDim} + if rate != 0 { + unbilled = seg{s: formatMoney(t.Unbilled) + " · " + entries, fg: cAmber} + } + } + box = append(box, + fact("Hourly rate", seg{s: rateText, bold: true}, dropRate), + fact("Since", seg{s: since, fg: cDim}, dropDate), + fact("All time", seg{s: hoursText(t.allSeconds) + " · " + moneyOrDash(float64(t.allSeconds)/3600*rate, rate, 0), fg: cDim}, dropMoney), + fact("Unbilled", unbilled, dropMoney), + boxRow{blankLine(inner), dropSpacing}, + ) + return box, slots } // viewForm is the New client or Edit client modal. func (m ClientsModel) viewForm(w, h int) []string { - sw := stripWidth(modalInner(theme.ModalWidth, w)) + sw := stripWidth(modalInner(theme.ModalWidthNarrow, w)) field := func(label string, idx int) modalField { return modalField{ label: label, @@ -427,6 +980,7 @@ func (m ClientsModel) viewForm(w, h int) []string { } return formModal{ title: title, + width: theme.ModalWidthNarrow, fields: []modalField{field("Name", clientFieldName), field("Rate ($/h)", clientFieldRate)}, left: []modalButton{ {label: "Save", kind: buttonPrimary, focused: m.focusIdx == clientFieldSave}, diff --git a/internal/ui/views/clients_detail_test.go b/internal/ui/views/clients_detail_test.go new file mode 100644 index 0000000..fc57d51 --- /dev/null +++ b/internal/ui/views/clients_detail_test.go @@ -0,0 +1,496 @@ +package views + +// The Clients tab's master-detail (ALI-2617): the projects pane, its keys, +// and the project form and confirm opened from it. These replace the old +// Projects tab's list tests; the form's own tests are in projects_test.go. + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/aliasproject/notch/internal/db" + "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/theme" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" +) + +// loadedClients is the tab at w×h on d's data. +func loadedClients(t *testing.T, d *db.DB, w, h int) ClientsModel { + t.Helper() + m := NewClients(d) + m.SetSize(w, h) + return feedClients(t, m, m.Init()) +} + +// feedClients runs cmd and gives the model every message it makes, as the app +// would, and the commands those make in turn. +func feedClients(t *testing.T, m ClientsModel, cmd tea.Cmd) ClientsModel { + t.Helper() + if cmd == nil { + return m + } + for _, msg := range runCmd(t, cmd) { + var next tea.Cmd + m, next = m.Update(msg) + m = feedClients(t, m, next) + } + return m +} + +func press(m ClientsModel, keys ...tea.KeyMsg) (ClientsModel, tea.Cmd) { + var cmd tea.Cmd + for _, k := range keys { + m, cmd = m.Update(k) + } + return m, cmd +} + +var ( + keyRight = tea.KeyMsg{Type: tea.KeyRight} + keyLeft = tea.KeyMsg{Type: tea.KeyLeft} +) + +func typeText(m ClientsModel, s string) ClientsModel { + for _, r := range s { + m, _ = m.Update(runeKey(r)) + } + return m +} + +func clientsDB(t *testing.T) (*db.DB, *model.Client, *model.Client) { + t.Helper() + d := newTestDB(t) + acme, _ := d.CreateClient("Acme", 100) + beta, _ := d.CreateClient("Beta", 0) + if _, err := d.CreateProject(acme.ID, "Website"); err != nil { + t.Fatal(err) + } + return d, acme, beta +} + +// a in the list, and enter on "+ Add project" in the pane, open New +// project for the selected client, filled in; saving puts it in the pane. +func TestClients_AddProjectFromThePane(t *testing.T) { + d, acme, beta := clientsDB(t) + m := loadedClients(t, d, 140, 40) + + m, _ = press(m, keyRight, keyDown) // past Website onto "+ Add project" + if !m.inProjects || m.selectedProject() != nil { + t.Fatalf("inProjects %v, cursor %d; want the pane's add row", m.inProjects, m.projCursor) + } + m, _ = press(m, keyEnter) + if m.proj.mode != projectsModeNewProject || !m.IsBusy() { + t.Fatalf("enter on + Add project: mode %v; want New project open and the tab busy", m.proj.mode) + } + if got := m.proj.inputs[projFieldClient].Value(); got != "Acme" || m.proj.clientID != acme.ID { + t.Errorf("Client = %q (id %d), want Acme filled in", got, m.proj.clientID) + } + if m.proj.focusedInput != projFieldName { + t.Errorf("focus on %d, want Name", m.proj.focusedInput) + } + m = typeText(m, "Booking app") + m, cmd := press(m, keyEnter) + m = feedClients(t, m, cmd) + if m.IsBusy() { + t.Fatalf("the form should close on save; errs %v", m.proj.errs) + } + view := ansi.Strip(m.View()) + if !strings.Contains(view, "Booking app") || !strings.Contains(view, "2 projects") { + t.Errorf("want Booking app in Acme's pane and the count updated:\n%s", view) + } + + // a from the list adds to the client under the cursor. + m, _ = press(m, keyLeft, keyDown, runeKey('a')) + if got := m.proj.inputs[projFieldClient].Value(); got != "Beta" || m.proj.clientID != beta.ID { + t.Errorf("a on Beta: Client = %q, want Beta", got) + } + m = typeText(m, "Retainer") + m, cmd = press(m, keyEnter) + m = feedClients(t, m, cmd) + if ps, _ := d.ListProjects(beta.ID); len(ps) != 1 || ps[0].Name != "Retainer" { + t.Errorf("Beta's projects = %v, want Retainer", ps) + } +} + +// a with no clients says to add one first, and opens nothing. +func TestClients_AddProjectNeedsAClient(t *testing.T) { + m := loadedClients(t, newTestDB(t), 140, 40) + m, cmd := press(m, runeKey('a')) + if m.IsBusy() || cmd == nil || cmd() != ErrMsg(errNoClientYet) { + t.Errorf("busy %v; want %q and no form", m.IsBusy(), errNoClientYet) + } +} + +// e and d act on the client in the list and on the project in the pane. +func TestClients_EditAndDeleteFollowTheFocus(t *testing.T) { + d, acme, _ := clientsDB(t) + m := loadedClients(t, d, 140, 40) + + got, _ := press(m, runeKey('e')) + if got.mode != clientModeForm || got.editingID != acme.ID { + t.Errorf("e in the list: mode %v, editing %d; want Edit client for Acme", got.mode, got.editingID) + } + got, _ = press(m, runeKey('d')) + if got.mode != clientModeConfirmDelete || got.deleteID != acme.ID { + t.Errorf("d in the list: mode %v; want the client confirm", got.mode) + } + + m, _ = press(m, keyRight) + web := m.selectedProject() + if web == nil || web.Name != "Website" { + t.Fatalf("→ should put the cursor on Website, got %v", web) + } + got, _ = press(m, runeKey('e')) + if got.proj.mode != projectsModeEditProject || got.proj.editingID != web.ID || got.proj.inputs[projFieldName].Value() != "Website" { + t.Errorf("e in the pane: mode %v; want Edit project for Website", got.proj.mode) + } + got, _ = press(m, keyEnter) + if got.proj.mode != projectsModeEditProject { + t.Errorf("enter on a project: mode %v; want Edit project", got.proj.mode) + } + got, _ = press(m, runeKey('d')) + if got.proj.mode != projectsModeConfirmDelete || got.proj.deleteID != web.ID { + t.Fatalf("d in the pane: mode %v; want the project confirm", got.proj.mode) + } + if v := ansi.Strip(got.View()); !strings.Contains(v, "Delete project?") || !strings.Contains(v, "“Website”") { + t.Errorf("the confirm should name Website:\n%s", v) + } + got, cmd := press(got, runeKey('y')) + got = feedClients(t, got, cmd) + if ps, _ := d.ListProjects(0); len(ps) != 0 { + t.Errorf("projects = %v, want Website deleted", ps) + } + if cs, _ := d.ListClients(); len(cs) != 2 { + t.Errorf("clients = %v, want both kept", cs) + } + if !got.inProjects || got.projCursor != 0 { + t.Errorf("after the delete: inProjects %v, cursor %d; want the pane's add row", got.inProjects, got.projCursor) + } + + // ← and esc go back to the list. + for _, k := range []tea.KeyMsg{keyLeft, keyEsc} { + if back, _ := press(m, k); back.inProjects { + t.Errorf("%q should go back to the clients", k.String()) + } + } +} + +// Edit project's Client field moves a project to another client, as the +// Projects tab's form did. +func TestClients_EditProjectMovesItToAnotherClient(t *testing.T) { + d, _, beta := clientsDB(t) + m := loadedClients(t, d, 140, 40) + m, _ = press(m, keyRight, runeKey('e'), tea.KeyMsg{Type: tea.KeyShiftTab}) + m.proj.inputs[projFieldClient].SetValue("") + m = typeText(m, "Beta") + m, cmd := press(m, keyEnter, keyEnter) // pick Beta, then save + m = feedClients(t, m, cmd) + if m.IsBusy() { + t.Fatalf("want it saved; errs %v", m.proj.errs) + } + if ps, _ := d.ListProjects(beta.ID); len(ps) != 1 || ps[0].Name != "Website" { + t.Errorf("Beta's projects = %v, want Website moved there", ps) + } +} + +// The pane's projects stay reachable however many there are: the cursor +// scrolls them, and the pane says how many are out of view. +func TestClients_PaneScrollsItsProjects(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 100) + for _, n := range strings.Fields("a b c d e f g h i j k l m n o p q r s t u v w x y z") { + if _, err := d.CreateProject(c.ID, "Project "+n); err != nil { + t.Fatal(err) + } + } + m := loadedClients(t, d, 140, 30) + m, _ = press(m, keyRight) + for range 26 { + m, _ = press(m, keyDown) + } + view := ansi.Strip(m.View()) + if !strings.Contains(view, "Project z") || !strings.Contains(view, "▌ + Add project") || !strings.Contains(view, "↑ ") { + t.Errorf("scrolled to the end, want Project z, the add row selected and a count above:\n%s", view) + } + if lines := strings.Split(m.View(), "\n"); len(lines) > m.innerHeight() { + t.Errorf("view is %d rows, want at most %d", len(lines), m.innerHeight()) + } +} + +// A reload keeps the selected client selected, and a new client is +// selected once it loads. +func TestClients_SelectionFollowsTheClient(t *testing.T) { + d, acme, _ := clientsDB(t) + m := loadedClients(t, d, 140, 40) + if _, err := d.CreateClient("Aardvark", 0); err != nil { + t.Fatal(err) + } + m = feedClients(t, m, m.Init()) + if c := m.selected(); c == nil || c.ID != acme.ID { + t.Errorf("after a client sorted before it, selected %v; want Acme still", c) + } + + m, _ = press(m, runeKey('n')) + m = typeText(m, "Zed") + m, cmd := press(m, keyEnter) + m = feedClients(t, m, cmd) + if c := m.selected(); c == nil || c.Name != "Zed" { + t.Errorf("selected %v after creating Zed; want Zed", c) + } +} + +func TestClients_HelpByFocus(t *testing.T) { + d, _, _ := clientsDB(t) + m := loadedClients(t, d, 140, 40) + keys := func(hs []Hotkey) string { + var out []string + for _, h := range hs { + out = append(out, h.Key+" "+h.Label) + } + return strings.Join(out, ", ") + } + if got, want := keys(m.Help()), "n new client, a add project, e edit, → projects, d delete"; got != want { + t.Errorf("list keys = %q, want %q", got, want) + } + m, _ = press(m, keyRight) + if got, want := keys(m.Help()), "n new client, a add project, e edit, d delete, ← clients"; got != want { + t.Errorf("pane keys = %q, want %q", got, want) + } + m, _ = press(m, runeKey('a')) + if got := keys(m.Help()); !strings.HasPrefix(got, "tab next field") { + t.Errorf("form keys = %q, want the form's", got) + } +} + +// Edit client: a rate that isn't a number is an error under Rate, in the +// narrow client modal. +func TestClients_EditClientRateError(t *testing.T) { + d, acme, _ := clientsDB(t) + m := loadedClients(t, d, 140, 40) + m, _ = press(m, runeKey('e'), keyTab) + m.inputs[clientFieldRate].SetValue("95/hr") + m, cmd := press(m, keyEnter) + if cmd != nil || m.mode != clientModeForm || m.FieldErrors() != 1 || m.errs[clientFieldRate] != errRate { + t.Fatalf("mode %v, errs %v; want the form kept with a rate error", m.mode, m.errs) + } + lines := strings.Split(ansi.Strip(m.View()), "\n") + top, rate := -1, -1 + for i, l := range lines { + if strings.Contains(l, "╭─ Edit client ") { + top = i + } + if strings.Contains(l, "Rate ($/h) ▌") { + rate = i + } + } + if top < 0 || rate < 0 || !strings.Contains(lines[rate+1], "✕ "+errRate) { + t.Fatalf("want the error under Rate:\n%s", strings.Join(lines, "\n")) + } + box := []rune(lines[top]) + from := strings.Index(lines[top], "╭") + from = len([]rune(lines[top][:from])) + to := from + for to < len(box) && box[to] != '╮' { + to++ + } + if w := to - from + 1; w != 60 { + t.Errorf("the client modal is %d wide, want 60 (tui-modal-width-narrow)", w) + } + if c, _ := d.GetClient(acme.ID); c.HourlyRate != 100 { + t.Errorf("rate saved as %v despite the error", c.HourlyRate) + } + // Typing in Rate clears its error. + m, _ = press(m, tea.KeyMsg{Type: tea.KeyBackspace}) + if m.FieldErrors() != 0 { + t.Error("changing the rate should clear its error") + } +} + +// The totals: this month's hours and earnings and every month's unbilled, +// leaving out the running timer; all-time time and unbilled entries. +func TestLoadClientsData_Totals(t *testing.T) { + d := newTestDB(t) + acme, _ := d.CreateClient("Acme", 100) + free, _ := d.CreateClient("Free", 0) + web, _ := d.CreateProject(acme.ID, "Website") + app, _ := d.CreateProject(acme.ID, "App") + pro, _ := d.CreateProject(free.ID, "Pro bono") + now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.Local) + add := func(pid int64, start time.Time, h float64, invoiced bool) { + end := start.Add(time.Duration(h * float64(time.Hour))) + e, err := d.AddEntry(pid, "work", "", start, &end) + if err != nil { + t.Fatal(err) + } + if invoiced { + if err := d.SetEntryInvoiced(e.ID, true); err != nil { + t.Fatal(err) + } + } + } + add(web.ID, time.Date(2026, 6, 10, 9, 0, 0, 0, time.Local), 2, false) + add(app.ID, time.Date(2026, 6, 11, 9, 0, 0, 0, time.Local), 1, true) + add(web.ID, time.Date(2026, 5, 20, 9, 0, 0, 0, time.Local), 3, false) + add(pro.ID, time.Date(2026, 6, 12, 9, 0, 0, 0, time.Local), 1.5, false) + + msg, ok := loadClientsData(d, now).(clientsDataMsg) + if !ok { + t.Fatalf("got %T, want clientsDataMsg", loadClientsData(d, now)) + } + m := ClientsModel{clients: msg.clients, projects: msg.projects, stats: msg.stats} + a := m.totalsFor(acme) + if a.MonthSeconds != 3*3600 || a.MonthEarned != 300 || a.Unbilled != 500 { + t.Errorf("Acme month %ds, earned %v, unbilled %v; want 3h, 300, 500", a.MonthSeconds, a.MonthEarned, a.Unbilled) + } + if a.allSeconds != 6*3600 || a.unbilledEntries != 2 || a.projects != 2 { + t.Errorf("Acme all-time %ds, %d unbilled entries, %d projects; want 6h, 2, 2", a.allSeconds, a.unbilledEntries, a.projects) + } + if st := msg.stats[web.ID]; st == nil || st.MonthSeconds != 2*3600 || st.allSeconds != 5*3600 { + t.Errorf("Website stats %+v, want 2h this month and 5h in all", st) + } + f := m.totalsFor(free) + if f.MonthSeconds != 5400 || f.Unbilled != 0 || f.unbilledEntries != 1 { + t.Errorf("Free %+v; want 1:30:00, no money, one unbilled entry", f) + } + + // The pane: a client with no rate shows dashes for money, and its + // unbilled entries without an amount. + m.width, m.height = 140, 40 + m.cursor = 1 + pane := ansi.Strip(strings.Join(m.renderPane(66, 34), "\n")) + for _, want := range []string{"Hourly rate —", "All time 1:30:00 · —", "Unbilled 1 entry", "Pro bono", "1:30:00"} { + if !strings.Contains(pane, want) { + t.Errorf("Free's pane is missing %q:\n%s", want, pane) + } + } + m.cursor = 0 + pane = ansi.Strip(strings.Join(m.renderPane(66, 34), "\n")) + for _, want := range []string{"Hourly rate $100.00", "All time 6:00:00 · $600.00", "Unbilled $500.00 · 2 entries"} { + if !strings.Contains(pane, want) { + t.Errorf("Acme's pane is missing %q:\n%s", want, pane) + } + } +} + +// A load that fails says so rather than showing an empty tab. +func TestLoadClientsData_Error(t *testing.T) { + d := newTestDB(t) + d.Close() + if _, ok := loadClientsData(d, time.Now()).(ErrMsg); !ok { + t.Error("want an ErrMsg from a closed database") + } +} + +// A reload without the pane's client closes the pane and says so, rather +// than show the next client's projects for e and d to act on. +func TestClients_PaneClosesWhenItsClientGoes(t *testing.T) { + d, acme, _ := clientsDB(t) + m := loadedClients(t, d, 140, 40) + m, _ = press(m, keyRight) + if err := d.DeleteClient(acme.ID); err != nil { + t.Fatal(err) + } + m, cmd := m.Update(loadClientsData(d, time.Now())) + if m.inProjects || m.projCursor != 0 || m.projOffset != 0 { + t.Errorf("inProjects %v, cursor %d, offset %d; want the pane closed", m.inProjects, m.projCursor, m.projOffset) + } + if cmd == nil || cmd() != ErrMsg(errClientGone) { + t.Errorf("want %q", errClientGone) + } + if got, _ := press(m, runeKey('e')); got.proj.IsBusy() { + t.Error("e opened a project form for another client") + } +} + +// The pane's fixed rows are counted from what it draws: an empty pane fits +// the shortest terminal whole, and a full one fills the body exactly. +func TestClients_PaneHeight(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 100) + m := loadedClients(t, d, 140, 22) + pane := m.renderPane(66, m.innerHeight()) + text := ansi.Strip(strings.Join(pane, "\n")) + if len(pane) > m.innerHeight() { + t.Errorf("empty pane is %d rows, body %d", len(pane), m.innerHeight()) + } + for _, want := range []string{"No projects yet.", "+ Add project", "Hourly rate", "Since", "All time", "Unbilled", "╰"} { + if !strings.Contains(text, want) { + t.Errorf("empty pane at 22 rows is missing %q:\n%s", want, text) + } + } + if got := len(pane); got != m.paneFixedRows()+1 { + t.Errorf("empty pane is %d rows, want paneFixedRows()+1 = %d", got, m.paneFixedRows()+1) + } + + for i := range 30 { + if _, err := d.CreateProject(c.ID, fmt.Sprintf("Project %02d", i)); err != nil { + t.Fatal(err) + } + } + m = loadedClients(t, d, 140, 30) + pane = m.renderPane(66, m.innerHeight()) + text = ansi.Strip(strings.Join(pane, "\n")) + if len(pane) != m.innerHeight() || !strings.Contains(text, "Unbilled") || !strings.Contains(text, "↓ ") { + t.Errorf("full pane is %d rows, want %d with its facts and a count below:\n%s", len(pane), m.innerHeight(), text) + } + // Nothing was dropped to fit: the window was sized from the rows the + // pane really draws. + end := min(30, m.projOffset+m.paneRows()) + if box, _ := m.paneBox(c, 64, m.projOffset, end); len(box)+2 != len(pane) { + t.Errorf("the pane drew %d of its %d rows: its fixed rows are miscounted", len(pane), len(box)+2) + } +} + +func TestFitMoney_NeverCutsANumber(t *testing.T) { + for _, c := range []struct { + x float64 + w int + want string + }{ + {123456.78, 11, "$123,456.78"}, + {123456.78, 10, "$123,457"}, + {123456.78, 7, "$123k"}, + {999.5, 4, "$1k"}, + {1_260_000, 9, "$1.3M"}, + {1_000_000, 9, "$1M"}, + {42_000_000, 9, "$42M"}, + } { + if got := fitMoney(c.x, c.w); got != c.want { + t.Errorf("fitMoney(%v, %d) = %q, want %q", c.x, c.w, got, c.want) + } + } + if got := fitRate(1_000_000, theme.ClientColRate-1); got != "$1M/h" { + t.Errorf("fitRate(1,000,000) = %q, want $1M/h", got) + } +} + +// Large amounts in the list and the pane are shortened, never cut with "…". +func TestClients_LargeAmountsAreNotCut(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Big", 1_000_000) + p, _ := d.CreateProject(c.ID, "Retainer") + now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.Local) + start := time.Date(2026, 6, 1, 9, 0, 0, 0, time.Local) + end := start.Add(123*time.Hour + 27*time.Minute) + if _, err := d.AddEntry(p.ID, "work", "", start, &end); err != nil { + t.Fatal(err) + } + m := ClientsModel{width: 140, height: 40} + m, _ = m.Update(loadClientsData(d, now)) + list := ansi.Strip(strings.Join(m.renderList(66), "\n")) + pane := ansi.Strip(strings.Join(m.renderPane(66, 34), "\n")) + if strings.Contains(list, "…") || strings.Contains(pane, "Retainer") && strings.Contains(strings.Split(pane, "Retainer")[1], "…") { + t.Errorf("an amount was cut:\n%s\n%s", list, pane) + } + for _, want := range []string{"$1M/h", "$123M"} { + if !strings.Contains(list, want) { + t.Errorf("list is missing %q:\n%s", want, list) + } + } + if !strings.Contains(pane, "$123,450,000 │") { + t.Errorf("pane earned should drop its cents to fit:\n%s", pane) + } +} diff --git a/internal/ui/views/clients_test.go b/internal/ui/views/clients_test.go index 5af04a5..acd59d7 100644 --- a/internal/ui/views/clients_test.go +++ b/internal/ui/views/clients_test.go @@ -351,25 +351,6 @@ func TestPadRight(t *testing.T) { } } -func TestClientsListColWidths_SpansAvailableWidth(t *testing.T) { - m := ClientsModel{width: 100} - nameCol, rateCol := m.listColWidths() - if nameCol < 24 { - t.Errorf("nameCol = %d, want >= 24 (minimum floor)", nameCol) - } - if rateCol != 18 { - t.Errorf("rateCol = %d, want fixed 18", rateCol) - } -} - -func TestClientsListColWidths_ClampsToMinimumWhenNarrow(t *testing.T) { - m := ClientsModel{width: 30} - nameCol, _ := m.listColWidths() - if nameCol != 24 { - t.Errorf("nameCol at width 30 = %d, want 24 (clamped floor)", nameCol) - } -} - // ── Constructor / small accessors ──────────────────────────────────────────── func TestNewClients(t *testing.T) { @@ -394,9 +375,9 @@ func TestClientsInit_LoadsClients(t *testing.T) { t.Fatal("Init() returned a nil cmd") } msg := cmd() - loaded, ok := msg.(clientsLoadedMsg) + loaded, ok := msg.(clientsDataMsg) if !ok { - t.Fatalf("Init cmd produced %T, want clientsLoadedMsg", msg) + t.Fatalf("Init cmd produced %T, want clientsDataMsg", msg) } if len(loaded.clients) != 1 || loaded.clients[0].Name != "Acme" { t.Errorf("loaded.clients = %+v, want one client named Acme", loaded.clients) @@ -428,7 +409,7 @@ func TestClientsHelp(t *testing.T) { }{ {clientModeForm, "tab", "next field"}, {clientModeConfirmDelete, "y", "delete"}, - {clientModeList, "n", "new"}, + {clientModeList, "n", "new client"}, } for _, c := range cases { m := ClientsModel{mode: c.mode} @@ -458,24 +439,24 @@ func TestClientsSetSize(t *testing.T) { func TestClientsUpdate_ClientsLoadedMsgClampsCursor(t *testing.T) { m := ClientsModel{cursor: 5} - got, cmd := m.Update(clientsLoadedMsg{clients: []*model.Client{{ID: 1}, {ID: 2}}}) + got, cmd := m.Update(clientsDataMsg{clients: []*model.Client{{ID: 1}, {ID: 2}}}) if got.cursor != 1 { t.Errorf("cursor after loading with an out-of-range cursor = %d, want 1 (clamped)", got.cursor) } if cmd != nil { - t.Error("want nil cmd from clientsLoadedMsg handling") + t.Error("want nil cmd from clientsDataMsg handling") } } func TestClientsUpdate_ClientsLoadedMsgLeavesInRangeCursorAlone(t *testing.T) { m := ClientsModel{cursor: 0} - got, _ := m.Update(clientsLoadedMsg{clients: nil}) + got, _ := m.Update(clientsDataMsg{clients: nil}) if got.cursor != 0 { t.Errorf("cursor = %d, want 0 (cursor > 0 guard should skip clamp)", got.cursor) } m2 := ClientsModel{cursor: 1} - got2, _ := m2.Update(clientsLoadedMsg{clients: []*model.Client{{ID: 1}, {ID: 2}, {ID: 3}}}) + got2, _ := m2.Update(clientsDataMsg{clients: []*model.Client{{ID: 1}, {ID: 2}, {ID: 3}}}) if got2.cursor != 1 { t.Errorf("cursor = %d, want 1 (already in range, untouched)", got2.cursor) } @@ -610,7 +591,7 @@ func TestClientsView_ListModeEmpty(t *testing.T) { if !strings.Contains(out, "No clients yet.") { t.Errorf("View() for empty list = %q, want to contain %q", out, "No clients yet.") } - if !strings.Contains(out, "Press n to add one.") { + if !strings.Contains(out, "Press n to add one") { t.Errorf("View() for empty list missing hint text: %q", out) } } @@ -619,14 +600,15 @@ func TestClientsView_ListModePopulated(t *testing.T) { m := ClientsModel{ mode: clientModeList, width: 100, + height: 30, cursor: 0, clients: []*model.Client{ {ID: 1, Name: "Acme", HourlyRate: 75}, {ID: 2, Name: "Globex", HourlyRate: 120}, }, } - out := m.View() - for _, want := range []string{"Name", "Hourly Rate", "Acme", "Globex", "$75.00 / hr"} { + out := ansi.Strip(m.View()) + for _, want := range []string{"CLIENT", "RATE", "HOURS", "EARNED", "UNBILLED", "Acme", "Globex", "$75/h", "No projects"} { if !strings.Contains(out, want) { t.Errorf("View() for populated list missing %q; got %q", want, out) } @@ -724,7 +706,7 @@ func TestClientsConfirm_DeletesTheClientItOpenedFor(t *testing.T) { m := ClientsModel{db: d, clients: []*model.Client{bravo, charlie}, width: 100, height: 30} m, _ = m.updateList(runeKey('d')) // on Bravo alpha, _ := d.CreateClient("Alpha", 0) - m, _ = m.Update(clientsLoadedMsg{clients: []*model.Client{alpha, bravo, charlie}}) + m, _ = m.Update(clientsDataMsg{clients: []*model.Client{alpha, bravo, charlie}}) if !strings.Contains(ansi.Strip(m.View()), "“Bravo”") { t.Errorf("the confirm should still name Bravo:\n%s", ansi.Strip(m.View())) } @@ -745,7 +727,7 @@ func TestClientsConfirm_DeletesTheClientItOpenedFor(t *testing.T) { m = ClientsModel{db: d, clients: []*model.Client{charlie}, width: 100, height: 30} m, _ = m.updateList(runeKey('d')) // on Charlie, then deleted elsewhere - got, cmd := m.Update(clientsLoadedMsg{clients: []*model.Client{alpha}}) + got, cmd := m.Update(clientsDataMsg{clients: []*model.Client{alpha}}) if got.mode != clientModeList || cmd == nil || cmd() != ErrMsg(errClientGone) { t.Errorf("mode %v; want the confirm closed with %q when its client is gone", got.mode, errClientGone) } @@ -760,7 +742,7 @@ func TestClientsEditForm_GoneClientClosesTheForm(t *testing.T) { other, _ := d.CreateClient("Beta", 0) m := ClientsModel{db: d, clients: []*model.Client{c, other}, width: 100, height: 30} m, _ = m.updateList(listKeyMsg("e")) // on Acme - m, _ = m.Update(clientsLoadedMsg{clients: []*model.Client{other, c}}) + m, _ = m.Update(clientsDataMsg{clients: []*model.Client{other, c}}) m.inputs[clientFieldName].SetValue("Acme Co") got, _ := m.submitForm() if got.mode != clientModeList { diff --git a/internal/ui/views/common.go b/internal/ui/views/common.go index a338e46..b8b58fc 100644 --- a/internal/ui/views/common.go +++ b/internal/ui/views/common.go @@ -54,8 +54,6 @@ type Hotkey struct { // ── Shared load message types ───────────────────────────────────────────────── -type clientsLoadedMsg struct{ clients []*model.Client } -type projectsLoadedMsg struct{ projects []*model.Project } type timerEntriesMsg []*model.Entry // ── Shared commands ─────────────────────────────────────────────────────────── @@ -72,26 +70,6 @@ func RunningChangedCmd() tea.Cmd { return func() tea.Msg { return RunningChangedMsg{} } } -func loadClientsCmd(database *db.DB) tea.Cmd { - return func() tea.Msg { - clients, err := database.ListClients() - if err != nil { - return ErrMsg(fmt.Sprintf("load clients: %v", err)) - } - return clientsLoadedMsg{clients: clients} - } -} - -func loadProjectsCmd(database *db.DB, clientID int64) tea.Cmd { - return func() tea.Msg { - projects, err := database.ListProjects(clientID) - if err != nil { - return ErrMsg(fmt.Sprintf("load projects: %v", err)) - } - return projectsLoadedMsg{projects: projects} - } -} - func loadTimerEntriesCmd(database *db.DB) tea.Cmd { return func() tea.Msg { entries, err := database.ListEntries(0, "", "", true) diff --git a/internal/ui/views/keys.go b/internal/ui/views/keys.go index 200c7ce..ec6697d 100644 --- a/internal/ui/views/keys.go +++ b/internal/ui/views/keys.go @@ -18,7 +18,7 @@ type keyGroup struct { // keyGroups lists every key by where it works. func keyGroups() []keyGroup { return []keyGroup{ - {"Everywhere", []Hotkey{{"1 2 3 4", "switch tab"}, {"?", "this help"}, {"q", "quit"}}}, + {"Everywhere", []Hotkey{{"1 2 3", "switch tab"}, {"?", "this help"}, {"q", "quit"}}}, {"Timers", []Hotkey{ {"n", "new timer"}, {"space", "start / stop"}, {"r", "resume entry"}, {"e", "edit"}, {"i", "toggle invoiced"}, {"p", "toggle paid"}, @@ -28,8 +28,10 @@ func keyGroups() []keyGroup { {"t", "today"}, {"y", "yesterday"}, {"w", "this week"}, {"m", "this month"}, {"a", "all time"}, {"f", "custom range"}, }}, - {"Projects", []Hotkey{{"n", "new project"}, {"e", "edit"}, {"d", "delete"}}}, - {"Clients", []Hotkey{{"n", "new client"}, {"e", "edit"}, {"d", "delete"}}}, + {"Clients", []Hotkey{ + {"n", "new client"}, {"a", "add project"}, {"e", "edit"}, + {"d", "delete"}, {"→ enter", "projects"}, {"← esc", "back to clients"}, + }}, {"Reports", []Hotkey{ {"enter", "show entries"}, {"e", "edit entry"}, {"f", "custom range"}, {"t w m", "day, week, month"}, {"y a", "year, all time"}, diff --git a/internal/ui/views/modal.go b/internal/ui/views/modal.go index a0ad4fa..d95c07e 100644 --- a/internal/ui/views/modal.go +++ b/internal/ui/views/modal.go @@ -201,6 +201,7 @@ type modalField struct { type formModal struct { title string + width int // borders included; 0 is tui-modal-width fields []modalField left []modalButton right []modalButton @@ -222,14 +223,19 @@ func stripWidth(inner int) int { return max(theme.StripMin, inner-fieldCol()-theme.ModalIndent) } -// render draws the modal for a body w×h: as wide as tui-modal-width allows, -// with spacing dropped until it fits in h rows where it can. +// render draws the modal for a body w×h: as wide as its width (or +// tui-modal-width) allows, with spacing dropped until it fits in h rows +// where it can. // // Suggestions float over the rows under their field, down to the button // row, rather than pushing them down: the box keeps its size and place // while they open and close, and the buttons and border always show. func (fm formModal) render(w, h int) []string { - inner := modalInner(theme.ModalWidth, w) + want := theme.ModalWidth + if fm.width > 0 { + want = fm.width + } + inner := modalInner(want, w) sw := stripWidth(inner) indent := blankLine(theme.ModalIndent) textCol := blankLine(fieldCol() + 1) diff --git a/internal/ui/views/projects.go b/internal/ui/views/projects.go index fbd5bbf..74a3846 100644 --- a/internal/ui/views/projects.go +++ b/internal/ui/views/projects.go @@ -42,33 +42,16 @@ const ( errProjectTaken = "That client already has a project with that name." ) -// listColWidths returns the PROJECT and CLIENT column widths so the list -// spans the full available content width. -func (m ProjectsModel) listColWidths() (nameCol, clientCol int) { - avail := usableWidth(m.width) - theme.Gutter - clientCol = avail / 3 - if clientCol < 18 { - clientCol = 18 - } - if clientCol > 36 { - clientCol = 36 - } - nameCol = avail - clientCol - if nameCol < 18 { - nameCol = 18 - } - return nameCol, clientCol -} - -type ProjectsModel struct { - db *db.DB - width int - height int - mode projectsMode +// projectsPane is the project form (New project, Edit project) and the +// project delete confirm. They open from the projects pane of the Clients +// tab (ALI-2617), which keeps the list and the cursor; this keeps the +// form's state and the loaded clients and projects it checks against. +type projectsPane struct { + db *db.DB + mode projectsMode clients []*model.Client projects []*model.Project - cursor int // form fields inputs []textinput.Model @@ -79,9 +62,8 @@ type ProjectsModel struct { clientSel int showClientDrop bool - // errs holds the form's field errors; err, a message for the list. + // errs holds the form's field errors. errs fieldErrors - err string // deleteFocused: Delete has the focus in the delete confirm (Keep it // has it at first). deleteID is the project it's for, kept from when @@ -94,22 +76,14 @@ type ProjectsModel struct { editingID int64 } -func NewProjects(database *db.DB) ProjectsModel { - return ProjectsModel{ - db: database, - mode: projectsModeList, - } -} - -// IsBusy returns true when the view is in a form or confirmation mode, -// meaning global key shortcuts should not fire. -func (m ProjectsModel) IsBusy() bool { +// IsBusy is true while the form or the confirm is open: they take every +// key, q included. +func (m projectsPane) IsBusy() bool { return m.mode != projectsModeList } -// Help returns the contextual hotkey string for the view's current mode, for -// display in the app-level hotkey bar (see app.go renderBottomBar). -func (m ProjectsModel) Help() []Hotkey { +// Help is the form's or the confirm's keys. +func (m projectsPane) Help() []Hotkey { switch m.mode { case projectsModeNewProject, projectsModeEditProject: keys := []Hotkey{{"tab", "next field"}} @@ -119,120 +93,67 @@ func (m ProjectsModel) Help() []Hotkey { return append(keys, Hotkey{"enter", "save"}, Hotkey{"esc", "cancel"}) case projectsModeConfirmDelete: return []Hotkey{{"y", "delete"}, {"esc", "keep"}} - default: - return []Hotkey{{"n", "new"}, {"e", "edit"}, {"d", "delete"}} } + return nil } -func (m ProjectsModel) Init() tea.Cmd { - return loadProjectsData(m.db) -} - -func (m *ProjectsModel) SetSize(w, h int) { - m.width = w - m.height = h -} - -// -- messages ----------------------------------------------------------------- - -type projectsDataMsg struct { - clients []*model.Client - projects []*model.Project +// openNew opens New project for client c, its Client field filled in and +// the focus on Name. +func (m projectsPane) openNew(c *model.Client) projectsPane { + name := "" + m.clientID = 0 + if c != nil { + name, m.clientID = c.Name, c.ID + } + m.mode = projectsModeNewProject + m.editingID = 0 + m.inputs = makeProjectInputs(nil, name) + m.errs = nil + m.clientSel = 0 + m.rebuildClientMatches() + return m.focus(projFieldName) } -func loadProjectsData(database *db.DB) tea.Cmd { - return func() tea.Msg { - clients, err := database.ListClients() - if err != nil { - return ErrMsg(err.Error()) - } - projects, err := database.ListProjects(0) - if err != nil { - return ErrMsg(err.Error()) - } - return projectsDataMsg{clients: clients, projects: projects} +// openEdit opens Edit project for p, focus on Name. Its Client field moves +// the project to another client. +func (m projectsPane) openEdit(p *model.Project) projectsPane { + clientName := "" + m.clientID = 0 + if p.Client != nil { + clientName = p.Client.Name + m.clientID = p.Client.ID } + m.mode = projectsModeEditProject + m.editingID = p.ID + m.inputs = makeProjectInputs(p, clientName) + m.errs = nil + m.clientSel = 0 + m.rebuildClientMatches() + return m.focus(projFieldName) } -// -- Update ------------------------------------------------------------------- - -func (m ProjectsModel) Update(msg tea.Msg) (ProjectsModel, tea.Cmd) { - switch msg := msg.(type) { - - case projectsDataMsg: - m.clients = msg.clients - m.projects = msg.projects - if m.cursor >= len(m.projects) && m.cursor > 0 { - m.cursor = len(m.projects) - 1 - } - m.err = "" - if m.mode == projectsModeConfirmDelete && m.projectByID(m.deleteID) == nil { - m.mode = projectsModeList - return m, ErrCmd(errProjectGone) - } - return m, nil - - case tea.KeyMsg: - if m.mode != projectsModeList { - return m.updateForm(msg) - } - return m.updateList(msg) - } - return m, nil +// openDelete opens the delete confirm for p. +func (m projectsPane) openDelete(p *model.Project) projectsPane { + m.mode = projectsModeConfirmDelete + m.deleteFocused = false + m.deleteID = p.ID + return m } -func (m ProjectsModel) updateList(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { - switch { - case key.Matches(msg, projectsKeys.Up): - if m.cursor > 0 { - m.cursor-- - } - - case key.Matches(msg, projectsKeys.Down): - if m.cursor < len(m.projects)-1 { - m.cursor++ - } - - case key.Matches(msg, projectsKeys.New): - if len(m.clients) == 0 { - m.err = "Create a client first (press 3)" - return m, nil - } - m.mode = projectsModeNewProject - m.inputs = makeProjectInputs(nil, "") - m.clientID = 0 - m.errs = nil - m = m.focus(projFieldClient) - m.rebuildClientMatches() - m.err = "" - - case key.Matches(msg, projectsKeys.Edit): - if p := m.selectedProject(); p != nil { - clientName := "" - if p.Client != nil { - clientName = p.Client.Name - m.clientID = p.Client.ID - } - m.mode = projectsModeEditProject - m.editingID = p.ID - m.inputs = makeProjectInputs(p, clientName) - m.errs = nil - m = m.focus(projFieldClient) - m.rebuildClientMatches() - m.err = "" - } +// -- Update ------------------------------------------------------------------- - case key.Matches(msg, projectsKeys.Delete): - if p := m.selectedProject(); p != nil { - m.mode = projectsModeConfirmDelete - m.deleteFocused = false - m.deleteID = p.ID - } +// setData takes a reload of the clients and projects. A confirm whose +// project has gone closes and says so. +func (m projectsPane) setData(clients []*model.Client, projects []*model.Project) (projectsPane, tea.Cmd) { + m.clients, m.projects = clients, projects + if m.mode == projectsModeConfirmDelete && m.projectByID(m.deleteID) == nil { + m.mode = projectsModeList + return m, ErrCmd(errProjectGone) } return m, nil } -func (m ProjectsModel) updateForm(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { +func (m projectsPane) updateForm(msg tea.KeyMsg) (projectsPane, tea.Cmd) { if m.mode == projectsModeConfirmDelete { return m.updateConfirm(msg) } @@ -297,7 +218,7 @@ func (m ProjectsModel) updateForm(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { // leave finishes the focused field before the focus moves or the form is // saved: open suggestions in Client pick the highlighted client. -func (m ProjectsModel) leave() ProjectsModel { +func (m projectsPane) leave() projectsPane { if m.focusedInput == projFieldClient && m.showClientDrop { m.applyClientSelection() } @@ -306,7 +227,7 @@ func (m ProjectsModel) leave() ProjectsModel { } // focus moves the form's focus to idx: an input or a button. -func (m ProjectsModel) focus(idx int) ProjectsModel { +func (m projectsPane) focus(idx int) projectsPane { for i := range m.inputs { m.inputs[i].Blur() } @@ -321,7 +242,7 @@ func (m ProjectsModel) focus(idx int) ProjectsModel { // updateConfirm handles the delete confirm: y deletes and esc keeps; tab // and the arrows move the focus between Delete and Keep it, and enter or // space presses the focused one. -func (m ProjectsModel) updateConfirm(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { +func (m projectsPane) updateConfirm(msg tea.KeyMsg) (projectsPane, tea.Cmd) { switch { case msg.String() == "y", msg.String() == "Y": return m.doDelete() @@ -339,7 +260,7 @@ func (m ProjectsModel) updateConfirm(msg tea.KeyMsg) (ProjectsModel, tea.Cmd) { } // saveForm saves the project, or puts what needs fixing under its field. -func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { +func (m projectsPane) saveForm() (projectsPane, tea.Cmd) { m.errs = fieldErrors{} name := strings.TrimSpace(m.inputs[projFieldName].Value()) if name == "" { @@ -353,7 +274,7 @@ func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { } var err error - status := "Project created" + status := "Project created." switch m.mode { case projectsModeNewProject: _, err = m.db.CreateProject(m.clientID, name) @@ -365,7 +286,7 @@ func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { if errors.Is(gerr, db.ErrNotFound) { m.mode = projectsModeList m.errs = nil - return m, tea.Batch(loadProjectsData(m.db), ErrCmd(errProjectGone)) + return m, tea.Batch(loadClientsCmd(m.db), ErrCmd(errProjectGone)) } if gerr != nil { return m, ErrCmd(gerr.Error()) @@ -374,7 +295,7 @@ func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { edited.ClientID = m.clientID edited.Name = name err = m.db.UpdateProject(&edited) - status = "Project updated" + status = "Project updated." default: return m, nil } @@ -387,34 +308,31 @@ func (m ProjectsModel) saveForm() (ProjectsModel, tea.Cmd) { } m.mode = projectsModeList m.errs = nil - return m, tea.Batch(loadProjectsData(m.db), StatusCmd(status)) + return m, tea.Batch(loadClientsCmd(m.db), StatusCmd(status)) } // FieldErrors is how many fields of the open form need fixing, for the // app's status line. -func (m ProjectsModel) FieldErrors() int { +func (m projectsPane) FieldErrors() int { if m.mode == projectsModeNewProject || m.mode == projectsModeEditProject { return len(m.errs) } return 0 } -func (m ProjectsModel) doDelete() (ProjectsModel, tea.Cmd) { +func (m projectsPane) doDelete() (projectsPane, tea.Cmd) { m.mode = projectsModeList // Checked in the database, not the loaded list: it may be gone // already, and deleting nothing would still say "deleted". if _, err := m.db.GetProject(m.deleteID); errors.Is(err, db.ErrNotFound) { - return m, tea.Batch(loadProjectsData(m.db), ErrCmd(errProjectGone)) + return m, tea.Batch(loadClientsCmd(m.db), ErrCmd(errProjectGone)) } else if err != nil { return m, ErrCmd(err.Error()) } if err := m.db.DeleteProject(m.deleteID); err != nil { return m, ErrCmd(err.Error()) } - if m.cursor > 0 { - m.cursor-- - } - return m, tea.Batch(loadProjectsData(m.db), StatusCmd("Project deleted")) + return m, tea.Batch(loadClientsCmd(m.db), StatusCmd("Project deleted.")) } // errProjectGone is the status when the project a delete confirm is for @@ -422,7 +340,7 @@ func (m ProjectsModel) doDelete() (ProjectsModel, tea.Cmd) { const errProjectGone = "That project no longer exists" // projectByID is the loaded project id, or nil. -func (m ProjectsModel) projectByID(id int64) *model.Project { +func (m projectsPane) projectByID(id int64) *model.Project { for _, p := range m.projects { if p.ID == id { return p @@ -433,7 +351,7 @@ func (m ProjectsModel) projectByID(id int64) *model.Project { // resolveClientID resolves the client from the dropdown selection or the typed text. // It must match an existing client exactly. -func (m *ProjectsModel) resolveClientID() error { +func (m *projectsPane) resolveClientID() error { if m.clientID != 0 { return nil } @@ -441,6 +359,13 @@ func (m *ProjectsModel) resolveClientID() error { if text == "" { return errors.New(errPickClient) } + // The exact name first, so "acme" is acme, not Acme listed before it. + for _, c := range m.clients { + if c.Name == text { + m.clientID = c.ID + return nil + } + } for _, c := range m.clients { if strings.EqualFold(c.Name, text) { m.clientID = c.ID @@ -451,7 +376,7 @@ func (m *ProjectsModel) resolveClientID() error { } // rebuildClientMatches filters clients by the current client input text. -func (m *ProjectsModel) rebuildClientMatches() { +func (m *projectsPane) rebuildClientMatches() { typed := strings.TrimSpace(m.inputs[projFieldClient].Value()) query := strings.ToLower(typed) // An exact name goes first, so it's what tab and enter take: "Acme" @@ -473,7 +398,7 @@ func (m *ProjectsModel) rebuildClientMatches() { } // applyClientSelection commits the highlighted dropdown item to the client field. -func (m *ProjectsModel) applyClientSelection() { +func (m *projectsPane) applyClientSelection() { if len(m.clientMatches) == 0 { return } @@ -490,73 +415,8 @@ func (m *ProjectsModel) applyClientSelection() { // -- View --------------------------------------------------------------------- -func (m ProjectsModel) View() string { - if m.mode == projectsModeList { - return m.viewList() - } - w, h := usableWidth(m.width), max(1, m.height-2) - if m.mode == projectsModeConfirmDelete { - if box := m.viewConfirm(w, h); box != nil { - return modalOver(m.viewList(), w, h, box) - } - return m.viewList() - } - return modalOver(m.viewList(), w, h, m.viewForm(w, h)) -} - -func (m ProjectsModel) viewList() string { - - var b strings.Builder - - b.WriteString(StyleTitle.Render("Projects") + "\n\n") - - if len(m.projects) == 0 { - if len(m.clients) == 0 { - b.WriteString(StyleMuted.Render("No clients yet. Create one on the Clients tab (press 3).")) - } else { - b.WriteString(StyleMuted.Render("No projects yet. Press n to add one.")) - } - } else { - nameCol, clientCol := m.listColWidths() - b.WriteString(RowPrefix(false) + - StyleTableHeader.Width(nameCol).Render("Project") + - StyleTableHeader.Width(clientCol).Render("Client") + "\n") - b.WriteString(StyleTableDiv.Render(strings.Repeat("─", usableWidth(m.width))) + "\n") - - for i, p := range m.projects { - sel := i == m.cursor - name := truncate(p.Name, nameCol-3) - client := "" - if p.Client != nil { - client = truncate(p.Client.Name, clientCol-3) - } - - row := RowPrefix(sel) - if sel { - row += StyleTableRowSel.Width(nameCol).Render(name) - // The client column keeps its own dim foreground even when - // selected (it's always secondary to the project name), but - // its background still needs to follow the row's cBgAlt - // tint — otherwise it'd leave a plain-cBg gap at the row's - // right edge. - row += StyleTableRowDim.Background(cBgAlt).Width(clientCol).Render(client) - } else { - row += StyleTableRow.Width(nameCol).Render(name) - row += StyleTableRowDim.Width(clientCol).Render(client) - } - b.WriteString(row + "\n") - } - } - - if m.err != "" { - b.WriteString("\n\n" + StyleDanger.Render("✖ "+m.err)) - } - - return b.String() -} - // viewForm is the New project or Edit project modal. -func (m ProjectsModel) viewForm(w, h int) []string { +func (m projectsPane) viewForm(w, h int) []string { sw := stripWidth(modalInner(theme.ModalWidth, w)) field := func(label string, idx int) modalField { return modalField{ @@ -589,7 +449,7 @@ func (m ProjectsModel) viewForm(w, h int) []string { } // viewConfirm is the delete confirm for the selected project. -func (m ProjectsModel) viewConfirm(w, h int) []string { +func (m projectsPane) viewConfirm(w, h int) []string { p := m.projectByID(m.deleteID) if p == nil { return nil @@ -609,13 +469,6 @@ func (m ProjectsModel) viewConfirm(w, h int) []string { // -- helpers ------------------------------------------------------------------ -func (m ProjectsModel) selectedProject() *model.Project { - if len(m.projects) == 0 || m.cursor >= len(m.projects) { - return nil - } - return m.projects[m.cursor] -} - func makeProjectInputs(p *model.Project, clientName string) []textinput.Model { client := makeTextInput("type to find a client", 64, theme.FieldWidth) if clientName != "" { @@ -633,11 +486,6 @@ func makeProjectInputs(p *model.Project, clientName string) []textinput.Model { // -- key map ------------------------------------------------------------------ type projectsKeyMap struct { - Up key.Binding - Down key.Binding - New key.Binding - Edit key.Binding - Delete key.Binding Confirm key.Binding Cancel key.Binding NextField key.Binding @@ -645,11 +493,6 @@ type projectsKeyMap struct { } var projectsKeys = projectsKeyMap{ - Up: key.NewBinding(key.WithKeys("up", "k")), - Down: key.NewBinding(key.WithKeys("down", "j")), - New: key.NewBinding(key.WithKeys("n")), - Edit: key.NewBinding(key.WithKeys("e")), - Delete: key.NewBinding(key.WithKeys("d")), Confirm: key.NewBinding(key.WithKeys("enter")), Cancel: key.NewBinding(key.WithKeys("esc")), NextField: key.NewBinding(key.WithKeys("tab")), diff --git a/internal/ui/views/projects_test.go b/internal/ui/views/projects_test.go index f2c288d..21bfb3d 100644 --- a/internal/ui/views/projects_test.go +++ b/internal/ui/views/projects_test.go @@ -1,49 +1,23 @@ package views import ( - "database/sql" - "path/filepath" "strings" "testing" - "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/x/ansi" - _ "modernc.org/sqlite" ) // ── "create a client first" gate ───────────────────────────────────────────── -func TestProjectsUpdateList_NewRequiresAClient(t *testing.T) { - m := ProjectsModel{} - got, _ := m.updateList(runeKey('n')) - if got.mode != projectsModeList { - t.Errorf("mode after 'n' with no clients = %v, want to stay projectsModeList", got.mode) - } - if got.err == "" { - t.Error("want an error telling the user to create a client first") - } -} - -func TestProjectsUpdateList_NewOpensFormWhenClientsExist(t *testing.T) { - m := ProjectsModel{clients: []*model.Client{{ID: 1, Name: "Acme"}}} - got, _ := m.updateList(runeKey('n')) - if got.mode != projectsModeNewProject { - t.Errorf("mode after 'n' with clients present = %v, want projectsModeNewProject", got.mode) - } - if got.err != "" { - t.Errorf("err = %q, want cleared", got.err) - } -} - // ── resolveClientID ────────────────────────────────────────────────────────── func TestResolveClientID(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme"}, {ID: 2, Name: "Beta"}} t.Run("already resolved is a no-op", func(t *testing.T) { - m := ProjectsModel{clients: clients, clientID: 2} + m := projectsPane{clients: clients, clientID: 2} if err := m.resolveClientID(); err != nil { t.Errorf("unexpected error: %v", err) } @@ -54,7 +28,7 @@ func TestResolveClientID(t *testing.T) { t.Run("blank input requires a selection", func(t *testing.T) { inputs := makeProjectInputs(nil, "") - m := ProjectsModel{clients: clients, inputs: inputs} + m := projectsPane{clients: clients, inputs: inputs} if err := m.resolveClientID(); err == nil { t.Error("want an error for a blank client field") } @@ -63,7 +37,7 @@ func TestResolveClientID(t *testing.T) { t.Run("exact case-insensitive match resolves", func(t *testing.T) { inputs := makeProjectInputs(nil, "") inputs[projFieldClient].SetValue("acme") - m := ProjectsModel{clients: clients, inputs: inputs} + m := projectsPane{clients: clients, inputs: inputs} if err := m.resolveClientID(); err != nil { t.Fatalf("unexpected error: %v", err) } @@ -75,7 +49,7 @@ func TestResolveClientID(t *testing.T) { t.Run("no match is an error", func(t *testing.T) { inputs := makeProjectInputs(nil, "") inputs[projFieldClient].SetValue("Gamma") - m := ProjectsModel{clients: clients, inputs: inputs} + m := projectsPane{clients: clients, inputs: inputs} if err := m.resolveClientID(); err == nil { t.Error("want an error when the typed text matches no existing client") } @@ -87,7 +61,7 @@ func TestResolveClientID(t *testing.T) { func TestProjectsSaveForm_BlankNameRejected(t *testing.T) { inputs := makeProjectInputs(nil, "Acme") inputs[projFieldName].SetValue(" ") - m := ProjectsModel{mode: projectsModeNewProject, clients: []*model.Client{{ID: 1, Name: "Acme"}}, clientID: 1, inputs: inputs} + m := projectsPane{mode: projectsModeNewProject, clients: []*model.Client{{ID: 1, Name: "Acme"}}, clientID: 1, inputs: inputs} got, cmd := m.saveForm() if got.errs[projFieldName] != errNameRequired { @@ -105,7 +79,7 @@ func TestProjectsSaveForm_UnresolvedClientRejected(t *testing.T) { inputs := makeProjectInputs(nil, "") inputs[projFieldName].SetValue("Website") inputs[projFieldClient].SetValue("Nonexistent") - m := ProjectsModel{mode: projectsModeNewProject, clients: []*model.Client{{ID: 1, Name: "Acme"}}, inputs: inputs} + m := projectsPane{mode: projectsModeNewProject, clients: []*model.Client{{ID: 1, Name: "Acme"}}, inputs: inputs} got, cmd := m.saveForm() if got.errs[projFieldClient] != errPickListClient { @@ -130,7 +104,7 @@ func TestProjectsUpdateForm_ConfirmDeleteDispatch(t *testing.T) { } t.Run("y deletes", func(t *testing.T) { - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p}, cursor: 0, deleteID: p.ID} + m := projectsPane{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p}, deleteID: p.ID} got, cmd := m.updateForm(runeKey('y')) if got.mode != projectsModeList { t.Errorf("mode after 'y' = %v, want projectsModeList", got.mode) @@ -150,7 +124,7 @@ func TestProjectsUpdateForm_ConfirmDeleteDispatch(t *testing.T) { if err != nil { t.Fatal(err) } - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p2}, cursor: 0, deleteID: p2.ID} + m := projectsPane{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p2}, deleteID: p2.ID} got, cmd := m.updateForm(runeKey('n')) if got.mode != projectsModeList { t.Errorf("mode after 'n' = %v, want projectsModeList", got.mode) @@ -165,7 +139,7 @@ func TestProjectsUpdateForm_ConfirmDeleteDispatch(t *testing.T) { }) t.Run("esc cancels", func(t *testing.T) { - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete} + m := projectsPane{db: d, mode: projectsModeConfirmDelete} got, cmd := m.updateForm(tea.KeyMsg{Type: tea.KeyEsc}) if got.mode != projectsModeList { t.Errorf("mode after esc = %v, want projectsModeList", got.mode) @@ -181,7 +155,7 @@ func TestProjectsUpdateForm_ConfirmDeleteDispatch(t *testing.T) { func TestProjectsRebuildClientMatches(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme Corp"}, {ID: 2, Name: "Beta LLC"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{clients: clients, inputs: inputs} + m := projectsPane{clients: clients, inputs: inputs} m.inputs[projFieldClient].SetValue("acme") m.rebuildClientMatches() @@ -199,7 +173,7 @@ func TestProjectsRebuildClientMatches(t *testing.T) { func TestProjectsApplyClientSelection(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme Corp"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{clients: clients, inputs: inputs} + m := projectsPane{clients: clients, inputs: inputs} m.inputs[projFieldClient].SetValue("Acme") m.rebuildClientMatches() m.clientSel = 0 @@ -218,75 +192,14 @@ func TestProjectsApplyClientSelection(t *testing.T) { // ── selectedProject / listColWidths ────────────────────────────────────────── -func TestProjectsSelectedProject(t *testing.T) { - m := ProjectsModel{} - if got := m.selectedProject(); got != nil { - t.Errorf("selectedProject() on empty list = %v, want nil", got) - } - - p := &model.Project{ID: 1, Name: "Website"} - m2 := ProjectsModel{projects: []*model.Project{p}, cursor: 0} - if got := m2.selectedProject(); got != p { - t.Errorf("selectedProject() = %v, want %v", got, p) - } -} - -func TestProjectsListColWidths_SpansAvailableWidth(t *testing.T) { - m := ProjectsModel{width: 100} - nameCol, clientCol := m.listColWidths() - if nameCol < 18 { - t.Errorf("nameCol = %d, want >= 18", nameCol) - } - if clientCol < 18 || clientCol > 36 { - t.Errorf("clientCol = %d, want within [18, 36]", clientCol) - } -} - -func TestProjectsListColWidths_NarrowClampsBothFloors(t *testing.T) { - // avail = usableWidth(30) - 2 = 24 - 2 = 22; clientCol = 22/3 = 7 -> clamps - // to 18, then nameCol = 22-18 = 4 -> also clamps to 18. - m := ProjectsModel{width: 30} - nameCol, clientCol := m.listColWidths() - if clientCol != 18 { - t.Errorf("clientCol = %d, want 18 (low clamp)", clientCol) - } - if nameCol != 18 { - t.Errorf("nameCol = %d, want 18 (low clamp)", nameCol) - } -} - -func TestProjectsListColWidths_WideClampsClientHigh(t *testing.T) { - // avail = usableWidth(200) - 2 = 194 - 2 = 192; clientCol = 192/3 = 64 -> - // clamps to 36. - m := ProjectsModel{width: 200} - nameCol, clientCol := m.listColWidths() - if clientCol != 36 { - t.Errorf("clientCol = %d, want 36 (high clamp)", clientCol) - } - if nameCol < 18 { - t.Errorf("nameCol = %d, want >= 18", nameCol) - } -} - // ── Trivial constructors / getters ─────────────────────────────────────────── -func TestNewProjects(t *testing.T) { - d := newTestDB(t) - m := NewProjects(d) - if m.mode != projectsModeList { - t.Errorf("mode = %v, want projectsModeList", m.mode) - } - if m.db != d { - t.Error("db not stored on the model") - } -} - func TestProjectsIsBusy(t *testing.T) { - list := ProjectsModel{mode: projectsModeList} + list := projectsPane{mode: projectsModeList} if list.IsBusy() { t.Error("IsBusy() in list mode = true, want false") } - form := ProjectsModel{mode: projectsModeNewProject} + form := projectsPane{mode: projectsModeNewProject} if !form.IsBusy() { t.Error("IsBusy() in new-project mode = false, want true") } @@ -300,11 +213,10 @@ func TestProjectsHelp(t *testing.T) { {"new", projectsModeNewProject}, {"edit", projectsModeEditProject}, {"confirm delete", projectsModeConfirmDelete}, - {"list", projectsModeList}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - m := ProjectsModel{mode: c.mode} + m := projectsPane{mode: c.mode} if got := m.Help(); len(got) == 0 { t.Error("Help() returned no hotkeys") } @@ -312,175 +224,12 @@ func TestProjectsHelp(t *testing.T) { } } -func TestProjectsInit(t *testing.T) { - d := newTestDB(t) - m := NewProjects(d) - cmd := m.Init() - if cmd == nil { - t.Fatal("Init() returned a nil cmd") - } - msg := cmd() - if _, ok := msg.(projectsDataMsg); !ok { - t.Errorf("Init() cmd produced %T, want projectsDataMsg", msg) - } -} +// ── openEdit / openDelete ───────────────────────────────────────────────────── -func TestProjectsSetSize(t *testing.T) { - m := &ProjectsModel{} - m.SetSize(80, 24) - if m.width != 80 || m.height != 24 { - t.Errorf("SetSize(80, 24) -> width=%d height=%d, want 80, 24", m.width, m.height) - } -} - -// ── loadProjectsData ────────────────────────────────────────────────────────── - -func TestLoadProjectsData_Success(t *testing.T) { - d := newTestDB(t) - c, err := d.CreateClient("Acme", 100) - if err != nil { - t.Fatal(err) - } - if _, err := d.CreateProject(c.ID, "Website"); err != nil { - t.Fatal(err) - } - - cmd := loadProjectsData(d) - msg := cmd() - data, ok := msg.(projectsDataMsg) - if !ok { - t.Fatalf("loadProjectsData produced %T, want projectsDataMsg", msg) - } - if len(data.clients) != 1 { - t.Errorf("clients = %+v, want 1", data.clients) - } - if len(data.projects) != 1 { - t.Errorf("projects = %+v, want 1", data.projects) - } -} - -func TestLoadProjectsData_ListClientsError(t *testing.T) { - d := newTestDB(t) - d.Close() - - cmd := loadProjectsData(d) - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("loadProjectsData on a closed db produced %T, want ErrMsg", msg) - } -} - -func TestLoadProjectsData_ListProjectsError(t *testing.T) { - // Isolate the second `if err != nil` branch in loadProjectsData (the - // ListProjects error path) from the first (the ListClients error path): - // open a second raw connection to the same sqlite file and drop the - // projects table out from under it, so ListClients still succeeds - // (clients table is untouched) while ListProjects fails. - path := filepath.Join(t.TempDir(), "test.db") - d, err := db.Open(path) - if err != nil { - t.Fatalf("db.Open: %v", err) - } - t.Cleanup(func() { d.Close() }) - - raw, err := sql.Open("sqlite", path) - if err != nil { - t.Fatalf("sql.Open: %v", err) - } - if _, err := raw.Exec("DROP TABLE projects"); err != nil { - t.Fatalf("drop table projects: %v", err) - } - if err := raw.Close(); err != nil { - t.Fatalf("close raw connection: %v", err) - } - - cmd := loadProjectsData(d) - msg := cmd() - if _, ok := msg.(ErrMsg); !ok { - t.Fatalf("loadProjectsData with projects table missing produced %T, want ErrMsg", msg) - } -} - -// ── Update dispatch ─────────────────────────────────────────────────────────── - -func TestProjectsUpdate_DataMsgClampsCursor(t *testing.T) { - m := ProjectsModel{cursor: 5, err: "stale error"} - got, cmd := m.Update(projectsDataMsg{ - clients: []*model.Client{{ID: 1, Name: "Acme"}}, - projects: []*model.Project{{ID: 1, Name: "A"}, {ID: 2, Name: "B"}}, - }) - if cmd != nil { - t.Error("want nil cmd from projectsDataMsg handling") - } - if got.cursor != 1 { - t.Errorf("cursor = %d, want clamped to len(projects)-1 = 1", got.cursor) - } - if got.err != "" { - t.Errorf("err = %q, want cleared", got.err) - } -} - -func TestProjectsUpdate_DataMsgCursorZeroStaysZero(t *testing.T) { - m := ProjectsModel{cursor: 0} - got, _ := m.Update(projectsDataMsg{}) - if got.cursor != 0 { - t.Errorf("cursor = %d, want 0 (cursor > 0 guard skips clamp)", got.cursor) - } -} - -func TestProjectsUpdate_KeyDispatchesToList(t *testing.T) { - m := ProjectsModel{mode: projectsModeList, projects: []*model.Project{{ID: 1}, {ID: 2}}} - got, _ := m.Update(tea.KeyMsg{Type: tea.KeyDown}) - if got.cursor != 1 { - t.Errorf("cursor = %d, want 1 (Update dispatched to updateList)", got.cursor) - } -} - -func TestProjectsUpdate_KeyDispatchesToForm(t *testing.T) { - m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, "")} - got, _ := m.Update(tea.KeyMsg{Type: tea.KeyEsc}) - if got.mode != projectsModeList { - t.Errorf("mode = %v, want projectsModeList (Update dispatched to updateForm)", got.mode) - } -} - -func TestProjectsUpdate_UnhandledMsgTypeIsNoop(t *testing.T) { - m := ProjectsModel{cursor: 3} - got, cmd := m.Update(StatusMsg("irrelevant")) - if cmd != nil { - t.Error("want nil cmd for an unhandled message type") - } - if got.cursor != 3 { - t.Errorf("cursor = %d, want unchanged", got.cursor) - } -} - -// ── updateList ──────────────────────────────────────────────────────────────── - -func TestProjectsUpdateList_CursorBounds(t *testing.T) { - m := ProjectsModel{projects: []*model.Project{{ID: 1}, {ID: 2}}} - - m, _ = m.updateList(tea.KeyMsg{Type: tea.KeyUp}) - if m.cursor != 0 { - t.Errorf("cursor after up at top = %d, want 0 (clamped)", m.cursor) - } - - m, _ = m.updateList(tea.KeyMsg{Type: tea.KeyDown}) - m, _ = m.updateList(tea.KeyMsg{Type: tea.KeyDown}) - if m.cursor != 1 { - t.Errorf("cursor after two downs with 2 projects = %d, want 1 (clamped at end)", m.cursor) - } - - m, _ = m.updateList(tea.KeyMsg{Type: tea.KeyUp}) - if m.cursor != 0 { - t.Errorf("cursor after up with cursor > 0 = %d, want decremented to 0", m.cursor) - } -} - -func TestProjectsUpdateList_EditWithClientSet(t *testing.T) { +func TestProjectsOpenEdit_WithClientSet(t *testing.T) { p := &model.Project{ID: 1, Name: "Website", Client: &model.Client{ID: 9, Name: "Acme"}} - m := ProjectsModel{projects: []*model.Project{p}, cursor: 0} - got, _ := m.updateList(runeKey('e')) + m := projectsPane{projects: []*model.Project{p}} + got := m.openEdit(p) if got.mode != projectsModeEditProject { t.Fatalf("mode = %v, want projectsModeEditProject", got.mode) } @@ -493,12 +242,15 @@ func TestProjectsUpdateList_EditWithClientSet(t *testing.T) { if got.inputs[projFieldName].Value() != "Website" { t.Errorf("name input = %q, want %q", got.inputs[projFieldName].Value(), "Website") } + if got.focusedInput != projFieldName { + t.Errorf("focus on %d, want Name: the client is already filled in", got.focusedInput) + } } -func TestProjectsUpdateList_EditWithNilClientFallsBack(t *testing.T) { +func TestProjectsOpenEdit_WithNilClientFallsBack(t *testing.T) { p := &model.Project{ID: 1, Name: "Website", Client: nil} - m := ProjectsModel{projects: []*model.Project{p}, cursor: 0} - got, _ := m.updateList(runeKey('e')) + m := projectsPane{projects: []*model.Project{p}} + got := m.openEdit(p) if got.mode != projectsModeEditProject { t.Fatalf("mode = %v, want projectsModeEditProject", got.mode) } @@ -510,18 +262,10 @@ func TestProjectsUpdateList_EditWithNilClientFallsBack(t *testing.T) { } } -func TestProjectsUpdateList_EditWithNoProjectsIsNoop(t *testing.T) { - m := ProjectsModel{} - got, _ := m.updateList(runeKey('e')) - if got.mode != projectsModeList { - t.Errorf("mode = %v, want to stay projectsModeList when there's nothing to edit", got.mode) - } -} - -func TestProjectsUpdateList_DeleteWithSelection(t *testing.T) { +func TestProjectsOpenDelete(t *testing.T) { p := &model.Project{ID: 1, Name: "Website"} - m := ProjectsModel{projects: []*model.Project{p}, cursor: 0} - got, _ := m.updateList(runeKey('d')) + m := projectsPane{projects: []*model.Project{p}} + got := m.openDelete(p) if got.mode != projectsModeConfirmDelete { t.Errorf("mode = %v, want projectsModeConfirmDelete", got.mode) } @@ -530,20 +274,12 @@ func TestProjectsUpdateList_DeleteWithSelection(t *testing.T) { } } -func TestProjectsUpdateList_DeleteWithoutSelectionIsNoop(t *testing.T) { - m := ProjectsModel{} - got, _ := m.updateList(runeKey('d')) - if got.mode != projectsModeList { - t.Errorf("mode = %v, want to stay projectsModeList with no projects to delete", got.mode) - } -} - // ── updateForm ──────────────────────────────────────────────────────────────── func TestProjectsUpdateForm_ClientDropdownNavigation(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme"}, {ID: 2, Name: "Beta"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{ + m := projectsPane{ mode: projectsModeNewProject, clients: clients, inputs: inputs, @@ -587,7 +323,7 @@ func TestProjectsUpdateForm_ClientDropdownNavigation(t *testing.T) { func TestProjectsUpdateForm_ConfirmOnClientAppliesSelection(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{ + m := projectsPane{ mode: projectsModeNewProject, clients: clients, inputs: inputs, @@ -622,7 +358,7 @@ func TestProjectsUpdateForm_ConfirmOnNameDispatchesSave(t *testing.T) { inputs := makeProjectInputs(nil, "") // Leave the name blank so saveForm hits its cheap validation-error return // rather than touching the DB. - m := ProjectsModel{ + m := projectsPane{ mode: projectsModeNewProject, clients: []*model.Client{{ID: 1, Name: "Acme"}}, clientID: 1, @@ -636,7 +372,7 @@ func TestProjectsUpdateForm_ConfirmOnNameDispatchesSave(t *testing.T) { } func TestProjectsUpdateForm_Cancel(t *testing.T) { - m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), errs: fieldErrors{projFieldName: "boom"}} + m := projectsPane{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), errs: fieldErrors{projFieldName: "boom"}} got, cmd := m.updateForm(tea.KeyMsg{Type: tea.KeyEsc}) if got.mode != projectsModeList { t.Errorf("mode = %v, want projectsModeList", got.mode) @@ -652,7 +388,7 @@ func TestProjectsUpdateForm_Cancel(t *testing.T) { func TestProjectsUpdateForm_NextFieldTogglesFocus(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{mode: projectsModeNewProject, clients: clients, inputs: inputs, focusedInput: projFieldClient} + m := projectsPane{mode: projectsModeNewProject, clients: clients, inputs: inputs, focusedInput: projFieldClient} m.inputs[projFieldClient].Focus() got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyTab}) @@ -681,7 +417,7 @@ func TestProjectsUpdateForm_NextFieldTogglesFocus(t *testing.T) { func TestProjectsUpdateForm_PrevFieldTogglesFocus(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{mode: projectsModeNewProject, clients: clients, inputs: inputs, focusedInput: projFieldName} + m := projectsPane{mode: projectsModeNewProject, clients: clients, inputs: inputs, focusedInput: projFieldName} m.inputs[projFieldName].Focus() got, _ := m.updateForm(tea.KeyMsg{Type: tea.KeyShiftTab}) @@ -698,7 +434,7 @@ func TestProjectsUpdateForm_PrevFieldTogglesFocus(t *testing.T) { func TestProjectsUpdateForm_DefaultForwardsToFocusedInput(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{ + m := projectsPane{ mode: projectsModeNewProject, clients: clients, inputs: inputs, @@ -716,7 +452,7 @@ func TestProjectsUpdateForm_DefaultForwardsToFocusedInput(t *testing.T) { } // Typing into the name field should not touch clientID or the dropdown. - m2 := ProjectsModel{ + m2 := projectsPane{ mode: projectsModeNewProject, clients: clients, inputs: makeProjectInputs(nil, ""), @@ -743,7 +479,7 @@ func TestProjectsSaveForm_CreateSuccess(t *testing.T) { } inputs := makeProjectInputs(nil, "") inputs[projFieldName].SetValue("Website") - m := ProjectsModel{db: d, mode: projectsModeNewProject, clients: []*model.Client{c}, clientID: c.ID, inputs: inputs} + m := projectsPane{db: d, mode: projectsModeNewProject, clients: []*model.Client{c}, clientID: c.ID, inputs: inputs} got, cmd := m.saveForm() if got.mode != projectsModeList { @@ -773,7 +509,7 @@ func TestProjectsSaveForm_CreateError(t *testing.T) { inputs := makeProjectInputs(nil, "") inputs[projFieldName].SetValue("Website") // duplicate (client, name) - m := ProjectsModel{db: d, mode: projectsModeNewProject, clients: []*model.Client{c}, clientID: c.ID, inputs: inputs} + m := projectsPane{db: d, mode: projectsModeNewProject, clients: []*model.Client{c}, clientID: c.ID, inputs: inputs} got, cmd := m.saveForm() if got.errs[projFieldName] != errProjectTaken { @@ -800,9 +536,9 @@ func TestProjectsSaveForm_EditSuccess(t *testing.T) { inputs := makeProjectInputs(p, c.Name) inputs[projFieldName].SetValue("Website Redesign") - m := ProjectsModel{ + m := projectsPane{ db: d, mode: projectsModeEditProject, - clients: []*model.Client{c}, projects: []*model.Project{p}, cursor: 0, + clients: []*model.Client{c}, projects: []*model.Project{p}, clientID: c.ID, inputs: inputs, editingID: p.ID, } @@ -840,9 +576,9 @@ func TestProjectsSaveForm_EditError(t *testing.T) { // Rename p2 to collide with p1's (client, name) pair. inputs := makeProjectInputs(p2, c.Name) inputs[projFieldName].SetValue("Website") - m := ProjectsModel{ + m := projectsPane{ db: d, mode: projectsModeEditProject, - clients: []*model.Client{c}, projects: []*model.Project{p2}, cursor: 0, + clients: []*model.Client{c}, projects: []*model.Project{p2}, clientID: c.ID, inputs: inputs, editingID: p2.ID, } @@ -870,9 +606,9 @@ func TestProjectsEditForm_SavesToTheProjectItOpenedFor(t *testing.T) { appP, _ := d.CreateProject(c.ID, "App") web, _ := d.GetProject(webP.ID) // with its client, as the tab loads them app, _ := d.GetProject(appP.ID) - m := ProjectsModel{db: d, clients: []*model.Client{c}, projects: []*model.Project{web, app}, width: 100, height: 30} - m, _ = m.updateList(runeKey('e')) // on Web - m, _ = m.Update(projectsDataMsg{clients: []*model.Client{c}, projects: []*model.Project{app, web}}) + m := projectsPane{db: d, clients: []*model.Client{c}, projects: []*model.Project{web, app}} + m = m.openEdit(web) + m, _ = m.setData([]*model.Client{c}, []*model.Project{app, web}) m.inputs[projFieldName].SetValue("Website") got, _ := m.saveForm() if got.mode != projectsModeList { @@ -885,7 +621,7 @@ func TestProjectsEditForm_SavesToTheProjectItOpenedFor(t *testing.T) { t.Errorf("App is now %q, want it untouched", p.Name) } - m, _ = got.updateList(runeKey('e')) + m = got.openEdit(web) if err := d.DeleteProject(m.editingID); err != nil { t.Fatal(err) } @@ -909,7 +645,7 @@ func TestProjectsSaveForm_UnknownModeFallsThrough(t *testing.T) { // through to the trailing "return m, nil". inputs := makeProjectInputs(nil, "") inputs[projFieldName].SetValue("Website") - m := ProjectsModel{mode: projectsModeList, clients: []*model.Client{{ID: 1, Name: "Acme"}}, clientID: 1, inputs: inputs} + m := projectsPane{mode: projectsModeList, clients: []*model.Client{{ID: 1, Name: "Acme"}}, clientID: 1, inputs: inputs} got, cmd := m.saveForm() if got.mode != projectsModeList { @@ -937,43 +673,22 @@ func TestProjectsDoDelete_Success(t *testing.T) { t.Fatal(err) } - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p1, p2}, cursor: 1, deleteID: p2.ID} + m := projectsPane{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p1, p2}, deleteID: p2.ID} got, cmd := m.doDelete() if got.mode != projectsModeList { t.Errorf("mode = %v, want projectsModeList", got.mode) } - if got.cursor != 0 { - t.Errorf("cursor = %d, want decremented to 0", got.cursor) - } if cmd == nil { t.Fatal("want a non-nil cmd on successful delete") } } -func TestProjectsDoDelete_CursorStaysAtZero(t *testing.T) { - d := newTestDB(t) - c, err := d.CreateClient("Acme", 100) - if err != nil { - t.Fatal(err) - } - p, err := d.CreateProject(c.ID, "Website") - if err != nil { - t.Fatal(err) - } - - m := ProjectsModel{db: d, projects: []*model.Project{p}, cursor: 0} - got, _ := m.doDelete() - if got.cursor != 0 { - t.Errorf("cursor = %d, want to stay 0", got.cursor) - } -} - func TestProjectsDoDelete_GoneProjectSaysSo(t *testing.T) { // The loaded list still has the project; the database doesn't. d := newTestDB(t) c, _ := d.CreateClient("Acme", 0) p, _ := d.CreateProject(c.ID, "Web") - m := ProjectsModel{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p}, deleteID: p.ID} + m := projectsPane{db: d, mode: projectsModeConfirmDelete, projects: []*model.Project{p}, deleteID: p.ID} if err := d.DeleteProject(p.ID); err != nil { t.Fatal(err) } @@ -1005,7 +720,7 @@ func TestProjectsDoDelete_Error(t *testing.T) { } d.Close() - m := ProjectsModel{db: d, projects: []*model.Project{p}, cursor: 0} + m := projectsPane{db: d, projects: []*model.Project{p}} _, cmd := m.doDelete() if cmd == nil { t.Fatal("want a non-nil error cmd when DeleteProject fails") @@ -1021,7 +736,7 @@ func TestProjectsDoDelete_Error(t *testing.T) { func TestProjectsRebuildClientMatches_ClampsSelectionWhenMatchesShrink(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme Corp"}, {ID: 2, Name: "Acme Two"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{clients: clients, inputs: inputs} + m := projectsPane{clients: clients, inputs: inputs} m.rebuildClientMatches() // 2 matches m.clientSel = 1 @@ -1034,7 +749,7 @@ func TestProjectsRebuildClientMatches_ClampsSelectionWhenMatchesShrink(t *testin func TestProjectsApplyClientSelection_NoMatchesIsNoop(t *testing.T) { inputs := makeProjectInputs(nil, "") - m := ProjectsModel{inputs: inputs, showClientDrop: true} + m := projectsPane{inputs: inputs, showClientDrop: true} m.applyClientSelection() if m.clientID != 0 { t.Errorf("clientID = %d, want unchanged 0 when there are no matches", m.clientID) @@ -1044,66 +759,14 @@ func TestProjectsApplyClientSelection_NoMatchesIsNoop(t *testing.T) { } } -// ── View ────────────────────────────────────────────────────────────────────── - -func TestProjectsView_DelegatesToFormWhenNotInListMode(t *testing.T) { - m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), width: 100} - if got := m.View(); got == "" { - t.Error("View() in form mode returned empty output") - } -} - -func TestProjectsView_NoClientsMessage(t *testing.T) { - m := ProjectsModel{width: 100} - got := m.View() - if !strings.Contains(got, "No clients yet") { - t.Errorf("View() = %q, want a message about creating a client first", got) - } -} - -func TestProjectsView_NoProjectsMessage(t *testing.T) { - m := ProjectsModel{width: 100, clients: []*model.Client{{ID: 1, Name: "Acme"}}} - got := m.View() - if !strings.Contains(got, "No projects yet") { - t.Errorf("View() = %q, want a message about adding a project", got) - } -} - -func TestProjectsView_ListWithClientAndWithoutClient(t *testing.T) { - m := ProjectsModel{ - width: 100, - clients: []*model.Client{{ID: 1, Name: "Acme"}}, - projects: []*model.Project{ - {ID: 1, Name: "Website", Client: &model.Client{ID: 1, Name: "Acme"}}, - {ID: 2, Name: "Orphan Project", Client: nil}, - }, - cursor: 0, - } - got := m.View() - if !strings.Contains(got, "Website") || !strings.Contains(got, "Acme") { - t.Errorf("View() missing project/client row: %q", got) - } - if !strings.Contains(got, "Orphan") { - t.Errorf("View() missing nil-client project row: %q", got) - } -} - -func TestProjectsView_ErrorLine(t *testing.T) { - m := ProjectsModel{width: 100, err: "something broke"} - got := m.View() - if !strings.Contains(got, "something broke") { - t.Errorf("View() = %q, want the error message rendered", got) - } -} - // ── viewForm ────────────────────────────────────────────────────────────────── func viewText(lines []string) string { return ansi.Strip(strings.Join(lines, "\n")) } func TestProjectsView_ConfirmDeleteNamesProjectAndClient(t *testing.T) { p := &model.Project{ID: 1, Name: "Website", Client: &model.Client{Name: "Acme"}} - m := ProjectsModel{mode: projectsModeConfirmDelete, projects: []*model.Project{p}, deleteID: p.ID, width: 100, height: 30} - got := ansi.Strip(m.View()) + m := projectsPane{mode: projectsModeConfirmDelete, projects: []*model.Project{p}, deleteID: p.ID} + got := viewText(m.viewConfirm(96, 28)) for _, want := range []string{"Delete project?", "“Website”", "Acme", "Its time entries go too.", "Keep it"} { if !strings.Contains(got, want) { t.Errorf("View() in confirm-delete mode missing %q; got %q", want, got) @@ -1112,12 +775,12 @@ func TestProjectsView_ConfirmDeleteNamesProjectAndClient(t *testing.T) { } func TestProjectsViewForm_TitlesByMode(t *testing.T) { - newM := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), width: 100, height: 30} + newM := projectsPane{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, "")} if got := viewText(newM.viewForm(96, 28)); !strings.Contains(got, "New project") { t.Errorf("viewForm() in new mode = %q, want it to contain %q", got, "New project") } - editM := ProjectsModel{mode: projectsModeEditProject, inputs: makeProjectInputs(nil, ""), width: 100, height: 30} + editM := projectsPane{mode: projectsModeEditProject, inputs: makeProjectInputs(nil, "")} if got := viewText(editM.viewForm(96, 28)); !strings.Contains(got, "Edit project") { t.Errorf("viewForm() in edit mode = %q, want it to contain %q", got, "Edit project") } @@ -1126,8 +789,8 @@ func TestProjectsViewForm_TitlesByMode(t *testing.T) { func TestProjectsViewForm_DropdownRenders(t *testing.T) { clients := []*model.Client{{ID: 1, Name: "Acme"}, {ID: 2, Name: "Beta"}} inputs := makeProjectInputs(nil, "") - m := ProjectsModel{ - mode: projectsModeNewProject, width: 100, + m := projectsPane{ + mode: projectsModeNewProject, clients: clients, inputs: inputs, focusedInput: projFieldClient, showClientDrop: true, } @@ -1140,7 +803,7 @@ func TestProjectsViewForm_DropdownRenders(t *testing.T) { } func TestProjectsViewForm_ErrorsSitUnderTheirFields(t *testing.T) { - m := ProjectsModel{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, ""), width: 100} + m := projectsPane{mode: projectsModeNewProject, inputs: makeProjectInputs(nil, "")} m, _ = m.saveForm() if m.FieldErrors() != 2 { t.Fatalf("FieldErrors() = %d, want 2 (Client and Name)", m.FieldErrors()) @@ -1163,7 +826,7 @@ func TestProjectsRenderField_FocusedAndUnfocused(t *testing.T) { inputs := makeProjectInputs(nil, "") inputs[projFieldClient].SetValue("Acme") inputs[projFieldName].SetValue("Website") - m := ProjectsModel{mode: projectsModeNewProject, inputs: inputs, focusedInput: projFieldClient, width: 100} + m := projectsPane{mode: projectsModeNewProject, inputs: inputs, focusedInput: projFieldClient} got := viewText(m.viewForm(96, 28)) if !strings.Contains(got, "Acme") || !strings.Contains(got, "Website") { @@ -1178,9 +841,9 @@ func TestProjectsConfirm_DeletesTheProjectItOpenedFor(t *testing.T) { c, _ := d.CreateClient("Acme", 0) web, _ := d.CreateProject(c.ID, "Web") app, _ := d.CreateProject(c.ID, "App") - m := ProjectsModel{db: d, projects: []*model.Project{web, app}, width: 100, height: 30} - m, _ = m.updateList(runeKey('d')) // on Web - m, _ = m.Update(projectsDataMsg{clients: []*model.Client{c}, projects: []*model.Project{app, web}}) + m := projectsPane{db: d, projects: []*model.Project{web, app}} + m = m.openDelete(web) + m, _ = m.setData([]*model.Client{c}, []*model.Project{app, web}) _, cmd := m.updateConfirm(runeKey('y')) if cmd == nil { t.Fatal("want the delete to run") @@ -1190,9 +853,9 @@ func TestProjectsConfirm_DeletesTheProjectItOpenedFor(t *testing.T) { t.Errorf("projects = %v, want only App left", projects) } - m = ProjectsModel{db: d, projects: []*model.Project{app}, width: 100, height: 30} - m, _ = m.updateList(runeKey('d')) - got, cmd := m.Update(projectsDataMsg{clients: []*model.Client{c}}) + m = projectsPane{db: d, projects: []*model.Project{app}} + m = m.openDelete(app) + got, cmd := m.setData([]*model.Client{c}, nil) if got.mode != projectsModeList || cmd == nil || cmd() != ErrMsg(errProjectGone) { t.Errorf("mode %v; want the confirm closed with %q when its project is gone", got.mode, errProjectGone) } @@ -1208,8 +871,8 @@ func TestProjectsForm_ExactClientNameWins(t *testing.T) { if clients[0].ID != corp.ID { t.Fatalf("setup: want ACME Corp listed first, got %q", clients[0].Name) } - m := ProjectsModel{db: d, clients: clients, width: 100, height: 30} - m, _ = m.updateList(runeKey('n')) + m := projectsPane{db: d, clients: clients} + m = m.openNew(nil).focus(projFieldClient) for _, r := range "Acme" { m, _ = m.updateForm(runeKey(r)) } @@ -1244,8 +907,8 @@ func TestProjectsForm_ExactCaseWinsOverOtherCase(t *testing.T) { lower, _ := d.CreateClient("acme", 0) clients, _ := d.ListClients() for typed, want := range map[string]int64{"Acme": upper.ID, "acme": lower.ID} { - m := ProjectsModel{db: d, clients: clients, width: 100, height: 30} - m, _ = m.updateList(runeKey('n')) + m := projectsPane{db: d, clients: clients} + m = m.openNew(nil).focus(projFieldClient) for _, r := range typed { m, _ = m.updateForm(runeKey(r)) } diff --git a/internal/ui/views/timers.go b/internal/ui/views/timers.go index c3ff83f..9793dac 100644 --- a/internal/ui/views/timers.go +++ b/internal/ui/views/timers.go @@ -785,7 +785,6 @@ func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { if m.form.entryID != 0 { closeForm, cmd := m.form.submitEdit(m.db, v, loadTimerEntriesCmd(m.db), - loadProjectsData(m.db), loadClientsCmd(m.db), ) if closeForm { @@ -832,7 +831,6 @@ func (m TimersModel) submitForm(now time.Time) (TimersModel, tea.Cmd) { return m, tea.Batch( RunningChangedCmd(), loadStartedCmd(m.db, e.ID), - loadProjectsData(m.db), loadClientsCmd(m.db), StatusCmd(status), ) diff --git a/landing/index.html b/landing/index.html index 8bb6df9..2324043 100644 --- a/landing/index.html +++ b/landing/index.html @@ -68,7 +68,7 @@