From b1dbf3ed75d989d3bf2bca2c3277b845cf31bc2e Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Sun, 23 Aug 2026 15:10:49 +0200 Subject: [PATCH] (4e4d88d) Split and search the campaign picker, and bump to 0.24.2 One flat list ordered by title put the completed campaigns among the open ones forever. The tail only grows, so on a board that has run for a while the campaigns worth picking were pushed towards the bottom of the box and eventually off it, and nothing in the picker helped find one. The rows are now two sections, open above completed, with completed by Created At newest first and truncated to a couple behind a grey line naming how many older ones are hidden. `/` starts a query, the key that already searches the board's cards, filtering case insensitively on short id, codename and title, and a query turns the truncation off: the campaign a reader is searching for is exactly the one it hid. `picker_list` is the one place that decides what a row is, so `Picker::row` counts drawn rows and `stepped_picker_row` walks past the headings and the truncation line rather than stopping on one. The highlight is placed by uuid, the answer `Tab::campaign` already gives for the filter, so typing, clearing the query and a tick that finishes a campaign all move it with its campaign instead of leaving it at a number that now names another. Every campaign's standing is settled at reload, counted by `standings_of` in one pass over the cards the reload already holds rather than the walk per campaign `campaign ls` pays. `Tab::standing` goes with it: the frame reads the row's, since two counts of one number are two numbers free to drift. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 14 + Cargo.lock | 2 +- Cargo.toml | 2 +- src/campaign.rs | 4 + src/main.rs | 5 +- src/tui.rs | 1147 ++++++++++++++++++++++++++++++++++++++++++++--- 6 files changed, 1102 insertions(+), 72 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c3f09ff..3193a6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -241,6 +241,20 @@ and this file is for what someone changing worklane's own code needs. - **`picker: Option` is the whole mode**, the shape `search` and `detail` use, and `Board::picker_key` runs beside `search_key` ahead of the action arms for the same reason: an open list owns the keyboard, so `d` must not toggle done and `q` must not quit while a campaign is being chosen. `ctrl-c` is the one key it declines and every other control combination is swallowed, or `ctrl-d` would reach the arm bound to `d` - **The picker's rows are `Tab::campaigns`, not a copy taken when it opened**, so a campaign filed elsewhere appears in an open picker on the next tick. It opens on the campaign already selected, so `c` on a filtered board says where you are as well as offering somewhere to go, and a board with no campaigns gets a `Notice` rather than an empty box that has to be dismissed to learn it was empty - **A picker row draws a real codename only.** The row opens with the short id, so the card's `~` fallback would print it twice and say nothing the second time +- **The picker draws two sections, open campaigns above completed, and truncates the completed tail.** One flat list by title put the finished campaigns among the open ones forever, and the tail only grows, so on a board that has run for a while the campaigns worth picking were pushed towards the bottom of the box and eventually off it. Open keeps the index's order, which is by title; completed is by `Created At` newest first, because what a reader recognises about a finished campaign is that it was finished recently. `COMPLETED_SHOWN` of them survive, behind a grey line naming how many older ones are being kept back — rows that are simply gone read as a board that never held them. An unstamped campaign sinks below every stamped one, the rule `by_status_order` holds for a column +- **`picker_list` is the one place that decides what a picker row is**, and `Picker::row` counts *drawn* rows. The sections reorder the campaigns and add rows of their own, so `Tab::campaigns` and the drawn list agree about no number past the first heading, and a row number that meant one thing to the draw and another to a keypress is how a highlight comes to name a campaign nobody chose. The list is derived on every draw and every keypress and never held, which is what keeps a campaign filed elsewhere reaching an open picker on the next tick +- **A heading is drawn only over rows that exist**, the bargain an untagged card's label row already makes, and it says which kind its rows are for as long as they are there — which is what a query filtering down to completed campaigns alone has to go on saying +- **`open` and `completed`, not `open` and `done`.** The split is taken from `Standing::state`, so the section a campaign lands in and the state the frame draws cannot come to disagree about what finished means, but the word is the section's own: a campaign sits in no status directory, so it is not *in* done the way a ticket under that heading is. A campaign with no members is neither, per that method, and lists as open — completed means every member is done, and it holds none to be done +- **Headings and the truncation line take no number: the highlight moves over campaigns only.** `stepped_picker_row` walks past the chrome rather than stopping on it, since a highlight resting on a heading gives `enter` nothing to do, and a step that runs out of campaigns is no move at all, the way a card at the end of a column clamps rather than cycling +- **`/` in the picker is the key it already is on the board**, and `picker_key` can take it because printable keys used to fall through `_ => {}`. Typing filters case insensitively against the short id, the codename and the title — the three things the row draws and the three a campaign is chosen by. Not the summary: a query that matched prose would answer `disk` with every campaign whose description mentions one. **An empty query matches everything**, the opposite of `first_match`'s answer and right for the opposite reason: a jump with nothing typed has nowhere to go, while a filter with nothing typed is not filtering, and pressing `/` must not empty the list +- **A query turns the truncation off**, which is the point of having one: the campaign a reader is searching for is exactly the one the truncation hid +- **The query is a layer, and `esc` takes it off before it takes the picker off**, the order `dismiss` closes the board's own layers in. So the list is whole again after that press, not still filtered with nothing on screen saying why. Movement and `enter` stay live under an open query, because a filtered list nothing can move in is a list nothing can be chosen from; every *printable* key goes into the buffer, so `q` types and so does `j` +- **The highlight follows its campaign, not its row number.** `place_picker` takes a uuid, the answer `Tab::campaign` already gives for the filter: typing, clearing the query and a tick that finishes a campaign all reshape the list, and a number kept across that names whichever campaign now sits at it. One the list no longer holds drops the highlight to the first row that does, which is where an incremental filter puts it. `reload` reads the highlighted uuid before the lists are rebuilt and puts it back after +- **A miss is a row in the box, `no match` in brightred**, where the search prompt puts its own, and `enter` on it leaves the picker and the query exactly as they are so the query can be corrected in place. An empty box says nothing about why it is empty +- **The picker's footer becomes its query**, the trade `draw_search` makes: with every printable key going into a buffer, a list of keys describes nothing that works. `/ search` is named only on the closed query, and the open one names what `esc` does to *it* rather than what it does to the picker +- **The title says both counts while a query is open**, `campaigns (2 of 6)`. The bare total is what the box is, but over a list a query has cut down it is a lie about what is on screen +- **Every campaign's standing is settled at reload, in one pass over the cards.** `standings_of` counts the cards naming each uuid off the columns the reload is already holding, which is what `Standing::of` builds for `campaign ls` without the walk of the status directories that one pays *per campaign*. A keypress must not pay that, and the picker needs every campaign's standing rather than just the selected one's, since the split is what it decides. Counted before the campaign filter is applied: how far a campaign has got is not a question about what the tab is showing +- **`Tab::standing` is gone with it.** The frame's standing is the row's, because two counts of one number are two numbers free to drift — the rule `wrapped_height` holds for the scroll. `the_standings_are_read_when_the_cards_are_and_not_per_draw` takes the status directories away after the board is built, paired with `a_member_finished_after_the_board_was_built_completes_its_campaign` for the reason the comment count's two tests are paired: a standing that never asked the filesystem again would pass the first by never changing - **`q` takes off one layer at a time, in the order they were put on**: the overlay, then the campaign filter, then the board. `Board::dismiss` holds all three, and it takes the screen now because clearing the filter reloads and has to follow the selection. Selecting a campaign closes an open ticket, the answer hiding the done column already gives: the ticket may not be on the filtered board at all, and swapping it for a different one without saying so is how a person acts on the wrong ticket - **`digest` watches the campaigns directory** as well as the statuses and the comments. A campaign filed elsewhere has to reach the picker and a codename edited by hand has to reach every card that names it, and a directory's own mtime would miss the edit - **The tags go under the title, dimmed, each prefixed with `#`.** The field was invisible on the board: nothing said a ticket was tagged `bug` without opening it. The marker is what stops the row reading as a third line of the title, since a tag is an ordinary word and the title sits directly above it. The row is dropped whole when the column will not hold it, the rule a corner follows, and an untagged ticket spends no row at all, the way a short title spends no second one diff --git a/Cargo.lock b/Cargo.lock index 184492a..16175b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.24.1" +version = "0.24.2" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 5fbca0b..f5e6c2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.24.1" +version = "0.24.2" edition = "2024" [dependencies] diff --git a/src/campaign.rs b/src/campaign.rs index b0fb773..dc7e911 100644 --- a/src/campaign.rs +++ b/src/campaign.rs @@ -224,6 +224,10 @@ pub fn members(worklane_dir: &Path, uuid: &str) -> Result Result<()> KeyCode::Char('d') => board.toggle_done(screen), // An ordinary single-shot action like the rest: it opens the prompt, and // from the next keypress on `search_key` above has the keyboard. A `/` - // typed into an open prompt is taken there as a character, so this arm - // is only ever the way in. + // typed into an open prompt is taken there as a character, and one pressed + // at an open picker is taken by `picker_key` to open the picker's own + // query, so this arm is only ever the way in to the board's prompt. KeyCode::Char('/') => board.open_search(), // `y` as in yank, for the readers this board is for, and the only letter // left that a vim hand would reach for. The clipboard is handed in rather diff --git a/src/tui.rs b/src/tui.rs index cd3a073..43c0b6e 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -169,9 +169,10 @@ pub struct Column { /// the campaign on each card. The description is cut to its opening line here rather than /// at draw time, because the file is only in hand while the directory is being read. /// -/// No member count. Counting them is a walk of the status directories per campaign, which -/// is what `campaign ls` pays and what a keypress should not; the standing of the *selected* -/// campaign is free, since the columns are then its members. +/// The standing is counted here too, off the cards the reload is already holding rather +/// than by the walk of the status directories per campaign that `campaign ls` pays. A +/// keypress must not pay that, and the picker needs every campaign's standing and not just +/// the selected one's: the split into open and completed is what it decides. #[derive(Clone, Debug)] pub struct CampaignRow { pub uuid: String, @@ -179,6 +180,13 @@ pub struct CampaignRow { pub codename: Option, /// The opening line of the description, or empty for a campaign with none. pub summary: String, + /// When it was filed, as the file spells it. What the completed section is ordered by, + /// so the couple that survive the truncation are the ones just finished. Compared as a + /// string: `%Y-%m-%d %H:%M:%S` is lexicographic in chronological order, the property + /// `by_status_order` already leans on. + pub created_at: String, + /// How far it has got, from the cards this board holds. + pub standing: Standing, /// The project it was filed in, on the All tab only. A campaign is resolved inside one /// `.worklane`, so across several boards the id alone does not say which board holds /// it — the same reason a card carries its project there. @@ -190,6 +198,16 @@ impl CampaignRow { pub fn label(&self) -> Cell { campaign_label(&self.uuid, self.codename.as_deref()) } + + /// Whether every member is done, which is what puts the row under `completed`. + /// + /// Off `Standing::state`, so the section a campaign lands in and the state the frame + /// draws cannot come to disagree about what finished means. A campaign with no members + /// is neither, per that method, and lists as open: completed means every member is + /// done, and this one holds none to be done. + fn completed(&self) -> bool { + self.standing.state() == Some(DONE) + } } /// One tab: a monitored board, or the merge across all of them. @@ -239,24 +257,6 @@ impl Tab { self.campaigns.iter().find(|row| row.uuid == uuid) } - /// How far the selected campaign has got, from the columns rather than from a scan. - /// - /// The columns *are* its members while it is selected, done included, so this is the - /// same count `Standing::of` builds for `campaign ls` without the walk per campaign - /// that one pays. Counted over every column, drawn or not: hiding done is a change to - /// what is drawn and never to what is counted, the rule the footer's own count follows. - fn standing(&self) -> Standing { - Standing { - done: self - .columns - .iter() - .filter(|column| column.status == DONE) - .map(|column| column.cards.len()) - .sum(), - total: self.columns.iter().map(|column| column.cards.len()).sum(), - } - } - /// The columns that are drawn: all of them, or everything up to done. /// /// A prefix rather than a filter, which is what keeps `column` and `offsets` usable @@ -400,9 +400,128 @@ impl Notice { /// than in a copy of the list that has gone stale. #[derive(Debug, Default)] pub struct Picker { + /// Which *drawn* row the highlight is on, headings and the truncation line included, + /// so it and `offset` are counted in the same units and `picker_list` is the one place + /// that decides what a row number means. pub row: usize, /// First visible row, counted in rows, since a picker row is one line. pub offset: u16, + /// The query while it is open, on the terms `search` is on the board: `None` is the + /// picker reading its keys as movement, and `Some("")` is an open query nothing has + /// been typed into yet, which filters nothing. + pub query: Option, +} + +/// The picker's section headings. +/// +/// Lowercase like the column headings, since they are the same kind of chrome, and +/// `completed` rather than the `done` `Standing::state` spells: a campaign sits in no +/// status directory, so it is not *in* done the way a ticket under that heading is. +const OPEN_SECTION: &str = "open"; +const COMPLETED_SECTION: &str = "completed"; + +/// How many completed campaigns the list shows before it starts keeping them back. +/// +/// A couple. The completed tail only grows, and the reason to see any of it is to +/// recognise what was finished recently; the rest is what `/` is for. +const COMPLETED_SHOWN: usize = 2; + +/// One drawn row of the picker: a campaign, or a line of chrome about the ones around it. +/// +/// Only `Campaign` is selectable, which is what `move_picker` steps over and `take_picked` +/// takes: a highlight resting on a heading would give `enter` nothing to do. +/// +/// Borrowed from the tab rather than owned, so the list stays what `Tab::campaigns` says it +/// is. Nothing here is held on the `Picker`: the rows are derived on every draw and every +/// keypress, which is what lets a campaign filed elsewhere reach an open picker on the next +/// tick instead of being missing from a copy taken when it opened. +enum PickerRow<'a> { + /// A section heading, naming what the rows under it are. + Heading(&'static str), + Campaign(&'a CampaignRow), + /// How many older completed campaigns the truncation is keeping back. + Hidden(usize), + /// The query matched nothing, said in the box rather than left as an empty one. + Missed, +} + +/// The rows the picker draws: open campaigns above completed, filtered by the query. +/// +/// One flat list ordered by title put the completed campaigns among the open ones forever. +/// The tail only grows, so on a board that has run for a while the ones worth picking were +/// pushed towards the bottom and off it by the ones that are finished. +/// +/// The open section keeps the index's order, which is by title. The completed section is by +/// `Created At` newest first, because what a reader recognises in a finished campaign is +/// that it was finished recently, and it is truncated to [`COMPLETED_SHOWN`] behind a line +/// saying how many are being kept back. An unstamped campaign sinks below every stamped one, +/// the rule `by_status_order` holds for a column: a missing time is unknown rather than +/// ancient, and unknown must not claim the head of a list. +/// +/// A query turns the truncation off, which is the point of having one: the campaign a reader +/// is searching for is exactly the one the truncation hid. +/// +/// A heading is drawn only over rows that exist. An `open` heading over nothing is a row of +/// the box spent saying there is nothing to say, the bargain an untagged card's label row +/// already makes — and a section that is there always says which kind its rows are, which +/// is what a query filtering down to completed campaigns alone has to keep saying. +fn picker_list<'a>(tab: &'a Tab, picker: &Picker) -> Vec> { + let query = picker.query.as_deref().unwrap_or_default(); + + let (mut completed, open): (Vec<&CampaignRow>, Vec<&CampaignRow>) = tab + .campaigns + .iter() + .filter(|campaign| picker_matches(campaign, query)) + .partition(|campaign| campaign.completed()); + + completed.sort_by(|a, b| b.created_at.cmp(&a.created_at)); + let found = completed.len(); + if query.is_empty() { + completed.truncate(COMPLETED_SHOWN); + } + + let mut rows: Vec = Vec::new(); + if !open.is_empty() { + rows.push(PickerRow::Heading(OPEN_SECTION)); + rows.extend(open.into_iter().map(PickerRow::Campaign)); + } + if !completed.is_empty() { + rows.push(PickerRow::Heading(COMPLETED_SECTION)); + rows.extend(completed.iter().copied().map(PickerRow::Campaign)); + } + if found > completed.len() { + rows.push(PickerRow::Hidden(found - completed.len())); + } + + // A box with nothing in it says nothing about why, and the query that emptied it is + // still on the footer to be corrected. + if rows.is_empty() { + rows.push(PickerRow::Missed); + } + + rows +} + +/// Whether a campaign answers the query: its short id, its codename or its title. +/// +/// The three things a picker row is chosen by, which is the three things the row draws. +/// Case insensitive for the reason `first_match` is: a title has to be to be worth typing, +/// and an id given the same treatment matches whatever case it was pasted in. +/// +/// An empty query matches everything, the opposite of the answer `first_match` gives and +/// right for the opposite reason: a jump with nothing typed has nowhere to go, while a +/// filter with nothing typed is not filtering. Pressing `/` must not empty the list. The +/// query is trimmed, so a space typed while composing one does not blank it either. +fn picker_matches(campaign: &CampaignRow, query: &str) -> bool { + let query = query.trim().to_lowercase(); + if query.is_empty() { + return true; + } + + let codename = campaign.codename.as_deref().unwrap_or_default(); + short_id(&campaign.uuid).to_lowercase().contains(&query) + || codename.to_lowercase().contains(&query) + || campaign.title.to_lowercase().contains(&query) } /// What is on screen. @@ -524,10 +643,18 @@ impl Board { true => Some(project.name.as_str()), false => None, }; + // The standing on each row is counted off these columns, before the campaign + // filter is applied to them further down: a campaign's standing is how far it + // has got, which is not a question about what the tab is currently showing. + per_campaigns.push(campaign_rows(&campaigns, label, &columns)); per_columns.push(columns); - per_campaigns.push(campaign_rows(&campaigns, label)); } + // The campaign the picker is highlighting, taken before the lists are rebuilt. The + // row is an index into a list a tick can reshape, so it is the uuid that has to + // survive the rebuild, the way `Tab::campaign` is a uuid and not an index. + let highlighted = self.picker_highlight().map(|row| row.uuid.clone()); + let mut built: Vec<(Vec, Vec)> = Vec::new(); if merged { // Every board's campaigns under the merge, each carrying the project it was @@ -556,6 +683,12 @@ impl Board { self.digest = digest_of(&self.projects); + // And put back, on the campaign rather than on the number: one filed or finished + // elsewhere splits the list differently, so the row that held it has moved. + if self.picker.is_some() { + self.place_picker(highlighted.as_deref()); + } + // The selected ticket may have moved or gone, so the open detail follows it. // The scroll offset stays where the reader put it: an edit elsewhere in the tree // should not throw them back to the top of what they are reading. A ticket that @@ -749,14 +882,51 @@ impl Board { return; } - let row = self - .current() - .campaign - .as_deref() - .and_then(|uuid| self.current().campaigns.iter().position(|row| row.uuid == uuid)) + let selected = self.current().campaign.clone(); + self.picker = Some(Picker::default()); + self.place_picker(selected.as_deref()); + } + + /// The campaign the highlight is on, or nothing when the picker is closed or the + /// highlight is on chrome. + /// + /// Through the drawn list rather than by indexing `Tab::campaigns`, because that is + /// what the row number counts: the sections reorder the campaigns and add rows of their + /// own, so the two lists agree about no number past the first heading. + fn picker_highlight(&self) -> Option<&CampaignRow> { + let picker = self.picker.as_ref()?; + + match picker_list(self.current(), picker).into_iter().nth(picker.row)? { + PickerRow::Campaign(campaign) => Some(campaign), + _ => None, + } + } + + /// Put the highlight on `uuid`, or on the first row that can be taken. + /// + /// By uuid rather than by keeping the number, the answer `Tab::campaign` gives for the + /// filter: a query typed into or a tick that finishes a campaign reshapes the list, and + /// a number kept across that names whichever campaign now sits at it. A campaign the + /// list no longer holds leaves nothing to hold on to, so the highlight goes to the top + /// of what is there — which is where an incremental filter puts it anyway. + /// + /// A list of nothing but chrome puts it on row zero, where `take_picked` finds no + /// campaign and does nothing. + fn place_picker(&mut self, uuid: Option<&str>) { + let Some(picker) = &self.picker else { return }; + let rows = picker_list(self.current(), picker); + + let held = uuid.and_then(|uuid| { + rows.iter() + .position(|row| matches!(row, PickerRow::Campaign(held) if held.uuid == uuid)) + }); + let at = held + .or_else(|| rows.iter().position(|row| matches!(row, PickerRow::Campaign(_)))) .unwrap_or(0); - self.picker = Some(Picker { row, offset: 0 }); + if let Some(picker) = &mut self.picker { + picker.row = at; + } } /// Feed a keypress to the open picker, and say whether it was taken. @@ -767,9 +937,17 @@ impl Board { /// and every other control combination is swallowed and does nothing, so `ctrl-d` /// cannot fall through to the arm bound to `d`. /// - /// Up and down only, and no `hjkl`: the list is one column, and a letter here would - /// have to be the letter that also selects nothing. `enter` takes the highlighted - /// campaign, `esc` and `q` leave the board as it was. + /// Up and down move the highlight, and `hjkl`'s `k` and `j` beside them while no query + /// is open. `enter` takes the highlighted campaign, `/` starts a query, and `esc` and + /// `q` leave the board as it was. + /// + /// `/` has the role the board's own dispatch gives it, which is why the picker can take + /// it at all: the key that searches a list of cards searches a list of campaigns. While + /// the query is open every printable key goes into it — `q` types and so does `j` — and + /// `esc` takes the query off before it takes the picker off, one layer at a time, the + /// order `dismiss` closes the board's own layers in. Movement and `enter` stay live + /// under an open query: a filtered list nothing can move in is a list nothing can be + /// chosen from, which is what the filter was for. pub fn picker_key(&mut self, key: KeyEvent, screen: Size) -> bool { if self.picker.is_none() { return false; @@ -780,46 +958,125 @@ impl Board { return false; } + let querying = self.picker.as_ref().is_some_and(|picker| picker.query.is_some()); + match key.code { + // Shared, query or no query, so the arms below can be about the letters alone. + KeyCode::Up if !control => self.move_picker(-1, screen), + KeyCode::Down if !control => self.move_picker(1, screen), + KeyCode::Enter if !control => self.take_picked(screen), + // The query, which owns every printable key while it is open. Ahead of the + // letters below rather than ordered against them by hand. + KeyCode::Esc if querying => self.requery(screen, |query| *query = None), + KeyCode::Backspace if querying => self.requery(screen, |query| { + if let Some(query) = query { + query.pop(); + } + }), + KeyCode::Char(typed) if querying && !control => self.requery(screen, |query| { + if let Some(query) = query { + query.push(typed); + } + }), KeyCode::Esc | KeyCode::Char('q') if !control => self.picker = None, - KeyCode::Up | KeyCode::Char('k') if !control => self.move_picker(-1, screen), - KeyCode::Down | KeyCode::Char('j') if !control => self.move_picker(1, screen), - KeyCode::Enter | KeyCode::Char(' ') if !control => self.take_picked(screen), + KeyCode::Char('/') if !control => { + self.requery(screen, |query| *query = Some(String::new())); + } + KeyCode::Char('k') if !control => self.move_picker(-1, screen), + KeyCode::Char('j') if !control => self.move_picker(1, screen), + KeyCode::Char(' ') if !control => self.take_picked(screen), _ => {} } true } + /// Change the query, and keep the highlight on the campaign it was on. + /// + /// The campaign rather than the row number, for the reason `place_picker` gives: typing + /// reshapes the list under the highlight. One that no longer matches drops it to the + /// first row that does. + /// + /// Opening and closing the query go through here too, since both change the list: an + /// empty query filters nothing but a closed one also untruncates nothing, and closing + /// one that had cut the list down gives every hidden row back. + fn requery(&mut self, screen: Size, edit: impl FnOnce(&mut Option)) { + let held = self.picker_highlight().map(|campaign| campaign.uuid.clone()); + + let Some(picker) = &mut self.picker else { + return; + }; + edit(&mut picker.query); + + self.place_picker(held.as_deref()); + self.align_picker(screen); + } + /// Move the highlight, clamped like a card rather than cycled like a tab. /// /// A list has a top and a bottom, and running off one end of a list of campaigns to /// the other is how a reader loses their place in it. fn move_picker(&mut self, delta: isize, screen: Size) { - let count = self.current().campaigns.len(); + let Some(row) = self.stepped_picker_row(delta) else { + return; + }; + + if let Some(picker) = &mut self.picker { + picker.row = row; + } + self.align_picker(screen); + } + + /// The row a step of `delta` lands the highlight on, over selectable rows only. + /// + /// Section headings and the truncation line take no number: they are not campaigns, so + /// the step walks on past them rather than stopping on one. A step that runs out of + /// campaigns in that direction is no move at all — the highlight stays where it is, + /// which is what a card at the end of a column does. + fn stepped_picker_row(&self, delta: isize) -> Option { + let picker = self.picker.as_ref()?; + let rows = picker_list(self.current(), picker); + + let mut at = picker.row as isize; + loop { + at += delta; + let at = usize::try_from(at).ok()?; + if matches!(rows.get(at)?, PickerRow::Campaign(_)) { + return Some(at); + } + } + } + + /// Bring the highlight into the box's window. + /// + /// Split from the move because the query moves the highlight too, and because the list + /// it is scrolling changes length: an offset left where a longer list put it would draw + /// the box scrolled past its own rows. The draw caps it again on its own geometry, the + /// way an unfocused column is capped, so a stale offset after a tick is corrected in + /// the frame that draws it. + fn align_picker(&mut self, screen: Size) { + let Some(picker) = &self.picker else { return }; + let count = picker_list(self.current(), picker).len() as u16; let height = picker_text_area(Rect::new(0, 0, screen.width, screen.height)).height; let Some(picker) = &mut self.picker else { return; }; - if count == 0 { - return; - } - - picker.row = (picker.row as isize + delta).clamp(0, count as isize - 1) as usize; - let start = picker.row as u16; - picker.offset = aligned_offset(picker.offset, start, start + 1, height, count as u16); + picker.offset = aligned_offset(picker.offset, start, start + 1, height, count); } /// Take the highlighted campaign and close the picker. + /// + /// A highlight on nothing takeable — the `no match` row, or a list of chrome — leaves + /// the picker and the query exactly as they are, so the query can be corrected in place. + /// That is what the search prompt does with a miss, and for the same reason: doing + /// nothing visible is what makes a reader retype a query that was already right. fn take_picked(&mut self, screen: Size) { - let Some(picker) = &self.picker else { return }; - let Some(row) = self.current().campaigns.get(picker.row) else { + let Some(uuid) = self.picker_highlight().map(|campaign| campaign.uuid.clone()) else { return; }; - let uuid = row.uuid.clone(); self.picker = None; self.select_campaign(Some(uuid), screen); } @@ -1189,7 +1446,13 @@ fn columns_of(worklane_dir: &Path) -> (Vec, CampaignIndex) { /// the label on the card cannot come from two different reads of the directory. The order /// is the index's, which is by title, so the list does not depend on what order the /// directory handed its files back in. -fn campaign_rows(campaigns: &CampaignIndex, project: Option<&str>) -> Vec { +fn campaign_rows( + campaigns: &CampaignIndex, + project: Option<&str>, + columns: &[Column], +) -> Vec { + let standings = standings_of(columns); + campaigns .iter() .map(|campaign| CampaignRow { @@ -1197,11 +1460,43 @@ fn campaign_rows(campaigns: &CampaignIndex, project: Option<&str>) -> Vec HashMap<&str, Standing> { + let mut standings: HashMap<&str, Standing> = HashMap::new(); + + for column in columns { + for card in &column.cards { + let Some(uuid) = card.ticket.campaign.as_deref() else { + continue; + }; + + let standing = standings.entry(uuid).or_default(); + standing.total += 1; + standing.done += usize::from(column.status == DONE); + } + } + + standings +} + /// The columns filtered to one campaign's members, or left as they are when none is /// selected. /// @@ -1417,7 +1712,7 @@ pub fn draw(frame: &mut Frame, board: &Board) { draw_tabs(frame, board, rows[TAB_ROW]); } if let Some(campaign) = board.campaign() { - draw_campaign(frame, campaign, &board.current().standing(), rows[CAMPAIGN_ROW]); + draw_campaign(frame, campaign, rows[CAMPAIGN_ROW]); } draw_columns(frame, board, rows[BOARD_ROW]); draw_footer(frame, board, rows[FOOTER_ROW]); @@ -1494,7 +1789,8 @@ fn draw_tabs(frame: &mut Frame, board: &Board, area: Rect) { /// in green, which is the colour guideline applied rather than a decision of its own. Cut /// by hand, like `detail_title`, because ratatui truncates a block title at whatever cell /// it reaches and would take the id with it. -fn draw_campaign(frame: &mut Frame, campaign: &CampaignRow, standing: &Standing, area: Rect) { +fn draw_campaign(frame: &mut Frame, campaign: &CampaignRow, area: Rect) { + let standing = &campaign.standing; let mut block = Block::default() .borders(Borders::ALL) .border_style(Style::default().fg(Color::Grey.into())) @@ -2070,14 +2366,8 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { // And the picker takes it on the same terms: it owns the keyboard, so the list of keys // the board answers to describes nothing that currently works either. - if board.picker.is_some() { - frame.render_widget( - Paragraph::new(Span::styled( - " ↑↓ select enter view esc cancel ", - Style::default().fg(Color::Grey.into()), - )), - area, - ); + if let Some(picker) = &board.picker { + draw_picker_row(frame, picker, area); return; } @@ -2183,6 +2473,36 @@ fn draw_search(frame: &mut Frame, search: &Search, area: Rect) { frame.set_cursor_position((area.x + at, area.y)); } +/// The picker's footer: its query while one is open, and the keys it answers to otherwise. +/// +/// The same division `draw_search` makes, and the same reason for it: while every printable +/// key is going into a buffer, a list of keys describes nothing that currently works. So `/` +/// is named only on the closed query, where it is the key to press, and the query's own row +/// names what `esc` does to it rather than what it does to the picker. +fn draw_picker_row(frame: &mut Frame, picker: &Picker, area: Rect) { + let grey = Style::default().fg(Color::Grey.into()); + + let Some(query) = &picker.query else { + frame.render_widget( + Paragraph::new(Span::styled(" ↑↓ select enter view / search esc cancel ", grey)), + area, + ); + return; + }; + + let prompt = format!(" /{query}"); + let spans = vec![ + Span::raw(prompt.clone()), + Span::styled(" ↑↓ select enter view esc clear ", grey), + ]; + frame.render_widget(Paragraph::new(Line::from(spans)), area); + + // Held on the row, the way the search prompt's cursor is, so a query longer than the + // terminal leaves it on the last cell rather than off the frame. + let at = (prompt.chars().count() as u16).min(area.width.saturating_sub(1)); + frame.set_cursor_position((area.x + at, area.y)); +} + /// How many tickets are in done on the tab in view, drawn or not. fn done_count(board: &Board) -> usize { board @@ -2198,7 +2518,11 @@ fn done_count(board: &Board) -> usize { /// Narrower than the detail overlay and no taller than it needs to be. A picker is a list /// of short rows, and one stretched to the shape of a ticket would be mostly blank space /// with the board hidden behind it. It grows with the list up to that ceiling, so a board -/// with two campaigns gets a box with two rows in it. +/// with two campaigns gets a box with the rows those two are drawn in. +/// +/// `rows` is the *drawn* rows, from `picker_list`, and not the campaigns: the sections and +/// the truncation line take a row each, and a box measured against the campaigns alone +/// would be short by however much chrome the split added. fn picker_overlay(area: Rect, rows: usize) -> Rect { let width = area .width @@ -2250,21 +2574,21 @@ fn picker_text_area(area: Rect) -> Rect { /// picker is open appears in it on the next tick instead of being missing from a copy of /// the list taken when it opened. fn draw_picker(frame: &mut Frame, tab: &Tab, picker: &Picker, area: Rect) { - let overlay = picker_overlay(area, tab.campaigns.len()); + let rows = picker_list(tab, picker); + let overlay = picker_overlay(area, rows.len()); let text = overlay.inner(Margin::new(1, 1)); - let lines: Vec = tab - .campaigns + let lines: Vec = rows .iter() .enumerate() - .map(|(at, campaign)| picker_line(campaign, at == picker.row, text.width)) + .map(|(at, row)| picker_row_line(row, at == picker.row, text.width)) .collect(); let block = Block::default() .borders(Borders::ALL) .border_style(Style::default().fg(Color::Cyan.into())) .title(Span::styled( - format!(" campaigns ({}) ", tab.campaigns.len()), + picker_title(tab, picker), Style::default().fg(Color::Orange.into()), )); @@ -2280,6 +2604,64 @@ fn draw_picker(frame: &mut Frame, tab: &Tab, picker: &Picker, area: Rect) { ); } +/// The picker's own title: how many campaigns the board has, and how many a query left. +/// +/// The bare count while nothing is typed, because that is what the box is. A query that +/// cuts the list down makes the total alone a lie about what is on screen, so it says both +/// — and the reader can see at a glance whether the query is narrow enough. +fn picker_title(tab: &Tab, picker: &Picker) -> String { + let total = tab.campaigns.len(); + let query = picker.query.as_deref().unwrap_or_default(); + if query.trim().is_empty() { + return format!(" campaigns ({total}) "); + } + + let found = tab + .campaigns + .iter() + .filter(|campaign| picker_matches(campaign, query)) + .count(); + + format!(" campaigns ({found} of {total}) ") +} + +/// One drawn row: a campaign, a section heading, the truncation line, or the miss. +/// +/// The chrome is never highlighted, because the highlight only ever sits on a campaign. +/// A heading is bold with its grey so it is not read as the summary of the row above it, +/// and `no match` is brightred where the search prompt's is, since grey is exactly what a +/// reader skips and this is the one row that has to be read. +fn picker_row_line(row: &PickerRow, selected: bool, width: u16) -> Line<'static> { + let grey = Style::default().fg(Color::Grey.into()); + + match row { + PickerRow::Campaign(campaign) => picker_line(campaign, selected, width), + PickerRow::Heading(name) => { + Line::from(Span::styled((*name).to_string(), grey.add_modifier(Modifier::BOLD))) + } + PickerRow::Hidden(count) => Line::from(Span::styled(hidden_line(*count), grey)), + PickerRow::Missed => Line::from(Span::styled( + "no match".to_string(), + Style::default().fg(Color::BrightRed.into()), + )), + } +} + +/// The truncation line: how many completed campaigns are being kept back, and that they +/// are the older ones. +/// +/// Named rather than merely counted. `… 3` beside a list says nothing about what the three +/// are, and the whole reason to draw the line is that the rows it stands for are not there +/// to be read. +fn hidden_line(count: usize) -> String { + let campaigns = match count { + 1 => "campaign", + _ => "campaigns", + }; + + format!("… {count} older completed {campaigns} hidden") +} + /// One picker row: `(1b78a24) ~beaver What the campaign is for`. /// /// The highlight is `REVERSED`, the way a selected card is, so the row reads the same @@ -5812,13 +6194,182 @@ mod tests { format!("- **Campaign**: {uuid}\n") } + /// Four completed campaigns, oldest first: the campaign, the member that finished it, + /// its title and the hour it was filed. + /// + /// An hour apart so the truncation has an order to keep, and named so no title is a + /// substring of another's or of a summary any of these boards draws. + const FINISHED: [(&str, &str, &str, &str); 4] = [ + ( + "aaaaaaaa-0000-4000-8000-000000000000", + "a1111111-0000-4000-8000-000000000000", + "Disk migration", + "2026-01-01 01:00:00", + ), + ( + "bbbbbbbb-0000-4000-8000-000000000000", + "b1111111-0000-4000-8000-000000000000", + "Log rework", + "2026-01-01 02:00:00", + ), + ( + "cccccccc-0000-4000-8000-000000000000", + "c1111111-0000-4000-8000-000000000000", + "Prompt polish", + "2026-01-01 03:00:00", + ), + ( + "dddddddd-0000-4000-8000-000000000000", + "d1111111-0000-4000-8000-000000000000", + "Tag audit", + "2026-01-01 04:00:00", + ), + ]; + + /// A board that has run for a while: two open campaigns and [`FINISHED`]'s four + /// completed ones, which is more completed than the picker shows. + /// + /// Beaver holds no members at all, so it is what pins a campaign with none listing as + /// open. Every completed one holds a done member, since a campaign with none is open + /// however long it has been on the board. + fn tail_board(dir: &Path) -> Board { + write_campaign(dir, V1, "First public release", "v1", "Everything for a public tag."); + write_campaign(dir, BEAVER, "Beaver migration", "beaver", "Move the store off one disk."); + write_ticket( + dir, + "backlog", + "11111111-0000-4000-8000-000000000000", + "In v1", + &campaign_field(V1), + ); + + for (campaign, member, title, created_at) in FINISHED { + write_dated_campaign(dir, campaign, title, created_at); + write_ticket(dir, "done", member, title, &campaign_field(campaign)); + } + + one_board(dir) + } + + /// A campaign with the filing time a test can set, and nothing else on it. + /// + /// A separate fixture rather than a sixth parameter on `write_campaign`, the split + /// `write_member_card` already makes: only the tests about the completed section's + /// order care when a campaign was filed, and five string arguments in a row is what + /// the Rust Style rule in AGENTS.md warns about. + fn write_dated_campaign(dir: &Path, uuid: &str, title: &str, created_at: &str) { + let campaigns = dir.join(CAMPAIGNS_DIR); + std::fs::create_dir_all(&campaigns).unwrap(); + + std::fs::write( + campaigns.join(format!("{}_{}.md", uuid, slug(title))), + format!( + "# {title}\n\n## Description\nWhat it was for.\n\n## Metadata\n\n\ + - **ID**: {uuid}\n- **Codename**: {NOT_SET}\n- **Owner**: alice\n\ + - **Created At**: {created_at}\n" + ), + ) + .unwrap(); + } + + /// Open the picker's query and type into it, `/` and all. + /// + /// Through `picker_key` rather than by writing the field, so what a test drives is what + /// a reader's keyboard drives: the `/` has to be taken by the picker for any of the + /// characters after it to land in a query at all. + fn type_picker_query(board: &mut Board, query: &str) { + press(board, KeyCode::Char('/')); + for c in query.chars() { + assert!(board.picker_key(letter(c), SCREEN), "'{c}' was not taken"); + } + } + + /// Press one key at the open picker. + fn press(board: &mut Board, code: KeyCode) { + assert!(board.picker_key(typed(code), SCREEN), "{code:?} was not taken"); + } + + /// The query the picker is holding, or nothing when it is reading keys as movement. + fn query_of(board: &Board) -> Option { + board + .picker + .as_ref() + .expect("the picker is not open") + .query + .clone() + } + + /// The uuid the highlight is on, so a test can name it without reaching for a row + /// number the sections have already moved. + fn highlighted(board: &Board) -> Option { + board.picker_highlight().map(|campaign| campaign.uuid.clone()) + } + + /// Which drawn row is exactly this heading, since a heading is the whole of its row. + fn row_at(rows: &[String], heading: &str) -> usize { + rows.iter() + .position(|row| row.trim() == heading) + .unwrap_or_else(|| panic!("no {heading:?} row: {rows:?}")) + } + + /// Which drawn row carries this text, for the rows that carry more than one thing. + fn row_with(rows: &[String], needle: &str) -> usize { + rows.iter() + .position(|row| row.contains(needle)) + .unwrap_or_else(|| panic!("no row with {needle:?}: {rows:?}")) + } + + /// The campaigns the picker is drawing, in the order it draws them. + /// + /// Off `picker_list` rather than off the frame, because what a filter is asked about is + /// which campaigns are in the list and not how their rows came out: a query narrow + /// enough to leave one row leaves nothing on screen to count against. + fn picked_ids(board: &Board) -> Vec { + let picker = board.picker.as_ref().expect("the picker is not open"); + + picker_list(board.current(), picker) + .iter() + .filter_map(|row| match row { + PickerRow::Campaign(campaign) => Some(campaign.uuid.clone()), + _ => None, + }) + .collect() + } + + /// The colour the picker drew the first character of one of its rows in. + /// + /// The first character, because that is where every row this is asked about starts + /// saying what it is: the ellipsis on the truncation line and the first letter of a + /// heading. Counted from the top of the list, which is where an unscrolled box is. + fn picker_row_color( + board: &Board, + at: usize, + width: u16, + height: u16, + ) -> ratatui::style::Color { + let picker = board.picker.as_ref().expect("the picker is not open"); + let rows = picker_list(board.current(), picker).len(); + let inner = picker_overlay(Rect::new(0, 0, width, height), rows).inner(Margin::new(1, 1)); + + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + terminal.draw(|frame| draw(frame, board)).unwrap(); + let buffer = terminal.backend().buffer().clone(); + + buffer[(inner.x, inner.y + at as u16)].fg + } + /// The picker's rows, cut out of the frame by its own geometry. /// /// The whole screen will not do: a card carries the same campaign label, so a search /// for one over every row finds the board rather than the list, which is the shape /// `overlay_title_row` exists for on the other overlay. + /// + /// Counted in *drawn* rows, which is what the box is sized against: the sections and the + /// truncation line are rows of it, so a count of the campaigns alone would cut the last + /// one or two off whatever the test is looking for. fn picker_rows(board: &Board, width: u16, height: u16) -> Vec { - let rows = board.current().campaigns.len(); + let picker = board.picker.as_ref().expect("the picker is not open"); + let rows = picker_list(board.current(), picker).len(); let overlay = picker_overlay(Rect::new(0, 0, width, height), rows); let inner = overlay.inner(Margin::new(1, 1)); let lines = render(board, width, height); @@ -6073,7 +6624,7 @@ mod tests { board.select_campaign(Some(V1.to_string()), SCREEN); assert!(!board.show_done, "done is hidden at startup"); - let standing = board.current().standing(); + let standing = board.campaign().expect("no campaign selected").standing; assert_eq!((standing.done, standing.total), (1, 2)); std::fs::remove_dir_all(&dir).ok(); @@ -6165,15 +6716,19 @@ mod tests { let mut board = campaign_board(&dir); board.open_picker(); - for code in [KeyCode::Char('d'), KeyCode::Char('/'), KeyCode::Char('y')] { + for code in [KeyCode::Char('d'), KeyCode::Char('y'), KeyCode::Char('/')] { assert!( board.picker_key(KeyEvent::new(code, KeyModifiers::NONE), SCREEN), "the picker let {code:?} through" ); } assert!(!board.show_done, "d reached the done column"); - assert!(board.search.is_none(), "/ opened the prompt"); assert!(board.picker.is_some(), "the picker closed on a key it does not use"); + // `/` last, and taken by the picker's own query rather than by the board's prompt: + // the key that searches a list of cards searches this list, and the two must not + // both be open. + assert!(board.search.is_none(), "/ opened the board's prompt"); + assert_eq!(query_of(&board).as_deref(), Some(""), "/ opened no query"); // Every other control combination is swallowed and does nothing, or `ctrl-d` would // reach the arm bound to `d`. @@ -6241,8 +6796,10 @@ mod tests { board.select_campaign(Some(V1.to_string()), SCREEN); board.open_picker(); - let row = board.picker.as_ref().expect("no picker").row; - assert_eq!(board.current().campaigns[row].uuid, V1); + let highlighted = board + .picker_highlight() + .expect("the highlight is on no campaign"); + assert_eq!(highlighted.uuid, V1); std::fs::remove_dir_all(&dir).ok(); } @@ -6353,6 +6910,460 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// One flat list ordered by title put the completed campaigns among the open ones + /// forever. The tail only grows, so the campaigns worth picking were pushed towards the + /// bottom of the picker and eventually off it by the ones that are finished. + #[test] + fn the_picker_draws_open_campaigns_above_completed() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + let rows = picker_rows(&board, 100, 24); + let open = row_at(&rows, OPEN_SECTION); + let completed = row_at(&rows, COMPLETED_SECTION); + assert!(open < completed, "completed came first: {rows:?}"); + + // An open campaign is under the first heading and a completed one under the second, + // which is the whole of the split. + let v1 = row_with(&rows, short_id(V1)); + let audit = row_with(&rows, short_id(FINISHED[3].0)); + assert!(open < v1 && v1 < completed, "an open campaign under completed: {rows:?}"); + assert!(completed < audit, "a completed campaign under open: {rows:?}"); + + // A heading is chrome, and grey is what the guideline gives to what a reader skips. + assert_eq!(picker_row_color(&board, open, 100, 24), Color::Grey.into()); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// `Standing::state` calls a campaign with no members neither open nor done. For the + /// split it lists under open, because completed means every member is done and it holds + /// none to be done. + #[test] + fn a_campaign_is_completed_only_when_it_holds_members_and_every_one_is_done() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + let campaigns = &board.current().campaigns; + let beaver = campaigns + .iter() + .find(|row| row.uuid == BEAVER) + .expect("no beaver"); + assert_eq!((beaver.standing.done, beaver.standing.total), (0, 0)); + assert!(!beaver.completed(), "a campaign with no members read as completed"); + + let audit = campaigns + .iter() + .find(|row| row.uuid == FINISHED[3].0) + .expect("no tag audit"); + assert_eq!((audit.standing.done, audit.standing.total), (1, 1)); + assert!(audit.completed(), "every member done and still open"); + + // And the drawn list agrees: the empty one is above the completed heading. + let rows = picker_rows(&board, 100, 24); + assert!( + row_with(&rows, short_id(BEAVER)) < row_at(&rows, COMPLETED_SECTION), + "a campaign with no members listed as completed: {rows:?}" + ); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The completed tail is truncated to the couple most recently filed, and the line under + /// them says how many are being kept back: rows that are simply gone read as a board + /// that never held them. + #[test] + fn the_completed_section_keeps_the_most_recent_and_names_what_it_hid() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + let rows = picker_rows(&board, 100, 24); + // By `Created At` newest first, and not by title: "Disk migration" and "Log rework" + // are the two that would survive an alphabetical order. + for (campaign, _, title, _) in [FINISHED[3], FINISHED[2]] { + assert!( + rows.iter().any(|row| row.contains(short_id(campaign))), + "{title} was hidden: {rows:?}" + ); + } + for (campaign, _, title, _) in [FINISHED[1], FINISHED[0]] { + assert!( + !rows.iter().any(|row| row.contains(short_id(campaign))), + "{title} survived the truncation: {rows:?}" + ); + } + + let hidden = row_with(&rows, "older completed"); + assert!( + rows[hidden].contains("2 older completed campaigns hidden"), + "the line does not say how many: {:?}", + rows[hidden] + ); + assert_eq!(picker_row_color(&board, hidden, 100, 24), Color::Grey.into()); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// One campaign hidden is one campaign, since a line that misspells what it is counting + /// is read twice before it is believed. + #[test] + fn the_truncation_line_counts_one_hidden_campaign_in_the_singular() { + assert_eq!(hidden_line(1), "… 1 older completed campaign hidden"); + assert_eq!(hidden_line(2), "… 2 older completed campaigns hidden"); + } + + /// `/` is the key that searches a list of cards, so it is the key that searches a list + /// of campaigns. Id, codename and title, case insensitively, which is the three things + /// the row draws and the three a campaign is chosen by. + #[test] + fn a_query_filters_the_picker_by_id_codename_and_title() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + // The codename, in the wrong case, since a query that has to be typed exactly is + // not worth typing. + type_picker_query(&mut board, "BEAV"); + assert_eq!(picked_ids(&board), vec![BEAVER.to_string()], "the codename missed"); + + // The title, in the middle of it. + board.picker = None; + board.open_picker(); + type_picker_query(&mut board, "public rel"); + assert_eq!(picked_ids(&board), vec![V1.to_string()], "the title missed"); + + // And the short id the row opens with. + board.picker = None; + board.open_picker(); + type_picker_query(&mut board, short_id(FINISHED[3].0)); + assert_eq!(picked_ids(&board), vec![FINISHED[3].0.to_string()], "the id missed"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The summary is drawn on the row but is not what the row is chosen by: a query that + /// matched prose would answer "disk" with every campaign whose description mentions one. + #[test] + fn a_query_does_not_match_the_summary_the_row_draws() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + // Beaver's summary reads "Move the store off one disk." and its title does not. + type_picker_query(&mut board, "disk"); + assert_eq!(picked_ids(&board), vec![FINISHED[0].0.to_string()], "the summary matched"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A search reaches the whole completed tail, untruncated, which is the point of having + /// one: the campaign a reader is looking for is exactly the one the truncation hid. + #[test] + fn a_query_finds_the_completed_campaigns_the_truncation_hid() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + let hidden = FINISHED[0].0; + assert!( + !picker_rows(&board, 100, 24) + .iter() + .any(|row| row.contains(short_id(hidden))), + "the oldest was not hidden to begin with" + ); + + type_picker_query(&mut board, "migration"); + let rows = picker_rows(&board, 100, 24); + assert!( + rows.iter().any(|row| row.contains(short_id(hidden))), + "the query did not reach the truncated tail: {rows:?}" + ); + assert!( + !rows.iter().any(|row| row.contains("older completed")), + "the query left the truncation on: {rows:?}" + ); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// While the query is open the picker still owns the keyboard, so `q` types rather than + /// closing anything, and `esc` takes the query off before it takes the picker off: one + /// layer at a time, the order `dismiss` closes the board's own layers in. + #[test] + fn the_query_takes_q_and_esc_closes_it_before_the_picker() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + type_picker_query(&mut board, "q"); + assert!(board.picker.is_some(), "q closed the picker"); + assert_eq!(query_of(&board).as_deref(), Some("q"), "q did not type"); + + // Backspace edits it in place rather than closing it, the way the search prompt's + // does: a query worth correcting is not a query worth retyping. + press(&mut board, KeyCode::Backspace); + assert_eq!(query_of(&board).as_deref(), Some(""), "backspace closed the query"); + + press(&mut board, KeyCode::Esc); + assert!(board.picker.is_some(), "esc closed the picker with a query open"); + assert_eq!(query_of(&board), None, "the query outlived the esc"); + + press(&mut board, KeyCode::Esc); + assert!(board.picker.is_none(), "the second esc left the picker open"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// Enter takes the highlighted row whether a query is open or not: filtering is how the + /// row is found, not a different way of taking it. + #[test] + fn enter_under_a_query_takes_the_highlighted_campaign() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + type_picker_query(&mut board, "beav"); + assert_eq!( + highlighted(&board).as_deref(), + Some(BEAVER), + "the highlight missed the match" + ); + + press(&mut board, KeyCode::Enter); + assert!(board.picker.is_none(), "the picker stayed open"); + assert_eq!(board.current().campaign, Some(BEAVER.to_string())); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A query that matches nothing keeps the picker and the query open, and says so in the + /// box rather than leaving an empty one: the query can then be corrected in place, + /// which is what the search prompt does with a miss. + #[test] + fn a_query_that_matches_nothing_keeps_the_picker_and_the_query_open() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + type_picker_query(&mut board, "zzz"); + let rows = picker_rows(&board, 100, 24); + assert!(rows[0].contains("no match"), "an empty box says nothing: {rows:?}"); + assert_eq!(picker_row_color(&board, 0, 100, 24), Color::BrightRed.into()); + + press(&mut board, KeyCode::Enter); + assert!(board.picker.is_some(), "enter on a miss closed the picker"); + assert_eq!(query_of(&board).as_deref(), Some("zzz"), "the query was taken away"); + assert_eq!(board.current().campaign, None, "a miss selected something"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// Section headings and the truncation line take no number: they are not campaigns, so + /// a highlight resting on one would give enter nothing to do. + #[test] + fn the_highlight_moves_over_campaigns_and_never_onto_the_chrome() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + // It opens on the first campaign, not on the heading above it. + assert_eq!(board.picker.as_ref().expect("no picker").row, 1); + + // Down until it stops, which is the last campaign and not the truncation line under + // it. Four campaigns are drawn: two open, and the two the truncation kept. + let mut walked = vec![highlighted(&board).expect("the highlight opened on chrome")]; + loop { + let before = board.picker.as_ref().expect("no picker").row; + press(&mut board, KeyCode::Down); + if board.picker.as_ref().expect("no picker").row == before { + break; + } + walked.push(highlighted(&board).expect("the highlight landed on chrome")); + } + assert_eq!(walked.len(), 4, "{walked:?}"); + assert_eq!(walked[0], BEAVER, "the list is not in the index's order: {walked:?}"); + assert_eq!(walked[3], FINISHED[2].0, "the walk stopped short: {walked:?}"); + + // And back up is the same walk in reverse, over the second heading rather than onto + // it, ending on the first campaign rather than the first row. + let mut back = Vec::new(); + loop { + let before = board.picker.as_ref().expect("no picker").row; + press(&mut board, KeyCode::Up); + if board.picker.as_ref().expect("no picker").row == before { + break; + } + back.push(highlighted(&board).expect("the highlight landed on chrome")); + } + back.reverse(); + assert_eq!(back, walked[..3], "the walk back is not the walk out"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The highlight follows the campaign it was on rather than the number it was at: a + /// query reshapes the list, and a number kept across that names whichever campaign now + /// sits at it. + #[test] + fn the_highlight_follows_its_campaign_through_a_query() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + press(&mut board, KeyCode::Down); + assert_eq!(highlighted(&board).as_deref(), Some(V1), "down did not reach v1"); + + // Still a match, so it stays on it however far the row has moved. + type_picker_query(&mut board, "release"); + assert_eq!(highlighted(&board).as_deref(), Some(V1), "the highlight left its campaign"); + + // And back to the whole list, still on it. + press(&mut board, KeyCode::Esc); + assert_eq!(highlighted(&board).as_deref(), Some(V1), "clearing the query lost it"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A query that excludes the highlighted campaign drops the highlight to the first row + /// that does match, which is where an incremental filter puts it. + #[test] + fn a_query_that_excludes_the_highlight_moves_it_to_the_first_match() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + assert_eq!(highlighted(&board).as_deref(), Some(BEAVER)); + + type_picker_query(&mut board, "polish"); + assert_eq!(highlighted(&board).as_deref(), Some(FINISHED[2].0)); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The footer is the picker's while it is open, and the query's while that is open: with + /// every printable key going into a buffer, a list of keys describes nothing that works. + #[test] + fn the_picker_footer_names_the_search_key_and_then_becomes_the_query() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + assert!(footer(&board, 100, 24).contains("/ search"), "the key is unfindable"); + + type_picker_query(&mut board, "beav"); + let row = footer(&board, 100, 24); + assert!(row.contains("/beav"), "the query is not on the row: {row:?}"); + assert!(row.contains("esc clear"), "the row does not say what esc does: {row:?}"); + assert!(!row.contains("/ search"), "the row names a key that types: {row:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The bare count is what the box is. A query that cuts the list down makes the total + /// alone a lie about what is on screen, so the title says both. + #[test] + fn the_picker_title_says_how_many_a_query_left() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + let title = |board: &Board| { + let picker = board.picker.as_ref().expect("no picker"); + picker_title(board.current(), picker) + }; + assert_eq!(title(&board), " campaigns (6) "); + + type_picker_query(&mut board, "migration"); + assert_eq!(title(&board), " campaigns (2 of 6) "); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The standing on every row is settled at reload, off the cards the reload already + /// holds. A walk of the status directories per campaign is what `campaign ls` pays and + /// what a keypress must not. + #[test] + fn the_standings_are_read_when_the_cards_are_and_not_per_draw() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + // Taken away after the board was built, so a standing that asked the filesystem + // again would have nothing left to ask it. + for status in Status::ALL { + std::fs::remove_dir_all(dir.join(status.as_str())).unwrap(); + } + + let rows = picker_rows(&board, 100, 24); + assert!( + rows.iter().any(|row| row.trim() == COMPLETED_SECTION), + "the split was recounted per draw: {rows:?}" + ); + assert!( + rows.iter().any(|row| row.contains(short_id(FINISHED[3].0))), + "a completed campaign left the section: {rows:?}" + ); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// Paired with the test above, which would pass by never asking the filesystem again: + /// a member finished elsewhere has to move its campaign into the completed section, and + /// the reload is what recounts. + #[test] + fn a_member_finished_after_the_board_was_built_completes_its_campaign() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + + let rows = picker_rows(&board, 100, 24); + assert!( + row_with(&rows, short_id(V1)) < row_at(&rows, COMPLETED_SECTION), + "v1 was completed to begin with: {rows:?}" + ); + + // Its one member moves to done, which is the whole of the campaign finishing. + let member = "11111111-0000-4000-8000-000000000000"; + let from = dir + .join("backlog") + .join(format!("{member}_{}.md", slug("In v1"))); + std::fs::rename(&from, dir.join("done").join(format!("{member}_{}.md", slug("In v1")))) + .unwrap(); + assert!(board.tick().unwrap(), "the tick saw nothing"); + + let campaigns = &board.current().campaigns; + let v1 = campaigns.iter().find(|row| row.uuid == V1).expect("no v1"); + assert_eq!((v1.standing.done, v1.standing.total), (1, 1), "the standing did not move"); + assert!(v1.completed(), "a campaign whose every member is done stayed open"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The highlight survives a tick, on the campaign rather than on the number: one filed + /// or finished elsewhere splits the list differently, so the row that held it moves. + #[test] + fn the_highlight_survives_a_campaign_filed_under_an_open_picker() { + let dir = board_dir(); + let mut board = tail_board(&dir); + board.open_picker(); + press(&mut board, KeyCode::Down); + assert_eq!(highlighted(&board).as_deref(), Some(V1)); + + // Filed first alphabetically, so every open row below it moves down one. + write_campaign(&dir, "eeeeeeee-0000-4000-8000-000000000000", "Aardvark", "aa", "New."); + assert!(board.tick().unwrap(), "the tick saw nothing"); + + assert_eq!( + highlighted(&board).as_deref(), + Some(V1), + "the highlight held its row rather than its campaign" + ); + + std::fs::remove_dir_all(&dir).ok(); + } + /// The key is named where a reader has to find it, and left out where the frame's own /// border says how to put a campaign away. #[test]